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.

refactor(web): migrate console API helpers to generated contracts (#44430)

Stephen Zhou05c538e69569
diff --git a/api/controllers/console/app/workflow.py b/api/controllers/console/app/workflow.py
index f8a448a91d9..b16ef9c21a3 100644
--- a/api/controllers/console/app/workflow.py
+++ b/api/controllers/console/app/workflow.py
@@ -69,6 +69,7 @@ from core.workflow.llm_environment_variable import (
LLM_ENVIRONMENT_VARIABLE_VALUE_TYPE,
LLMEnvironmentVariable,
)
+from core.workflow.nodes.human_input.entities import FormInputConfig, UserActionConfig
from extensions.ext_database import db
from extensions.ext_redis import redis_client
from factories import file_factory, variable_factory
@@ -429,8 +430,13 @@ class WorkflowRestoreResponse(ResponseModel):
updated_at: int
-class DefaultBlockConfigsResponse(RootModel[list[dict[str, Any]]]):
- root: list[dict[str, Any]]
+class DefaultBlockConfigItemResponse(ResponseModel):
+ type: str
+ config: dict[str, Any]
+
+
+class DefaultBlockConfigsResponse(RootModel[list[DefaultBlockConfigItemResponse]]):
+ pass
class DefaultBlockConfigResponse(RootModel[dict[str, Any]]):
@@ -442,8 +448,8 @@ class HumanInputFormPreviewResponse(ResponseModel):
node_id: str
node_title: str
form_content: str
- inputs: list[dict[str, Any]] = Field(default_factory=list)
- actions: list[dict[str, Any]] = Field(default_factory=list)
+ inputs: list[FormInputConfig] = Field(default_factory=list)
+ actions: list[UserActionConfig] = Field(default_factory=list)
display_in_ui: bool | None = None
form_token: str | None = None
resolved_default_values: dict[str, Any] = Field(default_factory=dict)
@@ -1024,7 +1030,7 @@ class AdvancedChatDraftHumanInputFormPreviewApi(Resource):
inputs=inputs,
session=db.session(),
)
- return jsonable_encoder(preview)
+ return dump_response(HumanInputFormPreviewResponse, preview)
@console_ns.route("/apps/<uuid:app_id>/advanced-chat/workflows/draft/human-input/nodes/<string:node_id>/form/run")
@@ -1092,7 +1098,7 @@ class WorkflowDraftHumanInputFormPreviewApi(Resource):
inputs=inputs,
session=db.session(),
)
- return jsonable_encoder(preview)
+ return dump_response(HumanInputFormPreviewResponse, preview)
@console_ns.route("/apps/<uuid:app_id>/workflows/draft/human-input/nodes/<string:node_id>/form/run")
diff --git a/api/controllers/console/datasets/rag_pipeline/rag_pipeline_workflow.py b/api/controllers/console/datasets/rag_pipeline/rag_pipeline_workflow.py
index a77521ea0e4..8ec20f589de 100644
--- a/api/controllers/console/datasets/rag_pipeline/rag_pipeline_workflow.py
+++ b/api/controllers/console/datasets/rag_pipeline/rag_pipeline_workflow.py
@@ -187,6 +187,10 @@ class RagPipelineRecommendedPluginsResponse(ResponseModel):
uninstalled_recommended_plugins: list[dict[str, Any]]
+class RagPipelinePublishedWorkflowResponse(RootModel[WorkflowResponse | None]):
+ """A null response means the pipeline has no published workflow."""
+
+
register_schema_models(
console_ns,
DraftWorkflowSyncPayload,
@@ -211,6 +215,7 @@ register_response_schema_models(
RagPipelineDatasourceProviderResponse,
RagPipelineOpaqueResponse,
RagPipelinePublishedRunResponse,
+ RagPipelinePublishedWorkflowResponse,
RagPipelineRecommendedPluginsResponse,
RagPipelineStepParametersResponse,
RagPipelineTransformResponse,
@@ -596,7 +601,7 @@ class PublishedRagPipelineApi(Resource):
@console_ns.response(
200,
"Published workflow retrieved successfully, or null if not exist",
- console_ns.models[WorkflowResponse.__name__],
+ console_ns.models[RagPipelinePublishedWorkflowResponse.__name__],
)
@setup_required
@login_required
@@ -620,7 +625,7 @@ class PublishedRagPipelineApi(Resource):
if workflow is None:
return None
- return dump_response(WorkflowResponse, WorkflowResponseSource(workflow, session=session))
+ return dump_response(RagPipelinePublishedWorkflowResponse, WorkflowResponseSource(workflow, session=session))
@console_ns.response(200, "Success", console_ns.models[RagPipelineWorkflowPublishResponse.__name__])
@setup_required
diff --git a/api/openapi/markdown/console-openapi.md b/api/openapi/markdown/console-openapi.md
index 38fb4deb230..85fb2b78258 100644
--- a/api/openapi/markdown/console-openapi.md
+++ b/api/openapi/markdown/console-openapi.md
@@ -9090,7 +9090,7 @@ Update account-level Step-by-step Tour state
| Code | Description | Schema |
| ---- | ----------- | ------ |
-| 200 | Published workflow retrieved successfully, or null if not exist | **application/json**: [WorkflowResponse](#workflowresponse)<br> |
+| 200 | Published workflow retrieved successfully, or null if not exist | **application/json**: [RagPipelinePublishedWorkflowResponse](#ragpipelinepublishedworkflowresponse)<br> |
| 404 | Not Found | **application/json**: [PipelineNotFoundError](#pipelinenotfounderror)<br>[ErrorResponse](#errorresponse)<br> |
| default | Error | **application/json**: [ErrorResponse](#errorresponse)<br> |
@@ -20907,6 +20907,13 @@ Per-output retry configuration that mirrors ``graphon.RetryConfig`` shape.
| ---- | ---- | ----------- | -------- |
| DeclaredOutputType | string | | |
+#### DefaultBlockConfigItemResponse
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| config | object | | Yes |
+| type | string | | Yes |
+
#### DefaultBlockConfigQuery
| Name | Type | Description | Required |
@@ -22373,13 +22380,13 @@ Enum class for form type.
| Name | Type | Description | Required |
| ---- | ---- | ----------- | -------- |
-| actions | [ object ] | | No |
+| actions | [ [UserActionConfig](#useractionconfig) ] | | No |
| display_in_ui | boolean | | No |
| expiration_time | integer | | No |
| form_content | string | | Yes |
| form_id | string | | Yes |
| form_token | string | | No |
-| inputs | [ object ] | | No |
+| inputs | [ [FormInputConfig](#forminputconfig) ] | | No |
| node_id | string | | Yes |
| node_title | string | | Yes |
| resolved_default_values | object | | No |
@@ -25624,6 +25631,14 @@ Blocking run result: a preview run returns the workflow result, a processing run
| ---- | ---- | ----------- | -------- |
| RagPipelinePublishedRunResponse | [PipelineGenerateResponse](#pipelinegenerateresponse)<br>[WorkflowAppBlockingResponse](#workflowappblockingresponse) | Blocking run result: a preview run returns the workflow result, a processing run the queued batch. | |
+#### RagPipelinePublishedWorkflowResponse
+
+A null response means the pipeline has no published workflow.
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| RagPipelinePublishedWorkflowResponse | [WorkflowResponse](#workflowresponse) | A null response means the pipeline has no published workflow. | |
+
#### RagPipelineRecommendedPluginQuery
| Name | Type | Description | Required |
diff --git a/api/tests/unit_tests/controllers/console/app/test_workflow_human_input_debug_api.py b/api/tests/unit_tests/controllers/console/app/test_workflow_human_input_debug_api.py
index be86ef6dc52..ea1dc087a1d 100644
--- a/api/tests/unit_tests/controllers/console/app/test_workflow_human_input_debug_api.py
+++ b/api/tests/unit_tests/controllers/console/app/test_workflow_human_input_debug_api.py
@@ -95,9 +95,34 @@ def test_human_input_preview_delegates_to_service(
preview_payload = {
"form_id": "node-42",
+ "node_id": "node-42",
+ "node_title": "Human input",
"form_content": "<div>example</div>",
- "inputs": [{"name": "topic"}],
- "actions": [{"id": "continue"}],
+ "inputs": [
+ {"type": "paragraph", "output_variable_name": "topic", "default": None},
+ {
+ "type": "select",
+ "output_variable_name": "choice",
+ "option_source": {"type": "constant", "selector": list[str](), "value": ["one", "two"]},
+ },
+ {
+ "type": "file",
+ "output_variable_name": "attachment",
+ "allowed_file_types": ["document"],
+ "allowed_file_extensions": list[str](),
+ "allowed_file_upload_methods": ["local_file", "remote_url"],
+ },
+ {
+ "type": "file-list",
+ "output_variable_name": "attachments",
+ "allowed_file_types": ["image"],
+ "allowed_file_extensions": list[str](),
+ "allowed_file_upload_methods": ["local_file"],
+ "number_limits": 0,
+ },
+ ],
+ "actions": [{"id": "continue", "title": "Continue", "button_style": "default"}],
+ "resolved_default_values": {"topic": ""},
}
service_instance = MagicMock()
service_instance.get_human_input_form_preview.return_value = preview_payload
@@ -106,7 +131,12 @@ def test_human_input_preview_delegates_to_service(
with app.test_request_context(case.path, method="POST", json={"inputs": {"topic": "tech"}}):
response = case.resource_cls().post(app_id=app_model.id, node_id="node-42")
- assert response == preview_payload
+ assert response == {
+ **preview_payload,
+ "display_in_ui": None,
+ "form_token": None,
+ "expiration_time": None,
+ }
service_instance.get_human_input_form_preview.assert_called_once_with(
app_model=app_model,
account=account,
diff --git a/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline_workflow_apis.py b/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline_workflow_apis.py
index 141614f07b1..8b8c9302ef0 100644
--- a/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline_workflow_apis.py
+++ b/api/tests/unit_tests/controllers/console/datasets/rag_pipeline/test_rag_pipeline_workflow_apis.py
@@ -20,6 +20,7 @@ from werkzeug.exceptions import BadRequest, Forbidden, HTTPException, NotFound
import models.workflow as workflow_models
import services
+import services.rag_pipeline.rag_pipeline as rag_pipeline_service
from controllers.console.app.error import DraftWorkflowNotExist, DraftWorkflowNotSync
from controllers.console.datasets.rag_pipeline import rag_pipeline_workflow as workflow_controller
from controllers.console.datasets.rag_pipeline.rag_pipeline_workflow import (
@@ -83,6 +84,7 @@ def sqlite_database(
database = SQLiteDatabase(engine=sqlite_engine, session=database_session)
monkeypatch.setattr(workflow_controller, "db", database)
monkeypatch.setattr(workflow_models, "db", database)
+ monkeypatch.setattr(rag_pipeline_service, "db", database)
with database_session() as session:
default_author = Account(name="Default Author", email="[email protected]")
@@ -495,6 +497,41 @@ class TestDraftNodeRun:
class TestPublishedPipelineApis:
+ def test_get_published_workflow_preserves_response_fields(
+ self, app: Flask, workflow_author: Account, sqlite_database: scoped_session[Session]
+ ) -> None:
+ workflow = make_workflow(id=str(uuid4()), created_by=workflow_author.id)
+ sqlite_database.add(workflow)
+ sqlite_database.commit()
+ pipeline = make_pipeline(
+ id=workflow.app_id,
+ tenant_id=workflow.tenant_id,
+ workflow_id=workflow.id,
+ is_published=True,
+ )
+
+ with app.test_request_context("/"):
+ result = unwrap(PublishedRagPipelineApi.get)(PublishedRagPipelineApi(), pipeline)
+
+ assert result["id"] == workflow.id
+ assert result["graph"] == {"nodes": [], "edges": []}
+ assert result["hash"] == workflow.unique_hash
+ assert result["created_by"]["id"] == workflow_author.id
+
+ @pytest.mark.parametrize("is_published", [False, True])
+ def test_get_without_published_workflow_returns_null(self, app: Flask, is_published: bool) -> None:
+ pipeline = make_pipeline(
+ id=DEFAULT_WORKFLOW_APP_ID,
+ tenant_id=DEFAULT_WORKFLOW_TENANT_ID,
+ workflow_id=str(uuid4()),
+ is_published=is_published,
+ )
+
+ with app.test_request_context("/"):
+ result = unwrap(PublishedRagPipelineApi.get)(PublishedRagPipelineApi(), pipeline)
+
+ assert result is None
+
def test_publish_success(self, app: Flask) -> None:
api = PublishedRagPipelineApi()
method = unwrap(api.post)
diff --git a/api/tests/unit_tests/controllers/test_swagger.py b/api/tests/unit_tests/controllers/test_swagger.py
index 6cc6496dbcd..3c49bd90f89 100644
--- a/api/tests/unit_tests/controllers/test_swagger.py
+++ b/api/tests/unit_tests/controllers/test_swagger.py
@@ -262,6 +262,36 @@ def test_agent_tts_routes_document_voice_queries_and_binary_audio(openapi_json:
assert _response_content_types(preview, status) == {"application/json"}
+def test_workflow_config_contracts_describe_node_defaults_and_unpublished_pipelines(
+ openapi_json: OpenAPIJSONLoader,
+) -> None:
+ from controllers.console import bp as console_bp
+
+ payload = json.loads(openapi_json(console_bp, "/console/api/openapi.json", False))
+ schemas = payload["components"]["schemas"]
+ for resource in ("apps/{app_id}", "rag/pipelines/{pipeline_id}", "snippets/{snippet_id}"):
+ operation = payload["paths"][f"/{resource}/workflows/default-workflow-block-configs"]["get"]
+ assert operation["responses"]["200"]["content"]["application/json"]["schema"] == {
+ "$ref": "#/components/schemas/DefaultBlockConfigsResponse"
+ }
+ assert schemas["DefaultBlockConfigsResponse"]["items"] == {
+ "$ref": "#/components/schemas/DefaultBlockConfigItemResponse"
+ }
+ item = schemas["DefaultBlockConfigItemResponse"]
+ assert set(item["required"]) == {"type", "config"}
+ assert item["properties"]["type"]["type"] == "string"
+ assert item["properties"]["config"]["type"] == "object"
+
+ published = payload["paths"]["/rag/pipelines/{pipeline_id}/workflows/publish"]["get"]
+ assert published["responses"]["200"]["content"]["application/json"]["schema"] == {
+ "$ref": "#/components/schemas/RagPipelinePublishedWorkflowResponse"
+ }
+ assert schemas["RagPipelinePublishedWorkflowResponse"]["anyOf"] == [
+ {"$ref": "#/components/schemas/WorkflowResponse"},
+ {"type": "null"},
+ ]
+
+
def test_console_segment_mutation_contracts_survive_admission(openapi_json: OpenAPIJSONLoader) -> None:
from controllers.console import bp as console_bp
diff --git a/oxlint-suppressions.json b/oxlint-suppressions.json
index 7cc95780240..03ac29fde19 100644
--- a/oxlint-suppressions.json
+++ b/oxlint-suppressions.json
@@ -1597,11 +1597,6 @@
"count": 1
}
},
- "web/app/components/rag-pipeline/hooks/use-pipeline-config.ts": {
- "typescript/no-explicit-any": {
- "count": 3
- }
- },
"web/app/components/rag-pipeline/hooks/use-pipeline-run.ts": {
"no-restricted-imports": {
"count": 2
@@ -2687,11 +2682,6 @@
"count": 5
}
},
- "web/app/components/workflow/panel/debug-and-preview/conversation-variable-modal.tsx": {
- "typescript/no-explicit-any": {
- "count": 2
- }
- },
"web/app/components/workflow/panel/debug-and-preview/hooks.ts": {
"no-restricted-imports": {
"count": 2
@@ -3025,11 +3015,6 @@
"count": 1
}
},
- "web/features/account-profile/client.ts": {
- "dify/require-disable-directive-description": {
- "count": 1
- }
- },
"web/features/agent-v2/agent-detail/configure/components/preview/working-directory-panel.tsx": {
"@tanstack/query/prefer-query-options": {
"count": 2
@@ -3125,9 +3110,6 @@
},
"web/service/access-control/use-app-access-control.ts": {
"@tanstack/query/prefer-query-options": {
- "count": 2
- },
- "no-restricted-imports": {
"count": 1
}
},
@@ -3207,7 +3189,7 @@
},
"web/service/use-plugins-auth.ts": {
"@tanstack/query/prefer-query-options": {
- "count": 3
+ "count": 1
},
"no-restricted-imports": {
"count": 1
@@ -3248,7 +3230,7 @@
},
"web/service/use-workflow.ts": {
"@tanstack/query/prefer-query-options": {
- "count": 6
+ "count": 4
}
},
"web/service/webapp-auth.ts": {
@@ -3281,7 +3263,7 @@
},
"web/types/workflow.ts": {
"typescript/no-explicit-any": {
- "count": 16
+ "count": 15
}
},
"web/utils/completion-params.ts": {
diff --git a/packages/contracts/generated/api/console/apps/types.gen.ts b/packages/contracts/generated/api/console/apps/types.gen.ts
index 53b6d3f4781..32270d56793 100644
--- a/packages/contracts/generated/api/console/apps/types.gen.ts
+++ b/packages/contracts/generated/api/console/apps/types.gen.ts
@@ -172,17 +172,13 @@ export type HumanInputFormPreviewPayload = {
}
export type HumanInputFormPreviewResponse = {
- actions?: Array<{
- [key: string]: unknown
- }>
+ actions?: Array<UserActionConfig>
display_in_ui?: boolean | null
expiration_time?: number | null
form_content: string
form_id: string
form_token?: string | null
- inputs?: Array<{
- [key: string]: unknown
- }>
+ inputs?: Array<FormInputConfig>
node_id: string
node_title: string
resolved_default_values?: {
@@ -1121,9 +1117,7 @@ export type WorkflowPaginationResponse = {
page: number
}
-export type DefaultBlockConfigsResponse = Array<{
- [key: string]: unknown
-}>
+export type DefaultBlockConfigsResponse = Array<DefaultBlockConfigItemResponse>
export type DefaultBlockConfigResponse = {
[key: string]: unknown
@@ -1664,6 +1658,26 @@ export type AdvancedChatWorkflowRunForListResponse = {
version?: string | null
}
+export type UserActionConfig = {
+ button_style?: ButtonStyle
+ id: string
+ title: string
+}
+
+export type FormInputConfig =
+ | ({
+ type: 'paragraph'
+ } & ParagraphInputConfig)
+ | ({
+ type: 'select'
+ } & SelectInputConfig)
+ | ({
+ type: 'file'
+ } & FileInputConfig)
+ | ({
+ type: 'file-list'
+ } & FileListInputConfig)
+
export type ShallowJsonValue =
| string
| number
@@ -2286,6 +2300,13 @@ export type WorkflowDailyTokenCostStatisticItem = {
token_count: number
}
+export type DefaultBlockConfigItemResponse = {
+ config: {
+ [key: string]: unknown
+ }
+ type: string
+}
+
export type WorkflowConversationVariableResponse = {
description: string
id: string
@@ -2799,6 +2820,37 @@ export type WorkflowOnlineUser = {
username: string
}
+export type ButtonStyle = 'accent' | 'default' | 'ghost' | 'primary'
+
+export type ParagraphInputConfig = {
+ default?: StringSource | null
+ output_variable_name: string
+ type?: 'paragraph'
+}
+
+export type SelectInputConfig = {
+ option_source: StringListSource
+ output_variable_name: string
+ type?: 'select'
+}
+
+export type FileInputConfig = {
+ allowed_file_extensions?: Array<string>
+ allowed_file_types?: Array<FileType>
+ allowed_file_upload_methods?: Array<FileTransferMethod>
+ output_variable_name: string
+ type?: 'file'
+}
+
+export type FileListInputConfig = {
+ allowed_file_extensions?: Array<string>
+ allowed_file_types?: Array<FileType>
+ allowed_file_upload_methods?: Array<FileTransferMethod>
+ number_limits?: number
+ output_variable_name: string
+ type?: 'file-list'
+}
+
export type AgentToolCallResponse = {
error?: string | null
status: string
@@ -3543,25 +3595,17 @@ export type AppUserInputFormConfigResponse = {
[key: string]: unknown
}
-export type UserActionConfig = {
- button_style?: ButtonStyle
- id: string
- title: string
+export type StringSource = {
+ selector?: Array<string>
+ type: ValueSourceType
+ value?: string
}
-export type FormInputConfig =
- | ({
- type: 'paragraph'
- } & ParagraphInputConfig)
- | ({
- type: 'select'
- } & SelectInputConfig)
- | ({
- type: 'file'
- } & FileInputConfig)
- | ({
- type: 'file-list'
- } & FileListInputConfig)
+export type StringListSource = {
+ selector?: Array<string>
+ type: ValueSourceType
+ value?: Array<string>
+}
export type AppProviderAgentToolPayload = {
credential_id?: string | null
@@ -4096,36 +4140,7 @@ export type AppVectorSettingResponse = {
[key: string]: unknown
}
-export type ButtonStyle = 'accent' | 'default' | 'ghost' | 'primary'
-
-export type ParagraphInputConfig = {
- default?: StringSource | null
- output_variable_name: string
- type?: 'paragraph'
-}
-
-export type SelectInputConfig = {
- option_source: StringListSource
- output_variable_name: string
- type?: 'select'
-}
-
-export type FileInputConfig = {
- allowed_file_extensions?: Array<string>
- allowed_file_types?: Array<FileType>
- allowed_file_upload_methods?: Array<FileTransferMethod>
- output_variable_name: string
- type?: 'file'
-}
-
-export type FileListInputConfig = {
- allowed_file_extensions?: Array<string>
- allowed_file_types?: Array<FileType>
- allowed_file_upload_methods?: Array<FileTransferMethod>
- number_limits?: number
- output_variable_name: string
- type?: 'file-list'
-}
+export type ValueSourceType = 'constant' | 'variable'
export type AppLegacyDatasetSelectionPayload = {
enabled?: boolean | null
@@ -4208,18 +4223,6 @@ export type AgentSoulDifyToolCredentialRef = {
type?: 'provider' | 'tool'
}
-export type StringSource = {
- selector?: Array<string>
- type: ValueSourceType
- value?: string
-}
-
-export type StringListSource = {
- selector?: Array<string>
- type: ValueSourceType
- value?: Array<string>
-}
-
export type AgentModerationIoConfig = {
enabled?: boolean
preset_response?: string | null
@@ -4258,8 +4261,6 @@ export type AgentKnowledgeWeightedScoreConfig = {
[key: string]: unknown
}
-export type ValueSourceType = 'constant' | 'variable'
-
export type AgentKnowledgeMetadataCondition = {
comparison_operator:
| '<'
diff --git a/packages/contracts/generated/api/console/apps/zod.gen.ts b/packages/contracts/generated/api/console/apps/zod.gen.ts
index b2ae22ef113..046d8958e34 100644
--- a/packages/contracts/generated/api/console/apps/zod.gen.ts
+++ b/packages/contracts/generated/api/console/apps/zod.gen.ts
@@ -146,22 +146,6 @@ export const zHumanInputFormPreviewPayload = z.object({
inputs: z.record(z.string(), z.unknown()).optional(),
})
-/**
- * HumanInputFormPreviewResponse
- */
-export const zHumanInputFormPreviewResponse = z.object({
- actions: z.array(z.record(z.string(), z.unknown())).optional(),
- display_in_ui: z.boolean().nullish(),
- expiration_time: z.int().nullish(),
- form_content: z.string(),
- form_id: z.string(),
- form_token: z.string().nullish(),
- inputs: z.array(z.record(z.string(), z.unknown())).optional(),
- node_id: z.string(),
- node_title: z.string(),
- resolved_default_values: z.record(z.string(), z.unknown()).optional(),
-})
-
/**
* HumanInputFormPreviewSubmitPayload
*/
@@ -1062,11 +1046,6 @@ export const zWorkflowCommentResolve = z.object({
resolved_by: z.string().nullish(),
})
-/**
- * DefaultBlockConfigsResponse
- */
-export const zDefaultBlockConfigsResponse = z.array(z.record(z.string(), z.unknown()))
-
/**
* DefaultBlockConfigResponse
*/
@@ -2322,6 +2301,19 @@ export const zWorkflowDailyTokenCostStatisticResponse = z.object({
data: z.array(zWorkflowDailyTokenCostStatisticItem),
})
+/**
+ * DefaultBlockConfigItemResponse
+ */
+export const zDefaultBlockConfigItemResponse = z.object({
+ config: z.record(z.string(), z.unknown()),
+ type: z.string(),
+})
+
+/**
+ * DefaultBlockConfigsResponse
+ */
+export const zDefaultBlockConfigsResponse = z.array(zDefaultBlockConfigItemResponse)
+
/**
* WorkflowConversationVariableResponse
*/
@@ -2873,6 +2865,27 @@ export const zWorkflowOnlineUsersResponse = z.object({
data: z.array(zWorkflowOnlineUsersByApp),
})
+/**
+ * ButtonStyle
+ *
+ * Button styles for user actions.
+ */
+export const zButtonStyle = z.enum(['accent', 'default', 'ghost', 'primary'])
+
+/**
+ * UserActionConfig
+ *
+ * User action configuration.
+ */
+export const zUserActionConfig = z.object({
+ button_style: zButtonStyle.optional().default('default'),
+ id: z
+ .string()
+ .max(20)
+ .regex(/^[A-Za-z_][A-Za-z0-9_]*$/),
+ title: z.string().max(100),
+})
+
/**
* AgentToolCallResponse
*/
@@ -3240,6 +3253,29 @@ export const zFileTransferMethod = z.enum([
'tool_file',
])
+/**
+ * FileInputConfig
+ */
+export const zFileInputConfig = z.object({
+ allowed_file_extensions: z.array(z.string()).optional(),
+ allowed_file_types: z.array(zFileType).optional(),
+ allowed_file_upload_methods: z.array(zFileTransferMethod).optional(),
+ output_variable_name: z.string(),
+ type: z.literal('file').optional().default('file'),
+})
+
+/**
+ * FileListInputConfig
+ */
+export const zFileListInputConfig = z.object({
+ allowed_file_extensions: z.array(z.string()).optional(),
+ allowed_file_types: z.array(zFileType).optional(),
+ allowed_file_upload_methods: z.array(zFileTransferMethod).optional(),
+ number_limits: z.int().gte(0).optional().default(0),
+ output_variable_name: z.string(),
+ type: z.literal('file-list').optional().default('file-list'),
+})
+
/**
* AppFileTypeUploadPayload
*/
@@ -5010,47 +5046,140 @@ export const zAppDetail = z.object({
})
/**
- * ButtonStyle
+ * ValueSourceType
*
- * Button styles for user actions.
+ * ValueSourceType records whether the value comes from a static setting
+ * in form definition, or a variable while the workflow is running.
*/
-export const zButtonStyle = z.enum(['accent', 'default', 'ghost', 'primary'])
+export const zValueSourceType = z.enum(['constant', 'variable'])
/**
- * UserActionConfig
+ * StringSource
*
- * User action configuration.
+ * Default configuration for form inputs.
*/
-export const zUserActionConfig = z.object({
- button_style: zButtonStyle.optional().default('default'),
- id: z
- .string()
- .max(20)
- .regex(/^[A-Za-z_][A-Za-z0-9_]*$/),
- title: z.string().max(100),
+export const zStringSource = z.object({
+ selector: z.array(z.string()).optional(),
+ type: zValueSourceType,
+ value: z.string().optional().default(''),
})
/**
- * FileInputConfig
+ * ParagraphInputConfig
+ *
+ * Form input definition.
*/
-export const zFileInputConfig = z.object({
- allowed_file_extensions: z.array(z.string()).optional(),
- allowed_file_types: z.array(zFileType).optional(),
- allowed_file_upload_methods: z.array(zFileTransferMethod).optional(),
+export const zParagraphInputConfig = z.object({
+ default: zStringSource.nullish(),
output_variable_name: z.string(),
- type: z.literal('file').optional().default('file'),
+ type: z.literal('paragraph').optional().default('paragraph'),
})
/**
- * FileListInputConfig
+ * StringListSource
*/
-export const zFileListInputConfig = z.object({
- allowed_file_extensions: z.array(z.string()).optional(),
- allowed_file_types: z.array(zFileType).optional(),
- allowed_file_upload_methods: z.array(zFileTransferMethod).optional(),
- number_limits: z.int().gte(0).optional().default(0),
+export const zStringListSource = z.object({
+ selector: z.array(z.string()).optional(),
+ type: zValueSourceType,
+ value: z.array(z.string()).optional(),
+})
+
+/**
+ * SelectInputConfig
+ */
+export const zSelectInputConfig = z.object({
+ option_source: zStringListSource,
output_variable_name: z.string(),
- type: z.literal('file-list').optional().default('file-list'),
+ type: z.literal('select').optional().default('select'),
+})
+
+export const zFormInputConfig = z.discriminatedUnion('type', [
+ zParagraphInputConfig,
+ zSelectInputConfig,
+ zFileInputConfig,
+ zFileListInputConfig,
+])
+
+/**
+ * HumanInputFormPreviewResponse
+ */
+export const zHumanInputFormPreviewResponse = z.object({
+ actions: z.array(zUserActionConfig).optional(),
+ display_in_ui: z.boolean().nullish(),
+ expiration_time: z.int().nullish(),
+ form_content: z.string(),
+ form_id: z.string(),
+ form_token: z.string().nullish(),
+ inputs: z.array(zFormInputConfig).optional(),
+ node_id: z.string(),
+ node_title: z.string(),
+ resolved_default_values: z.record(z.string(), z.unknown()).optional(),
+})
+
+/**
+ * HumanInputFormDefinition
+ */
+export const zHumanInputFormDefinition = z.object({
+ actions: z.array(zUserActionConfig).optional(),
+ display_in_ui: z.boolean().optional().default(false),
+ expiration_time: z.int(),
+ form_content: z.string(),
+ form_id: z.string(),
+ form_token: z.string().nullish(),
+ inputs: z.array(zFormInputConfig).optional(),
+ node_id: z.string(),
+ node_title: z.string(),
+ resolved_default_values: z.record(z.string(), z.unknown()).optional(),
+})
+
+/**
+ * HumanInputContent
+ */
+export const zHumanInputContent = z.object({
+ form_definition: zHumanInputFormDefinition.nullish(),
+ form_submission_data: zHumanInputFormSubmissionData.nullish(),
+ submitted: z.boolean(),
+ type: zExecutionContentType.optional().default('human_input'),
+ workflow_run_id: z.string(),
+})
+
+/**
+ * MessageDetailResponse
+ */
+export const zMessageDetailResponse = z.object({
+ agent_thoughts: z.array(zAgentThought),
+ annotation: zConversationAnnotation.nullish(),
+ annotation_hit_history: zConversationAnnotationHitHistory.nullish(),
+ answer: z.string(),
+ answer_tokens: z.int(),
+ conversation_id: z.string(),
+ created_at: z.int().nullish(),
+ error: z.string().nullish(),
+ extra_contents: z.array(zHumanInputContent).optional(),
+ feedbacks: z.array(zFeedback),
+ from_account_id: z.string().nullish(),
+ from_end_user_id: z.string().nullish(),
+ from_source: z.string(),
+ id: z.string(),
+ inputs: z.record(z.string(), zAnyJsonValue),
+ message: zAnyJsonValue,
+ message_files: z.array(zMessageFile),
+ message_tokens: z.int(),
+ metadata: zAnyJsonValue,
+ parent_message_id: z.string().nullish(),
+ provider_response_latency: z.number(),
+ query: z.string(),
+ status: z.string(),
+ workflow_run_id: z.string().nullish(),
+})
+
+/**
+ * MessageInfiniteScrollPaginationResponse
+ */
+export const zMessageInfiniteScrollPaginationResponse = z.object({
+ data: z.array(zMessageDetailResponse),
+ has_more: z.boolean(),
+ limit: z.int(),
})
/**
@@ -5525,127 +5654,6 @@ export const zAgentKnowledgeRetrievalConfig = z.object({
weights: zAgentKnowledgeWeightedScoreConfig.nullish(),
})
-/**
- * ValueSourceType
- *
- * ValueSourceType records whether the value comes from a static setting
- * in form definition, or a variable while the workflow is running.
- */
-export const zValueSourceType = z.enum(['constant', 'variable'])
-
-/**
- * StringSource
- *
- * Default configuration for form inputs.
- */
-export const zStringSource = z.object({
- selector: z.array(z.string()).optional(),
- type: zValueSourceType,
- value: z.string().optional().default(''),
-})
-
-/**
- * ParagraphInputConfig
- *
- * Form input definition.
- */
-export const zParagraphInputConfig = z.object({
- default: zStringSource.nullish(),
- output_variable_name: z.string(),
- type: z.literal('paragraph').optional().default('paragraph'),
-})
-
-/**
- * StringListSource
- */
-export const zStringListSource = z.object({
- selector: z.array(z.string()).optional(),
- type: zValueSourceType,
- value: z.array(z.string()).optional(),
-})
-
-/**
- * SelectInputConfig
- */
-export const zSelectInputConfig = z.object({
- option_source: zStringListSource,
- output_variable_name: z.string(),
- type: z.literal('select').optional().default('select'),
-})
-
-export const zFormInputConfig = z.discriminatedUnion('type', [
- zParagraphInputConfig,
- zSelectInputConfig,
- zFileInputConfig,
- zFileListInputConfig,
-])
-
-/**
- * HumanInputFormDefinition
- */
-export const zHumanInputFormDefinition = z.object({
- actions: z.array(zUserActionConfig).optional(),
- display_in_ui: z.boolean().optional().default(false),
- expiration_time: z.int(),
- form_content: z.string(),
- form_id: z.string(),
- form_token: z.string().nullish(),
- inputs: z.array(zFormInputConfig).optional(),
- node_id: z.string(),
- node_title: z.string(),
- resolved_default_values: z.record(z.string(), z.unknown()).optional(),
-})
-
-/**
- * HumanInputContent
- */
-export const zHumanInputContent = z.object({
- form_definition: zHumanInputFormDefinition.nullish(),
- form_submission_data: zHumanInputFormSubmissionData.nullish(),
- submitted: z.boolean(),
- type: zExecutionContentType.optional().default('human_input'),
- workflow_run_id: z.string(),
-})
-
-/**
- * MessageDetailResponse
- */
-export const zMessageDetailResponse = z.object({
- agent_thoughts: z.array(zAgentThought),
- annotation: zConversationAnnotation.nullish(),
- annotation_hit_history: zConversationAnnotationHitHistory.nullish(),
- answer: z.string(),
- answer_tokens: z.int(),
- conversation_id: z.string(),
- created_at: z.int().nullish(),
- error: z.string().nullish(),
- extra_contents: z.array(zHumanInputContent).optional(),
- feedbacks: z.array(zFeedback),
- from_account_id: z.string().nullish(),
- from_end_user_id: z.string().nullish(),
- from_source: z.string(),
- id: z.string(),
- inputs: z.record(z.string(), zAnyJsonValue),
- message: zAnyJsonValue,
- message_files: z.array(zMessageFile),
- message_tokens: z.int(),
- metadata: zAnyJsonValue,
- parent_message_id: z.string().nullish(),
- provider_response_latency: z.number(),
- query: z.string(),
- status: z.string(),
- workflow_run_id: z.string().nullish(),
-})
-
-/**
- * MessageInfiniteScrollPaginationResponse
- */
-export const zMessageInfiniteScrollPaginationResponse = z.object({
- data: z.array(zMessageDetailResponse),
- has_more: z.boolean(),
- limit: z.int(),
-})
-
/**
* AgentKnowledgeMetadataCondition
*
diff --git a/packages/contracts/generated/api/console/rag/types.gen.ts b/packages/contracts/generated/api/console/rag/types.gen.ts
index d8639a3ef1e..49341522373 100644
--- a/packages/contracts/generated/api/console/rag/types.gen.ts
+++ b/packages/contracts/generated/api/console/rag/types.gen.ts
@@ -188,9 +188,7 @@ export type WorkflowPaginationResponse = {
page: number
}
-export type DefaultBlockConfigsResponse = Array<{
- [key: string]: unknown
-}>
+export type DefaultBlockConfigsResponse = Array<DefaultBlockConfigItemResponse>
export type DefaultBlockConfigResponse = {
[key: string]: unknown
@@ -363,6 +361,8 @@ export type WorkflowDraftVariablePatchPayload = {
value?: unknown | null
}
+export type RagPipelinePublishedWorkflowResponse = WorkflowResponse | null
+
export type RagPipelineWorkflowPublishResponse = {
created_at: number
result: string
@@ -547,6 +547,13 @@ export type SimpleEndUser = {
type: string
}
+export type DefaultBlockConfigItemResponse = {
+ config: {
+ [key: string]: unknown
+ }
+ type: string
+}
+
export type WorkflowConversationVariableResponse = {
description: string
id: string
@@ -2051,7 +2058,7 @@ export type GetRagPipelinesByPipelineIdWorkflowsPublishError =
GetRagPipelinesByPipelineIdWorkflowsPublishErrors[keyof GetRagPipelinesByPipelineIdWorkflowsPublishErrors]
export type GetRagPipelinesByPipelineIdWorkflowsPublishResponses = {
- 200: WorkflowResponse
+ 200: RagPipelinePublishedWorkflowResponse
}
export type GetRagPipelinesByPipelineIdWorkflowsPublishResponse =
diff --git a/packages/contracts/generated/api/console/rag/zod.gen.ts b/packages/contracts/generated/api/console/rag/zod.gen.ts
index b0ea3725a06..e4ce174326b 100644
--- a/packages/contracts/generated/api/console/rag/zod.gen.ts
+++ b/packages/contracts/generated/api/console/rag/zod.gen.ts
@@ -110,11 +110,6 @@ export const zSimpleResultResponse = z.object({
result: z.string(),
})
-/**
- * DefaultBlockConfigsResponse
- */
-export const zDefaultBlockConfigsResponse = z.array(z.record(z.string(), z.unknown()))
-
/**
* DefaultBlockConfigResponse
*/
@@ -475,6 +470,19 @@ export const zWorkflowRunNodeExecutionListResponse = z.object({
data: z.array(zWorkflowRunNodeExecutionResponse),
})
+/**
+ * DefaultBlockConfigItemResponse
+ */
+export const zDefaultBlockConfigItemResponse = z.object({
+ config: z.record(z.string(), z.unknown()),
+ type: z.string(),
+})
+
+/**
+ * DefaultBlockConfigsResponse
+ */
+export const zDefaultBlockConfigsResponse = z.array(zDefaultBlockConfigItemResponse)
+
/**
* WorkflowConversationVariableResponse
*/
@@ -556,6 +564,13 @@ export const zRagPipelineStepParametersResponse = z.object({
variables: z.array(zPipelineVariableResponse),
})
+/**
+ * RagPipelinePublishedWorkflowResponse
+ *
+ * A null response means the pipeline has no published workflow.
+ */
+export const zRagPipelinePublishedWorkflowResponse = zWorkflowResponse.nullable()
+
/**
* EnvironmentVariableItemResponse
*/
@@ -1780,7 +1795,8 @@ export const zGetRagPipelinesByPipelineIdWorkflowsPublishPath = z.object({
/**
* Published workflow retrieved successfully, or null if not exist
*/
-export const zGetRagPipelinesByPipelineIdWorkflowsPublishResponse = zWorkflowResponse
+export const zGetRagPipelinesByPipelineIdWorkflowsPublishResponse =
+ zRagPipelinePublishedWorkflowResponse
export const zPostRagPipelinesByPipelineIdWorkflowsPublishPath = z.object({
pipeline_id: z.uuid(),
diff --git a/packages/contracts/generated/api/console/snippets/types.gen.ts b/packages/contracts/generated/api/console/snippets/types.gen.ts
index fa03cb5a41a..162b61e1223 100644
--- a/packages/contracts/generated/api/console/snippets/types.gen.ts
+++ b/packages/contracts/generated/api/console/snippets/types.gen.ts
@@ -54,9 +54,7 @@ export type SnippetWorkflowPaginationResponse = {
page: number
}
-export type DefaultBlockConfigsResponse = Array<{
- [key: string]: unknown
-}>
+export type DefaultBlockConfigsResponse = Array<DefaultBlockConfigItemResponse>
export type SnippetWorkflowResponse = {
conversation_variables: Array<WorkflowConversationVariableResponse>
@@ -357,6 +355,13 @@ export type SimpleEndUser = {
type: string
}
+export type DefaultBlockConfigItemResponse = {
+ config: {
+ [key: string]: unknown
+ }
+ type: string
+}
+
export type WorkflowConversationVariableResponse = {
description: string
id: string
diff --git a/packages/contracts/generated/api/console/snippets/zod.gen.ts b/packages/contracts/generated/api/console/snippets/zod.gen.ts
index 7981ab88b37..91fc59f61c6 100644
--- a/packages/contracts/generated/api/console/snippets/zod.gen.ts
+++ b/packages/contracts/generated/api/console/snippets/zod.gen.ts
@@ -25,11 +25,6 @@ export const zSimpleResultResponse = z.object({
result: z.string(),
})
-/**
- * DefaultBlockConfigsResponse
- */
-export const zDefaultBlockConfigsResponse = z.array(z.record(z.string(), z.unknown()))
-
/**
* DraftWorkflowNotExistError
*
@@ -353,6 +348,19 @@ export const zWorkflowRunNodeExecutionListResponse = z.object({
data: z.array(zWorkflowRunNodeExecutionResponse),
})
+/**
+ * DefaultBlockConfigItemResponse
+ */
+export const zDefaultBlockConfigItemResponse = z.object({
+ config: z.record(z.string(), z.unknown()),
+ type: z.string(),
+})
+
+/**
+ * DefaultBlockConfigsResponse
+ */
+export const zDefaultBlockConfigsResponse = z.array(zDefaultBlockConfigItemResponse)
+
/**
* WorkflowConversationVariableResponse
*/
diff --git a/web/__tests__/base/file-uploader-flow.test.tsx b/web/__tests__/base/file-uploader-flow.test.tsx
index 5905af1c3bc..305c9726920 100644
--- a/web/__tests__/base/file-uploader-flow.test.tsx
+++ b/web/__tests__/base/file-uploader-flow.test.tsx
@@ -5,18 +5,17 @@ import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import FileUploaderInAttachmentWrapper from '@/app/components/base/file-uploader/file-uploader-in-attachment'
import FileUploaderInChatInput from '@/app/components/base/file-uploader/file-uploader-in-chat-input'
import { FileContextProvider } from '@/app/components/base/file-uploader/store'
+import { createConsoleQueryWrapper } from '@/test/console/query-data'
import { TransferMethod } from '@/types/app'
-const mockUploadRemoteFileInfo = vi.fn()
+const request = vi.hoisted(() => vi.fn<typeof import('@/service/base').request>())
vi.mock('@/next/navigation', () => ({
useParams: () => ({}),
usePathname: () => '/',
}))
-vi.mock('@/service/common', () => ({
- uploadRemoteFileInfo: (...args: unknown[]) => mockUploadRemoteFileInfo(...args),
-}))
+vi.mock('@/service/base', () => ({ request }))
const createFileConfig = (overrides: Partial<FileUpload> = {}): FileUpload =>
({
@@ -38,19 +37,22 @@ const renderChatInput = (fileConfig: FileUpload, readonly = false) => {
<FileContextProvider>
<FileUploaderInChatInput fileConfig={fileConfig} readonly={readonly} />
</FileContextProvider>,
+ { wrapper: createConsoleQueryWrapper().wrapper },
)
}
describe('Base File Uploader Flow', () => {
beforeEach(() => {
vi.clearAllMocks()
- mockUploadRemoteFileInfo.mockResolvedValue({
- id: 'remote-file-1',
- mime_type: 'application/pdf',
- size: 2048,
- name: 'guide.pdf',
- url: 'https://cdn.example.com/guide.pdf',
- })
+ request.mockImplementation(async () =>
+ Response.json({
+ id: 'remote-file-1',
+ mime_type: 'application/pdf',
+ size: 2048,
+ name: 'guide.pdf',
+ url: 'https://cdn.example.com/guide.pdf',
+ }),
+ )
})
it('uploads a remote file from the attachment wrapper and pushes the updated file list to consumers', async () => {
@@ -63,6 +65,7 @@ describe('Base File Uploader Flow', () => {
onChange={onChange}
fileConfig={createFileConfig()}
/>,
+ { wrapper: createConsoleQueryWrapper().wrapper },
)
await user.click(screen.getByRole('button', { name: /fileUploader\.pasteFileLink/i }))
@@ -73,9 +76,12 @@ describe('Base File Uploader Flow', () => {
await user.click(screen.getByRole('button', { name: /operation\.ok/i }))
await waitFor(() => {
- expect(mockUploadRemoteFileInfo).toHaveBeenCalledWith('https://example.com/guide.pdf', false)
+ expect(request).toHaveBeenCalled()
})
+ expect(await request.mock.calls[0]?.[2]?.request?.json()).toEqual({
+ url: 'https://example.com/guide.pdf',
+ })
await waitFor(() => {
expect(onChange).toHaveBeenLastCalledWith([
expect.objectContaining({
diff --git a/web/app/account/(commonLayout)/account-page/__tests__/index.spec.tsx b/web/app/account/(commonLayout)/account-page/__tests__/index.spec.tsx
index 8bb4d78768f..dbe7a0c67cb 100644
--- a/web/app/account/(commonLayout)/account-page/__tests__/index.spec.tsx
+++ b/web/app/account/(commonLayout)/account-page/__tests__/index.spec.tsx
@@ -18,7 +18,10 @@ vi.mock('@/service/base', () => ({
get: mocks.get,
patch: vi.fn(),
post: vi.fn(),
- request: mocks.request,
+ request: (url: string, init: RequestInit, options: { request: Request }) =>
+ url.endsWith('/account/profile') && options.request.method === 'GET'
+ ? mocks.get(url, init, options)
+ : mocks.request(url, init, options),
sseGeneratorPost: vi.fn(),
}))
@@ -181,9 +184,7 @@ describe('AccountPage', () => {
expect(dialog).toBeInTheDocument()
expect(mocks.request).toHaveBeenCalledOnce()
- await act(async () =>
- saving.resolve(new Response(JSON.stringify(createAccountResponse('Alice Cooper')))),
- )
+ await act(async () => saving.resolve(Response.json(createAccountResponse('Alice Cooper'))))
await waitFor(() => expect(mocks.get).toHaveBeenCalled())
expect(cancel).toBeDisabled()
expect(within(dialog).getByRole('button', { name: 'common.operation.save' })).toHaveAttribute(
@@ -193,9 +194,7 @@ describe('AccountPage', () => {
await user.keyboard('{Escape}')
expect(dialog).toBeInTheDocument()
- await act(async () =>
- refreshing.resolve(new Response(JSON.stringify(createAccountResponse('Alice Cooper')))),
- )
+ await act(async () => refreshing.resolve(Response.json(createAccountResponse('Alice Cooper'))))
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
expect(screen.getByRole('button', { name: 'common.operation.edit' })).toBeEnabled()
expect(screen.getAllByText('Alice Cooper')[0]).toBeInTheDocument()
@@ -259,7 +258,7 @@ describe('AccountPage', () => {
const user = userEvent.setup()
mocks.request.mockRejectedValueOnce(new Error('Password update failed'))
mocks.get.mockResolvedValue(
- new Response(JSON.stringify({ ...createAccountResponse(), is_password_set: true })),
+ Response.json({ ...createAccountResponse(), is_password_set: true }),
)
renderPage({ isPasswordSet: true })
await user.click(screen.getByRole('button', { name: 'accountSettings.account.resetPassword' }))
@@ -326,9 +325,7 @@ describe('AccountPage', () => {
expect(mocks.request).toHaveBeenCalledOnce()
await act(async () =>
- saving.resolve(
- new Response(JSON.stringify({ ...createAccountResponse(), is_password_set: true })),
- ),
+ saving.resolve(Response.json({ ...createAccountResponse(), is_password_set: true })),
)
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
expect(mocks.get).toHaveBeenCalled()
@@ -337,9 +334,7 @@ describe('AccountPage', () => {
).toBeInTheDocument()
await act(async () =>
- refreshing.resolve(
- new Response(JSON.stringify({ ...createAccountResponse(), is_password_set: true })),
- ),
+ refreshing.resolve(Response.json({ ...createAccountResponse(), is_password_set: true })),
)
expect(
await screen.findByRole('button', { name: 'accountSettings.account.resetPassword' }),
diff --git a/web/app/account/oauth/authorize/__tests__/page.spec.tsx b/web/app/account/oauth/authorize/__tests__/page.spec.tsx
index 97d06abf632..afdebb25dfe 100644
--- a/web/app/account/oauth/authorize/__tests__/page.spec.tsx
+++ b/web/app/account/oauth/authorize/__tests__/page.spec.tsx
@@ -22,19 +22,18 @@ vi.mock('@/next/navigation', () => ({
}))
vi.mock('@/service/base', () => ({
- get: vi.fn(async () => {
- if (!mocks.profileLoggedIn) throw createHttpError(new Response(null, { status: 401 }))
- return new Response(
- JSON.stringify({
+ request: async (url: string, ...args: unknown[]) => {
+ if (url.endsWith('/account/profile')) {
+ if (!mocks.profileLoggedIn) throw createHttpError(new Response(null, { status: 401 }))
+ return jsonResponse({
avatar_url: null,
name: 'Test User',
- }),
- { status: 200 },
- )
- }),
+ })
+ }
+ return mocks.request(url, ...args)
+ },
post: vi.fn(),
- request: (...args: unknown[]) => mocks.request(...args),
sseGeneratorPost: vi.fn(),
}))
diff --git a/web/app/components/app/app-publisher/__tests__/index.spec.tsx b/web/app/components/app/app-publisher/__tests__/index.spec.tsx
index e78fee5a90a..2987959296b 100644
--- a/web/app/components/app/app-publisher/__tests__/index.spec.tsx
+++ b/web/app/components/app/app-publisher/__tests__/index.spec.tsx
@@ -45,7 +45,10 @@ const api = vi.hoisted(() => ({
typeof import('@/service/console').consoleClient.workspaces.current.toolProvider.workflow.create.post
>(),
access: vi.fn<typeof import('@/service/share').getUserCanAccess>(),
- patch: vi.fn<typeof import('@/service/base').patch>(),
+ patch:
+ vi.fn<
+ typeof import('@/service/console').consoleClient.apps.byAppId.workflows.byWorkflowId.patch
+ >(),
}))
vi.mock('@/service/console', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/service/console')>()
@@ -54,6 +57,7 @@ vi.mock('@/service/console', async (importOriginal) => {
return {
...actual,
consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'apps.byAppId.workflows.byWorkflowId.patch': api.patch,
'apps.byAppId.workflows.publish.get': api.published,
'enterprise.appDeploy.deploymentService.listAppEnvironments': api.environments,
'enterprise.appDeploy.deploymentService.listEnvironmentDeployments': api.deployments,
@@ -80,10 +84,6 @@ vi.mock('@/service/share', async (importOriginal) => ({
...(await importOriginal<typeof import('@/service/share')>()),
getUserCanAccess: api.access,
}))
-vi.mock('@/service/base', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@/service/base')>()),
- patch: api.patch,
-}))
beforeEach(() => {
api.published
@@ -241,7 +241,8 @@ it('edits a published workflow version and shows the saved title and notes when
api.published.mockResolvedValue(saved)
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
await waitFor(() =>
- expect(api.patch).toHaveBeenCalledWith('/apps/app-1/workflows/workflow-1', {
+ expect(api.patch).toHaveBeenCalledWith({
+ params: { app_id: 'app-1', workflow_id: 'workflow-1' },
body: { marked_name: 'Release 6', marked_comment: 'Updated notes' },
}),
)
diff --git a/web/app/components/app/app-publisher/publisher-content/index.tsx b/web/app/components/app/app-publisher/publisher-content/index.tsx
index 2730959d904..0c53cb832d7 100644
--- a/web/app/components/app/app-publisher/publisher-content/index.tsx
+++ b/web/app/components/app/app-publisher/publisher-content/index.tsx
@@ -115,7 +115,6 @@ export function PublisherContent({
const marketplace = useMarketplacePublish(appDetail.id)
const versionInfo = useVersionInfo({
appId: appDetail.id,
- appMode: appDetail.mode,
publishedWorkflow: publish.publishedWorkflow,
onClosePublisher: closePublisher,
})
diff --git a/web/app/components/app/app-publisher/publisher-content/use-version-info.ts b/web/app/components/app/app-publisher/publisher-content/use-version-info.ts
index 45cdfdf36c4..098faaeae3d 100644
--- a/web/app/components/app/app-publisher/publisher-content/use-version-info.ts
+++ b/web/app/components/app/app-publisher/publisher-content/use-version-info.ts
@@ -1,4 +1,4 @@
-import type { AppMode, WorkflowResponse } from '@dify/contracts/api/console/apps/types.gen'
+import type { WorkflowResponse } from '@dify/contracts/api/console/apps/types.gen'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { toast } from '@/app/notifications'
@@ -12,18 +12,16 @@ type VersionInfoUpdate = {
export function useVersionInfo({
appId,
- appMode,
publishedWorkflow,
onClosePublisher,
}: {
appId?: string
- appMode?: AppMode
publishedWorkflow?: WorkflowResponse | null
onClosePublisher: () => void
}) {
const { t } = useTranslation(['workflowHistory'])
const [isOpen, setIsOpen] = useState(false)
- const { mutate: updateWorkflow } = useUpdateWorkflow()
+ const { mutateAsync: updateWorkflow } = useUpdateWorkflow()
const invalidateAppWorkflow = useInvalidateAppWorkflow()
function openEditor() {
@@ -33,32 +31,23 @@ export function useVersionInfo({
setIsOpen(true)
}
- function updateVersionInfo(params: VersionInfoUpdate) {
+ async function updateVersionInfo(params: VersionInfoUpdate) {
if (!appId || !params.id) return
- updateWorkflow(
- {
- appId,
- appMode,
- url: `/apps/${appId}/workflows/${params.id}`,
+ try {
+ await updateWorkflow({
+ resource: { kind: 'app', appId },
+ versionId: params.id,
title: params.title,
releaseNotes: params.releaseNotes,
- },
- {
- onSuccess: () => {
- toast.success(
- t(($) => $['versionHistory.action.updateSuccess'], { ns: 'workflowHistory' }),
- )
- invalidateAppWorkflow(appId)
- },
- onError: () => {
- toast.error(t(($) => $['versionHistory.action.updateFailure'], { ns: 'workflowHistory' }))
- },
- onSettled: () => {
- setIsOpen(false)
- },
- },
- )
+ })
+ toast.success(t(($) => $['versionHistory.action.updateSuccess'], { ns: 'workflowHistory' }))
+ invalidateAppWorkflow(appId)
+ } catch {
+ toast.error(t(($) => $['versionHistory.action.updateFailure'], { ns: 'workflowHistory' }))
+ } finally {
+ setIsOpen(false)
+ }
}
return {
diff --git a/web/app/components/app/text-generate/item/__tests__/index.spec.tsx b/web/app/components/app/text-generate/item/__tests__/index.spec.tsx
index 0f99e076c92..a4c8378312a 100644
--- a/web/app/components/app/text-generate/item/__tests__/index.spec.tsx
+++ b/web/app/components/app/text-generate/item/__tests__/index.spec.tsx
@@ -129,7 +129,7 @@ describe('GenerationItem', () => {
expect(mockUpdateFeedback).toHaveBeenCalledWith(
{
body: { rating: 'like' },
- url: '/messages/msg-2/feedbacks',
+ messageId: 'msg-2',
},
AppSourceType.webApp,
undefined,
diff --git a/web/app/components/app/text-generate/item/index.tsx b/web/app/components/app/text-generate/item/index.tsx
index 5953aecf986..e5697f59df4 100644
--- a/web/app/components/app/text-generate/item/index.tsx
+++ b/web/app/components/app/text-generate/item/index.tsx
@@ -102,8 +102,9 @@ const GenerationItem: FC<IGenerationItemProps> = ({
const { config } = useChatContext()
const handleFeedback = async (childFeedback: FeedbackType) => {
+ if (!childMessageId) return
await updateFeedback(
- { url: `/messages/${childMessageId}/feedbacks`, body: { rating: childFeedback.rating } },
+ { messageId: childMessageId, body: { rating: childFeedback.rating } },
appSourceType,
installedAppId,
)
diff --git a/web/app/components/base/chat/chat-with-history/__tests__/hooks.spec.tsx b/web/app/components/base/chat/chat-with-history/__tests__/hooks.spec.tsx
index 54d61f9c0dc..c296613b9d5 100644
--- a/web/app/components/base/chat/chat-with-history/__tests__/hooks.spec.tsx
+++ b/web/app/components/base/chat/chat-with-history/__tests__/hooks.spec.tsx
@@ -749,7 +749,7 @@ describe('useChatWithHistory', () => {
// Assert
expect(mockUpdateFeedback).toHaveBeenCalledWith(
- { url: '/messages/message-1/feedbacks', body: { rating: 'like', content: 'Great!' } },
+ { messageId: 'message-1', body: { rating: 'like', content: 'Great!' } },
AppSourceType.webApp,
'app-1',
)
diff --git a/web/app/components/base/chat/chat-with-history/hooks.tsx b/web/app/components/base/chat/chat-with-history/hooks.tsx
index 1ae1c9cc683..bd6d0b3dc97 100644
--- a/web/app/components/base/chat/chat-with-history/hooks.tsx
+++ b/web/app/components/base/chat/chat-with-history/hooks.tsx
@@ -600,7 +600,7 @@ export const useChatWithHistory = (installedAppInfo?: InstalledAppResponse) => {
async (messageId, feedback) => {
await updateFeedback(
{
- url: `/messages/${messageId}/feedbacks`,
+ messageId,
body: { rating: feedback.rating, content: feedback.content },
},
appSourceType,
diff --git a/web/app/components/base/chat/chat/__tests__/index.spec.tsx b/web/app/components/base/chat/chat/__tests__/index.spec.tsx
index 52ad19dd9a3..d583230d175 100644
--- a/web/app/components/base/chat/chat/__tests__/index.spec.tsx
+++ b/web/app/components/base/chat/chat/__tests__/index.spec.tsx
@@ -2,6 +2,7 @@ import type { ChatConfig, ChatItem } from '../../types'
import type { ChatProps } from '../index'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { createConsoleQueryWrapper } from '@/test/console/query-data'
import Chat from '../index'
// Keep answer rendering at the component boundary; exercise real questions,
@@ -33,7 +34,8 @@ const makeChatItem = (overrides: Partial<ChatItem> = {}): ChatItem => ({
isAnswer: false,
...overrides,
})
-const renderChat = (props: Partial<ChatProps> = {}) => render(<Chat chatList={[]} {...props} />)
+const renderChat = (props: Partial<ChatProps> = {}) =>
+ render(<Chat chatList={[]} {...props} />, { wrapper: createConsoleQueryWrapper().wrapper })
const suggestionsConfig = { suggested_questions_after_answer: { enabled: true } } as ChatConfig
diff --git a/web/app/components/base/chat/chat/answer/human-input-content/utils.ts b/web/app/components/base/chat/chat/answer/human-input-content/utils.ts
index 74e55aa77c9..e226eefd625 100644
--- a/web/app/components/base/chat/chat/answer/human-input-content/utils.ts
+++ b/web/app/components/base/chat/chat/answer/human-input-content/utils.ts
@@ -2,7 +2,6 @@ import type { ButtonProps } from '@langgenius/dify-ui/button'
import type { HumanInputFieldValue } from './field-renderer'
import type { FormInputItem } from '@/app/components/workflow/nodes/human-input/types'
import type { Locale } from '@/i18n'
-import type { HumanInputResolvedValue } from '@/types/workflow'
import dayjs from 'dayjs'
import isSameOrAfter from 'dayjs/plugin/isSameOrAfter'
import relativeTime from 'dayjs/plugin/relativeTime'
@@ -49,7 +48,7 @@ export const getRenderedFormInputs = (formInputs: FormInputItem[], content: stri
export const initializeInputs = (
formInputs: FormInputItem[],
- defaultValues: Record<string, HumanInputResolvedValue> = {},
+ defaultValues: Record<string, unknown> = {},
) => {
const initialInputs: Record<string, HumanInputFieldValue> = {}
formInputs.forEach((item) => {
diff --git a/web/app/components/base/chat/chat/chat-input-area/__tests__/index.spec.tsx b/web/app/components/base/chat/chat/chat-input-area/__tests__/index.spec.tsx
index fca5499ee14..9ceb050a100 100644
--- a/web/app/components/base/chat/chat/chat-input-area/__tests__/index.spec.tsx
+++ b/web/app/components/base/chat/chat/chat-input-area/__tests__/index.spec.tsx
@@ -8,11 +8,21 @@ import { FeaturesProvider } from '@/app/components/base/features/context'
import { transcribeAudio } from '@/app/components/base/voice-input/api'
import { startVoiceRecorder } from '@/app/components/base/voice-input/recorder'
import { InputVarType } from '@/app/components/workflow/types'
+import { createConsoleQueryWrapper } from '@/test/console/query-data'
import { createFileUploadConfigFixture } from '@/test/fixtures/file-upload-config'
import { TransferMethod } from '@/types/app'
import ChatInputArea from '../index'
-const render = (ui: React.ReactNode) => rtlRender(ui, { wrapper: FeaturesProvider })
+const render = (ui: React.ReactNode) => {
+ const { wrapper: ConsoleWrapper } = createConsoleQueryWrapper()
+ return rtlRender(ui, {
+ wrapper: ({ children }) => (
+ <ConsoleWrapper>
+ <FeaturesProvider>{children}</FeaturesProvider>
+ </ConsoleWrapper>
+ ),
+ })
+}
// ---------------------------------------------------------------------------
// External dependency mocks
diff --git a/web/app/components/base/chat/embedded-chatbot/__tests__/hooks.spec.tsx b/web/app/components/base/chat/embedded-chatbot/__tests__/hooks.spec.tsx
index c825f5cb33d..19b4ad73e37 100644
--- a/web/app/components/base/chat/embedded-chatbot/__tests__/hooks.spec.tsx
+++ b/web/app/components/base/chat/embedded-chatbot/__tests__/hooks.spec.tsx
@@ -647,7 +647,7 @@ describe('useEmbeddedChatbot', () => {
expect(updateFeedback).toHaveBeenCalledExactlyOnceWith(
{
- url: '/messages/msg-123/feedbacks',
+ messageId: 'msg-123',
body: { rating: 'like', content: undefined },
},
AppSourceType.webApp,
diff --git a/web/app/components/base/chat/embedded-chatbot/hooks.tsx b/web/app/components/base/chat/embedded-chatbot/hooks.tsx
index 80505401ed7..c3dbf3a38d4 100644
--- a/web/app/components/base/chat/embedded-chatbot/hooks.tsx
+++ b/web/app/components/base/chat/embedded-chatbot/hooks.tsx
@@ -428,7 +428,7 @@ export const useEmbeddedChatbot = (appSourceType: AppSourceType, tryAppId?: stri
async (messageId, feedback) => {
await updateFeedback(
{
- url: `/messages/${messageId}/feedbacks`,
+ messageId,
body: { rating: feedback.rating, content: feedback.content },
},
appSourceType,
diff --git a/web/app/components/base/file-uploader/__tests__/hooks.spec.ts b/web/app/components/base/file-uploader/__tests__/hooks.spec.ts
index a5865f22f0b..2ae523b2f72 100644
--- a/web/app/components/base/file-uploader/__tests__/hooks.spec.ts
+++ b/web/app/components/base/file-uploader/__tests__/hooks.spec.ts
@@ -6,14 +6,19 @@ import { act, renderHook, waitFor } from '@testing-library/react'
import { createElement } from 'react'
import { toast } from '@/app/notifications'
import { captureAppAccessScope, handleAppAccessError } from '@/features/app-access-error/state'
-import { uploadRemoteFileInfo } from '@/service/common'
+import { uploadPublicRemoteFileInfo } from '@/service/common'
import { uploadHumanInputFormLocalFile, uploadHumanInputFormRemoteFileInfo } from '@/service/share'
+import { createConsoleQueryWrapper } from '@/test/console/query-data'
+import { createDeferred } from '@/test/deferred'
import { createFileUploadConfigFixture } from '@/test/fixtures/file-upload-config'
import { getFileSizeLimit, useFile } from '../hooks'
import { createFileStore, FileContext, useStore } from '../store'
import { FileUploadContext } from '../upload-context'
import { fileUpload } from '../utils'
+const request = vi.hoisted(() => vi.fn<typeof import('@/service/base').request>())
+vi.mock('@/service/base', () => ({ request }))
+
const navigation = vi.hoisted(() => ({ params: {} as { token?: string }, pathname: '/chat' }))
vi.mock('@/next/navigation', () => ({
useParams: () => navigation.params,
@@ -23,7 +28,7 @@ vi.mock('../utils', async (importOriginal) => ({
...(await importOriginal<typeof import('../utils')>()),
fileUpload: vi.fn(),
}))
-vi.mock('@/service/common', () => ({ uploadRemoteFileInfo: vi.fn() }))
+vi.mock('@/service/common', () => ({ uploadPublicRemoteFileInfo: vi.fn() }))
vi.mock('@/service/share', () => ({
uploadHumanInputFormLocalFile: vi.fn(),
uploadHumanInputFormRemoteFileInfo: vi.fn(),
@@ -66,16 +71,21 @@ function setup({
}: {
files?: FileEntity[]
fileConfig?: FileUpload
- uploadUrls?: { localUploadUrl?: string; remoteUploadUrl?: string }
+ uploadUrls?: { localUploadUrl?: string; trialAppId?: string }
checkEnabled?: boolean
} = {}) {
const onChange = vi.fn()
const store = createFileStore(files, onChange)
+ const { wrapper: ConsoleWrapper } = createConsoleQueryWrapper()
const wrapper = ({ children }: { children: ReactNode }) =>
createElement(
- FileContext,
- { value: store },
- createElement(FileUploadContext, { value: uploadUrls }, children),
+ ConsoleWrapper,
+ null,
+ createElement(
+ FileContext,
+ { value: store },
+ createElement(FileUploadContext, { value: uploadUrls }, children),
+ ),
)
return {
...renderHook(
@@ -89,12 +99,13 @@ function setup({
beforeEach(() => {
vi.clearAllMocks()
+ request.mockReset().mockImplementation(async () => Response.json(uploadResponse))
window.history.replaceState({}, '', '/')
captureAppAccessScope()
navigation.params = {}
navigation.pathname = '/chat'
vi.spyOn(toast, 'error').mockReturnValue('toast-id')
- vi.mocked(uploadRemoteFileInfo).mockResolvedValue(uploadResponse)
+ vi.mocked(uploadPublicRemoteFileInfo).mockResolvedValue(uploadResponse)
vi.mocked(uploadHumanInputFormRemoteFileInfo).mockResolvedValue(uploadResponse)
})
afterEach(() => {
@@ -258,20 +269,28 @@ it('respects disabled uploads when the caller enables the check', () => {
it('uses resource-specific local and remote upload endpoints', async () => {
const { result } = setup({
- uploadUrls: { localUploadUrl: '/resources/files', remoteUploadUrl: '/resources/remote-files' },
+ uploadUrls: { localUploadUrl: '/trial-apps/trial-1/files/upload', trialAppId: 'trial-1' },
})
act(() =>
result.current.handleLocalFileUpload(new File(['data'], 'a.txt', { type: 'text/plain' })),
)
await waitFor(() =>
- expect(fileUpload).toHaveBeenCalledWith(expect.any(Object), false, '/resources/files'),
+ expect(fileUpload).toHaveBeenCalledWith(
+ expect.any(Object),
+ false,
+ '/trial-apps/trial-1/files/upload',
+ ),
)
await act(async () => result.current.handleLoadFileFromLink('https://example.com/report.pdf'))
- expect(uploadRemoteFileInfo).toHaveBeenCalledWith(
- 'https://example.com/report.pdf',
- false,
- undefined,
- '/resources/remote-files',
+ await waitFor(() => expect(request).toHaveBeenCalled())
+ expect(new URL(request.mock.calls[0]![0]).pathname).toBe(
+ '/console/api/trial-apps/trial-1/remote-files/upload',
+ )
+ expect(await request.mock.calls[0]?.[2]?.request?.json()).toEqual({
+ url: 'https://example.com/report.pdf',
+ })
+ await waitFor(() =>
+ expect(result.current.files.find((file) => file.isRemote)?.uploadedId).toBe('uploaded-file'),
)
expect(result.current.files.find((file) => file.isRemote)?.uploadedId).toBe('uploaded-file')
})
@@ -294,7 +313,7 @@ it('routes human-input form uploads and retries through the form token', async (
'https://example.com/report.pdf',
)
expect(fileUpload).not.toHaveBeenCalled()
- expect(uploadRemoteFileInfo).not.toHaveBeenCalled()
+ expect(uploadPublicRemoteFileInfo).not.toHaveBeenCalled()
})
it('keeps public chat tokens on the normal upload transport', async () => {
@@ -306,42 +325,39 @@ it('keeps public chat tokens on the normal upload transport', async () => {
)
await waitFor(() => expect(fileUpload).toHaveBeenCalledWith(expect.any(Object), true, undefined))
await act(async () => result.current.handleLoadFileFromLink('https://example.com/report.pdf'))
- expect(uploadRemoteFileInfo).toHaveBeenCalledWith('https://example.com/report.pdf', true)
+ expect(uploadPublicRemoteFileInfo).toHaveBeenCalledWith('https://example.com/report.pdf')
expect(uploadHumanInputFormLocalFile).not.toHaveBeenCalled()
})
it.each(['unsupported', 'oversized', 'failed'] as const)(
'removes a remote file when it is %s',
async (condition) => {
- if (condition === 'failed')
- vi.mocked(uploadRemoteFileInfo).mockRejectedValueOnce(new Error('offline'))
+ if (condition === 'failed') request.mockRejectedValueOnce(new Error('offline'))
else
- vi.mocked(uploadRemoteFileInfo).mockResolvedValueOnce({
- ...uploadResponse,
- ...(condition === 'unsupported'
- ? { name: 'file.xyz', mime_type: 'application/octet-stream' }
- : { size: 100 * 1024 * 1024 }),
- })
+ request.mockResolvedValueOnce(
+ Response.json({
+ ...uploadResponse,
+ ...(condition === 'unsupported'
+ ? { name: 'file.xyz', mime_type: 'application/octet-stream' }
+ : { size: 100 * 1024 * 1024 }),
+ }),
+ )
const { result } = setup()
await act(async () => result.current.handleLoadFileFromLink('https://example.com/file'))
- expect(result.current.files).toEqual([])
+ await waitFor(() => expect(result.current.files).toEqual([]))
expect(toast.error).toHaveBeenCalled()
},
)
it('advances pending remote progress only to 80 percent and completes from the response', async () => {
vi.useFakeTimers()
- let resolve!: (value: typeof uploadResponse) => void
- vi.mocked(uploadRemoteFileInfo).mockReturnValueOnce(
- new Promise((done) => {
- resolve = done
- }),
- )
+ const pending = createDeferred<Response>()
+ request.mockReturnValueOnce(pending.promise)
const { result } = setup()
act(() => result.current.handleLoadFileFromLink('https://example.com/report.pdf'))
act(() => vi.advanceTimersByTime(2000))
expect(result.current.files[0]?.progress).toBe(80)
- await act(async () => resolve(uploadResponse))
+ await act(async () => pending.resolve(Response.json(uploadResponse)))
expect(result.current.files[0]).toEqual(
expect.objectContaining({
progress: 100,
@@ -364,9 +380,9 @@ it.each(['local', 'retry', 'remote'] as const)(
}
const { result, unmount } = setup({ files: uploadKind === 'retry' ? [entity('retry')] : [] })
if (uploadKind === 'remote') {
- vi.mocked(uploadRemoteFileInfo).mockRejectedValueOnce(error)
+ request.mockRejectedValueOnce(error)
await act(async () => result.current.handleLoadFileFromLink('https://example.com/file'))
- expect(result.current.files).toEqual([])
+ await waitFor(() => expect(result.current.files).toEqual([]))
} else {
if (uploadKind === 'retry') act(() => result.current.handleReUploadFile('retry'))
else {
@@ -386,3 +402,18 @@ it.each(['local', 'retry', 'remote'] as const)(
}
},
)
+
+it('keeps the original URL and infers the file type when remote metadata is nullable', async () => {
+ request.mockResolvedValueOnce(Response.json({ ...uploadResponse, mime_type: null, url: null }))
+ const { result } = setup()
+ await act(async () => result.current.handleLoadFileFromLink('https://example.com/report.pdf'))
+ await waitFor(() => expect(result.current.files[0]?.progress).toBe(100))
+ expect(result.current.files[0]).toMatchObject({
+ type: '',
+ supportFileType: 'document',
+ url: 'https://example.com/report.pdf',
+ uploadedId: 'uploaded-file',
+ })
+ expect(new URL(request.mock.calls[0]![0]).pathname).toBe('/console/api/remote-files/upload')
+ expect(uploadPublicRemoteFileInfo).not.toHaveBeenCalled()
+})
diff --git a/web/app/components/base/file-uploader/file-from-link-or-local/__tests__/index.spec.tsx b/web/app/components/base/file-uploader/file-from-link-or-local/__tests__/index.spec.tsx
index 3d5fc1ea6e0..615e3d739bf 100644
--- a/web/app/components/base/file-uploader/file-from-link-or-local/__tests__/index.spec.tsx
+++ b/web/app/components/base/file-uploader/file-from-link-or-local/__tests__/index.spec.tsx
@@ -4,15 +4,13 @@ import type { FileUpload } from '@/app/components/base/features/types'
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { SupportUploadFileTypes } from '@/app/components/workflow/types'
+import { createConsoleQueryWrapper } from '@/test/console/query-data'
import { TransferMethod } from '@/types/app'
import { FileContextProvider } from '../../store'
import FileFromLinkOrLocal from '../index'
-const uploadRemoteFileInfo = vi.hoisted(() => vi.fn())
-vi.mock('@/service/common', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@/service/common')>()),
- uploadRemoteFileInfo,
-}))
+const request = vi.hoisted(() => vi.fn<typeof import('@/service/base').request>())
+vi.mock('@/service/base', () => ({ request }))
vi.mock('@/next/navigation', () => ({ useParams: () => ({}), usePathname: () => '/apps' }))
const config: FileUpload = {
@@ -37,20 +35,23 @@ const setup = async (
{...props}
/>
</FileContextProvider>,
+ { wrapper: createConsoleQueryWrapper().wrapper },
)
await user.click(screen.getByRole('button', { name: 'Open uploads' }))
return { user, onChange }
}
beforeEach(() => {
- uploadRemoteFileInfo.mockReset()
- uploadRemoteFileInfo.mockResolvedValue({
- id: 'uploaded-file',
- name: 'report.pdf',
- mime_type: 'application/pdf',
- size: 10,
- url: 'https://example.com/report.pdf',
- })
+ request.mockReset()
+ request.mockImplementation(async () =>
+ Response.json({
+ id: 'uploaded-file',
+ name: 'report.pdf',
+ mime_type: 'application/pdf',
+ size: 10,
+ url: 'https://example.com/report.pdf',
+ }),
+ )
})
it.each([
@@ -71,12 +72,15 @@ it('rejects an invalid link, clears the error on editing, and persists a valid u
await user.type(input, 'invalid-url')
await user.click(submit)
expect(screen.getByText(/pasteFileLinkInvalid/)).toBeInTheDocument()
- expect(uploadRemoteFileInfo).not.toHaveBeenCalled()
+ expect(request).not.toHaveBeenCalled()
await user.clear(input)
await user.type(input, 'https://example.com/report.pdf')
expect(screen.queryByText(/pasteFileLinkInvalid/)).not.toBeInTheDocument()
await user.click(submit)
- expect(uploadRemoteFileInfo).toHaveBeenCalledWith('https://example.com/report.pdf', false)
+ await waitFor(() => expect(request).toHaveBeenCalled())
+ expect(await request.mock.calls[0]?.[2]?.request?.json()).toEqual({
+ url: 'https://example.com/report.pdf',
+ })
await waitFor(() =>
expect(onChange).toHaveBeenLastCalledWith([
expect.objectContaining({
diff --git a/web/app/components/base/file-uploader/file-uploader-in-chat-input/__tests__/file-list.spec.tsx b/web/app/components/base/file-uploader/file-uploader-in-chat-input/__tests__/file-list.spec.tsx
index c2fcfc517ca..17aa5e10976 100644
--- a/web/app/components/base/file-uploader/file-uploader-in-chat-input/__tests__/file-list.spec.tsx
+++ b/web/app/components/base/file-uploader/file-uploader-in-chat-input/__tests__/file-list.spec.tsx
@@ -2,6 +2,7 @@ import type { FileEntity } from '../../types'
import type { FileUpload } from '@/app/components/base/features/types'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { createConsoleQueryWrapper } from '@/test/console/query-data'
import { TransferMethod } from '@/types/app'
import { FileContextProvider } from '../../store'
import { FileListInChatInput } from '../file-list'
@@ -37,6 +38,7 @@ it('removes the selected attachment from a mixed chat file list and reports the
<FileContextProvider value={files} onChange={onChange}>
<FileListInChatInput fileConfig={config} />
</FileContextProvider>,
+ { wrapper: createConsoleQueryWrapper().wrapper },
)
expect(screen.getByRole('img')).toBeInTheDocument()
expect(screen.getByText('document.pdf')).toBeInTheDocument()
diff --git a/web/app/components/base/file-uploader/hooks.ts b/web/app/components/base/file-uploader/hooks.ts
index 0552e22f166..f8b94b6466e 100644
--- a/web/app/components/base/file-uploader/hooks.ts
+++ b/web/app/components/base/file-uploader/hooks.ts
@@ -2,6 +2,7 @@ import type { UploadConfig } from '@dify/contracts/api/console/files/types.gen'
import type { ClipboardEvent } from 'react'
import type { FileEntity } from './types'
import type { FileUpload } from '@/app/components/base/features/types'
+import { useMutation } from '@tanstack/react-query'
import { noop } from 'es-toolkit/function'
import { produce } from 'immer'
import { useCallback, useState } from 'react'
@@ -19,7 +20,8 @@ import { SupportUploadFileTypes } from '@/app/components/workflow/types'
import { toast } from '@/app/notifications'
import { isAppAccessError } from '@/features/app-access-error/state'
import { useParams, usePathname } from '@/next/navigation'
-import { uploadRemoteFileInfo } from '@/service/common'
+import { uploadPublicRemoteFileInfo } from '@/service/common'
+import { consoleQuery } from '@/service/console'
import { uploadHumanInputFormLocalFile, uploadHumanInputFormRemoteFileInfo } from '@/service/share'
import { TransferMethod } from '@/types/app'
import { formatFileSize } from '@/utils/format'
@@ -61,7 +63,13 @@ export const useFile = (fileConfig: FileUpload, noNeedToCheckEnable = true) => {
const fileStore = useFileStore()
const params = useParams()
const pathname = usePathname()
- const { localUploadUrl, remoteUploadUrl } = useFileUploadContext()
+ const { localUploadUrl, trialAppId } = useFileUploadContext()
+ const { mutateAsync: uploadConsoleRemoteFile } = useMutation(
+ consoleQuery.remoteFiles.upload.post.mutationOptions(),
+ )
+ const { mutateAsync: uploadTrialRemoteFile } = useMutation(
+ consoleQuery.trialApps.byAppId.remoteFiles.upload.post.mutationOptions(),
+ )
const { imgSizeLimit, docSizeLimit, audioSizeLimit, videoSizeLimit } = getFileSizeLimit(
fileConfig.fileUploadConfig,
)
@@ -244,29 +252,30 @@ export const useFile = (fileConfig: FileUpload, noNeedToCheckEnable = true) => {
let remoteUpload
if (isHumanInputFormPage) remoteUpload = uploadHumanInputFormRemoteFileInfo(formToken!, url)
- else if (remoteUploadUrl)
- remoteUpload = uploadRemoteFileInfo(url, !!params.token, undefined, remoteUploadUrl)
- else remoteUpload = uploadRemoteFileInfo(url, !!params.token)
+ else if (trialAppId)
+ remoteUpload = uploadTrialRemoteFile({ params: { app_id: trialAppId }, body: { url } })
+ else if (params.token) remoteUpload = uploadPublicRemoteFileInfo(url)
+ else remoteUpload = uploadConsoleRemoteFile({ body: { url } })
remoteUpload
.then((res) => {
const newFile = {
...uploadingFile,
- type: res.mime_type,
+ type: res.mime_type ?? '',
size: res.size,
progress: 100,
supportFileType: getSupportFileType(
res.name,
- res.mime_type,
+ res.mime_type ?? '',
allowedFileTypes?.includes(SupportUploadFileTypes.custom),
),
uploadedId: res.id,
- url: res.url,
+ url: res.url ?? url,
}
if (
!isAllowedFileExtension(
res.name,
- res.mime_type,
+ res.mime_type ?? '',
fileConfig.allowed_file_types || [],
fileConfig.allowed_file_extensions || [],
)
@@ -298,7 +307,9 @@ export const useFile = (fileConfig: FileUpload, noNeedToCheckEnable = true) => {
isHumanInputFormPage,
formToken,
params.token,
- remoteUploadUrl,
+ trialAppId,
+ uploadConsoleRemoteFile,
+ uploadTrialRemoteFile,
],
)
diff --git a/web/app/components/base/file-uploader/upload-context.ts b/web/app/components/base/file-uploader/upload-context.ts
index 098f3c3d265..ac21de58274 100644
--- a/web/app/components/base/file-uploader/upload-context.ts
+++ b/web/app/components/base/file-uploader/upload-context.ts
@@ -2,7 +2,7 @@ import { createContext, use } from 'react'
export const FileUploadContext = createContext<{
localUploadUrl?: string
- remoteUploadUrl?: string
+ trialAppId?: string
}>({})
export function useFileUploadContext() {
diff --git a/web/app/components/explore/try-app/app/index.tsx b/web/app/components/explore/try-app/app/index.tsx
index 792098accd1..101fc66d5a8 100644
--- a/web/app/components/explore/try-app/app/index.tsx
+++ b/web/app/components/explore/try-app/app/index.tsx
@@ -20,7 +20,7 @@ function TryApp({ appId, appDetail }: Props) {
<FileUploadContext
value={{
localUploadUrl: `/trial-apps/${appId}/files/upload`,
- remoteUploadUrl: `/trial-apps/${appId}/remote-files/upload`,
+ trialAppId: appId,
}}
>
<div className="flex size-full">
diff --git a/web/app/components/header/account-setting/data-source-page-new/__tests__/card.spec.tsx b/web/app/components/header/account-setting/data-source-page-new/__tests__/card.spec.tsx
index f3576042c6b..a28ffea24a1 100644
--- a/web/app/components/header/account-setting/data-source-page-new/__tests__/card.spec.tsx
+++ b/web/app/components/header/account-setting/data-source-page-new/__tests__/card.spec.tsx
@@ -9,13 +9,13 @@ import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/console
import { createDeferred } from '@/test/deferred'
import Card from '../card'
-const { mockPost, mockGetPluginOAuthUrl } = vi.hoisted(() => ({
- mockPost: vi.fn(),
+const { mockRequest, mockGetPluginOAuthUrl } = vi.hoisted(() => ({
+ mockRequest: vi.fn(),
mockGetPluginOAuthUrl: vi.fn(),
}))
vi.mock('@/service/base', async (importOriginal) => ({
...(await importOriginal<typeof import('@/service/base')>()),
- post: (...args: unknown[]) => mockPost(...args),
+ request: (...args: unknown[]) => mockRequest(...args),
}))
vi.mock('@/hooks/use-oauth', async (importOriginal) => ({
...(await importOriginal<typeof import('@/hooks/use-oauth')>()),
@@ -62,7 +62,15 @@ const oauthItem: DatasourceProviderAuthResponse = {
credentials_list: [{ ...item.credentials_list[0]!, type: CredentialTypeEnum.OAUTH2 }],
}
const providerId = 'test-plugin-id/test-name'
-const endpoint = `/auth/plugin/datasource/${providerId}`
+const endpoint = `/console/api/auth/plugin/datasource/${encodeURIComponent(providerId)}`
+
+async function expectCommand(path: string, { body }: { body: unknown }) {
+ expect(mockRequest).toHaveBeenCalledOnce()
+ const request = mockRequest.mock.calls[0]![2].request as Request
+ expect(new URL(request.url).pathname).toBe(path)
+ expect(request.method).toBe('POST')
+ await expect(request.clone().json()).resolves.toEqual(body)
+}
const renderCard = (
data = item,
permissions = ['credential.use', 'credential.create', 'credential.manage'],
@@ -120,7 +128,7 @@ const chooseAction = async (user: ReturnType<typeof userEvent.setup>, name: stri
describe('Datasource Card', () => {
beforeEach(() => {
vi.clearAllMocks()
- mockPost.mockReset().mockResolvedValue({ result: 'success' })
+ mockRequest.mockReset().mockImplementation(async () => Response.json({ result: 'success' }))
mockGetPluginOAuthUrl
.mockReset()
.mockResolvedValue({ authorization_url: 'https://oauth.example/authorize' })
@@ -143,8 +151,8 @@ describe('Datasource Card', () => {
it('edits an actual API-key form and invalidates datasource caches after success', async () => {
const user = userEvent.setup()
- const pending = createDeferred<{ result: string }>()
- mockPost.mockReturnValueOnce(pending.promise)
+ const pending = createDeferred<Response>()
+ mockRequest.mockReturnValueOnce(pending.promise)
const { expectFresh, expectInvalidated } = renderCard()
await chooseAction(user, 'common.operation.edit')
const dialog = await screen.findByRole('dialog', { name: 'plugin.auth.useApiAuth' })
@@ -154,12 +162,14 @@ describe('Datasource Card', () => {
await user.type(keyInput, 'new-key')
const save = within(dialog).getByRole('button', { name: 'common.operation.save' })
await user.click(save)
- expect(mockPost).toHaveBeenCalledExactlyOnceWith(`${endpoint}/update`, {
- body: { credential_id: 'c1', name: 'Credential 1', credentials: { apiKey: 'new-key' } },
- })
+ await waitFor(() =>
+ expectCommand(`${endpoint}/update`, {
+ body: { credential_id: 'c1', name: 'Credential 1', credentials: { apiKey: 'new-key' } },
+ }),
+ )
expect(save).toBeDisabled()
expectFresh()
- await act(async () => pending.resolve({ result: 'success' }))
+ await act(async () => pending.resolve(Response.json({ result: 'success' })))
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
expectInvalidated()
})
@@ -170,28 +180,28 @@ describe('Datasource Card', () => {
await chooseAction(user, 'common.operation.edit')
await user.click(await screen.findByRole('button', { name: 'common.operation.cancel' }))
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
- expect(mockPost).not.toHaveBeenCalled()
+ expect(mockRequest).not.toHaveBeenCalled()
expectFresh()
})
it('requires delete confirmation and waits for completion before invalidating', async () => {
const user = userEvent.setup()
- const pending = createDeferred<{ result: string }>()
- mockPost.mockReturnValueOnce(pending.promise)
+ const pending = createDeferred<Response>()
+ mockRequest.mockReturnValueOnce(pending.promise)
const { expectFresh, expectInvalidated } = renderCard()
await chooseAction(user, 'common.operation.remove')
await user.click(await screen.findByRole('button', { name: 'common.operation.cancel' }))
- expect(mockPost).not.toHaveBeenCalled()
+ expect(mockRequest).not.toHaveBeenCalled()
await chooseAction(user, 'common.operation.remove')
const confirm = await screen.findByRole('button', { name: 'common.operation.confirm' })
await user.click(confirm)
await user.click(confirm)
expect(confirm).toBeDisabled()
- expect(mockPost).toHaveBeenCalledExactlyOnceWith(`${endpoint}/delete`, {
+ await expectCommand(`${endpoint}/delete`, {
body: { credential_id: 'c1' },
})
expectFresh()
- await act(async () => pending.resolve({ result: 'success' }))
+ await act(async () => pending.resolve(Response.json({ result: 'success' })))
await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
expectInvalidated()
})
@@ -201,7 +211,7 @@ describe('Datasource Card', () => {
const { expectInvalidated } = renderCard(oauthItem, ['credential.use'])
await chooseAction(user, 'plugin.auth.setDefault')
await waitFor(() =>
- expect(mockPost).toHaveBeenCalledExactlyOnceWith(`${endpoint}/default`, {
+ expectCommand(`${endpoint}/default`, {
body: { id: 'c1' },
}),
)
@@ -218,7 +228,7 @@ describe('Datasource Card', () => {
}
expect(screen.queryByRole('textbox')).not.toBeInTheDocument()
expect(mockGetPluginOAuthUrl).not.toHaveBeenCalled()
- expect(mockPost).toHaveBeenCalledTimes(1)
+ expect(mockRequest).toHaveBeenCalledTimes(1)
})
it('blocks credential operations without use or manage permission', async () => {
@@ -236,7 +246,7 @@ describe('Datasource Card', () => {
}
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()
- expect(mockPost).not.toHaveBeenCalled()
+ expect(mockRequest).not.toHaveBeenCalled()
})
it('renames OAuth credentials through the inline editor', async () => {
@@ -251,7 +261,7 @@ describe('Datasource Card', () => {
await user.type(input, 'New Name')
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
await waitFor(() =>
- expect(mockPost).toHaveBeenCalledExactlyOnceWith(`${endpoint}/update`, {
+ expectCommand(`${endpoint}/update`, {
body: { credential_id: 'c1', name: 'New Name' },
}),
)
@@ -298,11 +308,10 @@ describe('Datasource Card', () => {
await user.type(inputs[1]!, 'secret')
await user.click(within(dialog).getByRole('button', { name: 'common.operation.save' }))
await waitFor(() =>
- expect(mockPost).toHaveBeenCalledExactlyOnceWith(endpoint, {
+ expectCommand(endpoint, {
body: expect.objectContaining({
name: 'New key',
credentials: { apiKey: 'secret' },
- type: CredentialTypeEnum.API_KEY,
}),
}),
)
@@ -317,6 +326,6 @@ describe('Datasource Card', () => {
expect(add).toBeDisabled()
await user.click(add)
expect(screen.queryByRole('dialog', { name: 'plugin.auth.addApi' })).not.toBeInTheDocument()
- expect(mockPost).not.toHaveBeenCalled()
+ expect(mockRequest).not.toHaveBeenCalled()
})
})
diff --git a/web/app/components/header/account-setting/preference-page/__tests__/index.spec.tsx b/web/app/components/header/account-setting/preference-page/__tests__/index.spec.tsx
index 227cb05dad5..a8624381854 100644
--- a/web/app/components/header/account-setting/preference-page/__tests__/index.spec.tsx
+++ b/web/app/components/header/account-setting/preference-page/__tests__/index.spec.tsx
@@ -19,7 +19,10 @@ let mockUserProfile: GetAccountProfileResponse
vi.mock('@/service/base', () => ({
get: mockGet,
- request: mockRequest,
+ request: (url: string, init: RequestInit, options: { request: Request }) =>
+ url.endsWith('/account/profile') && options.request.method === 'GET'
+ ? mockGet(url, init, options)
+ : mockRequest(url, init, options),
sseGeneratorPost: vi.fn(),
}))
diff --git a/web/app/components/integrations/__tests__/tool-provider-list.spec.tsx b/web/app/components/integrations/__tests__/tool-provider-list.spec.tsx
index a967d00d482..cefeaf2afb8 100644
--- a/web/app/components/integrations/__tests__/tool-provider-list.spec.tsx
+++ b/web/app/components/integrations/__tests__/tool-provider-list.spec.tsx
@@ -68,6 +68,16 @@ vi.mock('@/service/console', async (importOriginal) => {
return {
...actual,
consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'remoteFiles.upload.post': async () => ({
+ id: 'favicon',
+ name: 'favicon.png',
+ size: 10,
+ mime_type: 'image/png',
+ url: '/favicon.png',
+ created_at: null,
+ created_by: null,
+ extension: null,
+ }),
'workspaces.current.plugin.uninstall.post': api.uninstall,
'workspaces.current.toolProviders.get': api.providers,
'workspaces.current.plugin.list.installations.ids.post': api.installed,
@@ -117,17 +127,6 @@ vi.mock('@/next/navigation', async (importOriginal) => ({
vi.mock('@/service/base', async (importOriginal) => ({
...(await importOriginal<typeof import('@/service/base')>()),
- post: async (url: string) => {
- if (url === '/remote-files/upload')
- return {
- id: 'favicon',
- name: 'favicon.png',
- size: 10,
- mime_type: 'image/png',
- url: '/favicon.png',
- }
- throw new Error(`Unexpected service request: ${url}`)
- },
get: async (url: string) => {
if (
url ===
diff --git a/web/app/components/plugins/plugin-auth/authorize/__tests__/add-oauth-button.spec.tsx b/web/app/components/plugins/plugin-auth/authorize/__tests__/add-oauth-button.spec.tsx
index 425e97cc5dd..55dc2435742 100644
--- a/web/app/components/plugins/plugin-auth/authorize/__tests__/add-oauth-button.spec.tsx
+++ b/web/app/components/plugins/plugin-auth/authorize/__tests__/add-oauth-button.spec.tsx
@@ -25,17 +25,25 @@ vi.mock('@/hooks/use-oauth', () => ({
vi.mock('@/service/base', async (importOriginal) => ({
...(await importOriginal<typeof import('@/service/base')>()),
- get: (url: string, options?: { params?: { visibility?: string } }) => {
- if (url.endsWith('/oauth/client-schema'))
- return Promise.resolve({
+ request: async (url: string, _init: RequestInit, options: { request: Request }) => {
+ const target = new URL(url)
+ const path = target.pathname.replace('/console/api', '')
+ if (path.endsWith('/oauth/client-schema'))
+ return Response.json({
schema: [],
is_oauth_custom_client_enabled: false,
is_system_oauth_params_exists: true,
client_params: {},
+ redirect_uri: '',
})
- return mockGetPluginOAuthUrl(url, options)
+ if (options.request.method === 'POST')
+ return Response.json(await mockSaveClient(path, { body: await options.request.json() }))
+ return Response.json(
+ await mockGetPluginOAuthUrl(path, {
+ params: { visibility: target.searchParams.get('visibility') ?? undefined },
+ }),
+ )
},
- post: (...args: unknown[]) => mockSaveClient(...args),
}))
vi.mock('@/app/notifications', () => ({ toast: { success: vi.fn() } }))
@@ -208,10 +216,7 @@ describe('AddOAuthButton', () => {
})
it('should skip visibility picker for categories without backend visibility support', async () => {
- // Trigger / model OAuth endpoints don't yet accept a visibility value on
- // the backend — the picker would let users select "Only me" while the
- // credential silently defaults to all_team_members. Tool and datasource
- // are both wired end-to-end so they DO get the picker.
+ // This shared hook has no endpoint for trigger/model OAuth.
const triggerPayload = { category: AuthCategory.trigger, provider: 'test-trigger' }
renderWithAccountProfile(
<AddOAuthButton
@@ -223,9 +228,8 @@ describe('AddOAuthButton', () => {
fireEvent.click(await screen.findByRole('button', { name: 'Use OAuth' }))
- await waitFor(() => {
- expect(mockGetPluginOAuthUrl).toHaveBeenCalledWith('', { params: { visibility: undefined } })
- })
+ expect(mockGetPluginOAuthUrl).not.toHaveBeenCalled()
+ expect(mockOpenOAuthPopup).not.toHaveBeenCalled()
// No pre-OAuth visibility modal should ever appear for unsupported categories.
expect(screen.queryByText('plugin.auth.authorize')).not.toBeInTheDocument()
})
diff --git a/web/app/components/plugins/plugin-auth/authorize/__tests__/index.spec.tsx b/web/app/components/plugins/plugin-auth/authorize/__tests__/index.spec.tsx
index c6633c7581e..cc12ef6f887 100644
--- a/web/app/components/plugins/plugin-auth/authorize/__tests__/index.spec.tsx
+++ b/web/app/components/plugins/plugin-auth/authorize/__tests__/index.spec.tsx
@@ -7,14 +7,21 @@ import Authorize from '../index'
const requests = vi.hoisted(() => ({ authorize: vi.fn(), popup: vi.fn() }))
vi.mock('@/service/base', async (importOriginal) => ({
...(await importOriginal<typeof import('@/service/base')>()),
- get: (url: string, options: unknown) => {
- if (url.endsWith('/oauth/client-schema'))
- return Promise.resolve({
+ request: async (url: string) => {
+ const target = new URL(url)
+ const path = target.pathname.replace('/console/api', '')
+ if (path.endsWith('/oauth/client-schema'))
+ return Response.json({
schema: [],
is_system_oauth_params_exists: true,
is_oauth_custom_client_enabled: false,
+ redirect_uri: '',
})
- return requests.authorize(url, options)
+ return Response.json(
+ await requests.authorize(path, {
+ params: { visibility: target.searchParams.get('visibility') ?? undefined },
+ }),
+ )
},
}))
vi.mock('@/hooks/use-oauth', () => ({ openOAuthPopup: requests.popup }))
diff --git a/web/app/components/plugins/plugin-auth/authorized/__tests__/index.spec.tsx b/web/app/components/plugins/plugin-auth/authorized/__tests__/index.spec.tsx
index 80ad8246766..7537638b789 100644
--- a/web/app/components/plugins/plugin-auth/authorized/__tests__/index.spec.tsx
+++ b/web/app/components/plugins/plugin-auth/authorized/__tests__/index.spec.tsx
@@ -12,7 +12,17 @@ import Authorized from '../index'
const requests = vi.hoisted(() => ({ get: vi.fn(), post: vi.fn() }))
vi.mock('@/service/base', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/service/base')>()
- return { ...actual, get: requests.get, post: requests.post }
+ return {
+ ...actual,
+ request: async (url: string, _init: RequestInit, options: { request: Request }) => {
+ const path = new URL(url).pathname.replace('/console/api', '')
+ return Response.json(
+ options.request.method === 'GET'
+ ? await requests.get(path)
+ : await requests.post(path, { body: await options.request.json() }),
+ )
+ },
+ }
})
const permissions = vi.hoisted(() => ({
keys: ['credential.use', 'credential.create', 'credential.manage'],
@@ -48,7 +58,12 @@ beforeEach(() => {
requests.get.mockImplementation((url: string) => {
if (url.endsWith('/credential/schema/api-key'))
return Promise.resolve([
- { name: 'api_key', label: 'API Key', type: FormTypeEnum.secretInput, required: true },
+ {
+ name: 'api_key',
+ label: { en_US: 'API Key' },
+ type: FormTypeEnum.secretInput,
+ required: true,
+ },
])
if (url.endsWith('/oauth/client-schema'))
return Promise.resolve({
diff --git a/web/app/components/plugins/plugin-auth/hooks/__tests__/get-api.spec.ts b/web/app/components/plugins/plugin-auth/hooks/__tests__/get-api.spec.ts
index e8b70d93050..74318788fcb 100644
--- a/web/app/components/plugins/plugin-auth/hooks/__tests__/get-api.spec.ts
+++ b/web/app/components/plugins/plugin-auth/hooks/__tests__/get-api.spec.ts
@@ -1,88 +1,15 @@
-import { describe, expect, it } from 'vite-plus/test'
-import { AuthCategory, CredentialTypeEnum } from '../../types'
+import { AuthCategory } from '../../types'
import { getApi } from '../get-api'
-describe('getApi', () => {
- const provider = 'test-provider'
-
- describe('tool category', () => {
- it('returns correct API paths for tool category', () => {
- const api = getApi({ category: AuthCategory.tool, provider })
- expect(api.getCredentialInfo).toBe(
- `/workspaces/current/tool-provider/builtin/${provider}/credential/info`,
- )
- expect(api.setDefaultCredential).toBe(
- `/workspaces/current/tool-provider/builtin/${provider}/default-credential`,
- )
- expect(api.getCredentials).toBe(
- `/workspaces/current/tool-provider/builtin/${provider}/credentials`,
- )
- expect(api.addCredential).toBe(`/workspaces/current/tool-provider/builtin/${provider}/add`)
- expect(api.updateCredential).toBe(
- `/workspaces/current/tool-provider/builtin/${provider}/update`,
- )
- expect(api.deleteCredential).toBe(
- `/workspaces/current/tool-provider/builtin/${provider}/delete`,
- )
- expect(api.getOauthUrl).toBe(`/oauth/plugin/${provider}/tool/authorization-url`)
- })
-
- it('maps the API key credential schema endpoint', () => {
- const api = getApi({ category: AuthCategory.tool, provider })
- const schemaUrl = api.getCredentialSchema(CredentialTypeEnum.API_KEY)
- expect(schemaUrl).toBe(
- `/workspaces/current/tool-provider/builtin/${provider}/credential/schema/api-key`,
- )
- })
-
- it('includes OAuth client endpoints', () => {
- const api = getApi({ category: AuthCategory.tool, provider })
- expect(api.getOauthClientSchema).toBe(
- `/workspaces/current/tool-provider/builtin/${provider}/oauth/client-schema`,
- )
- expect(api.setCustomOauthClient).toBe(
- `/workspaces/current/tool-provider/builtin/${provider}/oauth/custom-client`,
- )
- })
- })
-
- describe('datasource category', () => {
- it('returns correct API paths for datasource category', () => {
- const api = getApi({ category: AuthCategory.datasource, provider })
- expect(api.getCredentials).toBe(`/auth/plugin/datasource/${provider}`)
- expect(api.addCredential).toBe(`/auth/plugin/datasource/${provider}`)
- expect(api.updateCredential).toBe(`/auth/plugin/datasource/${provider}/update`)
- expect(api.deleteCredential).toBe(`/auth/plugin/datasource/${provider}/delete`)
- expect(api.setDefaultCredential).toBe(`/auth/plugin/datasource/${provider}/default`)
- expect(api.getOauthUrl).toBe(`/oauth/plugin/${provider}/datasource/get-authorization-url`)
- })
-
- it('returns empty string for getCredentialInfo', () => {
- const api = getApi({ category: AuthCategory.datasource, provider })
- expect(api.getCredentialInfo).toBe('')
- })
-
- it('returns a function for getCredentialSchema that returns empty string', () => {
- const api = getApi({ category: AuthCategory.datasource, provider })
- expect(api.getCredentialSchema(CredentialTypeEnum.API_KEY)).toBe('')
- })
- })
-
- describe('other categories', () => {
- it('returns empty strings as fallback for unsupported category', () => {
- const api = getApi({ category: AuthCategory.model, provider })
- expect(api.getCredentialInfo).toBe('')
- expect(api.setDefaultCredential).toBe('')
- expect(api.getCredentials).toBe('')
- expect(api.addCredential).toBe('')
- expect(api.updateCredential).toBe('')
- expect(api.deleteCredential).toBe('')
- expect(api.getOauthUrl).toBe('')
- })
-
- it('returns a function for getCredentialSchema that returns empty string', () => {
- const api = getApi({ category: AuthCategory.model, provider })
- expect(api.getCredentialSchema(CredentialTypeEnum.API_KEY)).toBe('')
- })
- })
+it('keeps the legacy credential-info endpoint for tools', () => {
+ expect(getApi({ category: AuthCategory.tool, provider: 'test-provider' }).getCredentialInfo).toBe(
+ '/workspaces/current/tool-provider/builtin/test-provider/credential/info',
+ )
})
+
+it.each([AuthCategory.datasource, AuthCategory.model, AuthCategory.trigger])(
+ 'does not request legacy credential info for %s',
+ (category) => {
+ expect(getApi({ category, provider: 'test-provider' }).getCredentialInfo).toBe('')
+ },
+)
diff --git a/web/app/components/plugins/plugin-auth/hooks/__tests__/use-credential.spec.ts b/web/app/components/plugins/plugin-auth/hooks/__tests__/use-credential.spec.ts
index ee4942f5389..b8dfd5469d7 100644
--- a/web/app/components/plugins/plugin-auth/hooks/__tests__/use-credential.spec.ts
+++ b/web/app/components/plugins/plugin-auth/hooks/__tests__/use-credential.spec.ts
@@ -80,9 +80,7 @@ describe('use-credential hooks', () => {
describe('useDeletePluginCredentialHook', () => {
it('should call service with correct URL', () => {
renderHook(() => useDeletePluginCredentialHook(toolPayload))
- expect(mockUseDeletePluginCredential).toHaveBeenCalledWith(
- `/workspaces/current/tool-provider/builtin/${toolPayload.provider}/delete`,
- )
+ expect(mockUseDeletePluginCredential).toHaveBeenCalledWith(toolPayload)
})
})
@@ -110,9 +108,7 @@ describe('use-credential hooks', () => {
describe('useSetPluginDefaultCredentialHook', () => {
it('should call service with correct URL', () => {
renderHook(() => useSetPluginDefaultCredentialHook(toolPayload))
- expect(mockUseSetPluginDefaultCredential).toHaveBeenCalledWith(
- `/workspaces/current/tool-provider/builtin/${toolPayload.provider}/default-credential`,
- )
+ expect(mockUseSetPluginDefaultCredential).toHaveBeenCalledWith(toolPayload)
})
})
@@ -120,14 +116,16 @@ describe('use-credential hooks', () => {
it('should call service with correct schema URL for API_KEY', () => {
renderHook(() => useGetPluginCredentialSchemaHook(toolPayload, CredentialTypeEnum.API_KEY))
expect(mockUseGetPluginCredentialSchema).toHaveBeenCalledWith(
- `/workspaces/current/tool-provider/builtin/${toolPayload.provider}/credential/schema/${CredentialTypeEnum.API_KEY}`,
+ toolPayload,
+ CredentialTypeEnum.API_KEY,
)
})
it('should call service with correct schema URL for OAUTH2', () => {
renderHook(() => useGetPluginCredentialSchemaHook(toolPayload, CredentialTypeEnum.OAUTH2))
expect(mockUseGetPluginCredentialSchema).toHaveBeenCalledWith(
- `/workspaces/current/tool-provider/builtin/${toolPayload.provider}/credential/schema/${CredentialTypeEnum.OAUTH2}`,
+ toolPayload,
+ CredentialTypeEnum.OAUTH2,
)
})
})
@@ -135,69 +133,55 @@ describe('use-credential hooks', () => {
describe('useAddPluginCredentialHook', () => {
it('should call service with correct URL', () => {
renderHook(() => useAddPluginCredentialHook(toolPayload))
- expect(mockUseAddPluginCredential).toHaveBeenCalledWith(
- `/workspaces/current/tool-provider/builtin/${toolPayload.provider}/add`,
- )
+ expect(mockUseAddPluginCredential).toHaveBeenCalledWith(toolPayload)
})
})
describe('useUpdatePluginCredentialHook', () => {
it('should call service with correct URL', () => {
renderHook(() => useUpdatePluginCredentialHook(toolPayload))
- expect(mockUseUpdatePluginCredential).toHaveBeenCalledWith(
- `/workspaces/current/tool-provider/builtin/${toolPayload.provider}/update`,
- )
+ expect(mockUseUpdatePluginCredential).toHaveBeenCalledWith(toolPayload)
})
})
describe('useGetPluginOAuthUrlHook', () => {
it('should call service with correct URL', () => {
renderHook(() => useGetPluginOAuthUrlHook(toolPayload))
- expect(mockUseGetPluginOAuthUrl).toHaveBeenCalledWith(
- `/oauth/plugin/${toolPayload.provider}/tool/authorization-url`,
- )
+ expect(mockUseGetPluginOAuthUrl).toHaveBeenCalledWith(toolPayload)
})
})
describe('useGetPluginOAuthClientSchemaHook', () => {
it('should call service with correct URL', () => {
renderHook(() => useGetPluginOAuthClientSchemaHook(toolPayload))
- expect(mockUseGetPluginOAuthClientSchema).toHaveBeenCalledWith(
- `/workspaces/current/tool-provider/builtin/${toolPayload.provider}/oauth/client-schema`,
- )
+ expect(mockUseGetPluginOAuthClientSchema).toHaveBeenCalledWith(toolPayload, true)
})
it('should disable the service query when OAuth data is provided by the caller', () => {
renderHook(() => useGetPluginOAuthClientSchemaHook(toolPayload, false))
- expect(mockUseGetPluginOAuthClientSchema).toHaveBeenCalledWith('')
+ expect(mockUseGetPluginOAuthClientSchema).toHaveBeenCalledWith(toolPayload, false)
})
})
describe('useInvalidPluginOAuthClientSchemaHook', () => {
it('should call service with correct URL', () => {
renderHook(() => useInvalidPluginOAuthClientSchemaHook(toolPayload))
- expect(mockUseInvalidPluginOAuthClientSchema).toHaveBeenCalledWith(
- `/workspaces/current/tool-provider/builtin/${toolPayload.provider}/oauth/client-schema`,
- )
+ expect(mockUseInvalidPluginOAuthClientSchema).toHaveBeenCalledWith(toolPayload)
})
})
describe('useSetPluginOAuthCustomClientHook', () => {
it('should call service with correct URL', () => {
renderHook(() => useSetPluginOAuthCustomClientHook(toolPayload))
- expect(mockUseSetPluginOAuthCustomClient).toHaveBeenCalledWith(
- `/workspaces/current/tool-provider/builtin/${toolPayload.provider}/oauth/custom-client`,
- )
+ expect(mockUseSetPluginOAuthCustomClient).toHaveBeenCalledWith(toolPayload)
})
})
describe('useDeletePluginOAuthCustomClientHook', () => {
it('should call service with correct URL', () => {
renderHook(() => useDeletePluginOAuthCustomClientHook(toolPayload))
- expect(mockUseDeletePluginOAuthCustomClient).toHaveBeenCalledWith(
- `/workspaces/current/tool-provider/builtin/${toolPayload.provider}/oauth/custom-client`,
- )
+ expect(mockUseDeletePluginOAuthCustomClient).toHaveBeenCalledWith(toolPayload)
})
})
})
diff --git a/web/app/components/plugins/plugin-auth/hooks/get-api.ts b/web/app/components/plugins/plugin-auth/hooks/get-api.ts
index 959476cf437..e550e19600c 100644
--- a/web/app/components/plugins/plugin-auth/hooks/get-api.ts
+++ b/web/app/components/plugins/plugin-auth/hooks/get-api.ts
@@ -1,53 +1,9 @@
-import type { CredentialTypeEnum, PluginPayload } from '../types'
+import type { PluginPayload } from '../types'
import { AuthCategory } from '../types'
-export const getApi = ({ category = AuthCategory.tool, provider }: PluginPayload) => {
- if (category === AuthCategory.tool) {
- return {
- getCredentialInfo: `/workspaces/current/tool-provider/builtin/${provider}/credential/info`,
- setDefaultCredential: `/workspaces/current/tool-provider/builtin/${provider}/default-credential`,
- getCredentials: `/workspaces/current/tool-provider/builtin/${provider}/credentials`,
- addCredential: `/workspaces/current/tool-provider/builtin/${provider}/add`,
- updateCredential: `/workspaces/current/tool-provider/builtin/${provider}/update`,
- deleteCredential: `/workspaces/current/tool-provider/builtin/${provider}/delete`,
- getCredentialSchema: (credential_type: CredentialTypeEnum) =>
- `/workspaces/current/tool-provider/builtin/${provider}/credential/schema/${credential_type}`,
- getOauthUrl: `/oauth/plugin/${provider}/tool/authorization-url`,
- getOauthClientSchema: `/workspaces/current/tool-provider/builtin/${provider}/oauth/client-schema`,
- setCustomOauthClient: `/workspaces/current/tool-provider/builtin/${provider}/oauth/custom-client`,
- getCustomOAuthClientValues: `/workspaces/current/tool-provider/builtin/${provider}/oauth/custom-client`,
- deleteCustomOAuthClient: `/workspaces/current/tool-provider/builtin/${provider}/oauth/custom-client`,
- }
- }
-
- if (category === AuthCategory.datasource) {
- return {
- getCredentialInfo: '',
- setDefaultCredential: `/auth/plugin/datasource/${provider}/default`,
- getCredentials: `/auth/plugin/datasource/${provider}`,
- addCredential: `/auth/plugin/datasource/${provider}`,
- updateCredential: `/auth/plugin/datasource/${provider}/update`,
- deleteCredential: `/auth/plugin/datasource/${provider}/delete`,
- getCredentialSchema: () => '',
- getOauthUrl: `/oauth/plugin/${provider}/datasource/get-authorization-url`,
- getOauthClientSchema: '',
- setCustomOauthClient: `/auth/plugin/datasource/${provider}/custom-client`,
- deleteCustomOAuthClient: `/auth/plugin/datasource/${provider}/custom-client`,
- }
- }
-
- return {
- getCredentialInfo: '',
- setDefaultCredential: '',
- getCredentials: '',
- addCredential: '',
- updateCredential: '',
- deleteCredential: '',
- getCredentialSchema: () => '',
- getOauthUrl: '',
- getOauthClientSchema: '',
- setCustomOauthClient: '',
- getCustomOAuthClientValues: '',
- deleteCustomOAuthClient: '',
- }
-}
+export const getApi = ({ category = AuthCategory.tool, provider }: PluginPayload) => ({
+ getCredentialInfo:
+ category === AuthCategory.tool
+ ? `/workspaces/current/tool-provider/builtin/${provider}/credential/info`
+ : '',
+})
diff --git a/web/app/components/plugins/plugin-auth/hooks/use-credential.ts b/web/app/components/plugins/plugin-auth/hooks/use-credential.ts
index 40995dc8d4d..62eba0b9121 100644
--- a/web/app/components/plugins/plugin-auth/hooks/use-credential.ts
+++ b/web/app/components/plugins/plugin-auth/hooks/use-credential.ts
@@ -34,9 +34,7 @@ export const useGetPluginCredentialInfoHook = (
}
export const useDeletePluginCredentialHook = (pluginPayload: PluginPayload) => {
- const apiMap = getApi(pluginPayload)
-
- return useDeletePluginCredential(apiMap.deleteCredential)
+ return useDeletePluginCredential(pluginPayload)
}
export const useInvalidPluginCredentialInfoHook = (pluginPayload: PluginPayload) => {
@@ -52,58 +50,40 @@ export const useInvalidPluginCredentialInfoHook = (pluginPayload: PluginPayload)
}
export const useSetPluginDefaultCredentialHook = (pluginPayload: PluginPayload) => {
- const apiMap = getApi(pluginPayload)
-
- return useSetPluginDefaultCredential(apiMap.setDefaultCredential)
+ return useSetPluginDefaultCredential(pluginPayload)
}
export const useGetPluginCredentialSchemaHook = (
pluginPayload: PluginPayload,
credentialType: CredentialTypeEnum,
) => {
- const apiMap = getApi(pluginPayload)
-
- return useGetPluginCredentialSchema(apiMap.getCredentialSchema(credentialType))
+ return useGetPluginCredentialSchema(pluginPayload, credentialType)
}
export const useAddPluginCredentialHook = (pluginPayload: PluginPayload) => {
- const apiMap = getApi(pluginPayload)
-
- return useAddPluginCredential(apiMap.addCredential)
+ return useAddPluginCredential(pluginPayload)
}
export const useUpdatePluginCredentialHook = (pluginPayload: PluginPayload) => {
- const apiMap = getApi(pluginPayload)
-
- return useUpdatePluginCredential(apiMap.updateCredential)
+ return useUpdatePluginCredential(pluginPayload)
}
export const useGetPluginOAuthUrlHook = (pluginPayload: PluginPayload) => {
- const apiMap = getApi(pluginPayload)
-
- return useGetPluginOAuthUrl(apiMap.getOauthUrl)
+ return useGetPluginOAuthUrl(pluginPayload)
}
export const useGetPluginOAuthClientSchemaHook = (pluginPayload: PluginPayload, enabled = true) => {
- const apiMap = getApi(pluginPayload)
-
- return useGetPluginOAuthClientSchema(enabled ? apiMap.getOauthClientSchema : '')
+ return useGetPluginOAuthClientSchema(pluginPayload, enabled)
}
export const useInvalidPluginOAuthClientSchemaHook = (pluginPayload: PluginPayload) => {
- const apiMap = getApi(pluginPayload)
-
- return useInvalidPluginOAuthClientSchema(apiMap.getOauthClientSchema)
+ return useInvalidPluginOAuthClientSchema(pluginPayload)
}
export const useSetPluginOAuthCustomClientHook = (pluginPayload: PluginPayload) => {
- const apiMap = getApi(pluginPayload)
-
- return useSetPluginOAuthCustomClient(apiMap.setCustomOauthClient)
+ return useSetPluginOAuthCustomClient(pluginPayload)
}
export const useDeletePluginOAuthCustomClientHook = (pluginPayload: PluginPayload) => {
- const apiMap = getApi(pluginPayload)
-
- return useDeletePluginOAuthCustomClient(apiMap.deleteCustomOAuthClient)
+ return useDeletePluginOAuthCustomClient(pluginPayload)
}
diff --git a/web/app/components/plugins/plugin-detail-panel/app-selector/__tests__/app-inputs-form.spec.tsx b/web/app/components/plugins/plugin-detail-panel/app-selector/__tests__/app-inputs-form.spec.tsx
index d4f76594e4a..6b277c9bcd1 100644
--- a/web/app/components/plugins/plugin-detail-panel/app-selector/__tests__/app-inputs-form.spec.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/app-selector/__tests__/app-inputs-form.spec.tsx
@@ -1,16 +1,19 @@
-import type { ComponentProps } from 'react'
+import type { ComponentProps, ReactNode } from 'react'
import type { FileUploaderInAttachmentWrapperProps } from '@/app/components/base/file-uploader/file-uploader-in-attachment'
import type { fileUpload } from '@/app/components/base/file-uploader/utils'
import { zAppAgentModePayload } from '@dify/contracts/api/console/apps/zod.gen'
-import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { fireEvent, render as rtlRender, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useRef, useState } from 'react'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import { useFile } from '@/app/components/base/file-uploader/hooks'
import { FileContextProvider, useStore } from '@/app/components/base/file-uploader/store'
import { InputVarType } from '@/app/components/workflow/types'
+import { createConsoleQueryWrapper } from '@/test/console/query-data'
import AppInputsForm from '../app-inputs-form'
+const render = (ui: ReactNode) => rtlRender(ui, { wrapper: createConsoleQueryWrapper().wrapper })
+
const mockFileUpload = vi.hoisted(() => vi.fn<typeof fileUpload>())
vi.mock('@/next/navigation', () => ({
diff --git a/web/app/components/rag-pipeline/components/panel/__tests__/index.spec.tsx b/web/app/components/rag-pipeline/components/panel/__tests__/index.spec.tsx
index 8844f6ca624..ba5da7e00eb 100644
--- a/web/app/components/rag-pipeline/components/panel/__tests__/index.spec.tsx
+++ b/web/app/components/rag-pipeline/components/panel/__tests__/index.spec.tsx
@@ -29,18 +29,16 @@ const api = vi.hoisted(() => ({
history: vi.fn<(url: string, options?: unknown) => Promise<FetchWorkflowDraftPageResponse>>(),
update:
vi.fn<
- (
- url: string,
- options: { body: { marked_name: string; marked_comment: string } },
- ) => Promise<ReturnType<typeof createWorkflowResponseFixture>>
+ typeof import('@/service/console').consoleClient.rag.pipelines.byPipelineId.workflows.byWorkflowId.patch
+ >(),
+ remove:
+ vi.fn<
+ typeof import('@/service/console').consoleClient.rag.pipelines.byPipelineId.workflows.byWorkflowId.delete
>(),
- remove: vi.fn<(url: string) => Promise<void>>(),
}))
vi.mock('@/service/base', async (importOriginal) => ({
...(await importOriginal<typeof import('@/service/base')>()),
get: api.history,
- patch: api.update,
- del: api.remove,
}))
vi.mock('@/next/navigation', async (importOriginal) => ({
...(await importOriginal<typeof import('@/next/navigation')>()),
@@ -53,6 +51,8 @@ vi.mock('@/service/console', async (importOriginal) => {
return {
...actual,
consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'rag.pipelines.byPipelineId.workflows.byWorkflowId.patch': api.update,
+ 'rag.pipelines.byPipelineId.workflows.byWorkflowId.delete': api.remove,
'rag.pipelines.byPipelineId.workflows.draft.preProcessing.parameters.get': async () => ({
variables: [],
}),
@@ -176,9 +176,15 @@ beforeEach(() => {
if (url !== '/rag/pipelines/pipeline-1/workflows') throw new Error(`Unexpected GET: ${url}`)
return { items: versions, page: 1, limit: 10, total: versions.length, has_more: false }
})
- api.update.mockReset().mockImplementation(async (_url, { body }) => {
- versions = [version(body)]
- return createWorkflowResponseFixture({ ...body, id: 'release-1' })
+ api.update.mockReset().mockImplementation(async ({ body }) => {
+ versions = [
+ version({ marked_name: body.marked_name ?? '', marked_comment: body.marked_comment ?? '' }),
+ ]
+ return createWorkflowResponseFixture({
+ marked_name: body.marked_name ?? '',
+ marked_comment: body.marked_comment ?? '',
+ id: 'release-1',
+ })
})
api.remove.mockReset().mockImplementation(async () => {
versions = []
@@ -209,20 +215,18 @@ it('loads, edits and deletes versions belonging to this pipeline', async () => {
await user.type(title, 'Pipeline v2')
await user.click(within(dialog).getByRole('button', { name: 'common.operation.save' }))
expect(await screen.findByText('Pipeline v2')).toBeVisible()
- expect(api.update).toHaveBeenCalledExactlyOnceWith(
- '/rag/pipelines/pipeline-1/workflows/release-1',
- {
- body: { marked_name: 'Pipeline v2', marked_comment: '' },
- },
- )
+ expect(api.update).toHaveBeenCalledExactlyOnceWith({
+ params: { pipeline_id: 'pipeline-1', workflow_id: 'release-1' },
+ body: { marked_name: 'Pipeline v2', marked_comment: '' },
+ })
await user.click(screen.getByRole('button', { name: 'common.operation.more' }))
await user.click(await screen.findByRole('menuitem', { name: 'common.operation.delete' }))
const confirm = await screen.findByRole('alertdialog')
await user.click(within(confirm).getByRole('button', { name: 'common.operation.delete' }))
await waitFor(() =>
- expect(api.remove).toHaveBeenCalledExactlyOnceWith(
- '/rag/pipelines/pipeline-1/workflows/release-1',
- ),
+ expect(api.remove).toHaveBeenCalledExactlyOnceWith({
+ params: { pipeline_id: 'pipeline-1', workflow_id: 'release-1' },
+ }),
)
await waitFor(() => expect(screen.queryByText('Pipeline v2')).not.toBeInTheDocument())
})
diff --git a/web/app/components/rag-pipeline/components/panel/index.tsx b/web/app/components/rag-pipeline/components/panel/index.tsx
index cd3432a1b7c..6ce31d6b141 100644
--- a/web/app/components/rag-pipeline/components/panel/index.tsx
+++ b/web/app/components/rag-pipeline/components/panel/index.tsx
@@ -62,10 +62,6 @@ const RagPipelinePanel = () => {
const versionHistoryPanelProps = useMemo(() => {
return {
getVersionListUrl: `/rag/pipelines/${pipelineId}/workflows`,
- deleteVersionUrl: (versionId: string) =>
- `/rag/pipelines/${pipelineId}/workflows/${versionId}`,
- updateVersionUrl: (versionId: string) =>
- `/rag/pipelines/${pipelineId}/workflows/${versionId}`,
latestVersionId: '',
}
}, [pipelineId])
diff --git a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/index.spec.tsx b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/index.spec.tsx
index 70bcf415c52..9929cf8b80e 100644
--- a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/index.spec.tsx
+++ b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/__tests__/index.spec.tsx
@@ -1,4 +1,4 @@
-import type { WorkflowPublishResponse } from '@dify/contracts/api/console/apps/types.gen'
+import type { RagPipelineWorkflowPublishResponse } from '@dify/contracts/api/console/rag/types.gen'
import type { InjectWorkflowStoreSliceFn } from '@/app/components/workflow/store'
import type { Node } from '@/app/components/workflow/types'
import { act, cleanup, screen, waitFor, within } from '@testing-library/react'
@@ -37,10 +37,7 @@ const api = vi.hoisted(() => ({
>(),
publish:
vi.fn<
- (
- url: string,
- options: { body: { marked_name: string; marked_comment: string } },
- ) => Promise<WorkflowPublishResponse>
+ typeof import('@/service/console').consoleClient.rag.pipelines.byPipelineId.workflows.publish.post
>(),
template:
vi.fn<
@@ -54,10 +51,6 @@ vi.mock('@/next/navigation', async (importOriginal) => ({
usePathname: () => '/datasets/dataset-1/pipeline',
useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
}))
-vi.mock('@/service/base', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@/service/base')>()),
- post: api.publish,
-}))
vi.mock('@/service/console', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/service/console')>()
const { withConsoleClientResponses, withConsoleResponses } =
@@ -72,6 +65,7 @@ vi.mock('@/service/console', async (importOriginal) => {
}),
}),
consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'rag.pipelines.byPipelineId.workflows.publish.post': api.publish,
'rag.pipelines.byPipelineId.workflows.publish.get': async () =>
createWorkflowResponseFixture(),
'rag.pipelines.byPipelineId.customized.publish.post': api.template,
@@ -260,10 +254,7 @@ it('publishes a valid pipeline and updates its publication state and dataset cac
await waitFor(() =>
expect(screen.getByRole('button', { name: 'workflow.common.published' })).toBeDisabled(),
)
- expect(api.publish).toHaveBeenCalledExactlyOnceWith(
- '/rag/pipelines/pipeline-1/workflows/publish',
- { body: { marked_name: '', marked_comment: '' } },
- )
+ expect(api.publish).toHaveBeenCalledExactlyOnceWith({ params: { pipeline_id: 'pipeline-1' } })
expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()
expect(screen.getByRole('link', { name: 'pipeline.common.goToAddDocuments' })).toHaveAttribute(
'href',
@@ -340,7 +331,7 @@ it('keeps the draft available after a publish failure and supports retry', async
it('publishes with the scoped shortcut and suppresses repeats during and after publication', async () => {
const user = userEvent.setup()
- const pending = createDeferred<WorkflowPublishResponse>()
+ const pending = createDeferred<RagPipelineWorkflowPublishResponse>()
api.publish.mockReturnValueOnce(pending.promise)
renderPipeline()
const button = await openPublisher(user)
diff --git a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/popup.tsx b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/popup.tsx
index 46ad9fa7dfe..dec0ee3ef40 100644
--- a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/popup.tsx
+++ b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/popup.tsx
@@ -15,7 +15,7 @@ import { Kbd, KbdGroup } from '@langgenius/dify-ui/kbd'
import { Separator } from '@langgenius/dify-ui/separator'
import { RiArrowRightUpLine, RiPlayCircleLine, RiTerminalBoxLine } from '@remixicon/react'
import { formatForDisplay, useHotkey } from '@tanstack/react-hotkeys'
-import { useQuery, useQueryClient, useSuspenseQuery } from '@tanstack/react-query'
+import { useMutation, useQuery, useSuspenseQuery } from '@tanstack/react-query'
import { useBoolean } from 'ahooks'
import { useAtomValue } from 'jotai'
import { useQueryState } from 'nuqs'
@@ -43,7 +43,6 @@ import { useFormatTimeFromNow } from '@/hooks/use-format-time-from-now'
import Link from '@/next/link'
import { useParams } from '@/next/navigation'
import { consoleQuery } from '@/service/console'
-import { usePublishWorkflow } from '@/service/use-workflow'
import { getDatasetACLCapabilities } from '@/utils/permission'
import { RAG_PIPELINE_PUBLISH_HOTKEY } from '../hotkeys'
@@ -85,7 +84,9 @@ export function Popup({
const [published, setPublished] = useState(false)
const { formatTimeFromNow } = useFormatTimeFromNow()
const { handleCheckBeforePublish } = useChecklistBeforePublish()
- const { mutateAsync: publishWorkflow } = usePublishWorkflow()
+ const { mutateAsync: publishWorkflow } = useMutation(
+ consoleQuery.rag.pipelines.byPipelineId.workflows.publish.post.mutationOptions(),
+ )
const workflowStore = useWorkflowStore()
const { data: isAllowPublishAsCustomKnowledgePipelineTemplate } = useQuery(
consoleQuery.features.get.queryOptions({
@@ -107,10 +108,6 @@ export function Popup({
const showConfirm = onShowConfirm ?? showLocalConfirm
const hideConfirm = onHideConfirm ?? hideLocalConfirm
const [publishing, { setFalse: hidePublishing, setTrue: showPublishing }] = useBoolean(false)
- const queryClient = useQueryClient()
- const invalidDatasetList = useCallback(() => {
- queryClient.invalidateQueries({ queryKey: consoleQuery.datasets.get.key() })
- }, [queryClient])
const handleHideConfirm = useCallback(() => {
hideConfirm()
onRequestClose?.()
@@ -129,9 +126,7 @@ export function Popup({
startedPublishing = true
showPublishing()
const res = await publishWorkflow({
- url: `/rag/pipelines/${pipelineId}/workflows/publish`,
- title: params?.title || '',
- releaseNotes: params?.releaseNotes || '',
+ params: { pipeline_id: pipelineId },
})
setPublished(true)
trackEvent('app_published_time', {
@@ -163,12 +158,6 @@ export function Popup({
)
workflowStore.getState().setPublishedAt(res.created_at)
mutateDatasetRes?.()
- queryClient.invalidateQueries({
- queryKey: consoleQuery.rag.pipelines.byPipelineId.workflows.publish.get.queryKey({
- input: { params: { pipeline_id: pipelineId || '' } },
- }),
- })
- invalidDatasetList()
}
}
} catch {
@@ -191,8 +180,6 @@ export function Popup({
t,
workflowStore,
mutateDatasetRes,
- queryClient,
- invalidDatasetList,
hidePublishing,
handleHideConfirm,
],
diff --git a/web/app/components/rag-pipeline/hooks/__tests__/use-DSL.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/use-DSL.spec.ts
index 9bf96603c28..bb656cc4cc7 100644
--- a/web/app/components/rag-pipeline/hooks/__tests__/use-DSL.spec.ts
+++ b/web/app/components/rag-pipeline/hooks/__tests__/use-DSL.spec.ts
@@ -43,6 +43,7 @@ vi.mock('../use-nodes-sync-draft', () => ({
}))
const mockExportPipelineConfig = vi.fn()
+const mockFetchWorkflowDraft = vi.fn()
vi.mock('@/service/console', async (importOriginal) => ({
...(await importOriginal<typeof import('@/service/console')>()),
consoleClient: {
@@ -50,17 +51,15 @@ vi.mock('@/service/console', async (importOriginal) => ({
pipelines: {
byPipelineId: {
exports: { get: (...args: unknown[]) => mockExportPipelineConfig(...args) },
+ workflows: {
+ draft: { get: (...args: unknown[]) => mockFetchWorkflowDraft(...args) },
+ },
},
},
},
},
}))
-const mockFetchWorkflowDraft = vi.fn()
-vi.mock('@/service/workflow', () => ({
- fetchWorkflowDraft: (...args: unknown[]) => mockFetchWorkflowDraft(...args),
-}))
-
const mockDownloadBlob = vi.fn()
vi.mock('@/utils/download', () => ({
downloadBlob: (...args: unknown[]) => mockDownloadBlob(...args),
@@ -162,7 +161,8 @@ describe('useDSLByCanEdit', () => {
await waitFor(() => {
expect(mockFetchWorkflowDraft).toHaveBeenCalledWith(
- '/rag/pipelines/test-pipeline-id/workflows/draft',
+ { params: { pipeline_id: 'test-pipeline-id' } },
+ { context: { silent: true } },
)
expect(mockDoSyncWorkflowDraft).toHaveBeenCalled()
})
diff --git a/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-config.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-config.spec.ts
index 25231d6ce6a..cdbfe2af12a 100644
--- a/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-config.spec.ts
+++ b/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-config.spec.ts
@@ -7,16 +7,19 @@ import { WorkflowContext } from '@/app/components/workflow/context'
import { EditorResourceScope } from '@/app/components/workflow/editor-resource/provider'
import { createWorkflowStore } from '@/app/components/workflow/store'
import { consoleQuery } from '@/service/console'
+import { createFileUploadConfigFixture } from '@/test/fixtures/file-upload-config'
+import { createWorkflowResponseFixture } from '@/test/fixtures/workflow-response'
import { createDatasourceProvider } from '../../__tests__/datasource-fixtures'
import { createRagPipelineSliceSlice } from '../../store'
import { usePipelineConfig } from '../use-pipeline-config'
const mocks = vi.hoisted(() => ({
request: vi.fn<(url: string) => Promise<Response>>(),
- workflowConfig: vi.fn<(url: string, callback: (data: unknown) => void) => void>(),
+ catalog: vi.fn<() => Promise<Response>>(),
+ defaults: vi.fn<(url: string) => Promise<Response>>(),
+ published: vi.fn<(url: string) => Promise<Response>>(),
}))
vi.mock('@/service/base', () => ({ request: mocks.request }))
-vi.mock('@/service/use-workflow', () => ({ useWorkflowConfig: mocks.workflowConfig }))
const catalog = consoleQuery.rag.pipelines.datasourcePlugins.get
@@ -39,7 +42,16 @@ describe('usePipelineConfig', () => {
client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: Infinity } } })
store = createWorkflowStore({ injectWorkflowStoreSliceFn: createRagPipelineSliceSlice })
pipelineId = 'pipeline-1'
- mocks.request.mockResolvedValue(Response.json([]))
+ mocks.catalog.mockImplementation(async () => Response.json([]))
+ mocks.defaults.mockImplementation(async () => Response.json([]))
+ mocks.published.mockImplementation(async () => Response.json(null))
+ mocks.request.mockImplementation(async (url) => {
+ if (url.endsWith('/datasource-plugins')) return mocks.catalog()
+ if (url.endsWith('/default-workflow-block-configs')) return mocks.defaults(url)
+ if (url.endsWith('/publish')) return mocks.published(url)
+ if (url.endsWith('/files/upload')) return Response.json(createFileUploadConfigFixture())
+ throw new Error(`Unexpected request ${url}`)
+ })
})
afterEach(() => client.clear())
@@ -47,7 +59,7 @@ describe('usePipelineConfig', () => {
const cached = [createDatasourceProvider()]
client.setQueryData(catalog.queryKey(), cached)
let resolveRequest!: (response: Response) => void
- mocks.request.mockReturnValue(
+ mocks.catalog.mockReturnValue(
new Promise((resolve) => {
resolveRequest = resolve
}),
@@ -60,8 +72,12 @@ describe('usePipelineConfig', () => {
const refreshed = [createDatasourceProvider({ is_authorized: false })]
await act(async () => resolveRequest(Response.json(refreshed)))
await waitFor(() => expect(store.getState().dataSourceList).toEqual(refreshed))
- expect(mocks.request).toHaveBeenCalledOnce()
- expect(mocks.request.mock.calls[0]?.[0]).toContain('/rag/pipelines/datasource-plugins')
+ expect(mocks.catalog).toHaveBeenCalledOnce()
+ expect(mocks.request).toHaveBeenCalledWith(
+ expect.stringContaining('/rag/pipelines/datasource-plugins'),
+ expect.anything(),
+ expect.anything(),
+ )
expect(client.getQueryData(catalog.queryKey())).toEqual(refreshed)
expect(store.getState().dataSourceList).toBe(client.getQueryData(catalog.queryKey()))
expect(cached[0]?.declaration.identity.icon).toBe('/datasource.svg')
@@ -69,14 +85,14 @@ describe('usePipelineConfig', () => {
it('reconciles an empty catalog on background invalidation', async () => {
const providers = [createDatasourceProvider()]
- mocks.request.mockResolvedValueOnce(Response.json(providers))
+ mocks.catalog.mockResolvedValueOnce(Response.json(providers))
renderHook(usePipelineConfig, { wrapper })
await waitFor(() => expect(store.getState().dataSourceList).toEqual(providers))
await act(async () => client.invalidateQueries({ queryKey: catalog.key() }))
await waitFor(() => expect(store.getState().dataSourceList).toEqual([]))
- expect(mocks.request).toHaveBeenCalledTimes(2)
+ expect(mocks.catalog).toHaveBeenCalledTimes(2)
})
it('does not request or hydrate datasource state before a pipeline is available', () => {
@@ -84,15 +100,16 @@ describe('usePipelineConfig', () => {
client.setQueryData(catalog.queryKey(), [createDatasourceProvider()])
renderHook(usePipelineConfig, { wrapper })
- expect(mocks.request).not.toHaveBeenCalled()
+ expect(mocks.catalog).not.toHaveBeenCalled()
expect(store.getState().dataSourceList).toEqual([])
- expect(mocks.workflowConfig).toHaveBeenCalledWith('', expect.any(Function))
+ expect(mocks.defaults).not.toHaveBeenCalled()
+ expect(mocks.published).not.toHaveBeenCalled()
})
it('fetches and synchronizes when the pipeline becomes available', async () => {
pipelineId = ''
const providers = [createDatasourceProvider()]
- mocks.request.mockResolvedValue(Response.json(providers))
+ mocks.catalog.mockResolvedValue(Response.json(providers))
const { rerender } = renderHook(usePipelineConfig, { wrapper })
pipelineId = 'pipeline-2'
@@ -104,49 +121,89 @@ describe('usePipelineConfig', () => {
it('keeps cached data when refreshing fails without retrying the availability request', async () => {
const providers = [createDatasourceProvider()]
client.setQueryData(catalog.queryKey(), providers)
- mocks.request.mockRejectedValue(new Error('Datasource catalog unavailable'))
+ mocks.catalog.mockRejectedValue(new Error('Datasource catalog unavailable'))
renderHook(usePipelineConfig, { wrapper })
await waitFor(() => expect(client.getQueryState(catalog.queryKey())?.status).toBe('error'))
expect(client.getQueryState(catalog.queryKey())?.fetchFailureCount).toBe(1)
- expect(mocks.request).toHaveBeenCalledOnce()
+ expect(mocks.catalog).toHaveBeenCalledOnce()
expect(store.getState().dataSourceList).toEqual(providers)
})
- it('retains the other pipeline configuration entrypoints', () => {
+ it('hydrates all configuration from the generated cache before refreshing', async () => {
+ const workflows = consoleQuery.rag.pipelines.byPipelineId.workflows
+ const input = { params: { pipeline_id: pipelineId } }
+ const defaultsKey = workflows.defaultWorkflowBlockConfigs.get.queryKey({ input })
+ const publishKey = workflows.publish.get.queryKey({ input })
+ const uploadKey = consoleQuery.files.upload.get.queryKey()
+ const config = [{ type: 'llm', config: { model: 'cached' } }]
+ const upload = createFileUploadConfigFixture({ file_size_limit: 23 })
+ client.setQueryData(defaultsKey, config)
+ client.setQueryData(publishKey, createWorkflowResponseFixture({ created_at: 123 }))
+ client.setQueryData(uploadKey, upload)
+ // Keep refreshes pending so only cached data can hydrate the new editor.
+ mocks.request.mockImplementation(() => new Promise(() => {}))
+
+ const { unmount } = renderHook(usePipelineConfig, { wrapper })
+
+ expect(store.getState().nodesDefaultConfigs).toEqual({ llm: { model: 'cached' } })
+ expect(store.getState().publishedAt).toBe(123_000)
+ expect(store.getState().fileUploadConfig).toEqual(upload)
+ unmount()
+ store = createWorkflowStore({ injectWorkflowStoreSliceFn: createRagPipelineSliceSlice })
renderHook(usePipelineConfig, { wrapper })
- expect(mocks.workflowConfig).toHaveBeenCalledWith(
- '/rag/pipelines/pipeline-1/workflows/default-workflow-block-configs',
- expect.any(Function),
+ expect(store.getState().nodesDefaultConfigs).toEqual({ llm: { model: 'cached' } })
+ expect(store.getState().publishedAt).toBe(123_000)
+ expect(store.getState().fileUploadConfig).toEqual(upload)
+ })
+
+ it('refreshes node defaults and clears the published timestamp for an unpublished pipeline', async () => {
+ mocks.defaults.mockResolvedValueOnce(
+ Response.json([{ type: 'llm', config: { model: 'first' } }]),
+ )
+ mocks.published.mockResolvedValueOnce(
+ Response.json(createWorkflowResponseFixture({ created_at: 123 })),
)
- expect(mocks.workflowConfig).toHaveBeenCalledWith(
- '/rag/pipelines/pipeline-1/workflows/publish',
- expect.any(Function),
+ renderHook(usePipelineConfig, { wrapper })
+ await waitFor(() => expect(store.getState().publishedAt).toBe(123_000))
+ expect(store.getState().nodesDefaultConfigs).toEqual({ llm: { model: 'first' } })
+
+ await act(async () =>
+ client.invalidateQueries({
+ queryKey: consoleQuery.rag.pipelines.byPipelineId.workflows.key(),
+ }),
)
- expect(mocks.workflowConfig).toHaveBeenCalledWith('/files/upload', expect.any(Function))
+
+ await waitFor(() => expect(store.getState().publishedAt).toBe(0))
+ expect(store.getState().nodesDefaultConfigs).toEqual({})
})
- it.each([[{ type: 'llm', config: { model: 'test' } }], { llm: { model: 'test' } }])(
- 'retains default node configuration normalization',
- (config) => {
- renderHook(usePipelineConfig, { wrapper })
- const callback = mocks.workflowConfig.mock.calls.find(([url]) =>
- url.endsWith('default-workflow-block-configs'),
- )?.[1]
- act(() => callback?.(config))
- expect(store.getState().nodesDefaultConfigs).toEqual({ llm: { model: 'test' } })
- },
- )
-
- it.each([{ created_at: 123 }, null])(
- 'retains the publication timestamp fallback',
- (published) => {
- renderHook(usePipelineConfig, { wrapper })
- const callback = mocks.workflowConfig.mock.calls.find(([url]) =>
- url.endsWith('/publish'),
- )?.[1]
- act(() => callback?.(published))
- expect(store.getState().publishedAt).toBe((published?.created_at ?? 0) * 1000)
- },
- )
+ it('does not apply a previous pipeline response after switching editors', async () => {
+ let resolvePrevious!: (response: Response) => void
+ mocks.defaults.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolvePrevious = resolve
+ }),
+ )
+ mocks.defaults.mockResolvedValueOnce(
+ Response.json([{ type: 'llm', config: { model: 'second' } }]),
+ )
+ const { rerender } = renderHook(usePipelineConfig, { wrapper })
+ await waitFor(() => expect(mocks.defaults).toHaveBeenCalledOnce())
+
+ pipelineId = 'pipeline-2'
+ rerender()
+ await waitFor(() =>
+ expect(store.getState().nodesDefaultConfigs).toEqual({ llm: { model: 'second' } }),
+ )
+ await act(async () =>
+ resolvePrevious(Response.json([{ type: 'llm', config: { model: 'first' } }])),
+ )
+
+ expect(store.getState().nodesDefaultConfigs).toEqual({ llm: { model: 'second' } })
+ expect(mocks.defaults).toHaveBeenLastCalledWith(
+ expect.stringContaining('/pipelines/pipeline-2/'),
+ )
+ })
})
diff --git a/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-init.spec.tsx b/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-init.spec.tsx
index 1bae28121ab..ced87926b09 100644
--- a/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-init.spec.tsx
+++ b/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-init.spec.tsx
@@ -11,10 +11,12 @@ import { createRagPipelineSliceSlice } from '../../store'
import { usePipelineInit } from '../use-pipeline-init'
const mockFetchWorkflowDraft = vi.fn()
-const mockSyncWorkflowDraft = vi.fn()
+const mockRequest = vi.hoisted(() => vi.fn<typeof import('@/service/base').request>())
+vi.mock('@/service/base', () => ({
+ request: mockRequest,
+}))
vi.mock('@/service/workflow', () => ({
fetchWorkflowDraft: (url: string) => mockFetchWorkflowDraft(url),
- syncWorkflowDraft: (params: unknown) => mockSyncWorkflowDraft(params),
}))
// Default block/publish/upload config queries are covered by use-pipeline-config.spec.
@@ -133,7 +135,7 @@ describe('usePipelineInit', () => {
}),
)
mockFetchWorkflowDraft.mockResolvedValueOnce(createDraft({ hash: 'new-hash' }))
- mockSyncWorkflowDraft.mockResolvedValue({ updated_at: 1_704_153_600 })
+ mockRequest.mockResolvedValue(Response.json({ updated_at: 1_704_153_600 }))
const { result, store } = renderPipelineInit()
await waitFor(() => expect(result.current.data?.hash).toBe('new-hash'))
@@ -142,15 +144,18 @@ describe('usePipelineInit', () => {
shouldAutoOpenStartNodeSelector: true,
isWorkflowDataLoaded: true,
})
- expect(mockSyncWorkflowDraft).toHaveBeenCalledExactlyOnceWith({
- url: '/rag/pipelines/test-pipeline-id/workflows/draft',
- params: {
- graph: {
- nodes: [expect.objectContaining({ id: 'knowledgeBase' })],
- edges: [],
- },
- environment_variables: [],
+ expect(mockRequest).toHaveBeenCalledOnce()
+ const request = mockRequest.mock.calls[0]![2]!.request!
+ expect(new URL(request.url).pathname).toBe(
+ '/console/api/rag/pipelines/test-pipeline-id/workflows/draft',
+ )
+ expect(request.method).toBe('POST')
+ await expect(request.json()).resolves.toEqual({
+ graph: {
+ nodes: [expect.objectContaining({ id: 'knowledgeBase' })],
+ edges: [],
},
+ environment_variables: [],
})
})
})
diff --git a/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-run.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-run.spec.ts
index 6a5e118cae2..10fd97382d3 100644
--- a/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-run.spec.ts
+++ b/web/app/components/rag-pipeline/hooks/__tests__/use-pipeline-run.spec.ts
@@ -1,7 +1,7 @@
import type { InjectWorkflowStoreSliceFn } from '@/app/components/workflow/store/workflow'
import type { EnvironmentVariable } from '@/app/components/workflow/types'
import type { FetchWorkflowDraftResponse } from '@/types/workflow'
-import { act } from '@testing-library/react'
+import { act, waitFor } from '@testing-library/react'
import { useNodes } from 'reactflow'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import { createEdge, createNode } from '@/app/components/workflow/__tests__/fixtures'
@@ -48,14 +48,14 @@ vi.mock('@/app/components/workflow/hooks/use-fetch-workflow-inspect-vars', () =>
useSetWorkflowVarsWithValue: () => ({ fetchInspectVars: mockFetchInspectVars }),
}))
+const mockStopWorkflowRun = vi
+ .fn()
+ .mockImplementation(async () => Response.json({ result: 'success' }))
+
const mockSsePost = vi.fn()
vi.mock('@/service/base', () => ({
ssePost: (...args: unknown[]) => mockSsePost(...args),
-}))
-
-const mockStopWorkflowRun = vi.fn()
-vi.mock('@/service/workflow', () => ({
- stopWorkflowRun: (url: string) => mockStopWorkflowRun(url),
+ request: (...args: unknown[]) => mockStopWorkflowRun(...args),
}))
const mockInvalidAllLastRun = vi.fn()
@@ -347,8 +347,14 @@ describe('usePipelineRunByCanEdit', () => {
act(() => result.current.run.handleStopRun('task-123'))
- expect(mockStopWorkflowRun).toHaveBeenCalledExactlyOnceWith(
- '/rag/pipelines/test-pipeline-id/workflow-runs/tasks/task-123/stop',
+ await waitFor(() =>
+ expect(mockStopWorkflowRun).toHaveBeenCalledWith(
+ expect.stringContaining(
+ '/rag/pipelines/test-pipeline-id/workflow-runs/tasks/task-123/stop',
+ ),
+ expect.anything(),
+ expect.anything(),
+ ),
)
expect(controller.signal.aborted).toBe(true)
})
diff --git a/web/app/components/rag-pipeline/hooks/use-DSL.ts b/web/app/components/rag-pipeline/hooks/use-DSL.ts
index 40d57657de8..53c0666137d 100644
--- a/web/app/components/rag-pipeline/hooks/use-DSL.ts
+++ b/web/app/components/rag-pipeline/hooks/use-DSL.ts
@@ -10,7 +10,6 @@ import { useWorkflowStore } from '@/app/components/workflow/store'
import { toast } from '@/app/notifications'
import { useEventEmitterContextContext } from '@/context/event-emitter'
import { consoleClient } from '@/service/console'
-import { fetchWorkflowDraft } from '@/service/workflow'
import { downloadBlob } from '@/utils/download'
import { useNodesSyncDraftByCanEdit } from './use-nodes-sync-draft'
@@ -62,10 +61,11 @@ const useDSLBase = (doSyncWorkflowDraft: DoSyncWorkflowDraft) => {
const exportCheck = useCallback(async () => {
if (!pipelineId) return
try {
- const workflowDraft = await fetchWorkflowDraft(`/rag/pipelines/${pipelineId}/workflows/draft`)
- const list = (workflowDraft.environment_variables || []).filter(
- (env) => env.value_type === 'secret',
+ const workflowDraft = await consoleClient.rag.pipelines.byPipelineId.workflows.draft.get(
+ { params: { pipeline_id: pipelineId } },
+ { context: { silent: true } },
)
+ const list = workflowDraft.environment_variables.filter((env) => env.value_type === 'secret')
if (list.length === 0) {
await handleExportDSL()
return
diff --git a/web/app/components/rag-pipeline/hooks/use-pipeline-config.ts b/web/app/components/rag-pipeline/hooks/use-pipeline-config.ts
index 643d9e3df62..5de514b0e26 100644
--- a/web/app/components/rag-pipeline/hooks/use-pipeline-config.ts
+++ b/web/app/components/rag-pipeline/hooks/use-pipeline-config.ts
@@ -1,59 +1,47 @@
-import type { UploadConfig } from '@dify/contracts/api/console/files/types.gen'
-import type { FetchWorkflowDraftResponse } from '@/types/workflow'
-import { useQuery } from '@tanstack/react-query'
+import { skipToken, useQuery } from '@tanstack/react-query'
import { useAtomValue } from 'jotai'
-import { useCallback, useEffect } from 'react'
+import { useEffect } from 'react'
import { knowledgePipelineIdentityAtom } from '@/app/components/workflow/editor-resource/state'
import { useWorkflowStore } from '@/app/components/workflow/store'
import { consoleQuery } from '@/service/console'
-import { useWorkflowConfig } from '@/service/use-workflow'
export const usePipelineConfig = () => {
const pipelineId = useAtomValue(knowledgePipelineIdentityAtom).pipelineId
const workflowStore = useWorkflowStore()
- const handleUpdateNodesDefaultConfigs = useCallback(
- (nodesDefaultConfigs: Record<string, any> | Record<string, any>[]) => {
- const { setNodesDefaultConfigs } = workflowStore.getState()
- let res: Record<string, any> = {}
- if (Array.isArray(nodesDefaultConfigs)) {
- nodesDefaultConfigs.forEach((item) => {
- res[item.type] = item.config
- })
- } else {
- res = nodesDefaultConfigs
- }
-
- setNodesDefaultConfigs!(res)
- },
- [workflowStore],
- )
- useWorkflowConfig(
- pipelineId ? `/rag/pipelines/${pipelineId}/workflows/default-workflow-block-configs` : '',
- handleUpdateNodesDefaultConfigs,
+ const { data: nodesDefaultConfigs } = useQuery(
+ consoleQuery.rag.pipelines.byPipelineId.workflows.defaultWorkflowBlockConfigs.get.queryOptions({
+ input: pipelineId ? { params: { pipeline_id: pipelineId } } : skipToken,
+ staleTime: 0,
+ }),
)
+ useEffect(() => {
+ if (!nodesDefaultConfigs) return
+ workflowStore
+ .getState()
+ .setNodesDefaultConfigs?.(
+ Object.fromEntries(nodesDefaultConfigs.map(({ type, config }) => [type, config])),
+ )
+ }, [nodesDefaultConfigs, workflowStore])
- const handleUpdatePublishedAt = useCallback(
- (publishedWorkflow: FetchWorkflowDraftResponse | null) => {
- const { setPublishedAt } = workflowStore.getState()
-
- setPublishedAt(publishedWorkflow?.created_at ?? 0)
- },
- [workflowStore],
- )
- useWorkflowConfig(
- pipelineId ? `/rag/pipelines/${pipelineId}/workflows/publish` : '',
- handleUpdatePublishedAt,
+ const { data: publishedWorkflow } = useQuery(
+ consoleQuery.rag.pipelines.byPipelineId.workflows.publish.get.queryOptions({
+ input: pipelineId ? { params: { pipeline_id: pipelineId } } : skipToken,
+ staleTime: 0,
+ }),
)
+ useEffect(() => {
+ if (publishedWorkflow === undefined) return
+ workflowStore.getState().setPublishedAt(publishedWorkflow?.created_at ?? 0)
+ }, [publishedWorkflow, workflowStore])
- const handleUpdateWorkflowFileUploadConfig = useCallback(
- (config: UploadConfig) => {
- const { setFileUploadConfig } = workflowStore.getState()
- setFileUploadConfig(config)
- },
- [workflowStore],
+ const { data: fileUploadConfig } = useQuery(
+ consoleQuery.files.upload.get.queryOptions({ staleTime: 0 }),
)
- useWorkflowConfig('/files/upload', handleUpdateWorkflowFileUploadConfig)
+ useEffect(() => {
+ if (!fileUploadConfig) return
+ workflowStore.getState().setFileUploadConfig(fileUploadConfig)
+ }, [fileUploadConfig, workflowStore])
const { data: dataSourceList } = useQuery(
consoleQuery.rag.pipelines.datasourcePlugins.get.queryOptions({
diff --git a/web/app/components/rag-pipeline/hooks/use-pipeline-init.ts b/web/app/components/rag-pipeline/hooks/use-pipeline-init.ts
index 85e4af35062..e1fee7cf7c4 100644
--- a/web/app/components/rag-pipeline/hooks/use-pipeline-init.ts
+++ b/web/app/components/rag-pipeline/hooks/use-pipeline-init.ts
@@ -6,7 +6,8 @@ import { toIconInfo } from '@/app/components/datasets/dataset-fields'
import { knowledgePipelineIdentityAtom } from '@/app/components/workflow/editor-resource/state'
import { useWorkflowStore } from '@/app/components/workflow/store'
import { useDatasetDetailContextWithSelector } from '@/context/dataset-detail'
-import { fetchWorkflowDraft, syncWorkflowDraft } from '@/service/workflow'
+import { consoleClient } from '@/service/console'
+import { fetchWorkflowDraft } from '@/service/workflow'
import { usePipelineConfig } from './use-pipeline-config'
import { usePipelineTemplate } from './use-pipeline-template'
@@ -67,20 +68,25 @@ export const usePipelineInit = () => {
notInitialWorkflow: true,
shouldAutoOpenStartNodeSelector: true,
})
- syncWorkflowDraft({
- url: `/rag/pipelines/${pipelineId}/workflows/draft`,
- params: {
- graph: {
- nodes: nodesTemplate,
- edges: edgesTemplate,
+ consoleClient.rag.pipelines.byPipelineId.workflows.draft
+ .post(
+ {
+ params: { pipeline_id: pipelineId },
+ body: {
+ graph: {
+ nodes: nodesTemplate,
+ edges: edgesTemplate,
+ },
+ environment_variables: [],
+ },
},
- environment_variables: [],
- },
- }).then((res) => {
- const { setDraftUpdatedAt } = workflowStore.getState()
- setDraftUpdatedAt(res.updated_at)
- handleGetInitialWorkflowData()
- })
+ { context: { silent: true } },
+ )
+ .then((res) => {
+ const { setDraftUpdatedAt } = workflowStore.getState()
+ setDraftUpdatedAt(res.updated_at)
+ handleGetInitialWorkflowData()
+ })
}
}
}
diff --git a/web/app/components/rag-pipeline/hooks/use-pipeline-run.ts b/web/app/components/rag-pipeline/hooks/use-pipeline-run.ts
index 1fcdb6eee22..4f6cab948a7 100644
--- a/web/app/components/rag-pipeline/hooks/use-pipeline-run.ts
+++ b/web/app/components/rag-pipeline/hooks/use-pipeline-run.ts
@@ -1,6 +1,7 @@
import type { useNodesSyncDraft } from './use-nodes-sync-draft'
import type { IOtherOptions } from '@/service/base'
import type { FetchWorkflowDraftResponse } from '@/types/workflow'
+import { useMutation } from '@tanstack/react-query'
import { produce } from 'immer'
import { useAtomValue } from 'jotai'
import { useCallback, useRef } from 'react'
@@ -15,8 +16,8 @@ import { useWorkflowUpdate } from '@/app/components/workflow/hooks/use-workflow-
import { useWorkflowStore } from '@/app/components/workflow/store'
import { WorkflowRunningStatus } from '@/app/components/workflow/types'
import { ssePost } from '@/service/base'
+import { consoleQuery } from '@/service/console'
import { useInvalidateAllLastRun, useInvalidateWorkflowRunHistory } from '@/service/use-workflow'
-import { stopWorkflowRun } from '@/service/workflow'
import { useNodesSyncDraftByCanEdit } from './use-nodes-sync-draft'
type DoSyncWorkflowDraft = ReturnType<typeof useNodesSyncDraft>['doSyncWorkflowDraft']
@@ -260,15 +261,19 @@ const usePipelineRunBase = (doSyncWorkflowDraft: DoSyncWorkflowDraft) => {
],
)
+ const { mutate: stopRun } = useMutation(
+ consoleQuery.rag.pipelines.byPipelineId.workflowRuns.tasks.byTaskId.stop.post.mutationOptions(),
+ )
+
const handleStopRun = useCallback(
(taskId: string) => {
- stopWorkflowRun(`/rag/pipelines/${pipelineId}/workflow-runs/tasks/${taskId}/stop`)
+ stopRun({ params: { pipeline_id: pipelineId, task_id: taskId } })
if (abortControllerRef.current) abortControllerRef.current.abort()
abortControllerRef.current = null
},
- [pipelineId],
+ [pipelineId, stopRun],
)
const handleRestoreFromPublishedWorkflow = useCallback(
diff --git a/web/app/components/rag-pipeline/utils/__tests__/query-select.spec.ts b/web/app/components/rag-pipeline/utils/__tests__/query-select.spec.ts
index e16a155a2fc..1af769ada56 100644
--- a/web/app/components/rag-pipeline/utils/__tests__/query-select.spec.ts
+++ b/web/app/components/rag-pipeline/utils/__tests__/query-select.spec.ts
@@ -88,6 +88,10 @@ describe('pipeline query selectors', () => {
).toEqual([graphNode])
})
+ it('returns no nodes when the pipeline has no published workflow', () => {
+ expect(selectPublishedPipelineNodes(null)).toEqual([])
+ })
+
it('should drop variables of unsupported types and unknown upload settings', () => {
const { variables } = selectPipelineStepParameters({
variables: [
diff --git a/web/app/components/rag-pipeline/utils/query-select.ts b/web/app/components/rag-pipeline/utils/query-select.ts
index ac65e3bfcda..109dc3f326c 100644
--- a/web/app/components/rag-pipeline/utils/query-select.ts
+++ b/web/app/components/rag-pipeline/utils/query-select.ts
@@ -10,9 +10,9 @@ import type {
PostRagPipelinesByPipelineIdWorkflowsPublishedDatasourceNodesByNodeIdPreviewResponse,
RagPipelineImportCheckDependenciesResponse,
RagPipelinePublishedRunResponse,
+ RagPipelinePublishedWorkflowResponse,
RagPipelineStepParametersResponse,
WorkflowAppBlockingResponse,
- WorkflowResponse,
WorkflowRunNodeExecutionResponse,
} from '@dify/contracts/api/console/rag/types.gen'
import type { Viewport } from 'reactflow'
@@ -120,8 +120,8 @@ export const selectPipelineTemplate = (
},
})
-export const selectPublishedPipelineNodes = (workflow: WorkflowResponse) =>
- toGraphNodes(workflow.graph)
+export const selectPublishedPipelineNodes = (workflow: RagPipelinePublishedWorkflowResponse) =>
+ workflow ? toGraphNodes(workflow.graph) : []
const toDefaultValue = (value: unknown) =>
typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean'
diff --git a/web/app/components/share/text-generation/result/hooks/__tests__/use-result-run-state.spec.ts b/web/app/components/share/text-generation/result/hooks/__tests__/use-result-run-state.spec.ts
index 927145feedb..9492cf7b31b 100644
--- a/web/app/components/share/text-generation/result/hooks/__tests__/use-result-run-state.spec.ts
+++ b/web/app/components/share/text-generation/result/hooks/__tests__/use-result-run-state.spec.ts
@@ -239,7 +239,7 @@ describe('useResultRunState', () => {
expect(updateFeedbackMock).toHaveBeenCalledWith(
{
- url: '/messages/message-1/feedbacks',
+ messageId: 'message-1',
body: {
rating: 'like',
content: undefined,
diff --git a/web/app/components/share/text-generation/result/hooks/use-result-run-state.ts b/web/app/components/share/text-generation/result/hooks/use-result-run-state.ts
index fe3098d920a..f9717996017 100644
--- a/web/app/components/share/text-generation/result/hooks/use-result-run-state.ts
+++ b/web/app/components/share/text-generation/result/hooks/use-result-run-state.ts
@@ -158,9 +158,10 @@ export const useResultRunState = ({
const handleFeedback = useCallback(
async (nextFeedback: FeedbackType) => {
+ if (!messageId) return
await updateFeedback(
{
- url: `/messages/${messageId}/feedbacks`,
+ messageId,
body: {
rating: nextFeedback.rating,
content: nextFeedback.content,
diff --git a/web/app/components/snippets/components/workflow-panel.tsx b/web/app/components/snippets/components/workflow-panel.tsx
index ea1f6ff0e04..5b7cdf4f5dd 100644
--- a/web/app/components/snippets/components/workflow-panel.tsx
+++ b/web/app/components/snippets/components/workflow-panel.tsx
@@ -35,8 +35,6 @@ const SnippetWorkflowPanel = ({ snippetId, fields }: SnippetWorkflowPanelProps)
const versionHistoryPanelProps = useMemo(() => {
return {
getVersionListUrl: `/snippets/${snippetId}/workflows`,
- deleteVersionUrl: (versionId: string) => `/snippets/${snippetId}/workflows/${versionId}`,
- updateVersionUrl: (versionId: string) => `/snippets/${snippetId}/workflows/${versionId}`,
latestVersionId: '',
}
}, [snippetId])
diff --git a/web/app/components/snippets/hooks/__tests__/use-snippet-run.spec.ts b/web/app/components/snippets/hooks/__tests__/use-snippet-run.spec.ts
index 3eedfac3463..1ed2f2ada4b 100644
--- a/web/app/components/snippets/hooks/__tests__/use-snippet-run.spec.ts
+++ b/web/app/components/snippets/hooks/__tests__/use-snippet-run.spec.ts
@@ -1,5 +1,5 @@
import type { FetchWorkflowDraftResponse } from '@/types/workflow'
-import { act } from '@testing-library/react'
+import { act, waitFor } from '@testing-library/react'
import { useNodes } from 'reactflow'
import { createEdge, createNode } from '@/app/components/workflow/__tests__/fixtures'
import {
@@ -47,14 +47,14 @@ vi.mock('@/app/components/workflow/hooks/use-fetch-workflow-inspect-vars', () =>
useSetWorkflowVarsWithValue: () => ({ fetchInspectVars: mockFetchInspectVars }),
}))
+const mockStopWorkflowRun = vi
+ .fn()
+ .mockImplementation(async () => Response.json({ result: 'success' }))
+
const mockSsePost = vi.fn()
vi.mock('@/service/base', () => ({
ssePost: (...args: unknown[]) => mockSsePost(...args),
-}))
-
-const mockStopWorkflowRun = vi.fn()
-vi.mock('@/service/workflow', () => ({
- stopWorkflowRun: (url: string) => mockStopWorkflowRun(url),
+ request: (...args: unknown[]) => mockStopWorkflowRun(...args),
}))
const mockInvalidAllLastRun = vi.fn()
@@ -295,8 +295,12 @@ describe('useSnippetRun', () => {
act(() => result.current.run.handleStopRun('task-1'))
- expect(mockStopWorkflowRun).toHaveBeenCalledExactlyOnceWith(
- '/snippets/snippet-1/workflow-runs/tasks/task-1/stop',
+ await waitFor(() =>
+ expect(mockStopWorkflowRun).toHaveBeenCalledWith(
+ expect.stringContaining('/snippets/snippet-1/workflow-runs/tasks/task-1/stop'),
+ expect.anything(),
+ expect.anything(),
+ ),
)
expect(controller.signal.aborted).toBe(true)
expect(store.getState().workflowRunningData?.result.status).toBe(
diff --git a/web/app/components/snippets/hooks/use-snippet-run.ts b/web/app/components/snippets/hooks/use-snippet-run.ts
index f2362fc15c7..906e0aba7c3 100644
--- a/web/app/components/snippets/hooks/use-snippet-run.ts
+++ b/web/app/components/snippets/hooks/use-snippet-run.ts
@@ -1,6 +1,7 @@
import type { IOtherOptions } from '@/service/base'
import type { SnippetDraftRunPayload } from '@/types/snippet'
import type { FetchWorkflowDraftResponse } from '@/types/workflow'
+import { useMutation } from '@tanstack/react-query'
import { produce } from 'immer'
import { useAtomValue } from 'jotai'
import { useCallback, useRef } from 'react'
@@ -12,8 +13,8 @@ import { useWorkflowUpdate } from '@/app/components/workflow/hooks/use-workflow-
import { useWorkflowStore } from '@/app/components/workflow/store'
import { WorkflowRunningStatus } from '@/app/components/workflow/types'
import { ssePost } from '@/service/base'
+import { consoleQuery } from '@/service/console'
import { useInvalidateAllLastRun, useInvalidateWorkflowRunHistory } from '@/service/use-workflow'
-import { stopWorkflowRun } from '@/service/workflow'
import { useNodesSyncDraft } from './use-nodes-sync-draft'
export const useSnippetRun = () => {
@@ -255,11 +256,15 @@ export const useSnippetRun = () => {
],
)
+ const { mutate: stopRun } = useMutation(
+ consoleQuery.snippets.bySnippetId.workflowRuns.tasks.byTaskId.stop.post.mutationOptions(),
+ )
+
const handleStopRun = useCallback(
(taskId: string) => {
const { workflowRunningData, setWorkflowRunningData } = workflowStore.getState()
- if (taskId) stopWorkflowRun(`/snippets/${snippetId}/workflow-runs/tasks/${taskId}/stop`)
+ if (taskId) stopRun({ params: { snippet_id: snippetId, task_id: taskId } })
if (abortControllerRef.current) abortControllerRef.current.abort()
@@ -273,7 +278,7 @@ export const useSnippetRun = () => {
)
}
},
- [snippetId, workflowStore],
+ [snippetId, stopRun, workflowStore],
)
const handleRestoreFromPublishedWorkflow = useCallback(
diff --git a/web/app/components/tools/mcp/__tests__/modal.spec.tsx b/web/app/components/tools/mcp/__tests__/modal.spec.tsx
index ed4d3cb23b4..064c624a86a 100644
--- a/web/app/components/tools/mcp/__tests__/modal.spec.tsx
+++ b/web/app/components/tools/mcp/__tests__/modal.spec.tsx
@@ -1,10 +1,10 @@
+import type { FileWithSignedUrl } from '@dify/contracts/api/console/remote-files/types.gen'
import type { SsoProtocol } from '@dify/contracts/api/console/system-features/types.gen'
import type { ComponentProps } from 'react'
import { act, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { toast } from '@/app/notifications'
import { AppToastHost } from '@/app/notifications/host'
-import { uploadRemoteFileInfo } from '@/service/common'
import { createHttpError } from '@/service/http-error'
import { createConsoleQueryWrapper } from '@/test/console/query-data'
import { createDeferred } from '@/test/deferred'
@@ -12,7 +12,8 @@ import { mockEmojiData, renderWithEmoji } from '@/test/emoji-picker'
import { createMcpProviderFixture as createProvider } from '@/test/fixtures/mcp'
import MCPModal from '../modal'
-vi.mock('@/service/common', () => ({ uploadRemoteFileInfo: vi.fn() }))
+const request = vi.hoisted(() => vi.fn<typeof import('@/service/base').request>())
+vi.mock('@/service/base', () => ({ request }))
const uploadedIcon = {
id: 'favicon-id',
@@ -20,7 +21,10 @@ const uploadedIcon = {
size: 100,
mime_type: 'image/png',
url: 'https://example.com/icon.png',
-} satisfies Awaited<ReturnType<typeof uploadRemoteFileInfo>>
+ created_at: null,
+ created_by: null,
+ extension: null,
+} satisfies FileWithSignedUrl
const setup = (
props: Partial<ComponentProps<typeof MCPModal>> = {},
@@ -69,7 +73,7 @@ const submitButton = (edit = false) =>
screen.getByRole('button', { name: `tools.mcp.modal.${edit ? 'save' : 'confirm'}` })
beforeEach(() => {
- vi.mocked(uploadRemoteFileInfo).mockReset().mockResolvedValue(uploadedIcon)
+ request.mockReset().mockImplementation(async () => Response.json(uploadedIcon))
})
afterEach(() => toast.dismiss())
mockEmojiData()
@@ -82,11 +86,15 @@ describe('MCP server configuration', () => {
await waitFor(() => expect(submitButton()).toBeEnabled())
await user.click(submitButton())
- expect(uploadRemoteFileInfo).toHaveBeenCalledWith(
- 'https://www.google.com/s2/favicons?domain=example.co.uk&sz=128',
- undefined,
- true,
+ expect(request).toHaveBeenCalledWith(
+ expect.stringContaining('/remote-files/upload'),
+ expect.anything(),
+ expect.objectContaining({ silent: true }),
)
+ expect(request.mock.calls[0]?.[2]?.request?.method).toBe('POST')
+ expect(await request.mock.calls[0]?.[2]?.request?.json()).toEqual({
+ url: 'https://www.google.com/s2/favicons?domain=example.co.uk&sz=128',
+ })
expect(onConfirm).toHaveBeenCalledWith({
name: 'Test Server',
server_url: 'https://api.example.co.uk/mcp',
@@ -121,7 +129,7 @@ describe('MCP server configuration', () => {
await user.click(submitButton())
expect(await screen.findByText(`tools.mcp.modal.${error}`)).toBeInTheDocument()
expect(onConfirm).not.toHaveBeenCalled()
- if (error === 'invalidServerUrl') expect(uploadRemoteFileInfo).not.toHaveBeenCalled()
+ if (error === 'invalidServerUrl') expect(request).not.toHaveBeenCalled()
})
it('preserves stored credentials, headers and timeouts without re-fetching the icon', async () => {
@@ -154,7 +162,7 @@ describe('MCP server configuration', () => {
is_dynamic_registration: false,
}),
)
- expect(uploadRemoteFileInfo).not.toHaveBeenCalled()
+ expect(request).not.toHaveBeenCalled()
expect(onHide).not.toHaveBeenCalled()
})
@@ -251,7 +259,7 @@ describe('MCP server configuration', () => {
}),
new TypeError('Failed to fetch'),
])('allows submission with the default icon after upload failure: $message', async (error) => {
- vi.mocked(uploadRemoteFileInfo).mockRejectedValueOnce(error)
+ request.mockRejectedValueOnce(error)
const { user, onConfirm } = setup()
await fillRequiredFields(user)
expect(await screen.findByText(error.message)).toBeInTheDocument()
@@ -266,23 +274,34 @@ describe('MCP server configuration', () => {
)
})
+ it('keeps the default icon when the upload has no preview URL', async () => {
+ request.mockResolvedValueOnce(Response.json({ ...uploadedIcon, url: null }))
+ const { user, onConfirm } = setup()
+ await fillRequiredFields(user)
+ await waitFor(() => expect(submitButton()).toBeEnabled())
+ await user.click(submitButton())
+ expect(onConfirm).toHaveBeenCalledWith(
+ expect.objectContaining({ icon_type: 'emoji', icon: '🔗' }),
+ )
+ })
+
it('keeps the newest URL icon when an earlier upload finishes last', async () => {
- const first = createDeferred<Awaited<ReturnType<typeof uploadRemoteFileInfo>>>()
- vi.mocked(uploadRemoteFileInfo).mockReturnValueOnce(first.promise)
+ const first = createDeferred<Response>()
+ request.mockReturnValueOnce(first.promise)
const { user, onConfirm } = setup()
await fillRequiredFields(user, 'https://first.example.com/mcp')
- await waitFor(() => expect(uploadRemoteFileInfo).toHaveBeenCalledOnce())
+ await waitFor(() => expect(request).toHaveBeenCalledOnce())
expect(submitButton()).toBeDisabled()
await replaceField(user, 'serverUrl', 'https://second.example.org/mcp')
await user.tab()
await waitFor(() => expect(submitButton()).toBeEnabled())
- expect(uploadRemoteFileInfo).toHaveBeenLastCalledWith(
- 'https://www.google.com/s2/favicons?domain=example.org&sz=128',
- undefined,
- true,
- )
+ expect(await request.mock.calls.at(-1)?.[2]?.request?.json()).toEqual({
+ url: 'https://www.google.com/s2/favicons?domain=example.org&sz=128',
+ })
await act(async () => {
- first.resolve({ ...uploadedIcon, id: 'stale-icon', url: 'https://example.com/stale.png' })
+ first.resolve(
+ Response.json({ ...uploadedIcon, id: 'stale-icon', url: 'https://example.com/stale.png' }),
+ )
await first.promise
})
await user.click(submitButton())
diff --git a/web/app/components/tools/mcp/hooks/use-mcp-modal-form.ts b/web/app/components/tools/mcp/hooks/use-mcp-modal-form.ts
index 54e427ca770..06443a3c9cb 100644
--- a/web/app/components/tools/mcp/hooks/use-mcp-modal-form.ts
+++ b/web/app/components/tools/mcp/hooks/use-mcp-modal-form.ts
@@ -2,11 +2,12 @@
import type { HeaderItem } from '../headers-input'
import type { IconPickerValue } from '@/app/components/base/icon-picker'
import type { ToolWithProvider } from '@/app/components/workflow/types'
+import { useMutation } from '@tanstack/react-query'
import { useCallback, useMemo, useRef, useState } from 'react'
import { v4 as uuid } from 'uuid'
import { MCPAuthMethod } from '@/app/components/tools/types'
import { toast } from '@/app/notifications'
-import { uploadRemoteFileInfo } from '@/service/common'
+import { consoleQuery } from '@/service/console'
const DEFAULT_ICON = { type: 'emoji', icon: '🔗', background: '#6366F1' } satisfies IconPickerValue
const extractFileId = (url: string) => {
@@ -82,6 +83,9 @@ type MCPModalFormActions = {
* directly, and the key change triggers a remount of the consumer component.
*/
export const useMCPModalForm = (data?: ToolWithProvider) => {
+ const { mutateAsync: uploadRemoteFile } = useMutation(
+ consoleQuery.remoteFiles.upload.post.mutationOptions({ context: { silent: true } }),
+ )
const isCreate = !data
const originalServerUrl = data?.server_url
const originalServerID = data?.server_identifier
@@ -128,8 +132,8 @@ export const useMCPModalForm = (data?: ToolWithProvider) => {
if (!domain) return
const remoteIcon = `https://www.google.com/s2/favicons?domain=${domain}&sz=128`
- const res = await uploadRemoteFileInfo(remoteIcon, undefined, true)
- if (isStale()) return
+ const res = await uploadRemoteFile({ body: { url: remoteIcon } })
+ if (isStale() || !res.url) return
setAppIcon({ type: 'image', url: res.url, fileId: res.id })
} catch (e) {
@@ -145,7 +149,7 @@ export const useMCPModalForm = (data?: ToolWithProvider) => {
if (!isStale()) setIsFetchingIcon(false)
}
},
- [data],
+ [data, uploadRemoteFile],
)
const resetIcon = useCallback(() => {
setAppIcon(getIcon(data))
diff --git a/web/app/components/workflow-app/components/__tests__/workflow-panel.spec.tsx b/web/app/components/workflow-app/components/__tests__/workflow-panel.spec.tsx
index 7baf9701c48..50bea666126 100644
--- a/web/app/components/workflow-app/components/__tests__/workflow-panel.spec.tsx
+++ b/web/app/components/workflow-app/components/__tests__/workflow-panel.spec.tsx
@@ -25,12 +25,12 @@ const api = vi.hoisted(() => ({
history: vi.fn<(url: string, options?: unknown) => Promise<FetchWorkflowDraftPageResponse>>(),
update:
vi.fn<
- (
- url: string,
- options: { body: { marked_name: string; marked_comment: string } },
- ) => Promise<ReturnType<typeof createWorkflowResponseFixture>>
+ typeof import('@/service/console').consoleClient.apps.byAppId.workflows.byWorkflowId.patch
+ >(),
+ remove:
+ vi.fn<
+ typeof import('@/service/console').consoleClient.apps.byAppId.workflows.byWorkflowId.delete
>(),
- remove: vi.fn<(url: string) => Promise<void>>(),
}))
vi.mock('@/next/navigation', async (importOriginal) => ({
...(await importOriginal<typeof import('@/next/navigation')>()),
@@ -40,8 +40,6 @@ vi.mock('@/next/navigation', async (importOriginal) => ({
vi.mock('@/service/base', async (importOriginal) => ({
...(await importOriginal<typeof import('@/service/base')>()),
get: api.history,
- patch: api.update,
- del: api.remove,
}))
vi.mock('@/service/log', () => ({
fetchRunDetail: api.run,
@@ -54,6 +52,8 @@ vi.mock('@/service/console', async (importOriginal) => {
return {
...actual,
consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'apps.byAppId.workflows.byWorkflowId.patch': api.update,
+ 'apps.byAppId.workflows.byWorkflowId.delete': api.remove,
'workspaces.current.agentProviders.get': async () => [],
'apps.byAppId.workflows.draft.environmentVariables.get': async () => ({ items: [] }),
}),
@@ -168,10 +168,17 @@ beforeEach(() => {
if (url !== '/apps/app-123/workflows') throw new Error(`Unexpected GET: ${url}`)
return { items: versions, page: 1, limit: 10, total: versions.length, has_more: false }
})
- api.update.mockReset().mockImplementation(async (_url, { body }) => {
- const updated = version(body)
+ api.update.mockReset().mockImplementation(async ({ body }) => {
+ const updated = version({
+ marked_name: body.marked_name ?? '',
+ marked_comment: body.marked_comment ?? '',
+ })
versions = [updated]
- return createWorkflowResponseFixture({ ...body, id: updated.id })
+ return createWorkflowResponseFixture({
+ marked_name: body.marked_name ?? '',
+ marked_comment: body.marked_comment ?? '',
+ id: updated.id,
+ })
})
api.remove.mockReset().mockImplementation(async () => {
versions = []
@@ -197,9 +204,19 @@ it('loads this app’s version history and protects the published version from d
it('edits and deletes an older version through this app’s real history actions', async () => {
versions = [version({ id: 'old-release' })]
- api.update.mockImplementation(async (_url, { body }) => {
- versions = [version({ ...body, id: 'old-release' })]
- return createWorkflowResponseFixture({ ...body, id: 'old-release' })
+ api.update.mockImplementation(async ({ body }) => {
+ versions = [
+ version({
+ marked_name: body.marked_name ?? '',
+ marked_comment: body.marked_comment ?? '',
+ id: 'old-release',
+ }),
+ ]
+ return createWorkflowResponseFixture({
+ marked_name: body.marked_name ?? '',
+ marked_comment: body.marked_comment ?? '',
+ id: 'old-release',
+ })
})
const { user } = setup({ showWorkflowVersionHistoryPanel: true })
await screen.findByText('First release')
@@ -223,7 +240,8 @@ it('edits and deletes an older version through this app’s real history actions
)
await user.click(within(dialog).getByRole('button', { name: 'common.operation.save' }))
expect(await screen.findByText('Renamed release')).toBeInTheDocument()
- expect(api.update).toHaveBeenCalledExactlyOnceWith('/apps/app-123/workflows/old-release', {
+ expect(api.update).toHaveBeenCalledExactlyOnceWith({
+ params: { app_id: 'app-123', workflow_id: 'old-release' },
body: { marked_name: 'Renamed release', marked_comment: 'Updated notes' },
})
await user.click(screen.getByRole('button', { name: 'common.operation.more' }))
@@ -231,7 +249,9 @@ it('edits and deletes an older version through this app’s real history actions
const confirm = await screen.findByRole('alertdialog')
await user.click(within(confirm).getByRole('button', { name: 'common.operation.delete' }))
await waitFor(() =>
- expect(api.remove).toHaveBeenCalledExactlyOnceWith('/apps/app-123/workflows/old-release'),
+ expect(api.remove).toHaveBeenCalledExactlyOnceWith({
+ params: { app_id: 'app-123', workflow_id: 'old-release' },
+ }),
)
await waitFor(() => expect(screen.queryByText('Renamed release')).not.toBeInTheDocument())
})
diff --git a/web/app/components/workflow-app/components/__tests__/workflow-publishing.spec.tsx b/web/app/components/workflow-app/components/__tests__/workflow-publishing.spec.tsx
index eb68d92bbb7..32aea8d4c18 100644
--- a/web/app/components/workflow-app/components/__tests__/workflow-publishing.spec.tsx
+++ b/web/app/components/workflow-app/components/__tests__/workflow-publishing.spec.tsx
@@ -1,7 +1,4 @@
-import type {
- WorkflowAgentComposerResponse,
- WorkflowPublishResponse,
-} from '@dify/contracts/api/console/apps/types.gen'
+import type { WorkflowAgentComposerResponse } from '@dify/contracts/api/console/apps/types.gen'
import type { CloudPlan } from '@dify/contracts/api/console/features/types.gen'
import type { DeploymentEdition } from '@dify/contracts/api/console/system-features/types.gen'
import type { QueryClient } from '@tanstack/react-query'
@@ -47,12 +44,7 @@ import WorkflowMain from '../workflow-main'
const api = vi.hoisted(() => ({
save: vi.fn<typeof import('@/service/console').consoleClient.apps.byAppId.workflows.draft.post>(),
publish:
- vi.fn<
- (
- url: string,
- options: { body: { marked_name: string; marked_comment: string } },
- ) => Promise<WorkflowPublishResponse>
- >(),
+ vi.fn<typeof import('@/service/console').consoleClient.apps.byAppId.workflows.publish.post>(),
createTool:
vi.fn<
typeof import('@/service/console').consoleClient.workspaces.current.toolProvider.workflow.create.post
@@ -72,10 +64,6 @@ vi.mock('@/next/navigation', async (importOriginal) => ({
usePathname: () => '/app/app-1/workflow',
useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
}))
-vi.mock('@/service/base', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@/service/base')>()),
- post: api.publish,
-}))
vi.mock('@/service/console', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/service/console')>()
const { withConsoleClientResponses, withConsoleResponses } =
@@ -83,6 +71,7 @@ vi.mock('@/service/console', async (importOriginal) => {
return {
...actual,
consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'apps.byAppId.workflows.publish.post': api.publish,
'apps.byAppId.get': api.app,
'workspaces.current.toolProvider.workflow.get.get': api.toolDetail,
'workspaces.current.tools.workflow.get': async () => [],
@@ -332,7 +321,8 @@ it('waits for the current graph to save before publishing and updates the public
await waitFor(() =>
expect(screen.getByRole('button', { name: 'workflow.common.published' })).toBeDisabled(),
)
- expect(api.publish).toHaveBeenCalledExactlyOnceWith('/apps/app-1/workflows/publish', {
+ expect(api.publish).toHaveBeenCalledExactlyOnceWith({
+ params: { app_id: 'app-1' },
body: { marked_name: '', marked_comment: '' },
})
expect(store.getState()).toMatchObject({
diff --git a/web/app/components/workflow-app/components/workflow-header/features-trigger.tsx b/web/app/components/workflow-app/components/workflow-header/features-trigger.tsx
index c60223f9c12..e21e43b8b09 100644
--- a/web/app/components/workflow-app/components/workflow-header/features-trigger.tsx
+++ b/web/app/components/workflow-app/components/workflow-header/features-trigger.tsx
@@ -8,7 +8,7 @@ import type { StartNodeType } from '@/app/components/workflow/nodes/start/types'
import type { CommonEdgeType, Node } from '@/app/components/workflow/types'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
-import { useQuery, useQueryClient, useSuspenseQuery } from '@tanstack/react-query'
+import { useMutation, useQuery, useQueryClient, useSuspenseQuery } from '@tanstack/react-query'
import { useAtomValue } from 'jotai'
import { memo, useCallback, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
@@ -35,11 +35,7 @@ import { toast } from '@/app/notifications'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import useTheme from '@/hooks/use-theme'
import { consoleQuery } from '@/service/console'
-import {
- useInvalidateAppWorkflow,
- usePublishWorkflow,
- useResetWorkflowVersionHistory,
-} from '@/service/use-workflow'
+import { useResetWorkflowVersionHistory } from '@/service/use-workflow'
const FeaturesTrigger = () => {
const { t } = useTranslation(['common', 'workflow'])
@@ -156,11 +152,12 @@ const FeaturesTrigger = () => {
setShowFeaturesPanel(!showFeaturesPanel)
}, [workflowStore, getNodesReadOnly])
- const { mutateAsync: publishWorkflow } = usePublishWorkflow()
+ const { mutateAsync: publishWorkflow } = useMutation(
+ consoleQuery.apps.byAppId.workflows.publish.post.mutationOptions(),
+ )
// const { validateBeforeRun } = useWorkflowRunValidation()
const needWarningNodes = useChecklist(nodes, edges)
- const updatePublishedWorkflow = useInvalidateAppWorkflow()
const onPublish = useCallback(
async (params?: AppPublisherPublishParams, options?: AppPublisherPublishOptions) => {
const publishParams = params && 'title' in params ? params : undefined
@@ -179,26 +176,17 @@ const FeaturesTrigger = () => {
if (!draftSyncResult) throw new Error('Workflow draft sync failed')
const res = await publishWorkflow({
- url: publishParams?.url || `/apps/${appID}/workflows/publish`,
- title: publishParams?.title || '',
- releaseNotes: publishParams?.releaseNotes || '',
+ params: { app_id: appID },
+ body: {
+ marked_name: publishParams?.title || '',
+ marked_comment: publishParams?.releaseNotes || '',
+ },
})
if (res) {
// One toast per publish: a warning from the server replaces the success message.
if (res.warning) toast.warning(res.warning)
else if (options?.showSuccessToast !== false)
toast.success(t(($) => $['api.actionSuccess'], { ns: 'common' }))
- updatePublishedWorkflow(appID)
- void queryClient.invalidateQueries({
- queryKey: consoleQuery.apps.byAppId.get.queryKey({
- input: { params: { app_id: appID } },
- }),
- })
- void queryClient.invalidateQueries({
- queryKey: consoleQuery.apps.byAppId.triggers.get.queryKey({
- input: { params: { app_id: appID } },
- }),
- })
if (rosterAgentIds.length > 0) {
void queryClient.invalidateQueries({
queryKey: consoleQuery.agent.get.key(),
@@ -232,7 +220,6 @@ const FeaturesTrigger = () => {
publishWorkflow,
appID,
t,
- updatePublishedWorkflow,
rosterAgentIds,
queryClient,
workflowStore,
diff --git a/web/app/components/workflow-app/components/workflow-panel.tsx b/web/app/components/workflow-app/components/workflow-panel.tsx
index 590d6a12edb..692dcb026d1 100644
--- a/web/app/components/workflow-app/components/workflow-panel.tsx
+++ b/web/app/components/workflow-app/components/workflow-panel.tsx
@@ -85,8 +85,6 @@ const WorkflowPanel = () => {
const versionHistoryPanelProps = useMemo(() => {
return {
getVersionListUrl: `/apps/${appId}/workflows`,
- deleteVersionUrl: (versionId: string) => `/apps/${appId}/workflows/${versionId}`,
- updateVersionUrl: (versionId: string) => `/apps/${appId}/workflows/${versionId}`,
latestVersionId: appDetail.workflow?.id,
}
}, [appId, appDetail.workflow?.id])
diff --git a/web/app/components/workflow-app/hooks/__tests__/use-workflow-init.spec.ts b/web/app/components/workflow-app/hooks/__tests__/use-workflow-init.spec.ts
index f90d3e4cbd3..c747373a17b 100644
--- a/web/app/components/workflow-app/hooks/__tests__/use-workflow-init.spec.ts
+++ b/web/app/components/workflow-app/hooks/__tests__/use-workflow-init.spec.ts
@@ -63,9 +63,14 @@ vi.mock('../use-workflow-template', () => ({
vi.mock('@/service/base', async (importOriginal) => ({
...(await importOriginal<typeof import('@/service/base')>()),
- get: async (url: string) => {
- if (url === '/files/upload') return workflowConfigState.data ?? createFileUploadConfigFixture()
- throw new Error(`Unexpected GET ${url}`)
+ request: async (url: string, _init: RequestInit, { request }: { request: Request }) => {
+ if (request.method === 'POST' && new URL(url).pathname.endsWith('/apps/app-1/workflows/draft'))
+ return Response.json(await mockSyncWorkflowDraft(await request.json()))
+ if (new URL(url).pathname.endsWith('/files/upload'))
+ return Response.json(workflowConfigState.data ?? createFileUploadConfigFixture())
+ if (new URL(url).pathname.endsWith('/workflows/default-workflow-block-configs'))
+ return Response.json(await mockFetchNodesDefaultConfigs())
+ throw new Error(`Unexpected request ${url}`)
},
}))
@@ -84,8 +89,6 @@ const mockFetchWorkflowDraft = vi.fn()
vi.mock('@/service/workflow', () => ({
fetchWorkflowDraft: (...args: unknown[]) => mockFetchWorkflowDraft(...args),
- syncWorkflowDraft: (...args: unknown[]) => mockSyncWorkflowDraft(...args),
- fetchNodesDefaultConfigs: (...args: unknown[]) => mockFetchNodesDefaultConfigs(...args),
}))
const notExistError = () =>
@@ -174,13 +177,11 @@ describe('useWorkflowInit', () => {
})
expect(mockSyncWorkflowDraft).toHaveBeenCalledWith(
expect.objectContaining({
- params: expect.objectContaining({
- graph: {
- nodes: [],
- edges: [],
- },
- force: true,
- }),
+ graph: {
+ nodes: [],
+ edges: [],
+ },
+ force: true,
}),
)
expect(store.getState().syncWorkflowDraftHash).toBe('new-workflow-hash')
@@ -204,13 +205,11 @@ describe('useWorkflowInit', () => {
await waitFor(() =>
expect(mockSyncWorkflowDraft).toHaveBeenCalledWith(
expect.objectContaining({
- params: expect.objectContaining({
- graph: {
- nodes: [{ id: 'start', data: { type: BlockEnum.Start } }],
- edges: [],
- },
- force: true,
- }),
+ graph: {
+ nodes: [{ id: 'start', data: { type: BlockEnum.Start } }],
+ edges: [],
+ },
+ force: true,
}),
),
)
diff --git a/web/app/components/workflow-app/hooks/__tests__/use-workflow-run.spec.tsx b/web/app/components/workflow-app/hooks/__tests__/use-workflow-run.spec.tsx
index 50e0fce61b0..1b739978559 100644
--- a/web/app/components/workflow-app/hooks/__tests__/use-workflow-run.spec.tsx
+++ b/web/app/components/workflow-app/hooks/__tests__/use-workflow-run.spec.tsx
@@ -46,7 +46,9 @@ const api = vi.hoisted(() => ({
ssePost: vi.fn<typeof import('@/service/base').ssePost>(),
sseGet: vi.fn<typeof import('@/service/base').sseGet>(),
post: vi.fn<typeof import('@/service/base').post>(),
- stop: vi.fn<typeof import('@/service/workflow').stopWorkflowRun>(),
+ stop: vi.fn<
+ typeof import('@/service/console').consoleClient.apps.byAppId.workflowRuns.tasks.byTaskId.stop.post
+ >(),
inspect: vi.fn<typeof import('@/service/workflow').fetchAllInspectVars>(),
track: vi.fn<typeof import('@/app/components/base/amplitude').trackEvent>(),
playAudio: vi.fn(),
@@ -59,6 +61,7 @@ vi.mock('@/service/console', async (importOriginal) => {
return {
...actual,
consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'apps.byAppId.workflowRuns.tasks.byTaskId.stop.post': api.stop,
'apps.byAppId.workflows.draft.systemVariables.get': async () => ({ items: [] }),
'apps.byAppId.workflows.draft.conversationVariables.get': async () => ({ items: [] }),
'apps.byAppId.workflows.draft.environmentVariables.get': async () => ({ items: [] }),
@@ -76,7 +79,6 @@ vi.mock('@/service/base', async (importOriginal) => ({
}))
vi.mock('@/service/workflow', async (importOriginal) => ({
...(await importOriginal<typeof import('@/service/workflow')>()),
- stopWorkflowRun: api.stop,
fetchAllInspectVars: api.inspect,
}))
vi.mock('@/app/components/base/amplitude', () => ({ trackEvent: api.track }))
@@ -382,7 +384,11 @@ it('stops an identified task through the stop endpoint', async () => {
assert(callbacks?.onWorkflowStarted)
act(() => callbacks.onWorkflowStarted?.(started))
act(() => result.current.run.handleStopRun('task-1'))
- expect(api.stop).toHaveBeenCalledExactlyOnceWith('/apps/app-1/workflow-runs/tasks/task-1/stop')
+ await waitFor(() =>
+ expect(api.stop).toHaveBeenCalledExactlyOnceWith({
+ params: { app_id: 'app-1', task_id: 'task-1' },
+ }),
+ )
expect(store.getState().workflowRunningData?.result.status).toBe(WorkflowRunningStatus.Stopped)
})
diff --git a/web/app/components/workflow-app/hooks/use-workflow-init.ts b/web/app/components/workflow-app/hooks/use-workflow-init.ts
index b0be1d009c6..71b75e30279 100644
--- a/web/app/components/workflow-app/hooks/use-workflow-init.ts
+++ b/web/app/components/workflow-app/hooks/use-workflow-init.ts
@@ -1,8 +1,7 @@
-import type { UploadConfig } from '@dify/contracts/api/console/files/types.gen'
import type { Edge, Node } from '@/app/components/workflow/types'
import type { FetchWorkflowDraftResponse } from '@/types/workflow'
import { ORPCError } from '@orpc/client'
-import { useQueryClient, useSuspenseQuery } from '@tanstack/react-query'
+import { useQuery, useQueryClient, useSuspenseQuery } from '@tanstack/react-query'
import { useAtomValue } from 'jotai'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { workflowAppIdentityAtom } from '@/app/components/workflow/editor-resource/state'
@@ -10,9 +9,8 @@ import { useStore, useWorkflowStore } from '@/app/components/workflow/store'
import { BlockEnum } from '@/app/components/workflow/types'
import { workspacePermissionKeysAtom } from '@/context/permission-state'
import { userProfileQueryOptions } from '@/features/account-profile/client'
-import { consoleQuery } from '@/service/console'
-import { useWorkflowConfig } from '@/service/use-workflow'
-import { fetchNodesDefaultConfigs, fetchWorkflowDraft, syncWorkflowDraft } from '@/service/workflow'
+import { consoleClient, consoleQuery } from '@/service/console'
+import { fetchWorkflowDraft } from '@/service/workflow'
import { appWorkflowQueryOptions } from '@/service/workflow-queries'
import { getAppACLCapabilities } from '@/utils/permission'
import { useWorkflowDraftGraphForCanvas } from './use-workflow-draft-graph-for-canvas'
@@ -82,15 +80,13 @@ export const useWorkflowInit = () => {
const [data, setData] = useState<FetchWorkflowDraftResponse>()
const [isLoading, setIsLoading] = useState(true)
- const handleUpdateWorkflowFileUploadConfig = useCallback(
- (config: UploadConfig) => {
- const { setFileUploadConfig } = workflowStore.getState()
- setFileUploadConfig(config)
- },
- [workflowStore],
+ const { data: fileUploadConfigResponse, isLoading: isFileUploadConfigLoading } = useQuery(
+ consoleQuery.files.upload.get.queryOptions({ staleTime: 0 }),
)
- const { data: fileUploadConfigResponse, isLoading: isFileUploadConfigLoading } =
- useWorkflowConfig('/files/upload', handleUpdateWorkflowFileUploadConfig)
+ useEffect(() => {
+ if (!fileUploadConfigResponse) return
+ workflowStore.getState().setFileUploadConfig(fileUploadConfigResponse)
+ }, [fileUploadConfigResponse, workflowStore])
const handleGetInitialWorkflowData = useCallback(async () => {
try {
@@ -161,21 +157,26 @@ export const useWorkflowInit = () => {
return
}
- syncWorkflowDraft({
- url: `/apps/${appDetail.id}/workflows/draft`,
- params: {
- graph: initialGraph,
- force: true,
- features: {
- retriever_resource: { enabled: true },
+ consoleClient.apps.byAppId.workflows.draft
+ .post(
+ {
+ params: { app_id: appDetail.id },
+ body: {
+ graph: initialGraph,
+ force: true,
+ features: {
+ retriever_resource: { enabled: true },
+ },
+ conversation_variables: [],
+ },
},
- conversation_variables: [],
- },
- }).then((res) => {
- workflowStore.getState().setDraftUpdatedAt(res.updated_at)
- setSyncWorkflowDraftHash(res.hash)
- handleGetInitialWorkflowData()
- })
+ { context: { silent: true } },
+ )
+ .then((res) => {
+ workflowStore.getState().setDraftUpdatedAt(res.updated_at)
+ setSyncWorkflowDraftHash(res.hash)
+ handleGetInitialWorkflowData()
+ })
}
}
}
@@ -195,7 +196,12 @@ export const useWorkflowInit = () => {
const handleFetchPreloadData = useCallback(async () => {
const [nodesDefaultConfigsResult, publishedWorkflowResult] = await Promise.allSettled([
- fetchNodesDefaultConfigs(`/apps/${appDetail.id}/workflows/default-workflow-block-configs`),
+ queryClient.query(
+ consoleQuery.apps.byAppId.workflows.defaultWorkflowBlockConfigs.get.queryOptions({
+ input: { params: { app_id: appDetail.id } },
+ staleTime: 0,
+ }),
+ ),
queryClient.query(appWorkflowQueryOptions(appDetail.id)),
])
diff --git a/web/app/components/workflow-app/hooks/use-workflow-run.ts b/web/app/components/workflow-app/hooks/use-workflow-run.ts
index c3cfa45da5c..a6a514ba2a6 100644
--- a/web/app/components/workflow-app/hooks/use-workflow-run.ts
+++ b/web/app/components/workflow-app/hooks/use-workflow-run.ts
@@ -3,7 +3,7 @@ import type { AudioPlayer } from '@/app/components/base/audio-btn/audio'
import type { Node } from '@/app/components/workflow/types'
import type { IOtherOptions } from '@/service/base'
import type { FetchWorkflowDraftResponse } from '@/types/workflow'
-import { useSuspenseQuery } from '@tanstack/react-query'
+import { useMutation, useSuspenseQuery } from '@tanstack/react-query'
import { noop } from 'es-toolkit/function'
import { produce } from 'immer'
import { useAtomValue } from 'jotai'
@@ -26,7 +26,6 @@ import { usePathname } from '@/next/navigation'
import { ssePost } from '@/service/base'
import { consoleQuery } from '@/service/console'
import { useInvalidateAllLastRun, useInvalidateWorkflowRunHistory } from '@/service/use-workflow'
-import { stopWorkflowRun } from '@/service/workflow'
import { useNodesSyncDraft, useNodesSyncDraftByCanEdit } from './use-nodes-sync-draft'
import {
createBaseWorkflowRunCallbacks,
@@ -480,6 +479,10 @@ const useWorkflowRunBase = (doSyncWorkflowDraft: DoSyncWorkflowDraft) => {
],
)
+ const { mutate: stopRun } = useMutation(
+ consoleQuery.apps.byAppId.workflowRuns.tasks.byTaskId.stop.post.mutationOptions(),
+ )
+
const handleStopRun = useCallback(
(taskId: string) => {
const setStoppedState = () => {
@@ -501,7 +504,7 @@ const useWorkflowRunBase = (doSyncWorkflowDraft: DoSyncWorkflowDraft) => {
}
if (taskId) {
- stopWorkflowRun(`/apps/${appId}/workflow-runs/tasks/${taskId}/stop`)
+ stopRun({ params: { app_id: appId, task_id: taskId } })
setStoppedState()
return
}
@@ -527,7 +530,7 @@ const useWorkflowRunBase = (doSyncWorkflowDraft: DoSyncWorkflowDraft) => {
abortControllerRef.current = null
setStoppedState()
},
- [appId, workflowStore],
+ [appId, stopRun, workflowStore],
)
const handleRestoreFromPublishedWorkflow = useCallback(
diff --git a/web/app/components/workflow/nodes/human-input/hooks/__tests__/use-single-run-form-params.spec.ts b/web/app/components/workflow/nodes/human-input/hooks/__tests__/use-single-run-form-params.spec.ts
index d2cc7e590d8..09c3260bcec 100644
--- a/web/app/components/workflow/nodes/human-input/hooks/__tests__/use-single-run-form-params.spec.ts
+++ b/web/app/components/workflow/nodes/human-input/hooks/__tests__/use-single-run-form-params.spec.ts
@@ -1,3 +1,4 @@
+import type { HumanInputFormPreviewResponse } from '@dify/contracts/api/console/apps/types.gen'
import type { HumanInputNodeType } from '../../types'
import type { WorkflowAppMode } from '@/app/components/apps/app-type'
import type { FileEntity } from '@/app/components/base/file-uploader/types'
@@ -11,15 +12,9 @@ import { createAppDetailFixture } from '@/test/fixtures/app'
import { TransferMethod } from '@/types/app'
import useSingleRunFormParams from '../use-single-run-form-params'
-const mockFetchHumanInputNodeStepRunForm = vi.hoisted(() => vi.fn())
-const mockSubmitHumanInputNodeStepRunForm = vi.hoisted(() => vi.fn())
-
-vi.mock('@/service/workflow', () => ({
- fetchHumanInputNodeStepRunForm: (...args: unknown[]) =>
- mockFetchHumanInputNodeStepRunForm(...args),
- submitHumanInputNodeStepRunForm: (...args: unknown[]) =>
- mockSubmitHumanInputNodeStepRunForm(...args),
-}))
+const previewForm = vi.hoisted(() => vi.fn())
+const request = vi.hoisted(() => vi.fn<typeof import('@/service/base').request>())
+vi.mock('@/service/base', () => ({ request }))
const createPayload = (overrides: Partial<HumanInputNodeType> = {}): HumanInputNodeType => ({
title: 'Human Input',
@@ -109,8 +104,15 @@ describe('human-input/hooks/use-single-run-form-params', () => {
variable: undefined,
} as unknown as InputVar,
])
- mockFetchHumanInputNodeStepRunForm.mockResolvedValue(mockFormData)
- mockSubmitHumanInputNodeStepRunForm.mockResolvedValue({})
+ previewForm.mockResolvedValue(mockFormData)
+ request.mockReset().mockImplementation(async (url, _init, options) => {
+ if (new URL(url).pathname.endsWith('/form/preview')) {
+ return Response.json(
+ await previewForm(new URL(url).pathname, await options?.request?.json()),
+ )
+ }
+ return Response.json({})
+ })
})
const uploadedFile: FileEntity = {
@@ -254,7 +256,7 @@ describe('human-input/hooks/use-single-run-form-params', () => {
},
],
} satisfies HumanInputFormData
- mockFetchHumanInputNodeStepRunForm.mockResolvedValue(formDataWithFiles)
+ previewForm.mockResolvedValue(formDataWithFiles)
const { result } = renderHook(() =>
useSingleRunFormParams({
@@ -273,8 +275,8 @@ describe('human-input/hooks/use-single-run-form-params', () => {
expect(previewInputs).toHaveProperty('ignored', undefined)
expect(result.current.showGeneratedForm).toBe(true)
- expect(mockFetchHumanInputNodeStepRunForm).toHaveBeenCalledWith(
- '/apps/app-1/workflows/draft/human-input/nodes/node-1/form',
+ expect(previewForm).toHaveBeenCalledWith(
+ '/console/api/apps/app-1/workflows/draft/human-input/nodes/node-1/form/preview',
{
inputs: { topic: 'AI' },
},
@@ -293,36 +295,37 @@ describe('human-input/hooks/use-single-run-form-params', () => {
})
})
- expect(mockSubmitHumanInputNodeStepRunForm).toHaveBeenCalledWith(
- '/apps/app-1/workflows/draft/human-input/nodes/node-1/form',
- {
- inputs: { topic: 'AI' },
- form_inputs: {
- answer: 'approved',
- attachment: {
+ expect(new URL(request.mock.calls[1]![0]).pathname).toBe(
+ '/console/api/apps/app-1/workflows/draft/human-input/nodes/node-1/form/run',
+ )
+ expect(request.mock.calls[1]?.[2]?.request?.method).toBe('POST')
+ expect(await request.mock.calls[1]?.[2]?.request?.json()).toEqual({
+ inputs: { topic: 'AI' },
+ form_inputs: {
+ answer: 'approved',
+ attachment: {
+ type: 'document',
+ transfer_method: TransferMethod.local_file,
+ url: '',
+ upload_file_id: 'upload-file-1',
+ },
+ references: [
+ {
type: 'document',
transfer_method: TransferMethod.local_file,
url: '',
upload_file_id: 'upload-file-1',
},
- references: [
- {
- type: 'document',
- transfer_method: TransferMethod.local_file,
- url: '',
- upload_file_id: 'upload-file-1',
- },
- {
- type: 'document',
- transfer_method: TransferMethod.remote_url,
- url: 'https://example.com/reference.pdf',
- upload_file_id: '',
- },
- ],
- },
- action: 'approve',
+ {
+ type: 'document',
+ transfer_method: TransferMethod.remote_url,
+ url: 'https://example.com/reference.pdf',
+ upload_file_id: '',
+ },
+ ],
},
- )
+ action: 'approve',
+ })
act(() => {
result.current.handleHideGeneratedForm()
@@ -351,13 +354,99 @@ describe('human-input/hooks/use-single-run-form-params', () => {
await result.current.handleFetchFormContent({ topic: 'hello' })
})
- expect(mockFetchHumanInputNodeStepRunForm).toHaveBeenCalledWith(
- '/apps/app-2/advanced-chat/workflows/draft/human-input/nodes/node-9/form',
+ expect(previewForm).toHaveBeenCalledWith(
+ '/console/api/apps/app-2/advanced-chat/workflows/draft/human-input/nodes/node-9/form/preview',
{
inputs: { topic: 'hello' },
},
)
- expect(mockFetchHumanInputNodeStepRunForm).toHaveBeenCalledTimes(1)
+ expect(previewForm).toHaveBeenCalledTimes(1)
+ await act(async () => {
+ await result.current.handleSubmitHumanInputForm({
+ inputs: undefined,
+ form_inputs: undefined,
+ action: 'approve',
+ })
+ })
+ expect(new URL(request.mock.calls[1]![0]).pathname).toBe(
+ '/console/api/apps/app-2/advanced-chat/workflows/draft/human-input/nodes/node-9/form/run',
+ )
+ expect(await request.mock.calls[1]?.[2]?.request?.json()).toEqual({
+ inputs: { topic: 'hello' },
+ form_inputs: {},
+ action: 'approve',
+ })
+ })
+
+ it('should normalize optional field settings without losing empty defaults or zero limits', async () => {
+ previewForm.mockResolvedValue({
+ form_id: 'preview',
+ node_id: 'node-1',
+ node_title: 'Human Input',
+ form_content: '{{#$output.answer#}}',
+ inputs: [
+ { type: 'paragraph', output_variable_name: 'answer', default: null },
+ {
+ type: 'paragraph',
+ output_variable_name: 'topic',
+ default: { type: 'variable', selector: ['start', 'topic'], value: '' },
+ },
+ {
+ type: 'select',
+ output_variable_name: 'choice',
+ option_source: { type: 'constant', value: [] },
+ },
+ { type: 'file', output_variable_name: 'attachment' },
+ { type: 'file-list', output_variable_name: 'attachments', number_limits: 0 },
+ ],
+ actions: [{ id: 'approve', title: 'Approve' }],
+ resolved_default_values: { topic: '' },
+ display_in_ui: false,
+ expiration_time: 0,
+ } satisfies HumanInputFormPreviewResponse)
+
+ const { result } = renderHook(() =>
+ useSingleRunFormParams({
+ id: 'node-1',
+ payload: currentInputs,
+ runInputData: {},
+ getInputVars,
+ setRunInputData: mockSetRunInputData,
+ }),
+ )
+
+ await act(async () => {
+ await result.current.handleFetchFormContent({})
+ })
+
+ expect(result.current.formData).toMatchObject({
+ inputs: [
+ { type: 'paragraph', default: { type: 'constant', selector: [], value: '' } },
+ {
+ type: 'paragraph',
+ default: { type: 'variable', selector: ['start', 'topic'], value: '' },
+ },
+ { type: 'select', option_source: { type: 'constant', selector: [], value: [] } },
+ {
+ type: 'file',
+ allowed_file_types: [],
+ allowed_file_extensions: [],
+ allowed_file_upload_methods: [],
+ },
+ {
+ type: 'file-list',
+ allowed_file_types: [],
+ allowed_file_extensions: [],
+ allowed_file_upload_methods: [],
+ number_limits: 0,
+ },
+ ],
+ actions: [{ id: 'approve', title: 'Approve', button_style: 'default' }],
+ resolved_default_values: { topic: '' },
+ form_token: null,
+ display_in_ui: false,
+ expiration_time: 0,
+ })
})
})
diff --git a/web/app/components/workflow/nodes/human-input/hooks/use-single-run-form-params.ts b/web/app/components/workflow/nodes/human-input/hooks/use-single-run-form-params.ts
index 695ce6ff05d..3c682bc8a95 100644
--- a/web/app/components/workflow/nodes/human-input/hooks/use-single-run-form-params.ts
+++ b/web/app/components/workflow/nodes/human-input/hooks/use-single-run-form-params.ts
@@ -3,13 +3,15 @@ import type { HumanInputFieldValue } from '@/app/components/base/chat/chat/answe
import type { Props as FormProps } from '@/app/components/workflow/nodes/_base/components/before-run-form/form'
import type { InputVar } from '@/app/components/workflow/types'
import type { HumanInputFormData } from '@/types/workflow'
+import { useMutation } from '@tanstack/react-query'
import { useAtomValue } from 'jotai'
import { useCallback, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { getProcessedHumanInputFormInputs } from '@/app/components/base/chat/chat/answer/human-input-content/utils'
import { editorResourceAtom } from '@/app/components/workflow/editor-resource/state'
-import { fetchHumanInputNodeStepRunForm, submitHumanInputNodeStepRunForm } from '@/service/workflow'
+import { consoleQuery } from '@/service/console'
import useNodeCrud from '../../_base/hooks/use-node-crud'
+import { selectHumanInputFormPreview } from '../query-select'
import { getHumanInputFormDependencySelectors, isOutput } from '../utils'
const i18nPrefix = 'nodes.humanInput'
@@ -29,6 +31,18 @@ const useSingleRunFormParams = ({
getInputVars,
setRunInputData,
}: Params) => {
+ const { mutateAsync: previewWorkflowForm } = useMutation(
+ consoleQuery.apps.byAppId.workflows.draft.humanInput.nodes.byNodeId.form.preview.post.mutationOptions(),
+ )
+ const { mutateAsync: previewChatflowForm } = useMutation(
+ consoleQuery.apps.byAppId.advancedChat.workflows.draft.humanInput.nodes.byNodeId.form.preview.post.mutationOptions(),
+ )
+ const { mutateAsync: submitWorkflowForm } = useMutation(
+ consoleQuery.apps.byAppId.workflows.draft.humanInput.nodes.byNodeId.form.run.post.mutationOptions(),
+ )
+ const { mutateAsync: submitChatflowForm } = useMutation(
+ consoleQuery.apps.byAppId.advancedChat.workflows.draft.humanInput.nodes.byNodeId.form.run.post.mutationOptions(),
+ )
const { t } = useTranslation(['workflow', 'workflowHumanInput'])
const { inputs } = useNodeCrud<HumanInputNodeType>(id, payload)
const [showGeneratedForm, setShowGeneratedForm] = useState(false)
@@ -71,27 +85,23 @@ const useSingleRunFormParams = ({
const resource = useAtomValue(editorResourceAtom)
const appId = resource.kind === 'app' ? resource.appId : undefined
const isWorkflowMode = resource.kind === 'app' && resource.mode === 'workflow'
- const fetchURL = useMemo(() => {
- if (!appId) return ''
- if (!isWorkflowMode) {
- return `/apps/${appId}/advanced-chat/workflows/draft/human-input/nodes/${id}/form`
- } else {
- return `/apps/${appId}/workflows/draft/human-input/nodes/${id}/form`
- }
- }, [appId, id, isWorkflowMode])
-
const handleFetchFormContent = useCallback(
async (inputs: Record<string, string>) => {
- if (!fetchURL) return null
+ if (!appId) return null
const requestParamsObj = Object.fromEntries(
Object.entries(inputs).filter(([, value]) => value !== undefined),
)
- const data = await fetchHumanInputNodeStepRunForm(fetchURL, { inputs: requestParamsObj })
+ const previewForm = isWorkflowMode ? previewWorkflowForm : previewChatflowForm
+ const response = await previewForm({
+ params: { app_id: appId, node_id: id },
+ body: { inputs: requestParamsObj },
+ })
+ const data = selectHumanInputFormPreview(response)
setFormData(data)
setRequiredInputs(requestParamsObj)
return data
},
- [fetchURL],
+ [appId, id, isWorkflowMode, previewWorkflowForm, previewChatflowForm],
)
const handleSubmitHumanInputForm = useCallback(
@@ -100,15 +110,28 @@ const useSingleRunFormParams = ({
form_inputs: Record<string, HumanInputFieldValue> | undefined
action: string
}) => {
+ if (!appId) return
const formInputs = formData?.inputs?.length ? formData.inputs : inputs.inputs
-
- await submitHumanInputNodeStepRunForm(fetchURL, {
- inputs: requiredInputs,
- form_inputs: getProcessedHumanInputFormInputs(formInputs, submission.inputs),
- action: submission.action,
+ const submitForm = isWorkflowMode ? submitWorkflowForm : submitChatflowForm
+ await submitForm({
+ params: { app_id: appId, node_id: id },
+ body: {
+ inputs: requiredInputs,
+ form_inputs: getProcessedHumanInputFormInputs(formInputs, submission.inputs) ?? {},
+ action: submission.action,
+ },
})
},
- [fetchURL, formData?.inputs, inputs.inputs, requiredInputs],
+ [
+ appId,
+ id,
+ isWorkflowMode,
+ submitWorkflowForm,
+ submitChatflowForm,
+ formData?.inputs,
+ inputs.inputs,
+ requiredInputs,
+ ],
)
const handleShowGeneratedForm = async (formValue: Record<string, string>) => {
diff --git a/web/app/components/workflow/nodes/human-input/query-select.ts b/web/app/components/workflow/nodes/human-input/query-select.ts
new file mode 100644
index 00000000000..4af1c299f7a
--- /dev/null
+++ b/web/app/components/workflow/nodes/human-input/query-select.ts
@@ -0,0 +1,52 @@
+import type {
+ FormInputConfig,
+ HumanInputFormPreviewResponse,
+} from '@dify/contracts/api/console/apps/types.gen'
+import type { FormInputItem } from './types'
+import type { HumanInputFormData } from '@/types/workflow'
+
+const selectFormInput = (input: FormInputConfig): FormInputItem => {
+ switch (input.type) {
+ case 'paragraph':
+ return {
+ ...input,
+ default: {
+ type: input.default?.type ?? 'constant',
+ selector: input.default?.selector ?? [],
+ value: input.default?.value ?? '',
+ },
+ }
+ case 'select':
+ return {
+ ...input,
+ option_source: {
+ ...input.option_source,
+ selector: input.option_source.selector ?? [],
+ value: input.option_source.value ?? [],
+ },
+ }
+ case 'file':
+ case 'file-list':
+ return {
+ ...input,
+ allowed_file_extensions: input.allowed_file_extensions ?? [],
+ allowed_file_types: input.allowed_file_types ?? [],
+ allowed_file_upload_methods: input.allowed_file_upload_methods ?? [],
+ }
+ }
+}
+
+export const selectHumanInputFormPreview = (
+ response: HumanInputFormPreviewResponse,
+): HumanInputFormData => ({
+ ...response,
+ inputs: (response.inputs ?? []).map(selectFormInput),
+ actions: (response.actions ?? []).map((action) => ({
+ ...action,
+ button_style: action.button_style ?? 'default',
+ })),
+ form_token: response.form_token ?? null,
+ display_in_ui: response.display_in_ui ?? false,
+ expiration_time: response.expiration_time ?? null,
+ resolved_default_values: response.resolved_default_values ?? {},
+})
diff --git a/web/app/components/workflow/panel/debug-and-preview/__tests__/components.spec.tsx b/web/app/components/workflow/panel/debug-and-preview/__tests__/components.spec.tsx
index 4378a33d471..5bbfe4e97cc 100644
--- a/web/app/components/workflow/panel/debug-and-preview/__tests__/components.spec.tsx
+++ b/web/app/components/workflow/panel/debug-and-preview/__tests__/components.spec.tsx
@@ -1,3 +1,4 @@
+import type { PaginatedConversationVariableResponse } from '@dify/contracts/api/console/apps/types.gen'
import type { ChatWrapperRefType } from '../index'
import type { HumanInputFieldValue } from '@/app/components/base/chat/chat/answer/human-input-content/field-renderer'
import type { ConversationVariable } from '@/app/components/workflow/types'
@@ -16,7 +17,6 @@ import { ChatVarType } from '@/app/components/workflow/panel/chat-variable-panel
import { InputVarType } from '@/app/components/workflow/types'
import { EVENT_WORKFLOW_STOP } from '@/app/components/workflow/variable-inspect/types'
import { EventEmitterContext } from '@/context/event-emitter'
-import { fetchCurrentValueOfConversationVariable } from '@/service/workflow'
import ChatWrapper from '../chat-wrapper'
import ConversationVariableModal from '../conversation-variable-modal'
import UserInput from '../user-input'
@@ -41,10 +41,6 @@ vi.mock('@/service/console/browser', () => ({
consoleBrowserLink: { call: mockRequest },
}))
-vi.mock('@/service/workflow', () => ({
- fetchCurrentValueOfConversationVariable: vi.fn(),
-}))
-
vi.mock('@/hooks/use-timestamp', () => ({
default: () => ({
formatTime: (timestamp: number) => `formatted-${timestamp}`,
@@ -147,9 +143,6 @@ const renderWorkflowFlowComponent = (
options?: Parameters<typeof renderWorkflowFlowComponentBase>[1],
) => renderWorkflowFlowComponentBase(<Providers>{ui}</Providers>, options)
-const mockFetchCurrentValueOfConversationVariable = vi.mocked(
- fetchCurrentValueOfConversationVariable,
-)
const mockCopy = vi.mocked(copy)
const createConversationVariable = (
@@ -178,10 +171,8 @@ const createChatState = (overrides: Record<string, unknown> = {}) => ({
})
const createConversationVariableResponse = (
- data: Array<
- Awaited<ReturnType<typeof fetchCurrentValueOfConversationVariable>>['data'][number]
- > = [],
-): Awaited<ReturnType<typeof fetchCurrentValueOfConversationVariable>> => ({
+ data: PaginatedConversationVariableResponse['data'] = [],
+): PaginatedConversationVariableResponse => ({
data,
has_more: false,
limit: 20,
@@ -197,11 +188,8 @@ describe('debug-and-preview components', () => {
vi.clearAllMocks()
routeParams.appId = 'app-1'
mockRequest.mockReset()
- mockRequest.mockResolvedValue({ data: [] })
mockUseChat.mockReturnValue(createChatState())
- mockFetchCurrentValueOfConversationVariable.mockResolvedValue(
- createConversationVariableResponse(),
- )
+ mockRequest.mockResolvedValue(createConversationVariableResponse())
})
afterEach(() => {
@@ -212,7 +200,7 @@ describe('debug-and-preview components', () => {
it('copies the displayed runtime value and re-enables copying after the timeout', async () => {
vi.useFakeTimers({ shouldAdvanceTime: true })
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime })
- mockFetchCurrentValueOfConversationVariable.mockResolvedValue(
+ mockRequest.mockResolvedValue(
createConversationVariableResponse([
{
...createConversationVariable({ value: '{"latest":true}' }),
@@ -446,7 +434,7 @@ describe('debug-and-preview components', () => {
isResponding: true,
}),
)
- mockFetchCurrentValueOfConversationVariable.mockResolvedValue(
+ mockRequest.mockResolvedValue(
createConversationVariableResponse([
{
...createConversationVariable({
diff --git a/web/app/components/workflow/panel/debug-and-preview/__tests__/conversation-variable-modal.spec.tsx b/web/app/components/workflow/panel/debug-and-preview/__tests__/conversation-variable-modal.spec.tsx
index b29aa0b6be3..5b4a1ba742c 100644
--- a/web/app/components/workflow/panel/debug-and-preview/__tests__/conversation-variable-modal.spec.tsx
+++ b/web/app/components/workflow/panel/debug-and-preview/__tests__/conversation-variable-modal.spec.tsx
@@ -1,19 +1,19 @@
+import type { PaginatedConversationVariableResponse } from '@dify/contracts/api/console/apps/types.gen'
import type { ConversationVariable } from '@/app/components/workflow/types'
import { act, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import copy from 'copy-to-clipboard'
import { renderWorkflowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
import { ChatVarType } from '@/app/components/workflow/panel/chat-variable-panel/type'
-import { fetchCurrentValueOfConversationVariable } from '@/service/workflow'
+import { createDeferred } from '@/test/deferred'
import ConversationVariableModal from '../conversation-variable-modal'
vi.mock('copy-to-clipboard', () => ({
default: vi.fn(),
}))
-vi.mock('@/service/workflow', () => ({
- fetchCurrentValueOfConversationVariable: vi.fn(),
-}))
+const request = vi.hoisted(() => vi.fn<(url: string) => Promise<Response>>())
+vi.mock('@/service/base', () => ({ request }))
vi.mock('@/hooks/use-timestamp', () => ({
default: () => ({
@@ -27,9 +27,6 @@ vi.mock('@/app/components/workflow/nodes/_base/components/editor/code-editor', (
),
}))
-const mockFetchCurrentValueOfConversationVariable = vi.mocked(
- fetchCurrentValueOfConversationVariable,
-)
const mockCopy = vi.mocked(copy)
const createConversationVariable = (
@@ -44,10 +41,8 @@ const createConversationVariable = (
})
const createConversationVariableResponse = (
- data: Array<
- Awaited<ReturnType<typeof fetchCurrentValueOfConversationVariable>>['data'][number]
- > = [],
-): Awaited<ReturnType<typeof fetchCurrentValueOfConversationVariable>> => ({
+ data: PaginatedConversationVariableResponse['data'] = [],
+): PaginatedConversationVariableResponse => ({
data,
has_more: false,
limit: 20,
@@ -58,9 +53,7 @@ const createConversationVariableResponse = (
describe('ConversationVariableModal', () => {
beforeEach(() => {
vi.clearAllMocks()
- mockFetchCurrentValueOfConversationVariable.mockResolvedValue(
- createConversationVariableResponse(),
- )
+ request.mockImplementation(async () => Response.json(createConversationVariableResponse()))
})
afterEach(() => {
@@ -71,27 +64,29 @@ describe('ConversationVariableModal', () => {
it('loads latest values, switches the active variable, and closes the modal', async () => {
const user = userEvent.setup()
const onHide = vi.fn()
- mockFetchCurrentValueOfConversationVariable.mockResolvedValue(
- createConversationVariableResponse([
- {
- ...createConversationVariable({
- id: 'var-1',
- value: '{"latest":1}',
- }),
- updated_at: 100,
- created_at: 50,
- },
- {
- ...createConversationVariable({
- id: 'var-2',
- name: 'summary',
- value_type: ChatVarType.String,
- value: 'latest text',
- }),
- updated_at: 200,
- created_at: 150,
- },
- ]),
+ request.mockResolvedValue(
+ Response.json(
+ createConversationVariableResponse([
+ {
+ ...createConversationVariable({
+ id: 'var-1',
+ value: '{"latest":1}',
+ }),
+ updated_at: 100,
+ created_at: 50,
+ },
+ {
+ ...createConversationVariable({
+ id: 'var-2',
+ name: 'summary',
+ value_type: ChatVarType.String,
+ value: 'latest text',
+ }),
+ updated_at: 200,
+ created_at: 150,
+ },
+ ]),
+ ),
)
renderWorkflowComponent(
@@ -113,10 +108,13 @@ describe('ConversationVariableModal', () => {
)
await waitFor(() => {
- expect(mockFetchCurrentValueOfConversationVariable).toHaveBeenCalledWith({
- url: '/apps/app-1/conversation-variables',
- params: { conversation_id: 'conversation-1' },
- })
+ expect(request).toHaveBeenCalledWith(
+ expect.stringContaining(
+ '/apps/app-1/conversation-variables?conversation_id=conversation-1',
+ ),
+ expect.anything(),
+ expect.anything(),
+ )
})
expect(screen.getAllByText('session_state')).toHaveLength(2)
@@ -133,6 +131,37 @@ describe('ConversationVariableModal', () => {
expect(onHide).toHaveBeenCalledTimes(1)
})
+ it('keeps the current conversation values when a previous request finishes late', async () => {
+ const previous = createDeferred<Response>()
+ request.mockReturnValueOnce(previous.promise)
+ request.mockResolvedValueOnce(
+ Response.json(
+ createConversationVariableResponse([
+ { ...createConversationVariable(), value: '{"current":true}', updated_at: 200 },
+ ]),
+ ),
+ )
+ const { rerender } = renderWorkflowComponent(
+ <ConversationVariableModal conversationID="conversation-1" onHide={vi.fn()} />,
+ { initialStoreState: { conversationVariables: [createConversationVariable()] } },
+ )
+ await waitFor(() => expect(request).toHaveBeenCalledOnce())
+ rerender(<ConversationVariableModal conversationID="conversation-2" onHide={vi.fn()} />)
+ await waitFor(() =>
+ expect(screen.getByTestId('conversation-code-editor')).toHaveTextContent('{"current":true}'),
+ )
+ await act(async () =>
+ previous.resolve(
+ Response.json(
+ createConversationVariableResponse([
+ { ...createConversationVariable(), value: '{"previous":true}', updated_at: 100 },
+ ]),
+ ),
+ ),
+ )
+ expect(screen.getByTestId('conversation-code-editor')).toHaveTextContent('{"current":true}')
+ })
+
it('copies the current variable value and resets the copied state after the timeout', async () => {
vi.useFakeTimers({ shouldAdvanceTime: true })
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime })
diff --git a/web/app/components/workflow/panel/debug-and-preview/conversation-variable-modal.tsx b/web/app/components/workflow/panel/debug-and-preview/conversation-variable-modal.tsx
index 76aa1488042..141e7554b5c 100644
--- a/web/app/components/workflow/panel/debug-and-preview/conversation-variable-modal.tsx
+++ b/web/app/components/workflow/panel/debug-and-preview/conversation-variable-modal.tsx
@@ -5,7 +5,7 @@ import { cn } from '@langgenius/dify-ui/cn'
import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { RiCloseLine } from '@remixicon/react'
-import { useMount } from 'ahooks'
+import { skipToken, useQuery } from '@tanstack/react-query'
import copy from 'copy-to-clipboard'
import { capitalize } from 'es-toolkit/string'
import { useAtomValue } from 'jotai'
@@ -18,7 +18,7 @@ import { CodeLanguage } from '@/app/components/workflow/nodes/code/types'
import { ChatVarType } from '@/app/components/workflow/panel/chat-variable-panel/type'
import { useStore } from '@/app/components/workflow/store'
import useTimestamp from '@/hooks/use-timestamp'
-import { fetchCurrentValueOfConversationVariable } from '@/service/workflow'
+import { consoleQuery } from '@/service/console'
type Props = Readonly<{
conversationID: string
@@ -31,33 +31,19 @@ const ConversationVariableModal = ({ conversationID, onHide }: Props) => {
const varList = useStore((s) => s.conversationVariables) as ConversationVariable[]
const appID = useAtomValue(editorAppIdAtom)
const [currentVar, setCurrentVar] = React.useState<ConversationVariable>(varList[0]!)
- const [latestValueMap, setLatestValueMap] = React.useState<Record<string, string>>({})
- const [latestValueTimestampMap, setLatestValueTimestampMap] = React.useState<
- Record<string, number>
- >({})
-
- const getChatVarLatestValues = useCallback(async () => {
- if (conversationID && varList.length > 0) {
- const res = await fetchCurrentValueOfConversationVariable({
- url: `/apps/${appID}/conversation-variables`,
- params: { conversation_id: conversationID },
- })
- if (res.data.length > 0) {
- const valueMap = res.data.reduce((acc: any, cur) => {
- acc[cur.id] = cur.value
- return acc
- }, {})
- setLatestValueMap(valueMap)
- const timestampMap = res.data.reduce((acc: any, cur) => {
- acc[cur.id] = cur.updated_at
- return acc
- }, {})
- setLatestValueTimestampMap(timestampMap)
- }
- }
- }, [appID, conversationID, varList.length])
-
- const currentValue = latestValueMap[currentVar.id] ?? currentVar.value
+ const { data: latestValues } = useQuery(
+ consoleQuery.apps.byAppId.conversationVariables.get.queryOptions({
+ input:
+ appID && conversationID
+ ? { params: { app_id: appID }, query: { conversation_id: conversationID } }
+ : skipToken,
+ enabled: varList.length > 0,
+ staleTime: 0,
+ }),
+ )
+ const latestVariable = latestValues?.data.find((variable) => variable.id === currentVar.id)
+ const currentValue = latestVariable?.value ?? currentVar.value
+ const updatedAt = latestVariable?.updated_at
const copyResetTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)
useEffect(() => () => clearTimeout(copyResetTimer.current), [])
const [isCopied, setIsCopied] = React.useState(false)
@@ -70,10 +56,6 @@ const ConversationVariableModal = ({ conversationID, onHide }: Props) => {
}, 2000)
}, [currentValue])
- useMount(() => {
- getChatVarLatestValues()
- })
-
return (
<Dialog open>
<DialogContent className="h-[min(640px,calc(100dvh-2rem))] w-230 overflow-hidden">
@@ -153,13 +135,10 @@ const ConversationVariableModal = ({ conversationID, onHide }: Props) => {
'linear-gradient(to right, rgba(16, 24, 40, 0.08) 0%, rgba(255, 255, 255) 100%)',
}}
></div>
- {!!latestValueTimestampMap[currentVar.id] && (
+ {!!updatedAt && (
<div className="shrink-0 system-xs-regular text-text-tertiary">
{t(($) => $['chatVariable.updatedAt'], { ns: 'workflow' })}
- {formatTime(
- latestValueTimestampMap[currentVar.id]!,
- t(($) => $.dateTimeFormat, { ns: 'appLog' }) as string,
- )}
+ {formatTime(updatedAt!, t(($) => $.dateTimeFormat, { ns: 'appLog' }) as string)}
</div>
)}
</div>
diff --git a/web/app/components/workflow/panel/version-history-panel/__tests__/index.spec.tsx b/web/app/components/workflow/panel/version-history-panel/__tests__/index.spec.tsx
index 1d96faa9bce..cc87bcdf6b5 100644
--- a/web/app/components/workflow/panel/version-history-panel/__tests__/index.spec.tsx
+++ b/web/app/components/workflow/panel/version-history-panel/__tests__/index.spec.tsx
@@ -14,6 +14,7 @@ const mockHandleLoadBackupDraft = vi.fn()
const mockHandleRefreshWorkflowDraft = vi.fn()
const mockHandleExportDSL = vi.fn()
const mockRestoreWorkflow = vi.fn()
+const mockDeleteWorkflow = vi.fn()
const mockUpdateWorkflow = vi.fn()
const mockInvalidateAppWorkflow = vi.fn()
const mockEmitRestoreIntent = vi.fn()
@@ -64,7 +65,7 @@ vi.mock('@/app/notifications', () => ({ toast: mockToast }))
vi.mock('@/service/use-workflow', async (importOriginal) => ({
...(await importOriginal<typeof import('@/service/use-workflow')>()),
- useDeleteWorkflow: () => ({ mutateAsync: vi.fn() }),
+ useDeleteWorkflow: () => mockDeleteWorkflow,
useInvalidateAppWorkflow: () => mockInvalidateAppWorkflow,
useInvalidateAllLastRun: () => vi.fn(),
useResetWorkflowVersionHistory: () => vi.fn(),
@@ -128,7 +129,7 @@ vi.mock('@/app/components/app/app-publisher/version-info-modal', () => ({
vi.mock('@/service/base', async (importOriginal) => ({
...(await importOriginal<typeof import('@/service/base')>()),
- patch: (...args: unknown[]) => mockUpdateWorkflow(...args),
+ request: async (...args: unknown[]) => Response.json(await mockUpdateWorkflow(...args)),
}))
let renderedStore: ReturnType<typeof renderWorkflowComponent>['store']
@@ -142,6 +143,7 @@ const selectAction = async (name: RegExp) => {
describe('VersionHistoryPanel', () => {
beforeEach(() => {
vi.clearAllMocks()
+ mockDeleteWorkflow.mockResolvedValue(undefined)
mockRestoreWorkflow.mockResolvedValue(undefined)
mockUpdateWorkflow.mockResolvedValue(undefined)
mockCurrentVersion = null
@@ -278,6 +280,22 @@ describe('VersionHistoryPanel', () => {
expect(mockToast.error).not.toHaveBeenCalled()
})
+ it.each([false, true])('handles version deletion (failed: %s)', async (failed) => {
+ const user = userEvent.setup()
+ if (failed) mockDeleteWorkflow.mockRejectedValueOnce(new Error('Delete failed'))
+ const { VersionHistoryPanel } = await import('../index')
+ render(<VersionHistoryPanel latestVersionId="newer-version-id" />)
+ await selectAction(/operation\.delete/)
+ await user.click(screen.getByRole('button', { name: 'common.operation.delete' }))
+ await waitFor(() => expect(mockDeleteWorkflow).toHaveBeenCalledWith('published-version-id'))
+ await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
+ if (failed)
+ expect(mockToast.error).toHaveBeenCalledWith(
+ 'workflowHistory.versionHistory.action.deleteFailure',
+ )
+ else expect(mockToast.error).not.toHaveBeenCalled()
+ })
+
it('should keep restore mode backup state when restore request fails', async () => {
const user = userEvent.setup()
const { VersionHistoryPanel } = await import('../index')
@@ -317,20 +335,16 @@ describe('VersionHistoryPanel', () => {
})
const { VersionHistoryPanel } = await import('../index')
- render(
- <VersionHistoryPanel
- latestVersionId="published-version-id"
- updateVersionUrl={(versionId) => `/apps/app-1/workflows/${versionId}`}
- />,
- )
+ render(<VersionHistoryPanel latestVersionId="published-version-id" />)
await selectAction(/editVersionInfo/)
await user.click(screen.getByRole('button', { name: 'submit version info' }))
await waitFor(() => {
expect(mockUpdateWorkflow).toHaveBeenCalledWith(
- '/apps/app-1/workflows/published-version-id',
- { body: { marked_name: 'Updated release', marked_comment: 'Updated notes' } },
+ expect.stringContaining('/apps/app-1/workflows/published-version-id'),
+ expect.anything(),
+ expect.objectContaining({ request: expect.objectContaining({ method: 'PATCH' }) }),
)
expect(mockInvalidateAppWorkflow).toHaveBeenCalledWith('app-1')
})
diff --git a/web/app/components/workflow/panel/version-history-panel/index.tsx b/web/app/components/workflow/panel/version-history-panel/index.tsx
index 4ae8115605c..21a69acfe06 100644
--- a/web/app/components/workflow/panel/version-history-panel/index.tsx
+++ b/web/app/components/workflow/panel/version-history-panel/index.tsx
@@ -10,7 +10,6 @@ import { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
import VersionInfoModal from '@/app/components/app/app-publisher/version-info-modal'
import { PlanUpgradeModal } from '@/app/components/billing/plan-upgrade-modal'
-import { getEditorResourceId } from '@/app/components/workflow/editor-resource/resource'
import { editorResourceAtom } from '@/app/components/workflow/editor-resource/state'
import { getWorkflowVersionName } from '@/app/components/workflow/utils/version'
import { toast } from '@/app/notifications'
@@ -48,15 +47,11 @@ const INITIAL_PAGE = 1
export type VersionHistoryPanelProps = {
getVersionListUrl?: string
- deleteVersionUrl?: (versionId: string) => string
- updateVersionUrl?: (versionId: string) => string
latestVersionId?: string
}
export const VersionHistoryPanel = ({
getVersionListUrl,
- deleteVersionUrl,
- updateVersionUrl,
latestVersionId,
}: VersionHistoryPanelProps) => {
const [filterValue, setFilterValue] = useState<WorkflowVersionFilterOptions>(
@@ -88,7 +83,6 @@ export const VersionHistoryPanel = ({
select: (data) => data.profile,
})
const resource = useAtomValue(editorResourceAtom)
- const resourceId = getEditorResourceId(resource)
const canImportExportDSL = useHooksStore((s) => s.accessControl.canImportExportDSL)
const invalidAllLastRun = useInvalidateAllLastRun(resource)
const invalidateAppWorkflow = useInvalidateAppWorkflow()
@@ -303,33 +297,22 @@ export const VersionHistoryPanel = ({
],
)
- const { mutateAsync: deleteWorkflow } = useDeleteWorkflow()
+ const deleteWorkflow = useDeleteWorkflow(resource)
const handleDelete = useCallback(
async (id: string) => {
- await deleteWorkflow(deleteVersionUrl?.(id) || '', {
- onSuccess: () => {
- setDeleteConfirmOpen(false)
- resetWorkflowVersionHistory()
- deleteAllInspectVars()
- invalidAllLastRun()
- },
- onError: () => {
- toast.error(t(($) => $['versionHistory.action.deleteFailure'], { ns: 'workflowHistory' }))
- },
- onSettled: () => {
- setDeleteConfirmOpen(false)
- },
- })
+ try {
+ await deleteWorkflow(id)
+ resetWorkflowVersionHistory()
+ deleteAllInspectVars()
+ invalidAllLastRun()
+ } catch {
+ toast.error(t(($) => $['versionHistory.action.deleteFailure'], { ns: 'workflowHistory' }))
+ } finally {
+ setDeleteConfirmOpen(false)
+ }
},
- [
- deleteWorkflow,
- t,
- resetWorkflowVersionHistory,
- deleteAllInspectVars,
- invalidAllLastRun,
- deleteVersionUrl,
- ],
+ [deleteWorkflow, t, resetWorkflowVersionHistory, deleteAllInspectVars, invalidAllLastRun],
)
const { mutateAsync: updateWorkflow } = useUpdateWorkflow()
@@ -337,40 +320,17 @@ export const VersionHistoryPanel = ({
const handleUpdateWorkflow = useCallback(
async (params: { id?: string; title: string; releaseNotes: string }) => {
const { id, ...rest } = params
- await updateWorkflow(
- {
- ...(resource.kind === 'app' && resourceId
- ? { appId: resource.appId, appMode: resource.mode }
- : {}),
- url: updateVersionUrl?.(id || '') || '',
- ...rest,
- },
- {
- onSuccess: () => {
- setEditModalOpen(false)
- if (id === latestVersionId && resource.kind === 'app' && resourceId)
- invalidateAppWorkflow(resourceId)
- },
- onError: () => {
- toast.error(
- t(($) => $['versionHistory.action.updateFailure'], { ns: 'workflowHistory' }),
- )
- },
- onSettled: () => {
- setEditModalOpen(false)
- },
- },
- )
+ if (!id) return
+ try {
+ await updateWorkflow({ resource, versionId: id, ...rest })
+ if (id === latestVersionId && resource.kind === 'app') invalidateAppWorkflow(resource.appId)
+ } catch {
+ toast.error(t(($) => $['versionHistory.action.updateFailure'], { ns: 'workflowHistory' }))
+ } finally {
+ setEditModalOpen(false)
+ }
},
- [
- resourceId,
- resource,
- invalidateAppWorkflow,
- latestVersionId,
- t,
- updateWorkflow,
- updateVersionUrl,
- ],
+ [resource, invalidateAppWorkflow, latestVersionId, t, updateWorkflow],
)
return (
diff --git a/web/app/components/workflow/workflow-generator/__tests__/apply.spec.ts b/web/app/components/workflow/workflow-generator/__tests__/apply.spec.ts
index fc04e577237..3db3222784f 100644
--- a/web/app/components/workflow/workflow-generator/__tests__/apply.spec.ts
+++ b/web/app/components/workflow/workflow-generator/__tests__/apply.spec.ts
@@ -17,7 +17,28 @@ const mockDeleteApp = vi.fn()
vi.mock('@/service/base', async (importOriginal) => ({
...(await importOriginal<typeof import('@/service/base')>()),
request: async (_url: string, _init: RequestInit, { request }: { request: Request }) => {
- if (request.method === 'POST') return Response.json(await mockCreateApp(await request.json()))
+ if (request.method === 'GET' && new URL(request.url).pathname.endsWith('/workflows/draft')) {
+ const draft = await mockFetchWorkflowDraft(
+ new URL(request.url).pathname.replace(/^.*\/apps\//, 'apps/'),
+ )
+ return draft
+ ? Response.json(draft)
+ : Response.json(
+ { code: 'draft_workflow_not_exist', message: 'Draft not found', status: 404 },
+ { status: 404 },
+ )
+ }
+ if (request.method === 'POST') {
+ if (new URL(request.url).pathname.endsWith('/workflows/draft')) {
+ return Response.json(
+ await mockSyncWorkflowDraft({
+ url: new URL(request.url).pathname.replace(/^.*\/apps\//, 'apps/'),
+ body: await request.json(),
+ }),
+ )
+ }
+ return Response.json(await mockCreateApp(await request.json()))
+ }
if (request.method === 'DELETE') {
await mockDeleteApp(new URL(request.url).pathname.split('/').at(-1))
return new Response(null, { status: 204 })
@@ -26,11 +47,6 @@ vi.mock('@/service/base', async (importOriginal) => ({
},
}))
-vi.mock('@/service/workflow', () => ({
- fetchWorkflowDraft: (url: string) => mockFetchWorkflowDraft(url),
- syncWorkflowDraft: (params: unknown) => mockSyncWorkflowDraft(params),
-}))
-
const makeGraph = (): GeneratedGraph => ({
nodes: [
{
@@ -92,7 +108,7 @@ describe('applyToNewApp', () => {
)
expect(mockSyncWorkflowDraft).toHaveBeenCalledWith({
url: 'apps/new-app-1/workflows/draft',
- params: {
+ body: {
graph,
features: {},
conversation_variables: [],
@@ -131,7 +147,7 @@ describe('applyToNewApp', () => {
instruction: 'Summarize a URL',
})
- const savedGraph = mockSyncWorkflowDraft.mock.calls[0]![0].params.graph
+ const savedGraph = mockSyncWorkflowDraft.mock.calls[0]![0].body.graph
expect(savedGraph.nodes[1].data).not.toHaveProperty('memory')
})
@@ -144,7 +160,7 @@ describe('applyToNewApp', () => {
instruction: 'Answer questions in a conversation',
})
- const savedGraph = mockSyncWorkflowDraft.mock.calls[0]![0].params.graph
+ const savedGraph = mockSyncWorkflowDraft.mock.calls[0]![0].body.graph
expect(savedGraph.nodes[1].data).toHaveProperty('memory')
expect(savedGraph).toEqual(graph)
})
@@ -269,7 +285,7 @@ describe('applyToCurrentApp', () => {
graph: makeGraphWithMemory(),
})
- const savedGraph = mockSyncWorkflowDraft.mock.calls[0]![0].params.graph
+ const savedGraph = mockSyncWorkflowDraft.mock.calls[0]![0].body.graph
expect(savedGraph.nodes[1].data).not.toHaveProperty('memory')
})
@@ -280,7 +296,7 @@ describe('applyToCurrentApp', () => {
await applyToCurrentApp({ appId: 'app-42', appMode, graph })
- const savedGraph = mockSyncWorkflowDraft.mock.calls[0]![0].params.graph
+ const savedGraph = mockSyncWorkflowDraft.mock.calls[0]![0].body.graph
expect(savedGraph.nodes[1].data).toHaveProperty('memory')
expect(savedGraph).toEqual(graph)
},
@@ -303,7 +319,7 @@ describe('applyToCurrentApp', () => {
expect(mockFetchWorkflowDraft).toHaveBeenCalledWith('apps/app-42/workflows/draft')
expect(mockSyncWorkflowDraft).toHaveBeenCalledWith({
url: 'apps/app-42/workflows/draft',
- params: expect.objectContaining({
+ body: expect.objectContaining({
graph,
features: { file_upload: { enabled: true } },
hash: 'h-existing',
@@ -311,7 +327,7 @@ describe('applyToCurrentApp', () => {
})
// Environment variables are preserved server-side; conversation variables
// must still be forwarded verbatim.
- const params = mockSyncWorkflowDraft.mock.calls[0]![0].params
+ const params = mockSyncWorkflowDraft.mock.calls[0]![0].body
expect(params).not.toHaveProperty('environment_variables')
expect(params.conversation_variables).toEqual([
{ id: 'c1', name: 'memory', value_type: 'string', value: '' },
@@ -319,7 +335,7 @@ describe('applyToCurrentApp', () => {
})
// First-apply path: a freshly created Workflow app has no draft yet, so the
- // fetch resolves to undefined and we must sync without a hash field so the
+ // fetch returns 404 and we must sync without a hash field so the
// backend lazy-creates the draft instead of raising.
it('should sync without a hash when no draft yet exists', async () => {
mockFetchWorkflowDraft.mockResolvedValue(undefined)
@@ -327,7 +343,7 @@ describe('applyToCurrentApp', () => {
await applyToCurrentApp({ appId: 'fresh-app', graph: makeGraph() })
expect(mockSyncWorkflowDraft).toHaveBeenCalledTimes(1)
- const params = mockSyncWorkflowDraft.mock.calls[0]![0].params
+ const params = mockSyncWorkflowDraft.mock.calls[0]![0].body
expect(params).not.toHaveProperty('hash')
expect(params.features).toEqual({})
expect(params).not.toHaveProperty('environment_variables')
@@ -342,7 +358,7 @@ describe('applyToCurrentApp', () => {
await applyToCurrentApp({ appId: 'app-7', graph: makeGraph() })
expect(mockSyncWorkflowDraft).toHaveBeenCalledTimes(1)
- const params = mockSyncWorkflowDraft.mock.calls[0]![0].params
+ const params = mockSyncWorkflowDraft.mock.calls[0]![0].body
expect(params).not.toHaveProperty('hash')
})
diff --git a/web/app/components/workflow/workflow-generator/__tests__/index.spec.tsx b/web/app/components/workflow/workflow-generator/__tests__/index.spec.tsx
index 2e6a162b151..9aacd45aa82 100644
--- a/web/app/components/workflow/workflow-generator/__tests__/index.spec.tsx
+++ b/web/app/components/workflow/workflow-generator/__tests__/index.spec.tsx
@@ -59,9 +59,13 @@ vi.mock('@/service/workflow-generator', () => ({
generateWorkflowStream: (...args: unknown[]) => mockGenerateWorkflowStream(...args),
}))
-vi.mock('@/service/workflow', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@/service/workflow')>()),
- fetchWorkflowDraft: (...args: unknown[]) => mockFetchWorkflowDraft(...args),
+vi.mock('@/service/base', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/service/base')>()),
+ request: async (url: string, _init: RequestInit, { request }: { request: Request }) => {
+ if (request.method === 'GET' && new URL(url).pathname.endsWith('/workflows/draft'))
+ return Response.json(await mockFetchWorkflowDraft(new URL(url).pathname))
+ throw new Error(`Unexpected request: ${request.method} ${url}`)
+ },
}))
describe('WorkflowGeneratorModal', () => {
@@ -226,6 +230,7 @@ describe('WorkflowGeneratorModal', () => {
type: 'custom',
position: { x: 0, y: 0 },
data: { type: 'start', title: 'Start' },
+ width: 240,
},
],
edges: [],
@@ -258,6 +263,9 @@ describe('WorkflowGeneratorModal', () => {
await user.click(generateButton)
await waitFor(() => {
+ expect(mockFetchWorkflowDraft).toHaveBeenCalledWith(
+ '/console/api/apps/app-1/workflows/draft',
+ )
expect(mockGenerateWorkflowStream).toHaveBeenCalledWith(
expect.objectContaining({ current_graph: currentGraph }),
expect.any(Object),
diff --git a/web/app/components/workflow/workflow-generator/apply.ts b/web/app/components/workflow/workflow-generator/apply.ts
index a084d9060a9..59bb801f922 100644
--- a/web/app/components/workflow/workflow-generator/apply.ts
+++ b/web/app/components/workflow/workflow-generator/apply.ts
@@ -1,9 +1,9 @@
+import type { WorkflowResponse } from '@dify/contracts/api/console/apps/types.gen'
import type { GeneratedGraph, WorkflowGeneratorMode } from './types'
import type { WorkflowAppMode } from '@/app/components/apps/app-type'
import { normalizeWorkflowNodes } from '@/app/components/workflow/utils/normalize-workflow-nodes'
import { consoleClient } from '@/service/console'
import { getHttpErrorStatus } from '@/service/http-error'
-import { fetchWorkflowDraft, syncWorkflowDraft } from '@/service/workflow'
const MODE_TO_APP_MODE = {
workflow: 'workflow',
@@ -112,14 +112,17 @@ export const applyToNewApp = async ({
// so the caller can route to /apps where the orphan is still recoverable
// by hand.
try {
- await syncWorkflowDraft({
- url: `apps/${app.id}/workflows/draft`,
- params: {
- graph: { ...graph, nodes: normalizeWorkflowNodes(graph.nodes, appMode) },
- features: {},
- conversation_variables: [],
+ await consoleClient.apps.byAppId.workflows.draft.post(
+ {
+ params: { app_id: app.id },
+ body: {
+ graph: { ...graph, nodes: normalizeWorkflowNodes(graph.nodes, appMode) },
+ features: {},
+ conversation_variables: [],
+ },
},
- })
+ { context: { silent: true } },
+ )
} catch (syncErr) {
try {
await consoleClient.apps.byAppId.delete({ params: { app_id: app.id } })
@@ -156,31 +159,32 @@ export const applyToCurrentApp = async ({
appMode,
graph,
}: ApplyToCurrentAppParams): Promise<void> => {
- const url = `apps/${appId}/workflows/draft`
-
// First sync may have no existing draft (workflow apps can exist before Studio
- // has created/saved a draft). ``fetchWorkflowDraft`` rejects on non-2xx (e.g.
- // 404), so we treat any fetch failure as "no existing draft" and sync without
- // a hash.
- let existing: Awaited<ReturnType<typeof fetchWorkflowDraft>> | null = null
+ // has created/saved a draft). Preserve the existing fallback: treat a fetch
+ // failure as "no existing draft" and sync without a hash.
+ let existing: WorkflowResponse | null = null
try {
- existing = await fetchWorkflowDraft(url)
+ existing = await consoleClient.apps.byAppId.workflows.draft.get(
+ { params: { app_id: appId } },
+ { context: { silent: true } },
+ )
} catch {
existing = null
}
try {
- await syncWorkflowDraft({
- url,
- params: {
- graph: { ...graph, nodes: normalizeWorkflowNodes(graph.nodes, appMode) },
- features: existing?.features ?? {},
- conversation_variables: existing?.conversation_variables ?? [],
- // Field is accepted by the backend but not typed in the Pick<> shape of
- // ``syncWorkflowDraft``'s params — spread it in so it reaches the wire.
- ...(existing?.hash ? { hash: existing.hash } : {}),
- } as Parameters<typeof syncWorkflowDraft>[0]['params'],
- })
+ await consoleClient.apps.byAppId.workflows.draft.post(
+ {
+ params: { app_id: appId },
+ body: {
+ graph: { ...graph, nodes: normalizeWorkflowNodes(graph.nodes, appMode) },
+ features: existing?.features ?? {},
+ conversation_variables: existing?.conversation_variables ?? [],
+ ...(existing?.hash ? { hash: existing.hash } : {}),
+ },
+ },
+ { context: { silent: true } },
+ )
} catch (e) {
// 409 → draft was edited in another tab between our fetch and sync.
// Translate the HTTP error into a domain error so the caller
diff --git a/web/app/components/workflow/workflow-generator/graph-diff.ts b/web/app/components/workflow/workflow-generator/graph-diff.ts
index 134d828f199..a280a86d222 100644
--- a/web/app/components/workflow/workflow-generator/graph-diff.ts
+++ b/web/app/components/workflow/workflow-generator/graph-diff.ts
@@ -1,4 +1,8 @@
-import type { GeneratedGraph } from './types'
+import type { WorkflowGraphNode } from '@dify/contracts/api/console/workflow-generate/types.gen'
+
+type DiffGraph = {
+ nodes: ReadonlyArray<Pick<WorkflowGraphNode, 'id' | 'data'>>
+}
export type GraphDiff = {
/** Node ids present in the new graph but not the base. */
@@ -18,7 +22,7 @@ export type GraphDiff = {
* ``data``; edges and layout (which the generator always rewrites) are ignored
* so cosmetic re-layouts don't read as changes.
*/
-export const diffGraphs = (base: GeneratedGraph, next: GeneratedGraph): GraphDiff => {
+export const diffGraphs = (base: DiffGraph, next: DiffGraph): GraphDiff => {
const baseById = new Map(base.nodes.map((node) => [node.id, node]))
const nextById = new Map(next.nodes.map((node) => [node.id, node]))
diff --git a/web/app/components/workflow/workflow-generator/index.tsx b/web/app/components/workflow/workflow-generator/index.tsx
index 7f2ace3ac9c..9779e2a3593 100644
--- a/web/app/components/workflow/workflow-generator/index.tsx
+++ b/web/app/components/workflow/workflow-generator/index.tsx
@@ -4,12 +4,14 @@ import type {
WorkflowGenerateErrorResponse,
WorkflowGeneratePayload,
WorkflowGeneratePlanEventResponse,
+ WorkflowGraph,
} from '@dify/contracts/api/console/workflow-generate/types.gen'
import type { HotkeyChord } from '@tanstack/react-hotkeys'
import type { SelectorParam, TFunction } from 'i18next'
import type { GeneratedGraph } from './types'
import type { FormValue } from '@/app/components/header/account-setting/model-provider-page/declarations'
import type { CompletionParams, ModelModeType } from '@/types/app'
+import { zWorkflowGraph } from '@dify/contracts/api/console/workflow-generate/zod.gen'
import {
AlertDialog,
AlertDialogCancelButton,
@@ -39,7 +41,7 @@ import { WORKFLOW_GENERATION_TIMEOUT_MS } from '@/config'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import Link from '@/next/link'
import { useRouter } from '@/next/navigation'
-import { fetchWorkflowDraft } from '@/service/workflow'
+import { consoleClient } from '@/service/console'
import { generateWorkflow, generateWorkflowStream } from '@/service/workflow-generator'
import { getRedirectionPath } from '@/utils/app-redirection'
import {
@@ -222,7 +224,7 @@ function WorkflowGeneratorModal() {
const [genError, setGenError] = useState<WorkflowGenerateErrorResponse[] | null>(null)
// Refine base graph captured at Generate time, diffed against the result so
// the user can see what "apply" changes before overwriting their draft.
- const [refineBaseGraph, setRefineBaseGraph] = useState<GeneratedGraph | null>(null)
+ const [refineBaseGraph, setRefineBaseGraph] = useState<WorkflowGraph | null>(null)
const storageKey = `${mode}-${currentAppId ?? 'new'}`
const { addVersion, current, currentVersionIndex, setCurrentVersionIndex, versions } =
@@ -365,11 +367,18 @@ function WorkflowGeneratorModal() {
// provider, so we read the persisted draft rather than the live canvas. A
// fetch failure (no draft yet) degrades to from-scratch generation, but we
// warn since the user explicitly asked to refine.
- let currentGraph: GeneratedGraph | undefined
+ let currentGraph: WorkflowGraph | undefined
if (isRefine && currentAppId) {
try {
- const draft = await fetchWorkflowDraft(`apps/${currentAppId}/workflows/draft`)
- if (draft?.graph?.nodes?.length) currentGraph = draft.graph as GeneratedGraph
+ const draft = await consoleClient.apps.byAppId.workflows.draft.get(
+ { params: { app_id: currentAppId } },
+ { context: { silent: true } },
+ )
+ // Validate the generator's graph requirements without stripping editor metadata.
+ if (zWorkflowGraph.safeParse(draft.graph).success) {
+ const graph = draft.graph as WorkflowGraph
+ if (graph.nodes.length) currentGraph = graph
+ }
} catch {
currentGraph = undefined
}
@@ -386,9 +395,7 @@ function WorkflowGeneratorModal() {
mode: autoMode ? 'auto' : mode,
instruction,
model_config: { ...model, mode: model.mode || 'chat' },
- ...(currentGraph
- ? { current_graph: currentGraph as unknown as WorkflowGeneratePayload['current_graph'] }
- : {}),
+ ...(currentGraph ? { current_graph: currentGraph } : {}),
}
const finish = () => {
@@ -565,7 +572,7 @@ function WorkflowGeneratorModal() {
// Refine diff — what an "apply" would change vs. the draft we started from.
const refineDiff = useMemo(() => {
if (!isRefine || !refineBaseGraph || !current?.graph?.nodes?.length) return null
- return diffGraphs(refineBaseGraph, current.graph as GeneratedGraph)
+ return diffGraphs(refineBaseGraph, current.graph)
}, [isRefine, refineBaseGraph, current])
const hasRefineChanges =
!!refineDiff &&
diff --git a/web/app/signin/check-code/__tests__/page.spec.tsx b/web/app/signin/check-code/__tests__/page.spec.tsx
index 9cc170311ab..9e27bce61f4 100644
--- a/web/app/signin/check-code/__tests__/page.spec.tsx
+++ b/web/app/signin/check-code/__tests__/page.spec.tsx
@@ -17,7 +17,7 @@ const navigationMocks = vi.hoisted(() => ({
}))
const serviceBaseMocks = vi.hoisted(() => ({
- get: vi.fn(),
+ request: vi.fn(),
}))
type ScriptProps = {
@@ -69,17 +69,21 @@ vi.mock('@/next/navigation', () => ({
vi.mock('@/service/base', () => serviceBaseMocks)
-vi.mock('@/service/console', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@/service/console')>()),
- consoleClient: {
- emailCodeLogin: {
- validity: {
+vi.mock('@/service/console', async (importOriginal) => {
+ const original = await importOriginal<typeof import('@/service/console')>()
+ return {
+ ...original,
+ consoleClient: {
+ account: original.consoleClient.account,
+ emailCodeLogin: {
+ validity: {
+ post: vi.fn(),
+ },
post: vi.fn(),
},
- post: vi.fn(),
},
- },
-}))
+ }
+})
vi.mock('@/utils/timezone', () => ({
getBrowserTimezone: () => 'Asia/Singapore',
@@ -136,7 +140,7 @@ describe('CheckCode', () => {
beforeEach(() => {
vi.clearAllMocks()
localStorage.setItem(COUNT_DOWN_KEY, '0')
- serviceBaseMocks.get.mockReset()
+ serviceBaseMocks.request.mockReset()
vi.mocked(consoleClient.emailCodeLogin.validity.post)
.mockReset()
.mockResolvedValue({ result: 'success' })
@@ -513,7 +517,7 @@ describe('CheckCode', () => {
const profileResponse = new Promise<Response>((resolve) => {
resolveProfileResponse = resolve
})
- serviceBaseMocks.get
+ serviceBaseMocks.request
.mockRejectedValueOnce(createHttpError(new Response(null, { status: 401 })))
.mockReturnValueOnce(profileResponse)
await queryClient.query(profileQueryOptions).catch(noop)
@@ -529,7 +533,7 @@ describe('CheckCode', () => {
await user.click(screen.getByRole('button', { name: 'login.checkCode.verify' }))
await waitFor(() => {
- expect(serviceBaseMocks.get).toHaveBeenCalledTimes(2)
+ expect(serviceBaseMocks.request).toHaveBeenCalledTimes(2)
})
expect(queryClient.getQueryState(profileQueryKey)).toMatchObject({
fetchStatus: 'fetching',
@@ -562,7 +566,7 @@ describe('CheckCode', () => {
email: 'hanxujiang%2B4%40dify.ai',
token: 'email-login-token',
})
- serviceBaseMocks.get.mockResolvedValue(
+ serviceBaseMocks.request.mockResolvedValue(
new Response(JSON.stringify(accountProfile), {
headers: {
'content-type': 'application/json',
diff --git a/web/app/signin/invite-settings/__tests__/page.spec.tsx b/web/app/signin/invite-settings/__tests__/page.spec.tsx
index d0577c462fd..2de70651a98 100644
--- a/web/app/signin/invite-settings/__tests__/page.spec.tsx
+++ b/web/app/signin/invite-settings/__tests__/page.spec.tsx
@@ -32,7 +32,7 @@ vi.mock('@/next/navigation', () => ({
}))
vi.mock('@/service/base', async (importOriginal) => ({
...(await importOriginal<typeof import('@/service/base')>()),
- get: mocks.profile,
+ request: mocks.profile,
}))
vi.mock('@/service/console', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/service/console')>()
diff --git a/web/features/account-profile/__tests__/client.spec.ts b/web/features/account-profile/__tests__/client.spec.ts
new file mode 100644
index 00000000000..668e4236c18
--- /dev/null
+++ b/web/features/account-profile/__tests__/client.spec.ts
@@ -0,0 +1,85 @@
+import type { GetAccountProfileResponse } from '@dify/contracts/api/console/account/types.gen'
+import { QueryClient } from '@tanstack/react-query'
+import { createHttpError } from '@/service/http-error'
+import { userProfileQueryOptions } from '../client'
+
+const request = vi.hoisted(() => vi.fn<typeof import('@/service/base').request>())
+vi.mock('@/service/base', () => ({ request }))
+vi.mock('@/config', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/config')>()),
+ IS_DEV: false,
+}))
+
+const profile: GetAccountProfileResponse = {
+ id: 'account-1',
+ name: 'Account',
+ email: '[email protected]',
+ avatar: '',
+ avatar_url: null,
+ is_password_set: true,
+}
+
+afterEach(() => request.mockReset())
+
+it.each<{
+ headers: HeadersInit
+ currentVersion: string | null
+ currentEnv: string | null
+}>([
+ {
+ headers: { 'x-version': '1.2.3', 'x-env': 'PRODUCTION' },
+ currentVersion: '1.2.3',
+ currentEnv: 'PRODUCTION',
+ },
+ { headers: {}, currentVersion: null, currentEnv: null },
+])(
+ 'preserves profile response metadata: $currentVersion, $currentEnv',
+ async ({ headers, currentVersion, currentEnv }) => {
+ request.mockResolvedValueOnce(Response.json(profile, { headers }))
+ const client = new QueryClient()
+ try {
+ await expect(client.query(userProfileQueryOptions())).resolves.toEqual({
+ profile,
+ meta: { currentVersion, currentEnv },
+ })
+ expect(new URL(request.mock.calls[0]![0]).pathname).toBe('/console/api/account/profile')
+ expect(request.mock.calls[0]?.[2]).toMatchObject({ silent: true })
+ expect(request.mock.calls[0]?.[2]?.request?.method).toBe('GET')
+ } finally {
+ client.clear()
+ }
+ },
+)
+
+it('keeps response headers local to concurrent profile requests', async () => {
+ let count = 0
+ request.mockImplementation(async () => {
+ const version = `${++count}`
+ return Response.json({ ...profile, id: version }, { headers: { 'x-version': version } })
+ })
+ const first = new QueryClient()
+ const second = new QueryClient()
+ try {
+ const responses = await Promise.all([
+ first.query(userProfileQueryOptions()),
+ second.query(userProfileQueryOptions()),
+ ])
+ for (const response of responses) expect(response.meta.currentVersion).toBe(response.profile.id)
+ expect(responses[0]?.profile.id).not.toBe(responses[1]?.profile.id)
+ } finally {
+ first.clear()
+ second.clear()
+ }
+})
+
+it('does not retry an unauthorized profile request', async () => {
+ const error = createHttpError(new Response(null, { status: 401 }))
+ request.mockRejectedValue(error)
+ const client = new QueryClient()
+ try {
+ await expect(client.query(userProfileQueryOptions())).rejects.toBe(error)
+ expect(request).toHaveBeenCalledOnce()
+ } finally {
+ client.clear()
+ }
+})
diff --git a/web/features/account-profile/__tests__/server.spec.ts b/web/features/account-profile/__tests__/server.spec.ts
index bbd0731d00c..eb537fe3f17 100644
--- a/web/features/account-profile/__tests__/server.spec.ts
+++ b/web/features/account-profile/__tests__/server.spec.ts
@@ -1,3 +1,5 @@
+// @vitest-environment node
+
import type { GetAccountProfileResponse } from '@dify/contracts/api/console/account/types.gen'
import { QueryClient } from '@tanstack/react-query'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
@@ -65,13 +67,10 @@ describe('serverUserProfileQueryOptions', () => {
currentEnv: 'DEVELOPMENT',
},
})
- expect(fetchMock).toHaveBeenCalledWith(
- 'http://localhost:5001/console/api/account/profile',
- expect.objectContaining({
- method: 'GET',
- cache: 'no-store',
- headers: expect.any(Headers),
- }),
- )
+ const [request, init] = fetchMock.mock.calls[0]!
+ expect(request.url).toBe('http://localhost:5001/console/api/account/profile')
+ expect(request.method).toBe('GET')
+ expect(request.headers.get('cookie')).toBe('session=abc')
+ expect(init).toMatchObject({ cache: 'no-store' })
})
})
diff --git a/web/features/account-profile/client.ts b/web/features/account-profile/client.ts
index 5fa181b562e..aa40d525206 100644
--- a/web/features/account-profile/client.ts
+++ b/web/features/account-profile/client.ts
@@ -1,9 +1,7 @@
import type { GetAccountProfileResponse } from '@dify/contracts/api/console/account/types.gen'
import { queryOptions } from '@tanstack/react-query'
import { IS_DEV } from '@/config'
-// oxlint-disable-next-line no-restricted-imports
-import { get } from '@/service/base'
-import { consoleQuery } from '@/service/console'
+import { consoleClient, consoleQuery } from '@/service/console'
import { isUnauthorizedError } from '@/service/http-error'
export type UserProfileWithMeta = {
@@ -18,20 +16,20 @@ export const userProfileQueryOptions = () =>
queryOptions<UserProfileWithMeta>({
queryKey: consoleQuery.account.profile.get.queryKey(),
queryFn: async () => {
- const response = await get<Response>(
- '/account/profile',
- {},
- {
- needAllResponseContent: true,
+ let responseHeaders: Headers | undefined
+ const profile = await consoleClient.account.profile.get(undefined, {
+ context: {
silent: true,
+ onResponseHeaders: (headers) => {
+ responseHeaders = headers
+ },
},
- )
- const profile: GetAccountProfileResponse = await response.clone().json()
+ })
return {
profile,
meta: {
- currentVersion: response.headers.get('x-version'),
- currentEnv: IS_DEV ? 'DEVELOPMENT' : response.headers.get('x-env'),
+ currentVersion: responseHeaders?.get('x-version') ?? null,
+ currentEnv: IS_DEV ? 'DEVELOPMENT' : (responseHeaders?.get('x-env') ?? null),
},
}
},
diff --git a/web/features/account-profile/server.ts b/web/features/account-profile/server.ts
index 8ffac2a49a1..2745d14e084 100644
--- a/web/features/account-profile/server.ts
+++ b/web/features/account-profile/server.ts
@@ -1,36 +1,25 @@
-import type { GetAccountProfileResponse } from '@dify/contracts/api/console/account/types.gen'
import type { UserProfileWithMeta } from './client'
import { queryOptions } from '@tanstack/react-query'
-import { consoleQuery } from '@/service/console'
-import {
- getServerConsoleRequestHeaders,
- resolveServerConsoleApiUrl,
-} from '@/service/console/server'
-import { httpErrorFromResponse } from '@/service/http-error'
-
-const ACCOUNT_PROFILE_PATH = '/account/profile'
+import { consoleClient, consoleQuery } from '@/service/console'
+import '@/service/console/server'
export const serverUserProfileQueryOptions = () =>
queryOptions<UserProfileWithMeta>({
queryKey: consoleQuery.account.profile.get.queryKey(),
queryFn: async () => {
- const profileUrl = resolveServerConsoleApiUrl(ACCOUNT_PROFILE_PATH)
- if (!profileUrl) throw new Error('Server account profile URL is not configured')
-
- const response = await fetch(profileUrl, {
- method: 'GET',
- headers: await getServerConsoleRequestHeaders(),
- cache: 'no-store',
+ let responseHeaders: Headers | undefined
+ const profile = await consoleClient.account.profile.get(undefined, {
+ context: {
+ onResponseHeaders: (headers) => {
+ responseHeaders = headers
+ },
+ },
})
-
- if (!response.ok) throw await httpErrorFromResponse(response)
-
- const profile: GetAccountProfileResponse = await response.clone().json()
return {
profile,
meta: {
- currentVersion: response.headers.get('x-version'),
- currentEnv: response.headers.get('x-env'),
+ currentVersion: responseHeaders?.get('x-version') ?? null,
+ currentEnv: responseHeaders?.get('x-env') ?? null,
},
}
},
diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/chat.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/chat.spec.tsx
index e230b1a87df..6b9917f2340 100644
--- a/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/chat.spec.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/chat.spec.tsx
@@ -41,10 +41,6 @@ vi.mock('@/service/base', async (importOriginal) => ({
...(await importOriginal<typeof import('@/service/base')>()),
ssePost,
}))
-vi.mock('@/service/common', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@/service/common')>()),
- uploadRemoteFileInfo: api.uploadRemote,
-}))
// Audio capture/encoding is a platform boundary; keep VoiceInput and its service routing real.
vi.mock('@/app/components/base/voice-input/recorder', () => ({ startVoiceRecorder: api.record }))
vi.mock('@/service/console', async (importOriginal) => {
@@ -55,6 +51,7 @@ vi.mock('@/service/console', async (importOriginal) => {
...actual,
consoleQuery: withConsoleResponses(actual.consoleQuery, {
'agent.byAgentId.chatMessages.get': api.history,
+ 'remoteFiles.upload.post': api.uploadRemote,
}),
consoleClient: withConsoleClientResponses(actual.consoleClient, {
'agent.byAgentId.chatMessages.byMessageId.suggestedQuestions.get': api.suggestions,
diff --git a/web/service/__tests__/delete-workflow-version.spec.ts b/web/service/__tests__/delete-workflow-version.spec.ts
new file mode 100644
index 00000000000..7eb91c9e338
--- /dev/null
+++ b/web/service/__tests__/delete-workflow-version.spec.ts
@@ -0,0 +1,65 @@
+import type { QueryKey } from '@tanstack/react-query'
+import type { EditorResource } from '@/app/components/workflow/editor-resource/resource'
+import { act, renderHook } from '@testing-library/react'
+import { consoleQuery } from '@/service/console'
+import { createConsoleQueryWrapper } from '@/test/console/query-data'
+import { useDeleteWorkflow } from '../use-workflow'
+
+const request = vi.hoisted(() => vi.fn<() => Promise<Response>>())
+vi.mock('@/service/base', () => ({ request }))
+
+const cases = [
+ {
+ resource: { kind: 'app', appId: 'owner', mode: 'workflow' } satisfies EditorResource,
+ path: '/apps/owner/workflows/version-1',
+ key: (id: string) =>
+ consoleQuery.apps.byAppId.workflows.get.key({ input: { params: { app_id: id } } }),
+ },
+ {
+ resource: { kind: 'knowledge-pipeline', pipelineId: 'owner' } satisfies EditorResource,
+ path: '/rag/pipelines/owner/workflows/version-1',
+ key: (id: string) =>
+ consoleQuery.rag.pipelines.byPipelineId.workflows.get.key({
+ input: { params: { pipeline_id: id } },
+ }),
+ },
+ {
+ resource: { kind: 'snippet', snippetId: 'owner' } satisfies EditorResource,
+ path: '/snippets/owner/workflows/version-1',
+ key: (id: string) =>
+ consoleQuery.snippets.bySnippetId.workflows.get.key({
+ input: { params: { snippet_id: id } },
+ }),
+ },
+]
+
+it.each(cases)(
+ 'deletes a $resource.kind version and refreshes only its list',
+ async ({ resource, path, key }) => {
+ const { wrapper, queryClient } = createConsoleQueryWrapper()
+ const affected = key('owner')
+ const unrelated = key('other')
+ const otherResources: QueryKey[] = cases
+ .filter((item) => item.resource.kind !== resource.kind)
+ .map((item) => item.key('owner'))
+ for (const queryKey of [affected, unrelated, ...otherResources])
+ queryClient.setQueryData(queryKey, { cached: true })
+ request.mockResolvedValue(new Response(null, { status: 204 }))
+ const { result, unmount } = renderHook(() => useDeleteWorkflow(resource), { wrapper })
+ try {
+ await act(() => result.current('version-1'))
+ expect(request).toHaveBeenCalledWith(
+ expect.stringContaining(path),
+ expect.anything(),
+ expect.objectContaining({ request: expect.objectContaining({ method: 'DELETE' }) }),
+ )
+ expect(queryClient.getQueryState(affected)?.isInvalidated).toBe(true)
+ for (const queryKey of [unrelated, ...otherResources])
+ expect(queryClient.getQueryState(queryKey)?.isInvalidated).toBe(false)
+ } finally {
+ unmount()
+ queryClient.clear()
+ request.mockReset()
+ }
+ },
+)
diff --git a/web/service/__tests__/plugin-credential-commands.spec.ts b/web/service/__tests__/plugin-credential-commands.spec.ts
new file mode 100644
index 00000000000..f0db6b7f6ac
--- /dev/null
+++ b/web/service/__tests__/plugin-credential-commands.spec.ts
@@ -0,0 +1,298 @@
+import type { PluginPayload } from '@/app/components/plugins/plugin-auth/types'
+import { act, renderHook, waitFor } from '@testing-library/react'
+import { AuthCategory } from '@/app/components/plugins/plugin-auth/types'
+import { consoleQuery } from '@/service/console'
+import { createConsoleQueryWrapper } from '@/test/console/query-data'
+import {
+ useAddPluginCredential,
+ useDeletePluginCredential,
+ useDeletePluginOAuthCustomClient,
+ useGetPluginOAuthUrl,
+ useSetPluginDefaultCredential,
+ useSetPluginOAuthCustomClient,
+ useUpdatePluginCredential,
+} from '../use-plugins-auth'
+
+const request = vi.hoisted(() => vi.fn<typeof import('../base').request>())
+vi.mock('@/service/base', () => ({ request }))
+
+const categories = [
+ {
+ category: AuthCategory.tool,
+ path: '/workspaces/current/tool-provider/builtin/owner',
+ defaultPath: 'default-credential',
+ keys: (provider: string) => [
+ consoleQuery.workspaces.current.toolProvider.builtin.byProvider.credential.info.get.key({
+ input: { params: { provider } },
+ }),
+ consoleQuery.workspaces.current.toolProvider.builtin.byProvider.credentials.get.key({
+ input: { params: { provider } },
+ }),
+ ],
+ },
+ {
+ category: AuthCategory.datasource,
+ path: '/auth/plugin/datasource/owner',
+ defaultPath: 'default',
+ keys: (provider: string) => [
+ consoleQuery.auth.plugin.datasource.byProviderId.get.key({
+ input: { params: { provider_id: provider } },
+ }),
+ ],
+ },
+]
+
+afterEach(() => {
+ request.mockReset()
+ vi.restoreAllMocks()
+})
+
+it.each(categories)(
+ 'routes $category credential commands and refreshes only that provider',
+ async ({ category, path, defaultPath, keys }) => {
+ const { queryClient, wrapper } = createConsoleQueryWrapper()
+ const { result, unmount } = renderHook(
+ () => ({
+ remove: useDeletePluginCredential({ category, provider: 'owner' }),
+ setDefault: useSetPluginDefaultCredential({ category, provider: 'owner' }),
+ }),
+ { wrapper },
+ )
+ try {
+ for (const operation of ['default', 'delete'] as const) {
+ const affected = keys('owner')
+ const unrelated = keys('other')
+ for (const key of [...affected, ...unrelated])
+ queryClient.setQueryData(key, { cached: true })
+ request.mockReset().mockResolvedValue(Response.json({ result: 'success' }))
+ await act(async () => {
+ if (operation === 'default') await result.current.setDefault.mutateAsync('credential-1')
+ else await result.current.remove.mutateAsync({ credential_id: 'credential-1' })
+ })
+ const [url, , options] = request.mock.calls[0]!
+ expect(new URL(url).pathname).toBe(
+ `/console/api${path}/${operation === 'default' ? defaultPath : 'delete'}`,
+ )
+ expect(options?.request?.method).toBe('POST')
+ expect(await options?.request?.json()).toEqual(
+ operation === 'default' ? { id: 'credential-1' } : { credential_id: 'credential-1' },
+ )
+ for (const key of affected) expect(queryClient.getQueryState(key)?.isInvalidated).toBe(true)
+ for (const key of unrelated)
+ expect(queryClient.getQueryState(key)?.isInvalidated).toBe(false)
+ }
+ } finally {
+ unmount()
+ queryClient.clear()
+ }
+ },
+)
+
+it.each(categories)(
+ 'preserves $category cached credentials when the mutation fails',
+ async ({ category, keys }) => {
+ vi.spyOn(console, 'error').mockImplementation(() => {})
+ const { queryClient, wrapper } = createConsoleQueryWrapper()
+ const affected = keys('owner')
+ for (const key of affected) queryClient.setQueryData(key, { cached: true })
+ request.mockRejectedValue(new Error('Request rejected'))
+ const { result, unmount } = renderHook(
+ () => useDeletePluginCredential({ category, provider: 'owner' }),
+ { wrapper },
+ )
+ try {
+ await act(async () => {
+ await expect(result.current.mutateAsync({ credential_id: 'credential-1' })).rejects.toThrow(
+ 'Request rejected',
+ )
+ })
+ for (const key of affected) expect(queryClient.getQueryState(key)?.isInvalidated).toBe(false)
+ } finally {
+ unmount()
+ queryClient.clear()
+ }
+ },
+)
+
+it.each([
+ { category: AuthCategory.model, provider: 'owner' },
+ { category: AuthCategory.trigger, provider: 'owner' },
+ { category: AuthCategory.tool, provider: '' },
+] satisfies PluginPayload[])(
+ 'does not send unsupported credential commands ($category, $provider)',
+ async (payload) => {
+ const { queryClient, wrapper } = createConsoleQueryWrapper()
+ const { result, unmount } = renderHook(
+ () => ({
+ remove: useDeletePluginCredential(payload),
+ setDefault: useSetPluginDefaultCredential(payload),
+ }),
+ { wrapper },
+ )
+ try {
+ await expect(
+ result.current.remove.mutateAsync({ credential_id: 'credential-1' }),
+ ).rejects.toThrow()
+ await expect(result.current.setDefault.mutateAsync('credential-1')).rejects.toThrow()
+ expect(request).not.toHaveBeenCalled()
+ } finally {
+ unmount()
+ queryClient.clear()
+ }
+ },
+)
+
+it.each(categories)(
+ 'saves and removes $category OAuth client configuration',
+ async ({ category, path, keys }) => {
+ const { queryClient, wrapper } = createConsoleQueryWrapper()
+ const oauthKeys = (provider: string) =>
+ category === AuthCategory.tool
+ ? [
+ consoleQuery.workspaces.current.toolProvider.builtin.byProvider.oauth.clientSchema.get.key(
+ { input: { params: { provider } } },
+ ),
+ consoleQuery.workspaces.current.toolProvider.builtin.byProvider.oauth.customClient.get.key(
+ { input: { params: { provider } } },
+ ),
+ ]
+ : keys(provider)
+ const { result, unmount } = renderHook(
+ () => ({
+ save: useSetPluginOAuthCustomClient({ category, provider: 'owner' }),
+ remove: useDeletePluginOAuthCustomClient({ category, provider: 'owner' }),
+ }),
+ { wrapper },
+ )
+ try {
+ for (const operation of ['save', 'delete'] as const) {
+ const affected = oauthKeys('owner')
+ const unrelated = oauthKeys('other')
+ for (const key of [...affected, ...unrelated])
+ queryClient.setQueryData(key, { cached: true })
+ request.mockReset().mockResolvedValue(Response.json({ result: 'success' }))
+ const body = {
+ client_params: { client_id: 'test-client' },
+ enable_oauth_custom_client: false,
+ }
+ await act(async () => {
+ if (operation === 'save') await result.current.save.mutateAsync(body)
+ else await result.current.remove.mutateAsync()
+ })
+ const [url, , options] = request.mock.calls[0]!
+ expect(new URL(url).pathname).toBe(
+ `/console/api${path}/${category === AuthCategory.tool ? 'oauth/' : ''}custom-client`,
+ )
+ expect(options?.request?.method).toBe(operation === 'save' ? 'POST' : 'DELETE')
+ if (operation === 'save') expect(await options?.request?.json()).toEqual(body)
+ else expect(await options?.request?.text()).toBe('')
+ for (const key of affected) expect(queryClient.getQueryState(key)?.isInvalidated).toBe(true)
+ for (const key of unrelated)
+ expect(queryClient.getQueryState(key)?.isInvalidated).toBe(false)
+ }
+ } finally {
+ unmount()
+ queryClient.clear()
+ }
+ },
+)
+
+it.each(categories)(
+ 'adds and renames $category credentials with generated payloads',
+ async ({ category, path, keys }) => {
+ const { queryClient, wrapper } = createConsoleQueryWrapper()
+ const { result, unmount } = renderHook(
+ () => ({
+ add: useAddPluginCredential({ category, provider: 'owner' }),
+ update: useUpdatePluginCredential({ category, provider: 'owner' }),
+ }),
+ { wrapper },
+ )
+ try {
+ for (const operation of ['add', 'update'] as const) {
+ for (const key of [...keys('owner'), ...keys('other')])
+ queryClient.setQueryData(key, { cached: true })
+ request.mockReset().mockResolvedValue(
+ Response.json(
+ { result: 'success' },
+ {
+ status: category === AuthCategory.datasource && operation === 'update' ? 201 : 200,
+ },
+ ),
+ )
+ await act(async () => {
+ if (operation === 'add')
+ await result.current.add.mutateAsync({
+ type: 'api-key',
+ credentials: { api_key: 'test-key' },
+ name: 'New credential',
+ visibility: 'only_me',
+ })
+ else
+ await result.current.update.mutateAsync({
+ credential_id: 'credential-1',
+ name: 'Renamed',
+ })
+ })
+ const [url, , options] = request.mock.calls[0]!
+ expect(new URL(url).pathname).toBe(
+ `/console/api${path}${operation === 'add' && category === AuthCategory.datasource ? '' : `/${operation}`}`,
+ )
+ const body = await options?.request?.json()
+ if (operation === 'update')
+ expect(body).toEqual({ credential_id: 'credential-1', name: 'Renamed' })
+ else
+ expect(body).toEqual({
+ credentials: { api_key: 'test-key' },
+ name: 'New credential',
+ ...(category === AuthCategory.tool ? { type: 'api-key', visibility: 'only_me' } : {}),
+ })
+ for (const key of keys('owner'))
+ expect(queryClient.getQueryState(key)?.isInvalidated).toBe(true)
+ for (const key of keys('other'))
+ expect(queryClient.getQueryState(key)?.isInvalidated).toBe(false)
+ }
+ } finally {
+ unmount()
+ queryClient.clear()
+ }
+ },
+)
+
+it.each(categories)(
+ 'requests a fresh $category OAuth URL with the selected visibility',
+ async ({ category }) => {
+ const { queryClient, wrapper } = createConsoleQueryWrapper()
+ const { result, unmount } = renderHook(
+ () => useGetPluginOAuthUrl({ category, provider: 'owner' }),
+ { wrapper },
+ )
+ try {
+ for (const visibility of ['only_me', 'all_team_members'] as const) {
+ request.mockResolvedValueOnce(
+ Response.json({ authorization_url: `https://example.com/oauth/${visibility}` }),
+ )
+ await act(async () => {
+ await expect(result.current.mutateAsync({ visibility })).resolves.toMatchObject({
+ authorization_url: `https://example.com/oauth/${visibility}`,
+ })
+ })
+ }
+ expect(request).toHaveBeenCalledTimes(2)
+ for (const [index, [url, , options]] of request.mock.calls.entries()) {
+ const target = new URL(url)
+ expect(target.pathname).toBe(
+ `/console/api/oauth/plugin/owner/${category === AuthCategory.tool ? 'tool/authorization-url' : 'datasource/get-authorization-url'}`,
+ )
+ expect(target.searchParams.get('visibility')).toBe(
+ index === 0 ? 'only_me' : 'all_team_members',
+ )
+ expect(options?.request?.method).toBe('GET')
+ }
+ await waitFor(() => expect(result.current.isPending).toBe(false))
+ } finally {
+ unmount()
+ queryClient.clear()
+ }
+ },
+)
diff --git a/web/service/__tests__/plugin-credential-queries.spec.ts b/web/service/__tests__/plugin-credential-queries.spec.ts
new file mode 100644
index 00000000000..2d42c5694d1
--- /dev/null
+++ b/web/service/__tests__/plugin-credential-queries.spec.ts
@@ -0,0 +1,142 @@
+import type { CredentialTypeEnum as CredentialType } from '@/app/components/plugins/plugin-auth/types'
+import { act, renderHook, waitFor } from '@testing-library/react'
+import { AuthCategory, CredentialTypeEnum } from '@/app/components/plugins/plugin-auth/types'
+import { createConsoleQueryWrapper } from '@/test/console/query-data'
+import {
+ useGetPluginCredentialSchema,
+ useGetPluginOAuthClientSchema,
+ useSetPluginOAuthCustomClient,
+} from '../use-plugins-auth'
+
+const request = vi.hoisted(() => vi.fn<typeof import('../base').request>())
+vi.mock('@/service/base', () => ({ request }))
+afterEach(() => {
+ request.mockReset()
+})
+
+it('adapts nullable form fields without losing false or zero defaults and separates credential types', async () => {
+ request.mockImplementation(async () =>
+ Response.json([
+ {
+ type: 'boolean',
+ name: 'enabled',
+ label: { en_US: 'Enabled', zh_Hans: null },
+ default: false,
+ help: null,
+ options: null,
+ },
+ {
+ type: 'text-input',
+ name: 'retries',
+ label: null,
+ required: true,
+ default: 0,
+ options: [{ value: 'one', label: { en_US: 'One' } }],
+ },
+ ]),
+ )
+ const { queryClient, wrapper } = createConsoleQueryWrapper()
+ const initialProps: { credentialType: CredentialType } = {
+ credentialType: CredentialTypeEnum.API_KEY,
+ }
+ const { result, rerender, unmount } = renderHook(
+ ({ credentialType }: { credentialType: CredentialType }) =>
+ useGetPluginCredentialSchema(
+ { category: AuthCategory.tool, provider: 'owner' },
+ credentialType,
+ ),
+ { wrapper, initialProps },
+ )
+ try {
+ await waitFor(() => expect(result.current.isSuccess).toBe(true))
+ expect(result.current.data).toMatchObject([
+ {
+ name: 'enabled',
+ type: 'boolean',
+ label: { en_US: 'Enabled', zh_Hans: 'Enabled' },
+ default: false,
+ required: false,
+ },
+ {
+ name: 'retries',
+ label: 'retries',
+ default: 0,
+ required: true,
+ options: [{ value: 'one', label: { en_US: 'One', zh_Hans: 'One' } }],
+ },
+ ])
+ rerender({ credentialType: CredentialTypeEnum.OAUTH2 })
+ await waitFor(() => expect(result.current.isSuccess).toBe(true))
+ expect(request.mock.calls.map(([url]) => new URL(url).pathname)).toEqual([
+ '/console/api/workspaces/current/tool-provider/builtin/owner/credential/schema/api-key',
+ '/console/api/workspaces/current/tool-provider/builtin/owner/credential/schema/oauth2',
+ ])
+ } finally {
+ unmount()
+ queryClient.clear()
+ }
+})
+
+it('defers OAuth schema loading until enabled and refreshes it after saving configuration', async () => {
+ let configured = false
+ request.mockImplementation(async (_url, _init, options) => {
+ if (options?.request?.method === 'POST') {
+ configured = true
+ return Response.json({ result: 'success' })
+ }
+ return Response.json({
+ schema: [],
+ is_oauth_custom_client_enabled: configured,
+ is_system_oauth_params_exists: false,
+ client_params: null,
+ redirect_uri: 'https://example.com/callback',
+ })
+ })
+ const { queryClient, wrapper } = createConsoleQueryWrapper()
+ const payload = { category: AuthCategory.tool, provider: 'owner' }
+ const { result, rerender, unmount } = renderHook(
+ ({ enabled }) => ({
+ query: useGetPluginOAuthClientSchema(payload, enabled),
+ save: useSetPluginOAuthCustomClient(payload),
+ }),
+ { wrapper, initialProps: { enabled: false } },
+ )
+ try {
+ expect(request).not.toHaveBeenCalled()
+ rerender({ enabled: true })
+ await waitFor(() => expect(result.current.query.isSuccess).toBe(true))
+ expect(result.current.query.data?.client_params).toBeUndefined()
+ expect(result.current.query.data?.is_oauth_custom_client_enabled).toBe(false)
+ await act(async () => {
+ await result.current.save.mutateAsync({ client_params: {}, enable_oauth_custom_client: true })
+ })
+ await waitFor(() =>
+ expect(result.current.query.data?.is_oauth_custom_client_enabled).toBe(true),
+ )
+ expect(request).toHaveBeenCalledTimes(3)
+ } finally {
+ unmount()
+ queryClient.clear()
+ }
+})
+
+it.each([
+ { category: AuthCategory.datasource, provider: 'owner' },
+ { category: AuthCategory.trigger, provider: 'owner' },
+ { category: AuthCategory.tool, provider: '' },
+])('does not request unavailable schemas ($category, $provider)', async (payload) => {
+ const { queryClient, wrapper } = createConsoleQueryWrapper()
+ const { unmount } = renderHook(
+ () => {
+ useGetPluginCredentialSchema(payload, CredentialTypeEnum.API_KEY)
+ useGetPluginOAuthClientSchema(payload)
+ },
+ { wrapper },
+ )
+ try {
+ expect(request).not.toHaveBeenCalled()
+ } finally {
+ unmount()
+ queryClient.clear()
+ }
+})
diff --git a/web/service/__tests__/use-workflow.spec.tsx b/web/service/__tests__/use-workflow.spec.tsx
index 64078e2281f..6aad7f0e6d8 100644
--- a/web/service/__tests__/use-workflow.spec.tsx
+++ b/web/service/__tests__/use-workflow.spec.tsx
@@ -18,26 +18,22 @@ import {
OperatorType,
RuntimeState,
} from '@dify/contracts/enterprise-app-deploy/types.gen'
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { QueryClient, QueryClientProvider, useMutation } from '@tanstack/react-query'
import { act, renderHook } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import { consoleQuery } from '@/service/console'
-import { usePublishWorkflow, useRestoreWorkflow, useUpdateWorkflow } from '../use-workflow'
+import { useRestoreWorkflow, useUpdateWorkflow } from '../use-workflow'
import {
appWorkflowQueryOptions,
- appWorkflowVersionsInfiniteQueryKey,
appWorkflowVersionsInfiniteQueryOptions,
} from '../workflow-queries'
-const mockPatch = vi.hoisted(() => vi.fn())
-const mockPost = vi.hoisted(() => vi.fn())
-const mockRequest = vi.hoisted(() => vi.fn())
+const mockWorkflowResponse = vi.hoisted(() => vi.fn())
+const mockRequest = vi.hoisted(() => vi.fn<typeof import('../base').request>())
vi.mock('../base', async (importOriginal) => ({
...(await importOriginal<typeof import('../base')>()),
- request: (...args: unknown[]) => mockRequest(...args),
- patch: (...args: unknown[]) => mockPatch(...args),
- post: (...args: unknown[]) => mockPost(...args),
+ request: (...args: Parameters<typeof import('../base').request>) => mockRequest(...args),
}))
const createWrapper = (queryClient: QueryClient) =>
@@ -120,38 +116,71 @@ const createEnvironmentDeployment = ({
},
})
-describe('usePublishWorkflow', () => {
+describe('generated workflow publication', () => {
beforeEach(() => {
vi.clearAllMocks()
})
+ it('publishes a pipeline without a body and refreshes its published workflow and datasets', async () => {
+ mockRequest.mockReset().mockResolvedValue(Response.json({ result: 'success', created_at: 123 }))
+ const queryClient = createQueryClient()
+ const publishedKey = consoleQuery.rag.pipelines.byPipelineId.workflows.publish.get.queryKey({
+ input: { params: { pipeline_id: 'pipeline-1' } },
+ })
+ const unrelatedKey = consoleQuery.rag.pipelines.byPipelineId.workflows.publish.get.queryKey({
+ input: { params: { pipeline_id: 'other' } },
+ })
+ const datasetKey = consoleQuery.datasets.get.key()
+ for (const key of [publishedKey, unrelatedKey, datasetKey])
+ queryClient.setQueryData(key, { cached: true })
+ const { result } = renderHook(
+ () =>
+ useMutation(
+ consoleQuery.rag.pipelines.byPipelineId.workflows.publish.post.mutationOptions(),
+ ),
+ { wrapper: createWrapper(queryClient) },
+ )
+ await act(async () => {
+ await result.current.mutateAsync({ params: { pipeline_id: 'pipeline-1' } })
+ })
+ const [url, , options] = mockRequest.mock.calls[0]!
+ expect(new URL(url).pathname).toBe('/console/api/rag/pipelines/pipeline-1/workflows/publish')
+ expect(options?.request?.method).toBe('POST')
+ expect(await options?.request?.text()).toBe('')
+ expect(queryClient.getQueryState(publishedKey)?.isInvalidated).toBe(true)
+ expect(queryClient.getQueryState(datasetKey)?.isInvalidated).toBe(true)
+ expect(queryClient.getQueryState(unrelatedKey)?.isInvalidated).toBe(false)
+ })
+
it('returns the server warning with the publish result', async () => {
const published = {
result: 'success',
created_at: 1_710_000_100,
warning: '"Answer" ← "Producer"',
}
- mockPost.mockResolvedValue(published)
+ mockRequest.mockReset().mockResolvedValue(Response.json(published))
const queryClient = createQueryClient()
- const { result } = renderHook(() => usePublishWorkflow(), {
- wrapper: createWrapper(queryClient),
- })
+ const { result } = renderHook(
+ () => useMutation(consoleQuery.apps.byAppId.workflows.publish.post.mutationOptions()),
+ {
+ wrapper: createWrapper(queryClient),
+ },
+ )
let response: unknown
await act(async () => {
response = await result.current.mutateAsync({
- url: '/apps/app-1/workflows/publish',
- title: 'Release 1',
- releaseNotes: 'Notes',
+ params: { app_id: 'app-1' },
+ body: { marked_name: 'Release 1', marked_comment: 'Notes' },
})
})
expect(response).toEqual(published)
- expect(mockPost).toHaveBeenCalledWith('/apps/app-1/workflows/publish', {
- body: {
- marked_name: 'Release 1',
- marked_comment: 'Notes',
- },
+ const [url, , options] = mockRequest.mock.calls[0]!
+ expect(new URL(url).pathname).toBe('/console/api/apps/app-1/workflows/publish')
+ expect(await options?.request?.json()).toEqual({
+ marked_name: 'Release 1',
+ marked_comment: 'Notes',
})
})
})
@@ -159,9 +188,58 @@ describe('usePublishWorkflow', () => {
describe('useUpdateWorkflow', () => {
beforeEach(() => {
vi.clearAllMocks()
- mockPatch.mockResolvedValue({})
+ mockWorkflowResponse.mockResolvedValue(createWorkflow())
+ mockRequest.mockImplementation(async () => Response.json(await mockWorkflowResponse()))
})
+ it.each([
+ {
+ resource: { kind: 'app', appId: 'owner', mode: 'workflow' } satisfies EditorResource,
+ path: '/apps/owner',
+ key: (id: string) =>
+ consoleQuery.apps.byAppId.workflows.get.key({ input: { params: { app_id: id } } }),
+ },
+ {
+ resource: { kind: 'knowledge-pipeline', pipelineId: 'owner' } satisfies EditorResource,
+ path: '/rag/pipelines/owner',
+ key: (id: string) =>
+ consoleQuery.rag.pipelines.byPipelineId.workflows.get.key({
+ input: { params: { pipeline_id: id } },
+ }),
+ },
+ {
+ resource: { kind: 'snippet', snippetId: 'owner' } satisfies EditorResource,
+ path: '/snippets/owner',
+ key: (id: string) =>
+ consoleQuery.snippets.bySnippetId.workflows.get.key({
+ input: { params: { snippet_id: id } },
+ }),
+ },
+ ])(
+ 'updates $resource.kind metadata and scopes list refresh to its owner',
+ async ({ resource, path, key }) => {
+ const queryClient = createQueryClient()
+ queryClient.setQueryData(key('owner'), { cached: true })
+ queryClient.setQueryData(key('other'), { cached: true })
+ const { result } = renderHook(() => useUpdateWorkflow(), {
+ wrapper: createWrapper(queryClient),
+ })
+ await act(async () => {
+ await result.current.mutateAsync({
+ resource,
+ versionId: 'workflow-1',
+ title: '',
+ releaseNotes: '',
+ })
+ })
+ const [url, , options] = mockRequest.mock.calls[0]!
+ expect(new URL(url).pathname).toBe(`/console/api${path}/workflows/workflow-1`)
+ expect(await options?.request?.json()).toEqual({ marked_name: '', marked_comment: '' })
+ expect(queryClient.getQueryState(key('owner'))?.isInvalidated).toBe(true)
+ expect(queryClient.getQueryState(key('other'))?.isInvalidated).toBe(false)
+ },
+ )
+
it('should invalidate workflow version history after updating version information', async () => {
const queryClient = createQueryClient()
const legacyHistoryKey = ['workflow', 'versionHistory', 'app-1']
@@ -175,167 +253,168 @@ describe('useUpdateWorkflow', () => {
await act(async () => {
await result.current.mutateAsync({
- url: '/apps/app-1/workflows/workflow-1',
+ resource: { kind: 'app', appId: 'app-1' },
+ versionId: 'workflow-1',
title: 'Release 1',
releaseNotes: 'Notes',
})
})
- expect(mockPatch).toHaveBeenCalledWith('/apps/app-1/workflows/workflow-1', {
- body: { marked_name: 'Release 1', marked_comment: 'Notes' },
- })
+ expect(mockRequest).toHaveBeenCalledWith(
+ expect.stringContaining('/apps/app-1/workflows/workflow-1'),
+ expect.anything(),
+ expect.objectContaining({ request: expect.objectContaining({ method: 'PATCH' }) }),
+ )
+ const sentRequest = mockRequest.mock.calls[0]?.[2]?.request
+ expect(await sentRequest?.json()).toEqual({ marked_name: 'Release 1', marked_comment: 'Notes' })
expect(queryClient.getQueryState(legacyHistoryKey)?.isInvalidated).toBe(true)
expect(queryClient.getQueryState(generatedHistoryKey)?.isInvalidated).toBe(true)
expect(invalidateQueries).toHaveBeenCalledWith({
queryKey: ['workflow', 'versionHistory'],
})
expect(invalidateQueries).toHaveBeenCalledWith({
- queryKey: appWorkflowVersionsInfiniteQueryKey(),
+ queryKey: consoleQuery.apps.byAppId.workflows.get.key({
+ input: { params: { app_id: 'app-1' } },
+ }),
})
})
- it.each(['workflow', 'advanced-chat'] as const)(
- 'should synchronize every cached app deployment reference to the updated workflow version (%s)',
- async (appMode) => {
- const queryClient = createQueryClient()
- const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')
- const oldVersion: WorkflowVersion = {
- id: 'workflow-1',
- marked_comment: 'Old notes',
- marked_name: 'Old release',
- version: '2026-08-21.1',
- version_number: 1,
- }
- const unrelatedVersion: WorkflowVersion = {
- id: 'workflow-2',
- marked_comment: 'Keep these notes',
- marked_name: 'Keep this release',
- version: '2026-08-20.1',
- version_number: 2,
- }
- const updatedWorkflow = createWorkflow({
- marked_comment: '',
- marked_name: '',
- updated_at: 1_710_000_300,
- })
- const workflowVersionsQuery = appWorkflowVersionsInfiniteQueryOptions('app-1')
- const publishedWorkflowQuery = appWorkflowQueryOptions('app-1')
- const deploymentsQuery =
- consoleQuery.enterprise.appDeploy.deploymentService.listEnvironmentDeployments.queryOptions(
- {
- input: {
- params: {
- app_id: 'app-1',
- },
- },
- },
- )
- const deploymentDetailQuery =
- consoleQuery.enterprise.appDeploy.deploymentService.getEnvironmentDeployment.queryOptions({
- input: {
- params: {
- app_id: 'app-1',
- environment_id: 'staging',
- },
+ it('should synchronize every cached app deployment reference to the updated workflow version', async () => {
+ const queryClient = createQueryClient()
+ const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')
+ const oldVersion: WorkflowVersion = {
+ id: 'workflow-1',
+ marked_comment: 'Old notes',
+ marked_name: 'Old release',
+ version: '2026-08-21.1',
+ version_number: 1,
+ }
+ const unrelatedVersion: WorkflowVersion = {
+ id: 'workflow-2',
+ marked_comment: 'Keep these notes',
+ marked_name: 'Keep this release',
+ version: '2026-08-20.1',
+ version_number: 2,
+ }
+ const updatedWorkflow = createWorkflow({
+ marked_comment: '',
+ marked_name: '',
+ updated_at: 1_710_000_300,
+ })
+ const workflowVersionsQuery = appWorkflowVersionsInfiniteQueryOptions('app-1')
+ const publishedWorkflowQuery = appWorkflowQueryOptions('app-1')
+ const deploymentsQuery =
+ consoleQuery.enterprise.appDeploy.deploymentService.listEnvironmentDeployments.queryOptions({
+ input: {
+ params: {
+ app_id: 'app-1',
},
- })
- const stagingDeployment = createEnvironmentDeployment({
- currentVersion: oldVersion,
- environmentId: 'staging',
- targetVersion: oldVersion,
- })
- const productionDeployment = createEnvironmentDeployment({
- currentVersion: unrelatedVersion,
- environmentId: 'production',
- targetVersion: oldVersion,
- })
-
- queryClient.setQueryData(publishedWorkflowQuery.queryKey, createWorkflow())
- queryClient.setQueryData<InfiniteData<WorkflowPaginationResponse>>(
- workflowVersionsQuery.queryKey,
- {
- pageParams: [1],
- pages: [
- {
- has_more: false,
- items: [createWorkflow(), createWorkflow({ id: 'workflow-2' })],
- limit: 10,
- page: 1,
- },
- ],
},
- )
- queryClient.setQueryData<ListEnvironmentDeploymentsResponse>(deploymentsQuery.queryKey, {
- environment_deployments: [stagingDeployment, productionDeployment],
})
- queryClient.setQueryData<GetEnvironmentDeploymentResponse>(deploymentDetailQuery.queryKey, {
- environment_deployment: stagingDeployment,
- })
- mockPatch.mockResolvedValueOnce(updatedWorkflow)
- const { result } = renderHook(() => useUpdateWorkflow(), {
- wrapper: createWrapper(queryClient),
+ const deploymentDetailQuery =
+ consoleQuery.enterprise.appDeploy.deploymentService.getEnvironmentDeployment.queryOptions({
+ input: {
+ params: {
+ app_id: 'app-1',
+ environment_id: 'staging',
+ },
+ },
})
+ const stagingDeployment = createEnvironmentDeployment({
+ currentVersion: oldVersion,
+ environmentId: 'staging',
+ targetVersion: oldVersion,
+ })
+ const productionDeployment = createEnvironmentDeployment({
+ currentVersion: unrelatedVersion,
+ environmentId: 'production',
+ targetVersion: oldVersion,
+ })
- await act(async () => {
- await result.current.mutateAsync({
- appId: 'app-1',
- appMode,
- url: '/apps/app-1/workflows/workflow-1',
- title: '',
- releaseNotes: '',
- })
- })
+ queryClient.setQueryData(publishedWorkflowQuery.queryKey, createWorkflow())
+ queryClient.setQueryData<InfiniteData<WorkflowPaginationResponse>>(
+ workflowVersionsQuery.queryKey,
+ {
+ pageParams: [1],
+ pages: [
+ {
+ has_more: false,
+ items: [createWorkflow(), createWorkflow({ id: 'workflow-2' })],
+ limit: 10,
+ page: 1,
+ },
+ ],
+ },
+ )
+ queryClient.setQueryData<ListEnvironmentDeploymentsResponse>(deploymentsQuery.queryKey, {
+ environment_deployments: [stagingDeployment, productionDeployment],
+ })
+ queryClient.setQueryData<GetEnvironmentDeploymentResponse>(deploymentDetailQuery.queryKey, {
+ environment_deployment: stagingDeployment,
+ })
+ mockWorkflowResponse.mockResolvedValueOnce(updatedWorkflow)
+ const { result } = renderHook(() => useUpdateWorkflow(), {
+ wrapper: createWrapper(queryClient),
+ })
- expect(queryClient.getQueryData<WorkflowResponse>(publishedWorkflowQuery.queryKey)).toEqual(
- updatedWorkflow,
- )
- expect(
- queryClient.getQueryData<InfiniteData<WorkflowPaginationResponse>>(
- workflowVersionsQuery.queryKey,
- )?.pages[0]?.items,
- ).toEqual([updatedWorkflow, createWorkflow({ id: 'workflow-2' })])
-
- const deployments = queryClient.getQueryData<ListEnvironmentDeploymentsResponse>(
- deploymentsQuery.queryKey,
- )?.environment_deployments
- expect(deployments?.[0]?.deployment?.current_version).toEqual({
- ...oldVersion,
- marked_comment: '',
- marked_name: '',
- })
- expect(deployments?.[0]?.deployment?.latest_operation?.target_version).toEqual({
- ...oldVersion,
- marked_comment: '',
- marked_name: '',
- })
- expect(deployments?.[1]?.deployment?.current_version).toBe(unrelatedVersion)
- expect(deployments?.[1]?.deployment?.latest_operation?.target_version).toEqual({
- ...oldVersion,
- marked_comment: '',
- marked_name: '',
+ await act(async () => {
+ await result.current.mutateAsync({
+ resource: { kind: 'app', appId: 'app-1' },
+ versionId: 'workflow-1',
+ title: '',
+ releaseNotes: '',
})
+ })
- expect(
- queryClient.getQueryData<GetEnvironmentDeploymentResponse>(deploymentDetailQuery.queryKey)
- ?.environment_deployment.deployment?.current_version,
- ).toEqual({
- ...oldVersion,
- marked_comment: '',
- marked_name: '',
- })
- expect(
- queryClient.getQueryData<GetEnvironmentDeploymentResponse>(deploymentDetailQuery.queryKey)
- ?.environment_deployment.deployment?.latest_operation?.target_version,
- ).toEqual({
- ...oldVersion,
- marked_comment: '',
- marked_name: '',
- })
- expect(invalidateQueries).toHaveBeenCalledWith({
- queryKey: deploymentsQuery.queryKey,
- })
- },
- )
+ expect(queryClient.getQueryData<WorkflowResponse>(publishedWorkflowQuery.queryKey)).toEqual(
+ updatedWorkflow,
+ )
+ expect(
+ queryClient.getQueryData<InfiniteData<WorkflowPaginationResponse>>(
+ workflowVersionsQuery.queryKey,
+ )?.pages[0]?.items,
+ ).toEqual([updatedWorkflow, createWorkflow({ id: 'workflow-2' })])
+
+ const deployments = queryClient.getQueryData<ListEnvironmentDeploymentsResponse>(
+ deploymentsQuery.queryKey,
+ )?.environment_deployments
+ expect(deployments?.[0]?.deployment?.current_version).toEqual({
+ ...oldVersion,
+ marked_comment: '',
+ marked_name: '',
+ })
+ expect(deployments?.[0]?.deployment?.latest_operation?.target_version).toEqual({
+ ...oldVersion,
+ marked_comment: '',
+ marked_name: '',
+ })
+ expect(deployments?.[1]?.deployment?.current_version).toBe(unrelatedVersion)
+ expect(deployments?.[1]?.deployment?.latest_operation?.target_version).toEqual({
+ ...oldVersion,
+ marked_comment: '',
+ marked_name: '',
+ })
+
+ expect(
+ queryClient.getQueryData<GetEnvironmentDeploymentResponse>(deploymentDetailQuery.queryKey)
+ ?.environment_deployment.deployment?.current_version,
+ ).toEqual({
+ ...oldVersion,
+ marked_comment: '',
+ marked_name: '',
+ })
+ expect(
+ queryClient.getQueryData<GetEnvironmentDeploymentResponse>(deploymentDetailQuery.queryKey)
+ ?.environment_deployment.deployment?.latest_operation?.target_version,
+ ).toEqual({
+ ...oldVersion,
+ marked_comment: '',
+ marked_name: '',
+ })
+ expect(invalidateQueries).toHaveBeenCalledWith({
+ queryKey: deploymentsQuery.queryKey,
+ })
+ })
it('should keep the latest published workflow when editing an older app version', async () => {
const queryClient = createQueryClient()
@@ -346,7 +425,7 @@ describe('useUpdateWorkflow', () => {
})
const publishedWorkflowQuery = appWorkflowQueryOptions('app-1')
queryClient.setQueryData(publishedWorkflowQuery.queryKey, latestWorkflow)
- mockPatch.mockResolvedValueOnce(
+ mockWorkflowResponse.mockResolvedValueOnce(
createWorkflow({ marked_comment: 'Updated notes', marked_name: 'Updated release' }),
)
const { result } = renderHook(() => useUpdateWorkflow(), {
@@ -355,8 +434,8 @@ describe('useUpdateWorkflow', () => {
await act(async () => {
await result.current.mutateAsync({
- appId: 'app-1',
- url: '/apps/app-1/workflows/workflow-1',
+ resource: { kind: 'app', appId: 'app-1' },
+ versionId: 'workflow-1',
title: 'Updated release',
releaseNotes: 'Updated notes',
})
@@ -365,10 +444,10 @@ describe('useUpdateWorkflow', () => {
expect(queryClient.getQueryData(publishedWorkflowQuery.queryKey)).toBe(latestWorkflow)
})
- it('should skip deployment caches when editing a non-workflow app version', async () => {
+ it('should preserve deployment data referencing another workflow', async () => {
const queryClient = createQueryClient()
const oldVersion: WorkflowVersion = {
- id: 'workflow-1',
+ id: 'workflow-other',
marked_comment: 'Old notes',
marked_name: 'Old release',
}
@@ -395,16 +474,15 @@ describe('useUpdateWorkflow', () => {
})
queryClient.setQueryData(deploymentsQuery.queryKey, cachedDeployments)
queryClient.setQueryData(publishedWorkflowQuery.queryKey, createWorkflow())
- mockPatch.mockResolvedValueOnce(updatedWorkflow)
+ mockWorkflowResponse.mockResolvedValueOnce(updatedWorkflow)
const { result } = renderHook(() => useUpdateWorkflow(), {
wrapper: createWrapper(queryClient),
})
await act(async () => {
await result.current.mutateAsync({
- appId: 'app-1',
- appMode: 'chat' as const,
- url: '/apps/app-1/workflows/workflow-1',
+ resource: { kind: 'app', appId: 'app-1' },
+ versionId: 'workflow-1',
title: 'New release',
releaseNotes: 'New notes',
})
@@ -436,7 +514,7 @@ describe('useUpdateWorkflow', () => {
queryClient.setQueryData<ListEnvironmentDeploymentsResponse>(deploymentsQuery.queryKey, {
environment_deployments: [deployment],
})
- mockPatch.mockResolvedValueOnce(
+ mockWorkflowResponse.mockResolvedValueOnce(
createWorkflow({ marked_comment: 'New notes', marked_name: 'New release' }),
)
const { result } = renderHook(() => useUpdateWorkflow(), {
@@ -445,7 +523,8 @@ describe('useUpdateWorkflow', () => {
await act(async () => {
await result.current.mutateAsync({
- url: '/snippets/snippet-1/workflows/workflow-1',
+ resource: { kind: 'snippet', snippetId: 'snippet-1' },
+ versionId: 'workflow-1',
title: 'New release',
releaseNotes: 'New notes',
})
@@ -489,8 +568,8 @@ describe('useRestoreWorkflow', () => {
})
const [url, , options] = mockRequest.mock.calls[0]!
expect(new URL(url).pathname).toBe(`/console/api${path}/workflows/version-1/restore`)
- expect(options.request.method).toBe('POST')
- expect(options.silent).toBe(true)
+ expect(options?.request?.method).toBe('POST')
+ expect(options?.silent).toBe(true)
},
)
})
diff --git a/web/service/access-control/__tests__/use-app-access-control.spec.tsx b/web/service/access-control/__tests__/use-app-access-control.spec.tsx
index ae855e305b0..b20da1fe6aa 100644
--- a/web/service/access-control/__tests__/use-app-access-control.spec.tsx
+++ b/web/service/access-control/__tests__/use-app-access-control.spec.tsx
@@ -1,5 +1,5 @@
-import { renderHook, waitFor } from '@testing-library/react'
-import { get } from '@/service/base'
+import { act, renderHook, waitFor } from '@testing-library/react'
+import { request } from '@/service/base'
import { getUserCanAccess } from '@/service/share'
import { createConsoleQueryWrapper } from '@/test/console/query-data'
import {
@@ -16,7 +16,6 @@ const { mockGetWebAppWhitelistSubjects } = vi.hoisted(() => ({
}))
vi.mock('@/service/base', () => ({
- get: vi.fn(),
request: vi.fn(),
}))
@@ -48,7 +47,7 @@ describe('use-app-access-control', () => {
beforeEach(() => {
vi.clearAllMocks()
mockSystemFeatures.webappAuthEnabled = false
- vi.mocked(get).mockResolvedValue({ groups: [], members: [] })
+ vi.mocked(request).mockReset()
mockGetWebAppWhitelistSubjects.mockResolvedValue({ groups: [], members: [] })
vi.mocked(getUserCanAccess).mockResolvedValue({ result: true })
})
@@ -90,15 +89,11 @@ describe('use-app-access-control', () => {
})
})
- it('should search whitelist candidates with encoded query params', async () => {
- vi.mocked(get).mockResolvedValue({
- currPage: 1,
- totalPages: 1,
- subjects: [],
- hasMore: false,
- })
-
- renderHook(
+ it('searches and paginates candidates with generated query parameters', async () => {
+ vi.mocked(request)
+ .mockResolvedValueOnce(Response.json({ subjects: [], hasMore: true }))
+ .mockResolvedValueOnce(Response.json({ subjects: [], currPage: 2, hasMore: false }))
+ const { result } = renderHook(
() =>
useSearchForWhiteListCandidates(
{
@@ -110,12 +105,93 @@ describe('use-app-access-control', () => {
),
{ wrapper: createWrapper() },
)
+ await waitFor(() => expect(result.current.isSuccess).toBe(true))
+ expect(result.current.hasNextPage).toBe(true)
+ await act(async () => {
+ const next = await result.current.fetchNextPage()
+ expect(next.error).toBeNull()
+ expect(next.data?.pages).toHaveLength(2)
+ })
+ await waitFor(() => expect(result.current.data?.pages).toHaveLength(2))
+ const urls = vi.mocked(request).mock.calls.map(([url]) => new URL(url))
+ expect(urls.map((url) => url.searchParams.get('pageNumber'))).toEqual(['1', '2'])
+ for (const url of urls) {
+ expect(url.pathname).toContain('/enterprise/webapp/app/subject/search')
+ expect(url.searchParams.get('keyword')).toBe('team one')
+ expect(url.searchParams.get('groupId')).toBe('group-1')
+ expect(url.searchParams.get('resultsPerPage')).toBe('20')
+ }
+ expect(result.current.hasNextPage).toBe(false)
+ })
- await waitFor(() => {
- expect(get).toHaveBeenCalledWith(
- '/enterprise/webapp/app/subject/search?keyword=team+one&groupId=group-1&resultsPerPage=20&pageNumber=1',
- )
+ it('selects usable members and groups without inventing missing identities', async () => {
+ vi.mocked(request).mockResolvedValue(
+ Response.json({
+ subjects: [
+ {
+ subjectId: 'member-1',
+ subjectType: 'account',
+ accountData: {
+ id: 'member-1',
+ name: 'Ada',
+ email: '[email protected]',
+ avatar: 'avatar-url',
+ },
+ },
+ {
+ subjectId: 'group-1',
+ subjectType: 'group',
+ groupData: { id: 'group-1', name: 'Engineering' },
+ },
+ { subjectId: 'missing-data', subjectType: 'account' },
+ { subjectId: 'unknown-type', subjectType: 'other' },
+ { subjectType: 'group', groupData: { id: 'missing-subject', name: 'Other' } },
+ ],
+ }),
+ )
+ const { result } = renderHook(() => useSearchForWhiteListCandidates({}, true), {
+ wrapper: createWrapper(),
})
+ await waitFor(() => expect(result.current.isSuccess).toBe(true))
+ expect(result.current.data?.pages[0]?.subjects).toEqual([
+ {
+ subjectId: 'member-1',
+ subjectType: 'account',
+ accountData: {
+ id: 'member-1',
+ name: 'Ada',
+ email: '[email protected]',
+ avatar: 'avatar-url',
+ avatarUrl: 'avatar-url',
+ },
+ },
+ {
+ subjectId: 'group-1',
+ subjectType: 'group',
+ groupData: { id: 'group-1', name: 'Engineering', groupSize: 0 },
+ },
+ ])
+ })
+
+ it('does not request candidates while disabled and separates search caches', async () => {
+ vi.mocked(request).mockImplementation(async () =>
+ Response.json({ subjects: [], currPage: 1, hasMore: false }),
+ )
+ const { result, rerender } = renderHook(
+ ({ enabled, keyword }) => useSearchForWhiteListCandidates({ keyword }, enabled),
+ {
+ initialProps: { enabled: false, keyword: 'first' },
+ wrapper: createWrapper(),
+ },
+ )
+ expect(request).not.toHaveBeenCalled()
+ rerender({ enabled: true, keyword: 'first' })
+ await waitFor(() => expect(result.current.isSuccess).toBe(true))
+ rerender({ enabled: true, keyword: 'second' })
+ await waitFor(() => expect(result.current.isSuccess).toBe(true))
+ expect(
+ vi.mocked(request).mock.calls.map(([url]) => new URL(url).searchParams.get('keyword')),
+ ).toEqual(['first', 'second'])
})
it('should return public access when webapp auth is disabled', async () => {
diff --git a/web/service/access-control/index.ts b/web/service/access-control/index.ts
index d095a0e9cb4..75307d86617 100644
--- a/web/service/access-control/index.ts
+++ b/web/service/access-control/index.ts
@@ -1,15 +1,14 @@
-import type { AccessControlGroup } from '@/models/access-control'
+import type { WebAppAuthSearchForWhilteListCandidatesData } from '@dify/contracts/enterprise/types.gen'
import {
useAppWhiteListSubjects as useAppWhiteListSubjectsBase,
useGetUserCanAccessApp as useGetUserCanAccessAppBase,
useSearchForWhiteListCandidates as useSearchForWhiteListCandidatesBase,
} from './use-app-access-control'
-type SearchForWhiteListCandidatesQuery = {
- keyword?: string
- groupId?: AccessControlGroup['id']
- resultsPerPage?: number
-}
+type SearchForWhiteListCandidatesQuery = Omit<
+ NonNullable<WebAppAuthSearchForWhilteListCandidatesData['query']>,
+ 'pageNumber'
+>
type UserCanAccessAppParams = {
appId?: string
diff --git a/web/service/access-control/use-app-access-control.ts b/web/service/access-control/use-app-access-control.ts
index fb32a53e453..b0390d245d6 100644
--- a/web/service/access-control/use-app-access-control.ts
+++ b/web/service/access-control/use-app-access-control.ts
@@ -1,8 +1,12 @@
-import type { AccessControlGroup, Subject } from '@/models/access-control'
+import type {
+ Subject as ApiSubject,
+ WebAppAuthSearchForWhilteListCandidatesData,
+} from '@dify/contracts/enterprise/types.gen'
+import type { Subject } from '@/models/access-control'
import { useInfiniteQuery, useQuery, useSuspenseQuery } from '@tanstack/react-query'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
+import { SubjectType } from '@/models/access-control'
import { consoleQuery } from '@/service/console'
-import { get } from '../base'
import { getUserCanAccess } from '../share'
const NAME_SPACE = 'access-control'
@@ -36,46 +40,73 @@ export const useAppWhiteListSubjects = (appId: string | undefined, enabled: bool
})
}
-type SearchResults = {
- currPage: number
- totalPages: number
- subjects: Subject[]
- hasMore: boolean
-}
+type SearchForWhiteListCandidatesQuery = Omit<
+ NonNullable<WebAppAuthSearchForWhilteListCandidatesData['query']>,
+ 'pageNumber'
+>
-type SearchForWhiteListCandidatesQuery = {
- keyword?: string
- groupId?: AccessControlGroup['id']
- resultsPerPage?: number
+function selectCandidate(subject: ApiSubject): Subject[] {
+ if (!subject.subjectId) return []
+ if (subject.subjectType === SubjectType.GROUP) {
+ const group = subject.groupData
+ if (!group?.id || !group.name) return []
+ return [
+ {
+ subjectId: subject.subjectId,
+ subjectType: SubjectType.GROUP,
+ groupData: { id: group.id, name: group.name, groupSize: group.groupSize ?? 0 },
+ },
+ ]
+ }
+ if (subject.subjectType === SubjectType.ACCOUNT) {
+ const account = subject.accountData
+ if (!account?.id || !account.name || !account.email) return []
+ return [
+ {
+ subjectId: subject.subjectId,
+ subjectType: SubjectType.ACCOUNT,
+ accountData: {
+ id: account.id,
+ name: account.name,
+ email: account.email,
+ avatar: account.avatar ?? '',
+ avatarUrl: account.avatar ?? '',
+ },
+ },
+ ]
+ }
+ return []
}
export const useSearchForWhiteListCandidates = (
query: SearchForWhiteListCandidatesQuery,
enabled: boolean,
) => {
- const { keyword, groupId, resultsPerPage } = query
-
- return useInfiniteQuery({
- queryKey: [NAME_SPACE, 'app-whitelist-candidates', keyword, groupId, resultsPerPage],
- queryFn: ({ pageParam }) => {
- const params = new URLSearchParams()
- if (keyword) params.append('keyword', keyword)
- if (groupId) params.append('groupId', groupId)
- if (resultsPerPage) params.append('resultsPerPage', `${resultsPerPage}`)
- params.append('pageNumber', `${pageParam}`)
- return get<SearchResults>(
- `/enterprise/webapp/app/subject/search?${new URLSearchParams(params).toString()}`,
- )
- },
- initialPageParam: 1,
- getNextPageParam: (lastPage) => {
- if (lastPage.hasMore) return lastPage.currPage + 1
- return undefined
- },
- gcTime: 0,
- staleTime: 0,
- enabled,
- })
+ return useInfiniteQuery(
+ consoleQuery.enterprise.webAppAuth.searchForWhilteListCandidates.infiniteOptions({
+ input: (pageParam: number) => ({
+ query: {
+ keyword: query.keyword || undefined,
+ groupId: query.groupId || undefined,
+ resultsPerPage: query.resultsPerPage || undefined,
+ pageNumber: pageParam,
+ },
+ }),
+ initialPageParam: 1,
+ getNextPageParam: (lastPage, _pages, lastPageParam) =>
+ lastPage.hasMore ? (lastPage.currPage ?? lastPageParam) + 1 : undefined,
+ select: (data) => ({
+ ...data,
+ pages: data.pages.map((page) => ({
+ ...page,
+ subjects: (page.subjects ?? []).flatMap(selectCandidate),
+ })),
+ }),
+ gcTime: 0,
+ staleTime: 0,
+ enabled,
+ }),
+ )
}
export const useGetUserCanAccessApp = ({
diff --git a/web/service/common.ts b/web/service/common.ts
index acd61f56359..73a0ccb00ab 100644
--- a/web/service/common.ts
+++ b/web/service/common.ts
@@ -30,16 +30,11 @@ export const changeWebAppPasswordWithToken = ({
body: { token: string; new_password: string; password_confirm: string }
}): Promise<CommonResponse> => post<CommonResponse>(url, { body }, { isPublicAPI: true })
-export const uploadRemoteFileInfo = (
- url: string,
- isPublic?: boolean,
- silent?: boolean,
- uploadEndpoint?: string,
-): Promise<{ id: string; name: string; size: number; mime_type: string; url: string }> => {
+export const uploadPublicRemoteFileInfo = (url: string) => {
return post<{ id: string; name: string; size: number; mime_type: string; url: string }>(
- uploadEndpoint || '/remote-files/upload',
+ '/remote-files/upload',
{ body: { url } },
- { isPublicAPI: isPublic, silent },
+ { isPublicAPI: true },
)
}
diff --git a/web/service/console/__tests__/workflow-stop-policies.spec.ts b/web/service/console/__tests__/workflow-stop-policies.spec.ts
new file mode 100644
index 00000000000..ea663c99f36
--- /dev/null
+++ b/web/service/console/__tests__/workflow-stop-policies.spec.ts
@@ -0,0 +1,86 @@
+import type { QueryClient, QueryKey } from '@tanstack/react-query'
+import { MutationObserver } from '@tanstack/react-query'
+import { createConsoleQueryClient } from '@/test/console/query-data'
+import { consoleQuery } from '../index'
+
+const request = vi.hoisted(() => vi.fn<() => Promise<Response>>())
+vi.mock('@/service/base', () => ({ request }))
+
+const cases = [
+ {
+ name: 'app',
+ keys: (id: string) => [
+ consoleQuery.apps.byAppId.workflowRuns.get.queryKey({ input: { params: { app_id: id } } }),
+ consoleQuery.apps.byAppId.advancedChat.workflowRuns.get.queryKey({
+ input: { params: { app_id: id } },
+ }),
+ consoleQuery.apps.byAppId.workflowRuns.byRunId.get.queryKey({
+ input: { params: { app_id: id, run_id: 'run-1' } },
+ }),
+ ],
+ run: (client: QueryClient) =>
+ new MutationObserver(
+ client,
+ consoleQuery.apps.byAppId.workflowRuns.tasks.byTaskId.stop.post.mutationOptions(),
+ ).mutate({ params: { app_id: 'owner', task_id: 'task' } }),
+ },
+ {
+ name: 'pipeline',
+ keys: (id: string) => [
+ consoleQuery.rag.pipelines.byPipelineId.workflowRuns.get.queryKey({
+ input: { params: { pipeline_id: id } },
+ }),
+ consoleQuery.rag.pipelines.byPipelineId.workflowRuns.byRunId.get.queryKey({
+ input: { params: { pipeline_id: id, run_id: 'run-1' } },
+ }),
+ ],
+ run: (client: QueryClient) =>
+ new MutationObserver(
+ client,
+ consoleQuery.rag.pipelines.byPipelineId.workflowRuns.tasks.byTaskId.stop.post.mutationOptions(),
+ ).mutate({ params: { pipeline_id: 'owner', task_id: 'task' } }),
+ },
+ {
+ name: 'snippet',
+ keys: (id: string) => [
+ consoleQuery.snippets.bySnippetId.workflowRuns.get.queryKey({
+ input: { params: { snippet_id: id } },
+ }),
+ consoleQuery.snippets.bySnippetId.workflowRuns.byRunId.get.queryKey({
+ input: { params: { snippet_id: id, run_id: 'run-1' } },
+ }),
+ ],
+ run: (client: QueryClient) =>
+ new MutationObserver(
+ client,
+ consoleQuery.snippets.bySnippetId.workflowRuns.tasks.byTaskId.stop.post.mutationOptions(),
+ ).mutate({ params: { snippet_id: 'owner', task_id: 'task' } }),
+ },
+]
+
+it.each(cases)(
+ 'refreshes only the stopped $name resource after success or a lost response',
+ async ({ keys, run }) => {
+ vi.spyOn(console, 'error').mockImplementation(() => {})
+ try {
+ for (const failed of [false, true]) {
+ const client = createConsoleQueryClient()
+ const affected: QueryKey[] = keys('owner')
+ const unrelated: QueryKey[] = keys('other')
+ for (const key of [...affected, ...unrelated]) client.setQueryData(key, { cached: true })
+ if (failed) request.mockRejectedValue(new TypeError('Connection lost'))
+ else request.mockResolvedValue(Response.json({ result: 'success' }))
+ try {
+ if (failed) await expect(run(client)).rejects.toThrow('Connection lost')
+ else await run(client)
+ for (const key of affected) expect(client.getQueryState(key)?.isInvalidated).toBe(true)
+ for (const key of unrelated) expect(client.getQueryState(key)?.isInvalidated).toBe(false)
+ } finally {
+ client.clear()
+ }
+ }
+ } finally {
+ vi.restoreAllMocks()
+ }
+ },
+)
diff --git a/web/service/console/app-parameters-select.ts b/web/service/console/app-parameters-select.ts
new file mode 100644
index 00000000000..673b6a25b37
--- /dev/null
+++ b/web/service/console/app-parameters-select.ts
@@ -0,0 +1,289 @@
+import type { Parameters as AppParameters } from '@dify/contracts/api/console/installed-apps/types.gen'
+import type { ChatConfig } from '@/app/components/base/chat/types'
+import { SupportUploadFileTypes } from '@/app/components/workflow/types'
+import { ANNOTATION_DEFAULT, DEFAULT_AGENT_SETTING } from '@/config'
+import { PromptMode } from '@/models/debug'
+import { Resolution, RETRIEVE_TYPE, TransferMethod, TtsAutoPlay } from '@/types/app'
+
+const transferMethodValues = new Set<string>(Object.values(TransferMethod))
+const supportUploadFileTypeValues = new Set<string>(Object.values(SupportUploadFileTypes))
+
+const isRecord = (value: unknown): value is Record<string, unknown> => {
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
+}
+
+const getString = (value: unknown, fallback = '') => {
+ return typeof value === 'string' ? value : fallback
+}
+
+const getOptionalString = (value: unknown) => {
+ return typeof value === 'string' ? value : undefined
+}
+
+const getBoolean = (value: unknown, fallback = false) => {
+ return typeof value === 'boolean' ? value : fallback
+}
+
+const getNumber = (value: unknown, fallback: number) => {
+ return typeof value === 'number' ? value : fallback
+}
+
+const getStringArray = (value: unknown) => {
+ return Array.isArray(value)
+ ? value.filter((item): item is string => typeof item === 'string')
+ : []
+}
+
+const getStringRecord = (value: unknown) => {
+ if (!isRecord(value)) return undefined
+
+ const record: Record<string, string> = {}
+ Object.entries(value).forEach(([key, item]) => {
+ if (typeof item === 'string') record[key] = item
+ })
+ return record
+}
+
+const normalizeEnabledConfig = (value: Record<string, unknown>, fallback = false) => {
+ return {
+ ...value,
+ enabled: getBoolean(value.enabled, fallback),
+ }
+}
+
+const normalizeTextToSpeechConfig = (
+ value: Record<string, unknown>,
+): ChatConfig['text_to_speech'] => {
+ const autoPlay = getString(value.autoPlay)
+ const config = { ...value }
+ delete config.autoPlay
+ return {
+ ...normalizeEnabledConfig(config),
+ voice: getOptionalString(value.voice),
+ language: getOptionalString(value.language),
+ ...(autoPlay === TtsAutoPlay.enabled || autoPlay === TtsAutoPlay.disabled ? { autoPlay } : {}),
+ }
+}
+
+const normalizeAnnotationReplyConfig = (
+ value: Record<string, unknown>,
+): ChatConfig['annotation_reply'] => {
+ const embeddingModel = isRecord(value.embedding_model) ? value.embedding_model : {}
+ return {
+ id: getString(value.id),
+ enabled: getBoolean(value.enabled),
+ score_threshold: getNumber(value.score_threshold, ANNOTATION_DEFAULT.score_threshold),
+ embedding_model: {
+ embedding_provider_name: getString(embeddingModel.embedding_provider_name),
+ embedding_model_name: getString(embeddingModel.embedding_model_name),
+ },
+ }
+}
+
+const getTransferMethods = (value: unknown, fallback: TransferMethod[]) => {
+ if (!Array.isArray(value)) return fallback
+
+ const methods = value.filter((item): item is TransferMethod => {
+ return typeof item === 'string' && transferMethodValues.has(item)
+ })
+ return methods.length > 0 ? methods : fallback
+}
+
+const getSupportUploadFileTypes = (value: unknown): SupportUploadFileTypes[] => {
+ if (!Array.isArray(value)) return []
+
+ return value.filter((item): item is SupportUploadFileTypes => {
+ return typeof item === 'string' && supportUploadFileTypeValues.has(item)
+ })
+}
+
+const normalizeVisionSettings = (
+ value: unknown,
+): NonNullable<ChatConfig['file_upload']>['image'] => {
+ const image = isRecord(value) ? value : {}
+ return {
+ enabled: getBoolean(image.enabled),
+ number_limits: getNumber(image.number_limits, 3),
+ detail: getString(image.detail) === Resolution.low ? Resolution.low : Resolution.high,
+ transfer_methods: getTransferMethods(image.transfer_methods, [
+ TransferMethod.local_file,
+ TransferMethod.remote_url,
+ ]),
+ }
+}
+
+const normalizeFileUploadConfig = (value: Record<string, unknown>): ChatConfig['file_upload'] => {
+ const allowedUploadMethods = getTransferMethods(value.allowed_upload_methods, [
+ TransferMethod.local_file,
+ TransferMethod.remote_url,
+ ])
+ const allowedFileUploadMethods = getTransferMethods(
+ value.allowed_file_upload_methods,
+ allowedUploadMethods,
+ )
+
+ return {
+ enabled: typeof value.enabled === 'boolean' ? value.enabled : undefined,
+ image: normalizeVisionSettings(value.image),
+ allowed_file_upload_methods: allowedFileUploadMethods,
+ allowed_upload_methods: allowedUploadMethods,
+ allowed_file_types: getSupportUploadFileTypes(value.allowed_file_types),
+ allowed_file_extensions: getStringArray(value.allowed_file_extensions),
+ max_length: getNumber(value.max_length, 1),
+ number_limits: getNumber(value.number_limits, 1),
+ }
+}
+
+const defaultDatasetConfigs: ChatConfig['dataset_configs'] = {
+ retrieval_model: RETRIEVE_TYPE.oneWay,
+ reranking_model: {
+ reranking_provider_name: '',
+ reranking_model_name: '',
+ },
+ top_k: 4,
+ score_threshold_enabled: false,
+ score_threshold: null,
+ datasets: {
+ datasets: [],
+ },
+}
+
+const normalizeBaseInputForm = (value: Record<string, unknown>) => {
+ return {
+ default: getString(value.default),
+ label: getString(value.label),
+ variable: getString(value.variable),
+ required: getBoolean(value.required, true),
+ hide: getBoolean(value.hide),
+ }
+}
+
+const normalizeTextInputForm = (value: Record<string, unknown>) => {
+ return {
+ ...normalizeBaseInputForm(value),
+ max_length: getNumber(value.max_length, 0),
+ }
+}
+
+const normalizeFileInputForm = (value: Record<string, unknown>) => {
+ return {
+ ...normalizeBaseInputForm(value),
+ max_length: getNumber(value.max_length, 1),
+ allowed_file_upload_methods: getTransferMethods(value.allowed_file_upload_methods, [
+ TransferMethod.local_file,
+ TransferMethod.remote_url,
+ ]),
+ allowed_upload_methods: getTransferMethods(value.allowed_upload_methods, [
+ TransferMethod.local_file,
+ TransferMethod.remote_url,
+ ]),
+ allowed_file_types: getSupportUploadFileTypes(value.allowed_file_types),
+ allowed_file_extensions: getStringArray(value.allowed_file_extensions),
+ }
+}
+
+const normalizeUserInputFormItem = (
+ item: Record<string, unknown>,
+): ChatConfig['user_input_form'][number] | null => {
+ if (isRecord(item['text-input']))
+ return { 'text-input': normalizeTextInputForm(item['text-input']) }
+
+ if (isRecord(item.paragraph)) return { paragraph: normalizeTextInputForm(item.paragraph) }
+
+ if (isRecord(item.select)) {
+ return {
+ select: {
+ ...normalizeBaseInputForm(item.select),
+ options: getStringArray(item.select.options),
+ },
+ }
+ }
+
+ if (isRecord(item.number)) {
+ return {
+ number: {
+ ...normalizeBaseInputForm(item.number),
+ default:
+ typeof item.number.default === 'number'
+ ? item.number.default
+ : getString(item.number.default),
+ max_length: getNumber(item.number.max_length, 0),
+ },
+ }
+ }
+
+ if (isRecord(item.checkbox)) {
+ return {
+ checkbox: {
+ ...normalizeBaseInputForm(item.checkbox),
+ default: getBoolean(item.checkbox.default),
+ },
+ }
+ }
+
+ if (isRecord(item.file)) return { file: normalizeFileInputForm(item.file) }
+
+ if (isRecord(item['file-list'])) return { 'file-list': normalizeFileInputForm(item['file-list']) }
+
+ if (isRecord(item.external_data_tool)) {
+ return {
+ external_data_tool: {
+ label: getString(item.external_data_tool.label),
+ variable: getString(item.external_data_tool.variable),
+ required: getBoolean(item.external_data_tool.required, true),
+ hide: getBoolean(item.external_data_tool.hide),
+ type: getOptionalString(item.external_data_tool.type),
+ enabled: getBoolean(item.external_data_tool.enabled),
+ icon: getOptionalString(item.external_data_tool.icon),
+ icon_background: getOptionalString(item.external_data_tool.icon_background),
+ config: getStringRecord(item.external_data_tool.config),
+ },
+ }
+ }
+
+ if (isRecord(item.json_object)) {
+ const jsonSchema = item.json_object.json_schema
+ return {
+ json_object: {
+ ...normalizeBaseInputForm(item.json_object),
+ json_schema:
+ typeof jsonSchema === 'string' || isRecord(jsonSchema) ? jsonSchema : undefined,
+ },
+ }
+ }
+
+ return null
+}
+
+const normalizeUserInputForm = (
+ items: AppParameters['user_input_form'],
+): ChatConfig['user_input_form'] => {
+ return items.reduce<ChatConfig['user_input_form']>((result, item) => {
+ const normalized = normalizeUserInputFormItem(item)
+ if (normalized) result.push(normalized)
+ return result
+ }, [])
+}
+
+export const selectAppParameters = (params: AppParameters): ChatConfig => {
+ return {
+ opening_statement: params.opening_statement ?? '',
+ suggested_questions: params.suggested_questions,
+ suggested_questions_after_answer: normalizeEnabledConfig(
+ params.suggested_questions_after_answer,
+ ),
+ speech_to_text: normalizeEnabledConfig(params.speech_to_text),
+ text_to_speech: normalizeTextToSpeechConfig(params.text_to_speech),
+ retriever_resource: normalizeEnabledConfig(params.retriever_resource),
+ annotation_reply: normalizeAnnotationReplyConfig(params.annotation_reply),
+ more_like_this: normalizeEnabledConfig(params.more_like_this),
+ sensitive_word_avoidance: normalizeEnabledConfig(params.sensitive_word_avoidance),
+ file_upload: normalizeFileUploadConfig(params.file_upload),
+ user_input_form: normalizeUserInputForm(params.user_input_form),
+ system_parameters: params.system_parameters,
+ pre_prompt: '',
+ prompt_type: PromptMode.simple,
+ agent_mode: DEFAULT_AGENT_SETTING,
+ dataset_configs: defaultDatasetConfigs,
+ }
+}
diff --git a/web/service/console/browser.ts b/web/service/console/browser.ts
index d3e7c095178..37d90dfdee8 100644
--- a/web/service/console/browser.ts
+++ b/web/service/console/browser.ts
@@ -13,16 +13,18 @@ import { normalizeConsoleOpenAPIURL } from './openapi-url'
function createBrowserLink(contract: AnyContractRouter): ClientLink<ConsoleClientContext> {
return new OpenAPILink<ConsoleClientContext>(contract, {
url: () => new URL(API_PREFIX, window.location.origin),
- fetch: (input, init, options) => {
+ fetch: async (input, init, options) => {
const requestInit = options.context.keepalive ? { ...init, keepalive: true } : init
const normalizedURL = normalizeConsoleOpenAPIURL(input.url)
const normalizedRequest =
normalizedURL === input.url ? input : new Request(normalizedURL, input)
- return request(normalizedURL, requestInit, {
+ const response = await request<Response>(normalizedURL, requestInit, {
fetchCompat: true,
request: normalizedRequest,
silent: options.context.silent,
})
+ options.context.onResponseHeaders?.(response.headers)
+ return response
},
interceptors: [validateDefinedErrors(contract), onError((error) => console.error(error))],
})
diff --git a/web/service/console/index.ts b/web/service/console/index.ts
index 47f37098f93..107f6731bed 100644
--- a/web/service/console/index.ts
+++ b/web/service/console/index.ts
@@ -10,6 +10,7 @@ import { createConsoleQuery } from './query-policies'
export type ConsoleClientContext = TanstackQueryOperationContext & {
keepalive?: boolean
silent?: boolean
+ onResponseHeaders?: (headers: Headers) => void
}
export type ConsoleClient = JsonifiedClient<
diff --git a/web/service/console/plugin-auth-select.ts b/web/service/console/plugin-auth-select.ts
new file mode 100644
index 00000000000..21704cc29a5
--- /dev/null
+++ b/web/service/console/plugin-auth-select.ts
@@ -0,0 +1,30 @@
+import type { I18nObject, ProviderConfig } from '@dify/contracts/api/console/workspaces/types.gen'
+import type { FormSchema, TypeWithI18N } from '@/app/components/base/form/types'
+
+function selectLabel(label: I18nObject, fallback = label.en_US): TypeWithI18N {
+ return {
+ en_US: label.en_US,
+ zh_Hans: label.zh_Hans ?? fallback,
+ ...(label.ja_JP != null ? { ja_JP: label.ja_JP } : {}),
+ ...(label.pt_BR != null ? { pt_BR: label.pt_BR } : {}),
+ }
+}
+
+export function selectCredentialFormSchema(schema: ProviderConfig): FormSchema {
+ return {
+ type: schema.type,
+ name: schema.name,
+ label: schema.label ? selectLabel(schema.label) : schema.name,
+ required: schema.required ?? false,
+ multiple: schema.multiple,
+ default: schema.default ?? undefined,
+ scope: schema.scope ?? undefined,
+ help: schema.help ? selectLabel(schema.help) : undefined,
+ url: schema.url ?? undefined,
+ placeholder: schema.placeholder ? selectLabel(schema.placeholder) : undefined,
+ options: schema.options?.map((option) => ({
+ value: option.value,
+ label: selectLabel(option.label),
+ })),
+ }
+}
diff --git a/web/service/console/query-policies.ts b/web/service/console/query-policies.ts
index 1a5d6782236..15c42d225f6 100644
--- a/web/service/console/query-policies.ts
+++ b/web/service/console/query-policies.ts
@@ -11,6 +11,11 @@ import type { InfiniteData, QueryClient, QueryKey } from '@tanstack/react-query'
import type { ConsoleClient } from './index'
import { createTanstackQueryUtils } from '@orpc/tanstack-query'
import { getHttpErrorStatus, isNotFoundError } from '@/service/http-error'
+import {
+ legacyWorkflowVersionHistoryKey,
+ syncAppWorkflowVersionCaches,
+ syncWorkflowDeploymentCaches,
+} from './workflow-version-cache'
export function createConsoleQuery(consoleClient: ConsoleClient) {
const consoleQuery: RouterUtils<ConsoleClient> = createTanstackQueryUtils(consoleClient, {
@@ -80,7 +85,125 @@ export function createConsoleQuery(consoleClient: ConsoleClient) {
datasource: {
list: { get: { queryOptions: { retry: false } } },
defaultList: { get: { queryOptions: { retry: false } } },
- byProviderId: { get: { queryOptions: { retry: false } } },
+ byProviderId: {
+ post: {
+ mutationOptions: {
+ onSuccess: (_data, variables, _result, context) =>
+ Promise.all([
+ context.client.invalidateQueries({
+ queryKey: consoleQuery.auth.plugin.datasource.byProviderId.get.key({
+ input: { params: { provider_id: variables.params.provider_id } },
+ }),
+ }),
+ context.client.invalidateQueries({
+ queryKey: consoleQuery.auth.plugin.datasource.list.get.key(),
+ }),
+ context.client.invalidateQueries({
+ queryKey: consoleQuery.auth.plugin.datasource.defaultList.get.key(),
+ }),
+ ]),
+ },
+ },
+ update: {
+ post: {
+ mutationOptions: {
+ onSuccess: (_data, variables, _result, context) =>
+ Promise.all([
+ context.client.invalidateQueries({
+ queryKey: consoleQuery.auth.plugin.datasource.byProviderId.get.key({
+ input: { params: { provider_id: variables.params.provider_id } },
+ }),
+ }),
+ context.client.invalidateQueries({
+ queryKey: consoleQuery.auth.plugin.datasource.list.get.key(),
+ }),
+ context.client.invalidateQueries({
+ queryKey: consoleQuery.auth.plugin.datasource.defaultList.get.key(),
+ }),
+ ]),
+ },
+ },
+ },
+ customClient: {
+ post: {
+ mutationOptions: {
+ onSuccess: (_data, variables, _result, context) =>
+ Promise.all([
+ context.client.invalidateQueries({
+ queryKey: consoleQuery.auth.plugin.datasource.byProviderId.get.key({
+ input: { params: { provider_id: variables.params.provider_id } },
+ }),
+ }),
+ context.client.invalidateQueries({
+ queryKey: consoleQuery.auth.plugin.datasource.list.get.key(),
+ }),
+ context.client.invalidateQueries({
+ queryKey: consoleQuery.auth.plugin.datasource.defaultList.get.key(),
+ }),
+ ]),
+ },
+ },
+ delete: {
+ mutationOptions: {
+ onSuccess: (_data, variables, _result, context) =>
+ Promise.all([
+ context.client.invalidateQueries({
+ queryKey: consoleQuery.auth.plugin.datasource.byProviderId.get.key({
+ input: { params: { provider_id: variables.params.provider_id } },
+ }),
+ }),
+ context.client.invalidateQueries({
+ queryKey: consoleQuery.auth.plugin.datasource.list.get.key(),
+ }),
+ context.client.invalidateQueries({
+ queryKey: consoleQuery.auth.plugin.datasource.defaultList.get.key(),
+ }),
+ ]),
+ },
+ },
+ },
+ get: { queryOptions: { retry: false } },
+ default: {
+ post: {
+ mutationOptions: {
+ onSuccess: (_data, variables, _result, context) =>
+ Promise.all([
+ context.client.invalidateQueries({
+ queryKey: consoleQuery.auth.plugin.datasource.byProviderId.get.key({
+ input: { params: { provider_id: variables.params.provider_id } },
+ }),
+ }),
+ context.client.invalidateQueries({
+ queryKey: consoleQuery.auth.plugin.datasource.list.get.key(),
+ }),
+ context.client.invalidateQueries({
+ queryKey: consoleQuery.auth.plugin.datasource.defaultList.get.key(),
+ }),
+ ]),
+ },
+ },
+ },
+ delete: {
+ post: {
+ mutationOptions: {
+ onSuccess: (_data, variables, _result, context) =>
+ Promise.all([
+ context.client.invalidateQueries({
+ queryKey: consoleQuery.auth.plugin.datasource.byProviderId.get.key({
+ input: { params: { provider_id: variables.params.provider_id } },
+ }),
+ }),
+ context.client.invalidateQueries({
+ queryKey: consoleQuery.auth.plugin.datasource.list.get.key(),
+ }),
+ context.client.invalidateQueries({
+ queryKey: consoleQuery.auth.plugin.datasource.defaultList.get.key(),
+ }),
+ ]),
+ },
+ },
+ },
+ },
},
},
},
@@ -121,7 +244,81 @@ export function createConsoleQuery(consoleClient: ConsoleClient) {
},
},
byPipelineId: {
+ workflowRuns: {
+ tasks: {
+ byTaskId: {
+ stop: {
+ post: {
+ mutationOptions: {
+ // A failed response can still follow an accepted stop request.
+ onSettled: (_data, _error, variables, _result, context) => {
+ return context.client.invalidateQueries({
+ queryKey: consoleQuery.rag.pipelines.byPipelineId.workflowRuns.key({
+ input: { params: { pipeline_id: variables.params.pipeline_id } },
+ }),
+ })
+ },
+ },
+ },
+ },
+ },
+ },
+ },
workflows: {
+ publish: {
+ post: {
+ mutationOptions: {
+ onSuccess: (_data, variables, _result, context) =>
+ Promise.all([
+ context.client.invalidateQueries({
+ queryKey:
+ consoleQuery.rag.pipelines.byPipelineId.workflows.publish.get.key({
+ input: { params: variables.params },
+ }),
+ }),
+ context.client.invalidateQueries({
+ queryKey: consoleQuery.rag.pipelines.byPipelineId.workflows.get.key({
+ input: { params: variables.params },
+ }),
+ }),
+ context.client.invalidateQueries({
+ queryKey: legacyWorkflowVersionHistoryKey,
+ }),
+ context.client.invalidateQueries({
+ queryKey: consoleQuery.datasets.get.key(),
+ }),
+ ]),
+ },
+ },
+ },
+ byWorkflowId: {
+ patch: {
+ mutationOptions: {
+ onSuccess: (_data, variables, _result, context) => {
+ return Promise.all([
+ context.client.invalidateQueries({
+ queryKey: legacyWorkflowVersionHistoryKey,
+ }),
+ context.client.invalidateQueries({
+ queryKey: consoleQuery.rag.pipelines.byPipelineId.workflows.get.key({
+ input: { params: { pipeline_id: variables.params.pipeline_id } },
+ }),
+ }),
+ ])
+ },
+ },
+ },
+ delete: {
+ mutationOptions: {
+ onSuccess: (_data, variables, _result, context) =>
+ context.client.invalidateQueries({
+ queryKey: consoleQuery.rag.pipelines.byPipelineId.workflows.get.key({
+ input: { params: { pipeline_id: variables.params.pipeline_id } },
+ }),
+ }),
+ },
+ },
+ },
draft: {
processing: { parameters: { get: { queryOptions: { staleTime: 0 } } } },
preProcessing: { parameters: { get: { queryOptions: { staleTime: 0 } } } },
@@ -136,6 +333,150 @@ export function createConsoleQuery(consoleClient: ConsoleClient) {
},
workspaces: {
current: {
+ toolProvider: {
+ builtin: {
+ byProvider: {
+ add: {
+ post: {
+ mutationOptions: {
+ onSuccess: (_data, variables, _result, context) =>
+ Promise.all([
+ context.client.invalidateQueries({
+ queryKey:
+ consoleQuery.workspaces.current.toolProvider.builtin.byProvider.credential.info.get.key(
+ { input: { params: { provider: variables.params.provider } } },
+ ),
+ }),
+ context.client.invalidateQueries({
+ queryKey:
+ consoleQuery.workspaces.current.toolProvider.builtin.byProvider.credentials.get.key(
+ { input: { params: { provider: variables.params.provider } } },
+ ),
+ }),
+ context.client.invalidateQueries({
+ queryKey: consoleQuery.workspaces.current.tools.builtin.get.key(),
+ }),
+ ]),
+ },
+ },
+ },
+ update: {
+ post: {
+ mutationOptions: {
+ onSuccess: (_data, variables, _result, context) =>
+ Promise.all([
+ context.client.invalidateQueries({
+ queryKey:
+ consoleQuery.workspaces.current.toolProvider.builtin.byProvider.credential.info.get.key(
+ { input: { params: { provider: variables.params.provider } } },
+ ),
+ }),
+ context.client.invalidateQueries({
+ queryKey:
+ consoleQuery.workspaces.current.toolProvider.builtin.byProvider.credentials.get.key(
+ { input: { params: { provider: variables.params.provider } } },
+ ),
+ }),
+ context.client.invalidateQueries({
+ queryKey: consoleQuery.workspaces.current.tools.builtin.get.key(),
+ }),
+ ]),
+ },
+ },
+ },
+ oauth: {
+ customClient: {
+ post: {
+ mutationOptions: {
+ onSuccess: (_data, variables, _result, context) =>
+ Promise.all([
+ context.client.invalidateQueries({
+ queryKey:
+ consoleQuery.workspaces.current.toolProvider.builtin.byProvider.oauth.clientSchema.get.key(
+ { input: { params: { provider: variables.params.provider } } },
+ ),
+ }),
+ context.client.invalidateQueries({
+ queryKey:
+ consoleQuery.workspaces.current.toolProvider.builtin.byProvider.oauth.customClient.get.key(
+ { input: { params: { provider: variables.params.provider } } },
+ ),
+ }),
+ ]),
+ },
+ },
+ delete: {
+ mutationOptions: {
+ onSuccess: (_data, variables, _result, context) =>
+ Promise.all([
+ context.client.invalidateQueries({
+ queryKey:
+ consoleQuery.workspaces.current.toolProvider.builtin.byProvider.oauth.clientSchema.get.key(
+ { input: { params: { provider: variables.params.provider } } },
+ ),
+ }),
+ context.client.invalidateQueries({
+ queryKey:
+ consoleQuery.workspaces.current.toolProvider.builtin.byProvider.oauth.customClient.get.key(
+ { input: { params: { provider: variables.params.provider } } },
+ ),
+ }),
+ ]),
+ },
+ },
+ },
+ },
+ defaultCredential: {
+ post: {
+ mutationOptions: {
+ onSuccess: (_data, variables, _result, context) =>
+ Promise.all([
+ context.client.invalidateQueries({
+ queryKey:
+ consoleQuery.workspaces.current.toolProvider.builtin.byProvider.credential.info.get.key(
+ { input: { params: { provider: variables.params.provider } } },
+ ),
+ }),
+ context.client.invalidateQueries({
+ queryKey:
+ consoleQuery.workspaces.current.toolProvider.builtin.byProvider.credentials.get.key(
+ { input: { params: { provider: variables.params.provider } } },
+ ),
+ }),
+ context.client.invalidateQueries({
+ queryKey: consoleQuery.workspaces.current.tools.builtin.get.key(),
+ }),
+ ]),
+ },
+ },
+ },
+ delete: {
+ post: {
+ mutationOptions: {
+ onSuccess: (_data, variables, _result, context) =>
+ Promise.all([
+ context.client.invalidateQueries({
+ queryKey:
+ consoleQuery.workspaces.current.toolProvider.builtin.byProvider.credential.info.get.key(
+ { input: { params: { provider: variables.params.provider } } },
+ ),
+ }),
+ context.client.invalidateQueries({
+ queryKey:
+ consoleQuery.workspaces.current.toolProvider.builtin.byProvider.credentials.get.key(
+ { input: { params: { provider: variables.params.provider } } },
+ ),
+ }),
+ context.client.invalidateQueries({
+ queryKey: consoleQuery.workspaces.current.tools.builtin.get.key(),
+ }),
+ ]),
+ },
+ },
+ },
+ },
+ },
+ },
networkAccessGroups: {
post: {
mutationOptions: {
@@ -593,6 +934,33 @@ export function createConsoleQuery(consoleClient: ConsoleClient) {
},
},
byAppId: {
+ workflowRuns: {
+ tasks: {
+ byTaskId: {
+ stop: {
+ post: {
+ mutationOptions: {
+ // A failed response can still follow an accepted stop request.
+ onSettled: (_data, _error, variables, _result, context) => {
+ return Promise.all([
+ context.client.invalidateQueries({
+ queryKey: consoleQuery.apps.byAppId.workflowRuns.key({
+ input: { params: { app_id: variables.params.app_id } },
+ }),
+ }),
+ context.client.invalidateQueries({
+ queryKey: consoleQuery.apps.byAppId.advancedChat.workflowRuns.key({
+ input: { params: { app_id: variables.params.app_id } },
+ }),
+ }),
+ ])
+ },
+ },
+ },
+ },
+ },
+ },
+ },
trace: {
post: {
mutationOptions: {
@@ -858,6 +1226,79 @@ export function createConsoleQuery(consoleClient: ConsoleClient) {
},
},
workflows: {
+ publish: {
+ post: {
+ mutationOptions: {
+ onSuccess: (_data, variables, _result, context) =>
+ Promise.all([
+ context.client.invalidateQueries({
+ queryKey: consoleQuery.apps.byAppId.workflows.publish.get.key({
+ input: { params: variables.params },
+ }),
+ }),
+ context.client.invalidateQueries({
+ queryKey: consoleQuery.apps.byAppId.workflows.get.key({
+ input: { params: variables.params },
+ }),
+ }),
+ context.client.invalidateQueries({
+ queryKey: legacyWorkflowVersionHistoryKey,
+ }),
+ context.client.invalidateQueries({
+ queryKey: consoleQuery.apps.byAppId.get.key({
+ input: { params: variables.params },
+ }),
+ }),
+ context.client.invalidateQueries({
+ queryKey: consoleQuery.apps.byAppId.triggers.get.key({
+ input: { params: variables.params },
+ }),
+ }),
+ ]),
+ },
+ },
+ },
+ byWorkflowId: {
+ patch: {
+ mutationOptions: {
+ onSuccess: (data, variables, _result, context) => {
+ syncAppWorkflowVersionCaches(
+ context.client,
+ consoleQuery,
+ variables.params.app_id,
+ data,
+ )
+ const deploymentsKey = syncWorkflowDeploymentCaches(
+ context.client,
+ consoleQuery,
+ variables.params.app_id,
+ data,
+ )
+ return Promise.all([
+ context.client.invalidateQueries({
+ queryKey: legacyWorkflowVersionHistoryKey,
+ }),
+ context.client.invalidateQueries({
+ queryKey: consoleQuery.apps.byAppId.workflows.get.key({
+ input: { params: { app_id: variables.params.app_id } },
+ }),
+ }),
+ context.client.invalidateQueries({ queryKey: deploymentsKey }),
+ ])
+ },
+ },
+ },
+ delete: {
+ mutationOptions: {
+ onSuccess: (_data, variables, _result, context) =>
+ context.client.invalidateQueries({
+ queryKey: consoleQuery.apps.byAppId.workflows.get.key({
+ input: { params: { app_id: variables.params.app_id } },
+ }),
+ }),
+ },
+ },
+ },
draft: {
nodes: {
byNodeId: {
@@ -1128,7 +1569,55 @@ export function createConsoleQuery(consoleClient: ConsoleClient) {
},
snippets: {
bySnippetId: {
+ workflowRuns: {
+ tasks: {
+ byTaskId: {
+ stop: {
+ post: {
+ mutationOptions: {
+ // A failed response can still follow an accepted stop request.
+ onSettled: (_data, _error, variables, _result, context) => {
+ return context.client.invalidateQueries({
+ queryKey: consoleQuery.snippets.bySnippetId.workflowRuns.key({
+ input: { params: { snippet_id: variables.params.snippet_id } },
+ }),
+ })
+ },
+ },
+ },
+ },
+ },
+ },
+ },
workflows: {
+ byWorkflowId: {
+ patch: {
+ mutationOptions: {
+ onSuccess: (_data, variables, _result, context) => {
+ return Promise.all([
+ context.client.invalidateQueries({
+ queryKey: legacyWorkflowVersionHistoryKey,
+ }),
+ context.client.invalidateQueries({
+ queryKey: consoleQuery.snippets.bySnippetId.workflows.get.key({
+ input: { params: { snippet_id: variables.params.snippet_id } },
+ }),
+ }),
+ ])
+ },
+ },
+ },
+ delete: {
+ mutationOptions: {
+ onSuccess: (_data, variables, _result, context) =>
+ context.client.invalidateQueries({
+ queryKey: consoleQuery.snippets.bySnippetId.workflows.get.key({
+ input: { params: { snippet_id: variables.params.snippet_id } },
+ }),
+ }),
+ },
+ },
+ },
draft: {
nodes: {
byNodeId: {
diff --git a/web/service/console/server.ts b/web/service/console/server.ts
index 94c217086e9..281e3369f72 100644
--- a/web/service/console/server.ts
+++ b/web/service/console/server.ts
@@ -67,7 +67,7 @@ function createServerConsoleOpenAPILink(
return new OpenAPILink<ConsoleClientContext>(contract, {
url: getServerConsoleApiPrefix,
headers: getServerConsoleRequestHeaders,
- fetch: async (request, init) => {
+ fetch: async (request, init, options) => {
if (request.body && !request.headers.has('content-type'))
request.headers.set('Content-Type', 'application/json')
@@ -79,6 +79,7 @@ function createServerConsoleOpenAPILink(
cache: 'no-store',
})
if (isHttpErrorStatus(response.status)) throw await httpErrorFromResponse(response)
+ options.context.onResponseHeaders?.(response.headers)
return response
},
interceptors: [
diff --git a/web/service/console/workflow-version-cache.ts b/web/service/console/workflow-version-cache.ts
new file mode 100644
index 00000000000..d0887ddedb0
--- /dev/null
+++ b/web/service/console/workflow-version-cache.ts
@@ -0,0 +1,173 @@
+import type {
+ WorkflowPaginationResponse,
+ WorkflowResponse,
+} from '@dify/contracts/api/console/apps/types.gen'
+import type {
+ EnvironmentDeployment,
+ GetEnvironmentDeploymentResponse,
+ ListEnvironmentDeploymentsResponse,
+ WorkflowVersion,
+} from '@dify/contracts/enterprise-app-deploy/types.gen'
+import type { RouterUtils } from '@orpc/tanstack-query'
+import type { InfiniteData, QueryClient } from '@tanstack/react-query'
+import type { ConsoleClient } from './index'
+
+// Transitional key until the editor version list uses generated query options.
+export const legacyWorkflowVersionHistoryKey = ['workflow', 'versionHistory'] as const
+
+function syncWorkflowVersionMetadata(
+ version: WorkflowVersion | undefined,
+ updatedWorkflow: WorkflowResponse,
+) {
+ if (!version || version.id !== updatedWorkflow.id) return version
+ if (
+ version.marked_name === updatedWorkflow.marked_name &&
+ version.marked_comment === updatedWorkflow.marked_comment
+ )
+ return version
+
+ return {
+ ...version,
+ marked_name: updatedWorkflow.marked_name,
+ marked_comment: updatedWorkflow.marked_comment,
+ }
+}
+
+function syncEnvironmentDeploymentVersion(
+ environmentDeployment: EnvironmentDeployment,
+ updatedWorkflow: WorkflowResponse,
+) {
+ const deployment = environmentDeployment.deployment
+ if (!deployment) return environmentDeployment
+
+ const currentVersion = syncWorkflowVersionMetadata(deployment.current_version, updatedWorkflow)
+ const latestOperation = deployment.latest_operation
+ const targetVersion = syncWorkflowVersionMetadata(
+ latestOperation?.target_version,
+ updatedWorkflow,
+ )
+ const currentVersionChanged = currentVersion !== deployment.current_version
+ const targetVersionChanged = targetVersion !== latestOperation?.target_version
+
+ if (!currentVersionChanged && !targetVersionChanged) return environmentDeployment
+
+ return {
+ ...environmentDeployment,
+ deployment: {
+ ...deployment,
+ current_version: currentVersion,
+ latest_operation:
+ latestOperation && targetVersionChanged
+ ? {
+ ...latestOperation,
+ target_version: targetVersion,
+ }
+ : latestOperation,
+ },
+ }
+}
+
+function syncWorkflowVersionPages(
+ data: InfiniteData<WorkflowPaginationResponse> | undefined,
+ updatedWorkflow: WorkflowResponse,
+) {
+ if (!data) return data
+
+ let changed = false
+ const pages = data.pages.map((page) => {
+ let pageChanged = false
+ const items = page.items.map((workflow) => {
+ if (workflow.id !== updatedWorkflow.id) return workflow
+
+ changed = true
+ pageChanged = true
+ return updatedWorkflow
+ })
+
+ return pageChanged ? { ...page, items } : page
+ })
+
+ return changed ? { ...data, pages } : data
+}
+
+function syncEnvironmentDeployments(
+ data: ListEnvironmentDeploymentsResponse | undefined,
+ updatedWorkflow: WorkflowResponse,
+) {
+ if (!data) return data
+
+ let changed = false
+ const environmentDeployments = data.environment_deployments.map((deployment) => {
+ const updatedDeployment = syncEnvironmentDeploymentVersion(deployment, updatedWorkflow)
+ if (updatedDeployment !== deployment) changed = true
+ return updatedDeployment
+ })
+
+ return changed ? { ...data, environment_deployments: environmentDeployments } : data
+}
+
+export function syncAppWorkflowVersionCaches(
+ queryClient: QueryClient,
+ consoleQuery: RouterUtils<ConsoleClient>,
+ appId: string,
+ updatedWorkflow: WorkflowResponse,
+) {
+ const publishedWorkflowQuery = consoleQuery.apps.byAppId.workflows.publish.get.queryOptions({
+ input: { params: { app_id: appId } },
+ })
+
+ queryClient.setQueryData<WorkflowResponse>(publishedWorkflowQuery.queryKey, (workflow) =>
+ workflow?.id === updatedWorkflow.id ? updatedWorkflow : workflow,
+ )
+ queryClient.setQueriesData<InfiniteData<WorkflowPaginationResponse>>(
+ {
+ queryKey: consoleQuery.apps.byAppId.workflows.get.key({
+ type: 'infinite',
+ input: { params: { app_id: appId } },
+ }),
+ },
+ (data) => syncWorkflowVersionPages(data, updatedWorkflow),
+ )
+}
+
+export function syncWorkflowDeploymentCaches(
+ queryClient: QueryClient,
+ consoleQuery: RouterUtils<ConsoleClient>,
+ appId: string,
+ updatedWorkflow: WorkflowResponse,
+) {
+ const environmentDeploymentsQuery =
+ consoleQuery.enterprise.appDeploy.deploymentService.listEnvironmentDeployments.queryOptions({
+ input: {
+ params: {
+ app_id: appId,
+ },
+ },
+ })
+
+ queryClient.setQueryData<ListEnvironmentDeploymentsResponse>(
+ environmentDeploymentsQuery.queryKey,
+ (data) => syncEnvironmentDeployments(data, updatedWorkflow),
+ )
+ queryClient.setQueriesData<GetEnvironmentDeploymentResponse>(
+ {
+ queryKey: consoleQuery.enterprise.appDeploy.deploymentService.getEnvironmentDeployment.key({
+ type: 'query',
+ input: { params: { app_id: appId } },
+ }),
+ },
+ (data) => {
+ if (!data) return data
+
+ const environmentDeployment = syncEnvironmentDeploymentVersion(
+ data.environment_deployment,
+ updatedWorkflow,
+ )
+ return environmentDeployment === data.environment_deployment
+ ? data
+ : { ...data, environment_deployment: environmentDeployment }
+ },
+ )
+
+ return environmentDeploymentsQuery.queryKey
+}
diff --git a/web/service/share.spec.ts b/web/service/share.spec.ts
index c4a49faca3e..f2b9dbaad16 100644
--- a/web/service/share.spec.ts
+++ b/web/service/share.spec.ts
@@ -1,9 +1,14 @@
+import type { Parameters as AppParameters } from '@dify/contracts/api/console/installed-apps/types.gen'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import { userInputsFormToPromptVariables } from '@/utils/model-config'
import { createHttpError } from './http-error'
const getMock = vi.hoisted(() => vi.fn())
+const publicPost = vi.hoisted(() => vi.fn())
+const request = vi.hoisted(() => vi.fn<typeof import('./base').request>())
vi.mock('./base', () => ({
+ request,
del: vi.fn(),
delPublic: vi.fn(),
get: vi.fn(),
@@ -11,7 +16,7 @@ vi.mock('./base', () => ({
patch: vi.fn(),
patchPublic: vi.fn(),
post: vi.fn(),
- postPublic: vi.fn(),
+ postPublic: publicPost,
ssePost: vi.fn(),
upload: vi.fn(),
}))
@@ -21,7 +26,28 @@ vi.mock('./webapp-auth', () => ({
getWebAppAccessToken: vi.fn(() => ''),
}))
-const { fetchAccessToken } = await import('./share')
+const {
+ AppSourceType,
+ fetchAccessToken,
+ getUserCanAccess,
+ stopChatMessageResponding,
+ stopWorkflowMessage,
+ pinConversation,
+ unpinConversation,
+ delConversation,
+ renameConversation,
+ saveMessage,
+ removeMessage,
+ updateFeedback,
+ fetchMoreLikeThis,
+ fetchSavedMessage,
+ fetchSuggestedQuestions,
+ fetchConversations,
+ generationConversationName,
+ fetchAppMeta,
+ fetchAppParams,
+ fetchChatList,
+} = await import('./share')
describe('fetchAccessToken', () => {
const originalUrl = window.location.href
@@ -90,3 +116,319 @@ describe('fetchAccessToken', () => {
expect(getMock).toHaveBeenCalledTimes(2)
})
})
+
+describe('getUserCanAccess', () => {
+ beforeEach(() => {
+ request.mockReset()
+ getMock.mockReset()
+ })
+
+ it.each([true, false])('preserves the installed app permission result (%s)', async (allowed) => {
+ request.mockResolvedValueOnce(Response.json({ result: allowed }))
+ await expect(getUserCanAccess('app & special', true)).resolves.toEqual({ result: allowed })
+ const url = new URL(request.mock.calls[0]![0])
+ expect(url.pathname).toBe('/console/api/enterprise/webapp/permission')
+ expect(url.searchParams.get('appId')).toBe('app & special')
+ expect(request.mock.calls[0]?.[2]?.request?.method).toBe('GET')
+ expect(getMock).not.toHaveBeenCalled()
+ })
+
+ it('keeps public app access checks on the public transport', async () => {
+ getMock.mockResolvedValueOnce({ result: false })
+ await expect(getUserCanAccess('shared-app', false)).resolves.toEqual({ result: false })
+ expect(getMock).toHaveBeenCalledWith('/webapp/permission?appId=shared-app')
+ expect(request).not.toHaveBeenCalled()
+ })
+})
+
+describe('console commands shared with public apps', () => {
+ beforeEach(() => {
+ request
+ .mockReset()
+ .mockImplementation(async (_url, _init, options) =>
+ options?.request?.method === 'DELETE'
+ ? new Response(null, { status: 204 })
+ : Response.json({ result: 'success' }),
+ )
+ publicPost.mockReset().mockResolvedValue({ result: 'success' })
+ })
+
+ it.each([
+ { source: AppSourceType.installedApp, prefix: 'installed-apps' },
+ { source: AppSourceType.tryApp, prefix: 'trial-apps' },
+ ])('stops chat and workflow tasks through the $source contract', async ({ source, prefix }) => {
+ await stopChatMessageResponding('underlying-app', 'chat-task', source, 'selected-app')
+ await stopWorkflowMessage('underlying-app', 'workflow-task', source, 'selected-app')
+ expect(request.mock.calls.map(([url]) => new URL(url).pathname)).toEqual([
+ `/console/api/${prefix}/selected-app/chat-messages/chat-task/stop`,
+ `/console/api/${prefix}/selected-app/workflows/tasks/workflow-task/stop`,
+ ])
+ expect(request.mock.calls.map(([, , options]) => options?.request?.method)).toEqual([
+ 'POST',
+ 'POST',
+ ])
+ expect(publicPost).not.toHaveBeenCalled()
+ })
+
+ it('keeps public task cancellation on the public transport and ignores an absent workflow task', async () => {
+ await stopChatMessageResponding('app', 'chat-task', AppSourceType.webApp)
+ await stopWorkflowMessage('app', 'workflow-task', AppSourceType.webApp)
+ await stopWorkflowMessage('app', '', AppSourceType.installedApp, 'installed')
+ expect(publicPost.mock.calls).toEqual([
+ ['chat-messages/chat-task/stop'],
+ ['workflows/tasks/workflow-task/stop'],
+ ])
+ expect(request).not.toHaveBeenCalled()
+ })
+
+ it('uses the installed app identity for conversation commands and preserves the rename input', async () => {
+ await pinConversation(AppSourceType.installedApp, 'installed-1', 'conversation-1')
+ await unpinConversation(AppSourceType.installedApp, 'installed-1', 'conversation-1')
+ await renameConversation(AppSourceType.installedApp, 'installed-1', 'conversation-1', '')
+ await delConversation(AppSourceType.installedApp, 'installed-1', 'conversation-1')
+ expect(
+ request.mock.calls.map(([url, , options]) => [
+ new URL(url).pathname,
+ options?.request?.method,
+ ]),
+ ).toEqual([
+ ['/console/api/installed-apps/installed-1/conversations/conversation-1/pin', 'PATCH'],
+ ['/console/api/installed-apps/installed-1/conversations/conversation-1/unpin', 'PATCH'],
+ ['/console/api/installed-apps/installed-1/conversations/conversation-1/name', 'POST'],
+ ['/console/api/installed-apps/installed-1/conversations/conversation-1', 'DELETE'],
+ ])
+ expect(await request.mock.calls[2]?.[2]?.request?.json()).toEqual({ name: '' })
+ expect(publicPost).not.toHaveBeenCalled()
+ })
+
+ it('saves and removes messages in the installed app scope', async () => {
+ await saveMessage('message-1', AppSourceType.installedApp, 'installed-1')
+ await removeMessage('message-1', AppSourceType.installedApp, 'installed-1')
+ expect(
+ request.mock.calls.map(([url, , options]) => [
+ new URL(url).pathname,
+ options?.request?.method,
+ ]),
+ ).toEqual([
+ ['/console/api/installed-apps/installed-1/saved-messages', 'POST'],
+ ['/console/api/installed-apps/installed-1/saved-messages/message-1', 'DELETE'],
+ ])
+ expect(await request.mock.calls[0]?.[2]?.request?.json()).toEqual({ message_id: 'message-1' })
+ })
+
+ it('propagates rejected console requests without retrying through the public API', async () => {
+ const error = new Error('offline')
+ request.mockRejectedValueOnce(error)
+ await expect(
+ stopWorkflowMessage('app', 'task', AppSourceType.installedApp, 'installed'),
+ ).rejects.toThrow('offline')
+ expect(request).toHaveBeenCalledOnce()
+ expect(publicPost).not.toHaveBeenCalled()
+ })
+})
+
+describe('console message queries and feedback', () => {
+ beforeEach(() => {
+ request.mockReset()
+ getMock.mockReset()
+ publicPost.mockReset()
+ })
+
+ it.each([
+ { source: AppSourceType.installedApp, prefix: 'installed-apps' },
+ { source: AppSourceType.tryApp, prefix: 'trial-apps' },
+ ])('loads suggested questions for the selected $source message', async ({ source, prefix }) => {
+ request.mockResolvedValueOnce(Response.json({ data: ['What next?'] }))
+ await expect(fetchSuggestedQuestions('message-1', source, 'selected-app')).resolves.toEqual({
+ data: ['What next?'],
+ })
+ expect(new URL(request.mock.calls[0]![0]).pathname).toBe(
+ `/console/api/${prefix}/selected-app/messages/message-1/suggested-questions`,
+ )
+ expect(getMock).not.toHaveBeenCalled()
+ })
+
+ it('keeps saved-message errors silent and requests more-like-this in blocking mode', async () => {
+ request.mockResolvedValueOnce(Response.json({ data: [] }))
+ await expect(fetchSavedMessage(AppSourceType.installedApp, 'installed-1')).resolves.toEqual({
+ data: [],
+ })
+ expect(new URL(request.mock.calls[0]![0]).pathname).toBe(
+ '/console/api/installed-apps/installed-1/saved-messages',
+ )
+ expect(request.mock.calls[0]?.[2]?.silent).toBe(true)
+ request.mockResolvedValueOnce(Response.json({ answer: 'Another answer' }))
+ await expect(
+ fetchMoreLikeThis('message-1', AppSourceType.installedApp, 'installed-1'),
+ ).resolves.toEqual({ answer: 'Another answer' })
+ const url = new URL(request.mock.calls[1]![0])
+ expect(url.pathname).toBe(
+ '/console/api/installed-apps/installed-1/messages/message-1/more-like-this',
+ )
+ expect(url.searchParams.get('response_mode')).toBe('blocking')
+ })
+
+ it('preserves cleared feedback and intentional empty comments', async () => {
+ request.mockResolvedValueOnce(Response.json({ result: 'success' }))
+ await updateFeedback(
+ { messageId: 'message-1', body: { rating: null, content: '' } },
+ AppSourceType.installedApp,
+ 'installed-1',
+ )
+ expect(new URL(request.mock.calls[0]![0]).pathname).toBe(
+ '/console/api/installed-apps/installed-1/messages/message-1/feedbacks',
+ )
+ expect(await request.mock.calls[0]?.[2]?.request?.json()).toEqual({ rating: null, content: '' })
+ expect(publicPost).not.toHaveBeenCalled()
+ })
+
+ it('keeps suggested questions and feedback for public apps on the public transport', async () => {
+ getMock.mockResolvedValueOnce({ data: [] })
+ await fetchSuggestedQuestions('message-1', AppSourceType.webApp)
+ await updateFeedback({ messageId: 'message-1', body: { rating: 'like' } }, AppSourceType.webApp)
+ expect(getMock).toHaveBeenCalledWith('/messages/message-1/suggested-questions')
+ expect(publicPost).toHaveBeenCalledWith('/messages/message-1/feedbacks', {
+ body: { rating: 'like' },
+ })
+ expect(request).not.toHaveBeenCalled()
+ })
+})
+
+it('adapts nullable installed-app conversation introductions and preserves pagination filters', async () => {
+ request.mockReset()
+ const conversation = {
+ id: 'conversation-1',
+ name: '',
+ inputs: {},
+ status: 'normal',
+ introduction: null,
+ }
+ request.mockResolvedValueOnce(Response.json({ data: [conversation], has_more: false, limit: 10 }))
+ const result = await fetchConversations(
+ AppSourceType.installedApp,
+ 'installed-1',
+ 'cursor-1',
+ false,
+ 10,
+ )
+ expect(result).toEqual({
+ data: [{ id: 'conversation-1', name: '', inputs: {}, introduction: '' }],
+ has_more: false,
+ limit: 10,
+ })
+ const url = new URL(request.mock.calls[0]![0])
+ expect(url.pathname).toBe('/console/api/installed-apps/installed-1/conversations')
+ expect(Object.fromEntries(url.searchParams)).toEqual({
+ last_id: 'cursor-1',
+ pinned: 'false',
+ limit: '10',
+ })
+ request.mockResolvedValueOnce(Response.json(conversation))
+ await expect(
+ generationConversationName(AppSourceType.installedApp, 'installed-1', 'conversation-1'),
+ ).resolves.toEqual(result.data[0])
+ expect(await request.mock.calls[1]?.[2]?.request?.json()).toEqual({ auto_generate: true })
+})
+
+it('loads installed-app metadata and initial chat history without sending the old ignored cursor', async () => {
+ request.mockReset().mockResolvedValueOnce(Response.json({}))
+ await expect(fetchAppMeta(AppSourceType.installedApp, 'installed-1')).resolves.toEqual({
+ tool_icons: {},
+ })
+ expect(new URL(request.mock.calls[0]![0]).pathname).toBe(
+ '/console/api/installed-apps/installed-1/meta',
+ )
+ request.mockResolvedValueOnce(Response.json({ data: [], has_more: false, limit: 20 }))
+ await expect(
+ fetchChatList('conversation-1', AppSourceType.installedApp, 'installed-1'),
+ ).resolves.toEqual({ data: [], has_more: false, limit: 20 })
+ const url = new URL(request.mock.calls[1]![0])
+ expect(url.pathname).toBe('/console/api/installed-apps/installed-1/messages')
+ expect(Object.fromEntries(url.searchParams)).toEqual({
+ conversation_id: 'conversation-1',
+ limit: '20',
+ })
+})
+
+it.each([
+ { source: AppSourceType.installedApp, prefix: 'installed-apps' },
+ { source: AppSourceType.tryApp, prefix: 'trial-apps' },
+])('loads $source parameters through the shared typed UI adapter', async ({ source, prefix }) => {
+ const numberDefaults = [0, 42, -7.123456, '12.5']
+ const parameters: AppParameters = {
+ opening_statement: null,
+ suggested_questions: ['Next question'],
+ suggested_questions_after_answer: { enabled: false },
+ annotation_reply: {},
+ file_upload: { enabled: false },
+ more_like_this: {},
+ retriever_resource: {},
+ sensitive_word_avoidance: {},
+ speech_to_text: { enabled: false },
+ text_to_speech: {},
+ system_parameters: {
+ audio_file_size_limit: 1,
+ file_size_limit: 2,
+ image_file_size_limit: 3,
+ video_file_size_limit: 4,
+ workflow_file_upload_limit: 5,
+ },
+ user_input_form: [
+ {
+ 'text-input': {
+ variable: 'topic',
+ label: 'Topic',
+ default: '',
+ required: false,
+ max_length: 0,
+ },
+ },
+ {
+ checkbox: {
+ variable: 'include_details',
+ label: 'Details',
+ default: false,
+ required: false,
+ },
+ },
+ ...numberDefaults.map((defaultValue, index) => ({
+ number: {
+ variable: `count_${index}`,
+ label: `Count ${index}`,
+ default: defaultValue,
+ required: false,
+ hide: true,
+ },
+ })),
+ ],
+ }
+ request.mockReset().mockResolvedValueOnce(Response.json(parameters))
+ const result = await fetchAppParams(source, 'selected-app')
+ expect(new URL(request.mock.calls[0]![0]).pathname).toBe(
+ `/console/api/${prefix}/selected-app/parameters`,
+ )
+ expect(result).toMatchObject({
+ opening_statement: '',
+ suggested_questions: ['Next question'],
+ suggested_questions_after_answer: { enabled: false },
+ file_upload: { enabled: false },
+ system_parameters: parameters.system_parameters,
+ user_input_form: [
+ { 'text-input': { variable: 'topic', default: '', required: false, max_length: 0 } },
+ { checkbox: { variable: 'include_details', default: false, required: false } },
+ ...numberDefaults.map((defaultValue, index) => ({
+ number: {
+ variable: `count_${index}`,
+ default: defaultValue,
+ required: false,
+ hide: true,
+ },
+ })),
+ ],
+ })
+ expect(
+ userInputsFormToPromptVariables(result.user_input_form)
+ .filter((variable) => variable.type === 'number')
+ .map((variable) => variable.default),
+ ).toEqual(numberDefaults)
+})
diff --git a/web/service/share.ts b/web/service/share.ts
index 37f1bba0c03..978a8a9d9d5 100644
--- a/web/service/share.ts
+++ b/web/service/share.ts
@@ -1,6 +1,9 @@
+import type {
+ MessageFeedbackPayload,
+ SimpleConversation,
+} from '@dify/contracts/api/console/installed-apps/types.gen'
import type { IOnCompleted, IOnData, IOnError, IOnMessageReplace, IOtherOptions } from './base'
import type { FormData as HumanInputFormData } from '@/app/(humanInputLayout)/form/[token]/form'
-import type { FeedbackType } from '@/app/components/base/chat/chat/type'
import type { ChatConfig } from '@/app/components/base/chat/types'
import type { AccessMode } from '@/models/access-control'
import type { AppConversationData, AppData, AppMeta, ConversationItem } from '@/models/share'
@@ -12,6 +15,7 @@ import {
isAppAccessScopeCurrent,
} from '@/features/app-access-error/state'
import { consoleClient } from '@/service/console'
+import { selectAppParameters } from '@/service/console/app-parameters-select'
import {
del as consoleDel,
get as consoleGet,
@@ -72,10 +76,15 @@ export const stopChatMessageResponding = async (
appSourceType: AppSourceType,
installedAppId = '',
) => {
- return getAction(
- 'post',
- appSourceType,
- )(getUrl(`chat-messages/${taskId}/stop`, appSourceType, installedAppId))
+ if (appSourceType === AppSourceType.installedApp)
+ return consoleClient.installedApps.byInstalledAppId.chatMessages.byTaskId.stop.post({
+ params: { installed_app_id: installedAppId, task_id: taskId },
+ })
+ if (appSourceType === AppSourceType.tryApp)
+ return consoleClient.trialApps.byAppId.chatMessages.byTaskId.stop.post({
+ params: { app_id: installedAppId, task_id: taskId },
+ })
+ return post(getUrl(`chat-messages/${taskId}/stop`, appSourceType, installedAppId))
}
export const sendCompletionMessage = async (
@@ -143,16 +152,28 @@ export const stopWorkflowMessage = async (
installedAppId = '',
) => {
if (!taskId) return
- return getAction(
- 'post',
- appSourceType,
- )(getUrl(`workflows/tasks/${taskId}/stop`, appSourceType, installedAppId))
+ if (appSourceType === AppSourceType.installedApp)
+ return consoleClient.installedApps.byInstalledAppId.workflows.tasks.byTaskId.stop.post({
+ params: { installed_app_id: installedAppId, task_id: taskId },
+ })
+ if (appSourceType === AppSourceType.tryApp)
+ return consoleClient.trialApps.byAppId.workflows.tasks.byTaskId.stop.post({
+ params: { app_id: installedAppId, task_id: taskId },
+ })
+ return post(getUrl(`workflows/tasks/${taskId}/stop`, appSourceType, installedAppId))
}
export const fetchAppInfo = async () => {
return get('/site') as Promise<AppData>
}
+const selectConversation = (conversation: SimpleConversation): ConversationItem => ({
+ id: conversation.id,
+ name: conversation.name,
+ inputs: conversation.inputs,
+ introduction: conversation.introduction ?? '',
+})
+
export const fetchConversations = async (
appSourceType: AppSourceType,
installedAppId = '',
@@ -160,6 +181,17 @@ export const fetchConversations = async (
pinned?: boolean,
limit?: number,
) => {
+ if (appSourceType === AppSourceType.installedApp) {
+ const response = await consoleClient.installedApps.byInstalledAppId.conversations.get({
+ params: { installed_app_id: installedAppId },
+ query: {
+ limit: limit || 20,
+ ...(last_id ? { last_id } : {}),
+ ...(pinned !== undefined ? { pinned } : {}),
+ },
+ })
+ return { ...response, data: response.data.map(selectConversation) }
+ }
return getAction('get', appSourceType)(getUrl('conversations', appSourceType, installedAppId), {
params: {
limit: limit || 20,
@@ -174,6 +206,10 @@ export const pinConversation = async (
installedAppId = '',
id: string,
) => {
+ if (appSourceType === AppSourceType.installedApp)
+ return consoleClient.installedApps.byInstalledAppId.conversations.byCId.pin.patch({
+ params: { installed_app_id: installedAppId, c_id: id },
+ })
return getAction(
'patch',
appSourceType,
@@ -185,6 +221,10 @@ export const unpinConversation = async (
installedAppId = '',
id: string,
) => {
+ if (appSourceType === AppSourceType.installedApp)
+ return consoleClient.installedApps.byInstalledAppId.conversations.byCId.unpin.patch({
+ params: { installed_app_id: installedAppId, c_id: id },
+ })
return getAction(
'patch',
appSourceType,
@@ -196,6 +236,10 @@ export const delConversation = async (
installedAppId = '',
id: string,
) => {
+ if (appSourceType === AppSourceType.installedApp)
+ return consoleClient.installedApps.byInstalledAppId.conversations.byCId.delete({
+ params: { installed_app_id: installedAppId, c_id: id },
+ })
return getAction(
'del',
appSourceType,
@@ -208,6 +252,11 @@ export const renameConversation = async (
id: string,
name: string,
) => {
+ if (appSourceType === AppSourceType.installedApp)
+ return consoleClient.installedApps.byInstalledAppId.conversations.byCId.name.post({
+ params: { installed_app_id: installedAppId, c_id: id },
+ body: { name },
+ })
return getAction('post', appSourceType)(
getUrl(`conversations/${id}/name`, appSourceType, installedAppId),
{ body: { name } },
@@ -219,6 +268,14 @@ export const generationConversationName = async (
installedAppId = '',
id: string,
) => {
+ if (appSourceType === AppSourceType.installedApp) {
+ const response =
+ await consoleClient.installedApps.byInstalledAppId.conversations.byCId.name.post({
+ params: { installed_app_id: installedAppId, c_id: id },
+ body: { auto_generate: true },
+ })
+ return selectConversation(response)
+ }
return getAction('post', appSourceType)(
getUrl(`conversations/${id}/name`, appSourceType, installedAppId),
{ body: { auto_generate: true } },
@@ -230,6 +287,11 @@ export const fetchChatList = async (
appSourceType: AppSourceType,
installedAppId = '',
) => {
+ if (appSourceType === AppSourceType.installedApp)
+ return consoleClient.installedApps.byInstalledAppId.messages.get({
+ params: { installed_app_id: installedAppId },
+ query: { conversation_id: conversationId, limit: 20 },
+ })
return getAction('get', appSourceType)(getUrl('messages', appSourceType, installedAppId), {
params: { conversation_id: conversationId, limit: 20, last_id: '' },
}) as any
@@ -242,10 +304,16 @@ export const fetchChatList = async (
// init value. wait for server update
export const fetchAppParams = async (appSourceType: AppSourceType, appId = '') => {
- return getAction(
- 'get',
- appSourceType,
- )(getUrl('parameters', appSourceType, appId)) as Promise<ChatConfig>
+ if (appSourceType !== AppSourceType.webApp) {
+ const parameters =
+ appSourceType === AppSourceType.installedApp
+ ? await consoleClient.installedApps.byInstalledAppId.parameters.get({
+ params: { installed_app_id: appId },
+ })
+ : await consoleClient.trialApps.byAppId.parameters.get({ params: { app_id: appId } })
+ return selectAppParameters(parameters)
+ }
+ return get<ChatConfig>('parameters')
}
export const fetchWebSAMLSSOUrl = async (appCode: string, redirectUrl: string) => {
@@ -321,6 +389,12 @@ export const fetchMembersOAuth2SSOUrl = async (appCode: string, redirectUrl: str
}
export const fetchAppMeta = async (appSourceType: AppSourceType, installedAppId = '') => {
+ if (appSourceType === AppSourceType.installedApp) {
+ const response = await consoleClient.installedApps.byInstalledAppId.meta.get({
+ params: { installed_app_id: installedAppId },
+ })
+ return { tool_icons: response.tool_icons ?? {} }
+ }
return getAction(
'get',
appSourceType,
@@ -328,11 +402,19 @@ export const fetchAppMeta = async (appSourceType: AppSourceType, installedAppId
}
export const updateFeedback = async (
- { url, body }: { url: string; body: FeedbackType },
+ { messageId, body }: { messageId: string; body: MessageFeedbackPayload },
appSourceType: AppSourceType,
installedAppId = '',
) => {
- return getAction('post', appSourceType)(getUrl(url, appSourceType, installedAppId), { body })
+ if (appSourceType === AppSourceType.installedApp)
+ return consoleClient.installedApps.byInstalledAppId.messages.byMessageId.feedbacks.post({
+ params: { installed_app_id: installedAppId, message_id: messageId },
+ body,
+ })
+ return getAction('post', appSourceType)(
+ getUrl(`/messages/${messageId}/feedbacks`, appSourceType, installedAppId),
+ { body },
+ )
}
export const fetchMoreLikeThis = async (
@@ -340,6 +422,11 @@ export const fetchMoreLikeThis = async (
appSourceType: AppSourceType,
installedAppId = '',
) => {
+ if (appSourceType === AppSourceType.installedApp)
+ return consoleClient.installedApps.byInstalledAppId.messages.byMessageId.moreLikeThis.get({
+ params: { installed_app_id: installedAppId, message_id: messageId },
+ query: { response_mode: 'blocking' },
+ })
return getAction('get', appSourceType)(
getUrl(`/messages/${messageId}/more-like-this`, appSourceType, installedAppId),
{
@@ -355,6 +442,11 @@ export const saveMessage = (
appSourceType: AppSourceType,
installedAppId = '',
) => {
+ if (appSourceType === AppSourceType.installedApp)
+ return consoleClient.installedApps.byInstalledAppId.savedMessages.post({
+ params: { installed_app_id: installedAppId },
+ body: { message_id: messageId },
+ })
return getAction('post', appSourceType)(
getUrl('/saved-messages', appSourceType, installedAppId),
{ body: { message_id: messageId } },
@@ -362,6 +454,13 @@ export const saveMessage = (
}
export const fetchSavedMessage = async (appSourceType: AppSourceType, installedAppId = '') => {
+ if (appSourceType === AppSourceType.installedApp)
+ return consoleClient.installedApps.byInstalledAppId.savedMessages.get(
+ {
+ params: { installed_app_id: installedAppId },
+ },
+ { context: { silent: true } },
+ )
return getAction('get', appSourceType)(
getUrl('/saved-messages', appSourceType, installedAppId),
{},
@@ -376,21 +475,32 @@ export const removeMessage = (
appSourceType: AppSourceType,
installedAppId = '',
) => {
+ if (appSourceType === AppSourceType.installedApp)
+ return consoleClient.installedApps.byInstalledAppId.savedMessages.byMessageId.delete({
+ params: { installed_app_id: installedAppId, message_id: messageId },
+ })
return getAction(
'del',
appSourceType,
)(getUrl(`/saved-messages/${messageId}`, appSourceType, installedAppId))
}
-export const fetchSuggestedQuestions = (
+export const fetchSuggestedQuestions = async (
messageId: string,
appSourceType: AppSourceType,
installedAppId = '',
) => {
- return getAction(
- 'get',
- appSourceType,
- )(getUrl(`/messages/${messageId}/suggested-questions`, appSourceType, installedAppId))
+ if (appSourceType === AppSourceType.installedApp)
+ return consoleClient.installedApps.byInstalledAppId.messages.byMessageId.suggestedQuestions.get(
+ {
+ params: { installed_app_id: installedAppId, message_id: messageId },
+ },
+ )
+ if (appSourceType === AppSourceType.tryApp)
+ return consoleClient.trialApps.byAppId.messages.byMessageId.suggestedQuestions.get({
+ params: { app_id: installedAppId, message_id: messageId },
+ })
+ return get(getUrl(`/messages/${messageId}/suggested-questions`, appSourceType, installedAppId))
}
export const audioToText = (
@@ -471,9 +581,11 @@ export const fetchAccessToken = (params: { userId?: string; appCode: string }) =
return request
}
-export const getUserCanAccess = (appId: string, isInstalledApp: boolean) => {
+export const getUserCanAccess = async (appId: string, isInstalledApp: boolean) => {
if (isInstalledApp)
- return consoleGet<{ result: boolean }>(`/enterprise/webapp/permission?appId=${appId}`)
+ return consoleClient.enterprise.webAppAuth.isUserAllowedToAccessWebApp({
+ query: { appId },
+ })
return get<{ result: boolean }>(`/webapp/permission?appId=${appId}`)
}
diff --git a/web/service/try-app.ts b/web/service/try-app.ts
index 91aca72d62d..a9a37672e93 100644
--- a/web/service/try-app.ts
+++ b/web/service/try-app.ts
@@ -1,289 +1,5 @@
-import type { ChatConfig } from '@/app/components/base/chat/types'
-import { SupportUploadFileTypes } from '@/app/components/workflow/types'
-import { ANNOTATION_DEFAULT, DEFAULT_AGENT_SETTING } from '@/config'
-import { PromptMode } from '@/models/debug'
import { consoleClient } from '@/service/console'
-import { Resolution, RETRIEVE_TYPE, TransferMethod, TtsAutoPlay } from '@/types/app'
-
-type TryAppParameters = import('@dify/contracts/api/console/trial-apps/types.gen').Parameters
-
-const transferMethodValues = new Set<string>(Object.values(TransferMethod))
-const supportUploadFileTypeValues = new Set<string>(Object.values(SupportUploadFileTypes))
-
-const isRecord = (value: unknown): value is Record<string, unknown> => {
- return typeof value === 'object' && value !== null && !Array.isArray(value)
-}
-
-const getString = (value: unknown, fallback = '') => {
- return typeof value === 'string' ? value : fallback
-}
-
-const getOptionalString = (value: unknown) => {
- return typeof value === 'string' ? value : undefined
-}
-
-const getBoolean = (value: unknown, fallback = false) => {
- return typeof value === 'boolean' ? value : fallback
-}
-
-const getNumber = (value: unknown, fallback: number) => {
- return typeof value === 'number' ? value : fallback
-}
-
-const getStringArray = (value: unknown) => {
- return Array.isArray(value)
- ? value.filter((item): item is string => typeof item === 'string')
- : []
-}
-
-const getStringRecord = (value: unknown) => {
- if (!isRecord(value)) return undefined
-
- const record: Record<string, string> = {}
- Object.entries(value).forEach(([key, item]) => {
- if (typeof item === 'string') record[key] = item
- })
- return record
-}
-
-const normalizeEnabledConfig = (value: Record<string, unknown>, fallback = false) => {
- return {
- ...value,
- enabled: getBoolean(value.enabled, fallback),
- }
-}
-
-const normalizeTextToSpeechConfig = (
- value: Record<string, unknown>,
-): ChatConfig['text_to_speech'] => {
- const autoPlay = getString(value.autoPlay)
- const config = { ...value }
- delete config.autoPlay
- return {
- ...normalizeEnabledConfig(config),
- voice: getOptionalString(value.voice),
- language: getOptionalString(value.language),
- ...(autoPlay === TtsAutoPlay.enabled || autoPlay === TtsAutoPlay.disabled ? { autoPlay } : {}),
- }
-}
-
-const normalizeAnnotationReplyConfig = (
- value: Record<string, unknown>,
-): ChatConfig['annotation_reply'] => {
- const embeddingModel = isRecord(value.embedding_model) ? value.embedding_model : {}
- return {
- id: getString(value.id),
- enabled: getBoolean(value.enabled),
- score_threshold: getNumber(value.score_threshold, ANNOTATION_DEFAULT.score_threshold),
- embedding_model: {
- embedding_provider_name: getString(embeddingModel.embedding_provider_name),
- embedding_model_name: getString(embeddingModel.embedding_model_name),
- },
- }
-}
-
-const getTransferMethods = (value: unknown, fallback: TransferMethod[]) => {
- if (!Array.isArray(value)) return fallback
-
- const methods = value.filter((item): item is TransferMethod => {
- return typeof item === 'string' && transferMethodValues.has(item)
- })
- return methods.length > 0 ? methods : fallback
-}
-
-const getSupportUploadFileTypes = (value: unknown): SupportUploadFileTypes[] => {
- if (!Array.isArray(value)) return []
-
- return value.filter((item): item is SupportUploadFileTypes => {
- return typeof item === 'string' && supportUploadFileTypeValues.has(item)
- })
-}
-
-const normalizeVisionSettings = (
- value: unknown,
-): NonNullable<ChatConfig['file_upload']>['image'] => {
- const image = isRecord(value) ? value : {}
- return {
- enabled: getBoolean(image.enabled),
- number_limits: getNumber(image.number_limits, 3),
- detail: getString(image.detail) === Resolution.low ? Resolution.low : Resolution.high,
- transfer_methods: getTransferMethods(image.transfer_methods, [
- TransferMethod.local_file,
- TransferMethod.remote_url,
- ]),
- }
-}
-
-const normalizeFileUploadConfig = (value: Record<string, unknown>): ChatConfig['file_upload'] => {
- const allowedUploadMethods = getTransferMethods(value.allowed_upload_methods, [
- TransferMethod.local_file,
- TransferMethod.remote_url,
- ])
- const allowedFileUploadMethods = getTransferMethods(
- value.allowed_file_upload_methods,
- allowedUploadMethods,
- )
-
- return {
- image: normalizeVisionSettings(value.image),
- allowed_file_upload_methods: allowedFileUploadMethods,
- allowed_upload_methods: allowedUploadMethods,
- allowed_file_types: getSupportUploadFileTypes(value.allowed_file_types),
- allowed_file_extensions: getStringArray(value.allowed_file_extensions),
- max_length: getNumber(value.max_length, 1),
- number_limits: getNumber(value.number_limits, 1),
- }
-}
-
-const defaultDatasetConfigs: ChatConfig['dataset_configs'] = {
- retrieval_model: RETRIEVE_TYPE.oneWay,
- reranking_model: {
- reranking_provider_name: '',
- reranking_model_name: '',
- },
- top_k: 4,
- score_threshold_enabled: false,
- score_threshold: null,
- datasets: {
- datasets: [],
- },
-}
-
-const normalizeBaseInputForm = (value: Record<string, unknown>) => {
- return {
- default: getString(value.default),
- label: getString(value.label),
- variable: getString(value.variable),
- required: getBoolean(value.required, true),
- hide: getBoolean(value.hide),
- }
-}
-
-const normalizeTextInputForm = (value: Record<string, unknown>) => {
- return {
- ...normalizeBaseInputForm(value),
- max_length: getNumber(value.max_length, 0),
- }
-}
-
-const normalizeFileInputForm = (value: Record<string, unknown>) => {
- return {
- ...normalizeBaseInputForm(value),
- max_length: getNumber(value.max_length, 1),
- allowed_file_upload_methods: getTransferMethods(value.allowed_file_upload_methods, [
- TransferMethod.local_file,
- TransferMethod.remote_url,
- ]),
- allowed_upload_methods: getTransferMethods(value.allowed_upload_methods, [
- TransferMethod.local_file,
- TransferMethod.remote_url,
- ]),
- allowed_file_types: getSupportUploadFileTypes(value.allowed_file_types),
- allowed_file_extensions: getStringArray(value.allowed_file_extensions),
- }
-}
-
-const normalizeUserInputFormItem = (
- item: Record<string, unknown>,
-): ChatConfig['user_input_form'][number] | null => {
- if (isRecord(item['text-input']))
- return { 'text-input': normalizeTextInputForm(item['text-input']) }
-
- if (isRecord(item.paragraph)) return { paragraph: normalizeTextInputForm(item.paragraph) }
-
- if (isRecord(item.select)) {
- return {
- select: {
- ...normalizeBaseInputForm(item.select),
- options: getStringArray(item.select.options),
- },
- }
- }
-
- if (isRecord(item.number)) {
- return {
- number: {
- ...normalizeBaseInputForm(item.number),
- max_length: getNumber(item.number.max_length, 0),
- },
- }
- }
-
- if (isRecord(item.checkbox)) {
- return {
- checkbox: {
- ...normalizeBaseInputForm(item.checkbox),
- default: getBoolean(item.checkbox.default),
- },
- }
- }
-
- if (isRecord(item.file)) return { file: normalizeFileInputForm(item.file) }
-
- if (isRecord(item['file-list'])) return { 'file-list': normalizeFileInputForm(item['file-list']) }
-
- if (isRecord(item.external_data_tool)) {
- return {
- external_data_tool: {
- label: getString(item.external_data_tool.label),
- variable: getString(item.external_data_tool.variable),
- required: getBoolean(item.external_data_tool.required, true),
- hide: getBoolean(item.external_data_tool.hide),
- type: getOptionalString(item.external_data_tool.type),
- enabled: getBoolean(item.external_data_tool.enabled),
- icon: getOptionalString(item.external_data_tool.icon),
- icon_background: getOptionalString(item.external_data_tool.icon_background),
- config: getStringRecord(item.external_data_tool.config),
- },
- }
- }
-
- if (isRecord(item.json_object)) {
- const jsonSchema = item.json_object.json_schema
- return {
- json_object: {
- ...normalizeBaseInputForm(item.json_object),
- json_schema:
- typeof jsonSchema === 'string' || isRecord(jsonSchema) ? jsonSchema : undefined,
- },
- }
- }
-
- return null
-}
-
-const normalizeUserInputForm = (
- items: TryAppParameters['user_input_form'],
-): ChatConfig['user_input_form'] => {
- return items.reduce<ChatConfig['user_input_form']>((result, item) => {
- const normalized = normalizeUserInputFormItem(item)
- if (normalized) result.push(normalized)
- return result
- }, [])
-}
-
-const normalizeTryAppParams = (params: TryAppParameters): ChatConfig => {
- return {
- opening_statement: params.opening_statement ?? '',
- suggested_questions: params.suggested_questions,
- suggested_questions_after_answer: normalizeEnabledConfig(
- params.suggested_questions_after_answer,
- ),
- speech_to_text: normalizeEnabledConfig(params.speech_to_text),
- text_to_speech: normalizeTextToSpeechConfig(params.text_to_speech),
- retriever_resource: normalizeEnabledConfig(params.retriever_resource),
- annotation_reply: normalizeAnnotationReplyConfig(params.annotation_reply),
- more_like_this: normalizeEnabledConfig(params.more_like_this),
- sensitive_word_avoidance: normalizeEnabledConfig(params.sensitive_word_avoidance),
- file_upload: normalizeFileUploadConfig(params.file_upload),
- user_input_form: normalizeUserInputForm(params.user_input_form),
- system_parameters: params.system_parameters,
- pre_prompt: '',
- prompt_type: PromptMode.simple,
- agent_mode: DEFAULT_AGENT_SETTING,
- dataset_configs: defaultDatasetConfigs,
- }
-}
+import { selectAppParameters } from '@/service/console/app-parameters-select'
export const fetchTryAppDatasets = (appId: string, ids: string[]) => {
return consoleClient.trialApps.byAppId.datasets.get({
@@ -295,5 +11,5 @@ export const fetchTryAppDatasets = (appId: string, ids: string[]) => {
export const fetchTryAppParams = (appId: string) => {
return consoleClient.trialApps.byAppId.parameters
.get({ params: { app_id: appId } })
- .then(normalizeTryAppParams)
+ .then(selectAppParameters)
}
diff --git a/web/service/use-plugins-auth.ts b/web/service/use-plugins-auth.ts
index 6bc2180f2a2..c1169aa914b 100644
--- a/web/service/use-plugins-auth.ts
+++ b/web/service/use-plugins-auth.ts
@@ -1,8 +1,21 @@
-import type { FormSchema } from '@/app/components/base/form/types'
-import type { Credential, CredentialTypeEnum } from '@/app/components/plugins/plugin-auth/types'
-import type { CredentialPermission } from '@/models/permission'
-import { useMutation, useQuery } from '@tanstack/react-query'
-import { del, get, post } from './base'
+import type { GetOauthPluginByProviderToolAuthorizationUrlData } from '@dify/contracts/api/console/oauth/types.gen'
+import type {
+ BuiltinToolAddPayload,
+ BuiltinToolCredentialDeletePayload,
+ BuiltinToolUpdatePayload,
+ ToolOAuthCustomClientPayload,
+} from '@dify/contracts/api/console/workspaces/types.gen'
+import type {
+ Credential,
+ CredentialTypeEnum,
+ PluginPayload,
+} from '@/app/components/plugins/plugin-auth/types'
+import { skipToken, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
+import { useCallback } from 'react'
+import { AuthCategory } from '@/app/components/plugins/plugin-auth/types'
+import { get } from './base'
+import { consoleQuery } from './console'
+import { selectCredentialFormSchema } from './console/plugin-auth-select'
import { useInvalid } from './use-base'
const NAME_SPACE = 'plugins-auth'
@@ -26,107 +39,222 @@ export const useInvalidPluginCredentialInfo = (url: string) => {
return useInvalid([NAME_SPACE, 'credential-info', url])
}
-export const useSetPluginDefaultCredential = (url: string) => {
- return useMutation({
- mutationFn: (id: string) => {
- return post(url, { body: { id } })
+export const useSetPluginDefaultCredential = ({ category, provider }: PluginPayload) => {
+ const { mutateAsync: setToolDefault } = useMutation(
+ consoleQuery.workspaces.current.toolProvider.builtin.byProvider.defaultCredential.post.mutationOptions(),
+ )
+ const { mutateAsync: setDatasourceDefault } = useMutation(
+ consoleQuery.auth.plugin.datasource.byProviderId.default.post.mutationOptions(),
+ )
+ const mutateAsync = useCallback(
+ async (id: string) => {
+ if (!provider) throw new Error('Credential provider is required')
+ switch (category) {
+ case AuthCategory.tool:
+ return setToolDefault({ params: { provider }, body: { id } })
+ case AuthCategory.datasource:
+ return setDatasourceDefault({ params: { provider_id: provider }, body: { id } })
+ default:
+ throw new Error(`Unsupported credential category: ${category}`)
+ }
},
- })
+ [category, provider, setToolDefault, setDatasourceDefault],
+ )
+ return { mutateAsync }
}
-export const useAddPluginCredential = (url: string) => {
- return useMutation({
- mutationFn: (params: {
- credentials: Record<string, unknown>
- type: CredentialTypeEnum
- name?: string
- visibility?: string
- partial_member_list?: Array<{ user_id: string }>
- }) => {
- return post(url, { body: params })
+export const useAddPluginCredential = ({ category, provider }: PluginPayload) => {
+ const { mutateAsync: addToolCredential } = useMutation(
+ consoleQuery.workspaces.current.toolProvider.builtin.byProvider.add.post.mutationOptions(),
+ )
+ const { mutateAsync: addDatasourceCredential } = useMutation(
+ consoleQuery.auth.plugin.datasource.byProviderId.post.mutationOptions(),
+ )
+ const mutateAsync = useCallback(
+ async (body: BuiltinToolAddPayload) => {
+ if (!provider) throw new Error('Credential provider is required')
+ switch (category) {
+ case AuthCategory.tool:
+ return addToolCredential({ params: { provider }, body })
+ case AuthCategory.datasource:
+ return addDatasourceCredential({
+ params: { provider_id: provider },
+ body: { credentials: body.credentials, name: body.name },
+ })
+ default:
+ throw new Error(`Unsupported credential category: ${category}`)
+ }
},
- })
+ [category, provider, addToolCredential, addDatasourceCredential],
+ )
+ return { mutateAsync }
}
-export const useUpdatePluginCredential = (url: string) => {
- return useMutation({
- mutationFn: (params: {
- credential_id: string
- credentials?: Record<string, unknown>
- name?: string
- visibility?: string
- partial_member_list?: Array<{ user_id: string }>
- }) => {
- return post(url, { body: params })
+export const useUpdatePluginCredential = ({ category, provider }: PluginPayload) => {
+ const { mutateAsync: updateToolCredential } = useMutation(
+ consoleQuery.workspaces.current.toolProvider.builtin.byProvider.update.post.mutationOptions(),
+ )
+ const { mutateAsync: updateDatasourceCredential } = useMutation(
+ consoleQuery.auth.plugin.datasource.byProviderId.update.post.mutationOptions(),
+ )
+ const mutateAsync = useCallback(
+ async (body: BuiltinToolUpdatePayload) => {
+ if (!provider) throw new Error('Credential provider is required')
+ switch (category) {
+ case AuthCategory.tool:
+ return updateToolCredential({ params: { provider }, body })
+ case AuthCategory.datasource:
+ return updateDatasourceCredential({ params: { provider_id: provider }, body })
+ default:
+ throw new Error(`Unsupported credential category: ${category}`)
+ }
},
- })
+ [category, provider, updateToolCredential, updateDatasourceCredential],
+ )
+ return { mutateAsync }
}
-export const useDeletePluginCredential = (url: string) => {
- return useMutation({
- mutationFn: (params: { credential_id: string }) => {
- return post(url, { body: params })
+export const useDeletePluginCredential = ({ category, provider }: PluginPayload) => {
+ const { mutateAsync: deleteToolCredential } = useMutation(
+ consoleQuery.workspaces.current.toolProvider.builtin.byProvider.delete.post.mutationOptions(),
+ )
+ const { mutateAsync: deleteDatasourceCredential } = useMutation(
+ consoleQuery.auth.plugin.datasource.byProviderId.delete.post.mutationOptions(),
+ )
+ const mutateAsync = useCallback(
+ async (body: BuiltinToolCredentialDeletePayload) => {
+ if (!provider) throw new Error('Credential provider is required')
+ switch (category) {
+ case AuthCategory.tool:
+ return deleteToolCredential({ params: { provider }, body })
+ case AuthCategory.datasource:
+ return deleteDatasourceCredential({ params: { provider_id: provider }, body })
+ default:
+ throw new Error(`Unsupported credential category: ${category}`)
+ }
},
- })
+ [category, provider, deleteToolCredential, deleteDatasourceCredential],
+ )
+ return { mutateAsync }
}
-export const useGetPluginCredentialSchema = (url: string) => {
- return useQuery({
- enabled: !!url,
- queryKey: [NAME_SPACE, 'credential-schema', url],
- queryFn: () => get<FormSchema[]>(url),
- })
+export const useGetPluginCredentialSchema = (
+ { category, provider }: PluginPayload,
+ credentialType: CredentialTypeEnum,
+) => {
+ return useQuery(
+ consoleQuery.workspaces.current.toolProvider.builtin.byProvider.credential.schema.byCredentialType.get.queryOptions(
+ {
+ input:
+ category === AuthCategory.tool && provider
+ ? { params: { provider, credential_type: credentialType } }
+ : skipToken,
+ select: (schema) => schema.map(selectCredentialFormSchema),
+ },
+ ),
+ )
}
-export const useGetPluginOAuthUrl = (url: string) => {
- return useMutation({
- mutationKey: [NAME_SPACE, 'oauth-url', url],
- mutationFn: (params?: { visibility?: CredentialPermission }) => {
- const visibility = params?.visibility
- return get<{
- authorization_url: string
- state: string
- context_id: string
- }>(url, { params: { visibility } })
+export const useGetPluginOAuthUrl = ({ category, provider }: PluginPayload) => {
+ const { mutateAsync: getToolUrl, isPending: isToolPending } = useMutation(
+ consoleQuery.oauth.plugin.byProvider.tool.authorizationUrl.get.mutationOptions(),
+ )
+ const { mutateAsync: getDatasourceUrl, isPending: isDatasourcePending } = useMutation(
+ consoleQuery.oauth.plugin.byProviderId.datasource.getAuthorizationUrl.get.mutationOptions(),
+ )
+ const mutateAsync = useCallback(
+ async (query?: GetOauthPluginByProviderToolAuthorizationUrlData['query']) => {
+ if (!provider) throw new Error('Credential provider is required')
+ switch (category) {
+ case AuthCategory.tool:
+ return getToolUrl({ params: { provider }, query })
+ case AuthCategory.datasource:
+ return getDatasourceUrl({ params: { provider_id: provider }, query })
+ default:
+ throw new Error(`Unsupported credential category: ${category}`)
+ }
},
- })
+ [category, provider, getToolUrl, getDatasourceUrl],
+ )
+ return { mutateAsync, isPending: isToolPending || isDatasourcePending }
}
-export const useGetPluginOAuthClientSchema = (url: string) => {
- return useQuery({
- enabled: !!url,
- queryKey: [NAME_SPACE, 'oauth-client-schema', url],
- queryFn: () =>
- get<{
- schema: FormSchema[]
- is_oauth_custom_client_enabled: boolean
- is_system_oauth_params_exists?: boolean
- client_params?: Record<string, unknown>
- redirect_uri?: string
- }>(url),
- staleTime: 0,
- })
+export const useGetPluginOAuthClientSchema = (
+ { category, provider }: PluginPayload,
+ enabled = true,
+) => {
+ return useQuery(
+ consoleQuery.workspaces.current.toolProvider.builtin.byProvider.oauth.clientSchema.get.queryOptions(
+ {
+ input:
+ enabled && category === AuthCategory.tool && provider
+ ? { params: { provider } }
+ : skipToken,
+ select: (data) => ({
+ ...data,
+ client_params: data.client_params ?? undefined,
+ schema: data.schema.map(selectCredentialFormSchema),
+ }),
+ staleTime: 0,
+ },
+ ),
+ )
}
-export const useInvalidPluginOAuthClientSchema = (url: string) => {
- return useInvalid([NAME_SPACE, 'oauth-client-schema', url])
+export const useInvalidPluginOAuthClientSchema = ({ category, provider }: PluginPayload) => {
+ const queryClient = useQueryClient()
+ return useCallback(() => {
+ if (category !== AuthCategory.tool || !provider) return Promise.resolve()
+ return queryClient.invalidateQueries({
+ queryKey:
+ consoleQuery.workspaces.current.toolProvider.builtin.byProvider.oauth.clientSchema.get.key({
+ input: { params: { provider } },
+ }),
+ })
+ }, [queryClient, category, provider])
}
-export const useSetPluginOAuthCustomClient = (url: string) => {
- return useMutation({
- mutationFn: (params: {
- client_params: Record<string, unknown>
- enable_oauth_custom_client: boolean
- }) => {
- return post<{ result: string }>(url, { body: params })
+export const useSetPluginOAuthCustomClient = ({ category, provider }: PluginPayload) => {
+ const { mutateAsync: setToolClient } = useMutation(
+ consoleQuery.workspaces.current.toolProvider.builtin.byProvider.oauth.customClient.post.mutationOptions(),
+ )
+ const { mutateAsync: setDatasourceClient } = useMutation(
+ consoleQuery.auth.plugin.datasource.byProviderId.customClient.post.mutationOptions(),
+ )
+ const mutateAsync = useCallback(
+ async (body: ToolOAuthCustomClientPayload) => {
+ if (!provider) throw new Error('Credential provider is required')
+ switch (category) {
+ case AuthCategory.tool:
+ return setToolClient({ params: { provider }, body })
+ case AuthCategory.datasource:
+ return setDatasourceClient({ params: { provider_id: provider }, body })
+ default:
+ throw new Error(`Unsupported credential category: ${category}`)
+ }
},
- })
+ [category, provider, setToolClient, setDatasourceClient],
+ )
+ return { mutateAsync }
}
-export const useDeletePluginOAuthCustomClient = (url: string) => {
- return useMutation({
- mutationFn: () => {
- return del<{ result: string }>(url)
- },
- })
+export const useDeletePluginOAuthCustomClient = ({ category, provider }: PluginPayload) => {
+ const { mutateAsync: deleteToolClient } = useMutation(
+ consoleQuery.workspaces.current.toolProvider.builtin.byProvider.oauth.customClient.delete.mutationOptions(),
+ )
+ const { mutateAsync: deleteDatasourceClient } = useMutation(
+ consoleQuery.auth.plugin.datasource.byProviderId.customClient.delete.mutationOptions(),
+ )
+ const mutateAsync = useCallback(async () => {
+ if (!provider) throw new Error('Credential provider is required')
+ switch (category) {
+ case AuthCategory.tool:
+ return deleteToolClient({ params: { provider } })
+ case AuthCategory.datasource:
+ return deleteDatasourceClient({ params: { provider_id: provider } })
+ default:
+ throw new Error(`Unsupported credential category: ${category}`)
+ }
+ }, [category, provider, deleteToolClient, deleteDatasourceClient])
+ return { mutateAsync }
}
diff --git a/web/service/use-workflow.ts b/web/service/use-workflow.ts
index 7f89c69cb19..dd391a8f395 100644
--- a/web/service/use-workflow.ts
+++ b/web/service/use-workflow.ts
@@ -1,22 +1,8 @@
-import type {
- WorkflowPaginationResponse,
- WorkflowPublishResponse,
- WorkflowResponse,
-} from '@dify/contracts/api/console/apps/types.gen'
-import type {
- EnvironmentDeployment,
- GetEnvironmentDeploymentResponse,
- ListEnvironmentDeploymentsResponse,
- WorkflowVersion,
-} from '@dify/contracts/enterprise-app-deploy/types.gen'
-import type { InfiniteData, QueryClient, UseQueryOptions } from '@tanstack/react-query'
+import type { UseQueryOptions } from '@tanstack/react-query'
import type { EditorResource } from '@/app/components/workflow/editor-resource/resource'
import type {
FetchWorkflowDraftPageParams,
FetchWorkflowDraftPageResponse,
- PublishWorkflowParams,
- UpdateWorkflowParams,
- WorkflowConfigResponse,
WorkflowRunHistoryResponse,
} from '@/types/workflow'
import {
@@ -26,9 +12,11 @@ import {
useQuery,
useQueryClient,
} from '@tanstack/react-query'
+import { useCallback } from 'react'
import { consoleClient, consoleQuery } from '@/service/console'
-// oxlint-disable-next-line no-restricted-imports -- run history, config, version and publish hooks take prebuilt flow URLs
-import { del, get, patch, post } from './base'
+// oxlint-disable-next-line no-restricted-imports -- run and version history hooks take prebuilt flow URLs
+import { get } from './base'
+import { legacyWorkflowVersionHistoryKey } from './console/workflow-version-cache'
import { appWorkflowQueryOptions, appWorkflowVersionsInfiniteQueryKey } from './workflow-queries'
const NAME_SPACE = 'workflow'
@@ -71,23 +59,7 @@ export const useInvalidateAppWorkflow = () => {
}
}
-export const useWorkflowConfig = <T = WorkflowConfigResponse>(
- url: string,
- onSuccess: (v: T) => void,
-) => {
- return useQuery({
- enabled: !!url,
- queryKey: [NAME_SPACE, 'config', url],
- staleTime: 0,
- queryFn: async () => {
- const data = await get<T>(url)
- onSuccess(data)
- return data
- },
- })
-}
-
-const WorkflowVersionHistoryKey = [NAME_SPACE, 'versionHistory']
+const WorkflowVersionHistoryKey = legacyWorkflowVersionHistoryKey
export const useWorkflowVersionHistory = (params: FetchWorkflowDraftPageParams) => {
const { url, initialPage, limit, userId, namedOnly } = params
@@ -118,192 +90,79 @@ export const useResetWorkflowVersionHistory = () => {
])
}
-function syncWorkflowVersionMetadata(
- version: WorkflowVersion | undefined,
- updatedWorkflow: WorkflowResponse,
-) {
- if (!version || version.id !== updatedWorkflow.id) return version
- if (
- version.marked_name === updatedWorkflow.marked_name &&
- version.marked_comment === updatedWorkflow.marked_comment
- )
- return version
-
- return {
- ...version,
- marked_name: updatedWorkflow.marked_name,
- marked_comment: updatedWorkflow.marked_comment,
- }
-}
-
-function syncEnvironmentDeploymentVersion(
- environmentDeployment: EnvironmentDeployment,
- updatedWorkflow: WorkflowResponse,
-) {
- const deployment = environmentDeployment.deployment
- if (!deployment) return environmentDeployment
-
- const currentVersion = syncWorkflowVersionMetadata(deployment.current_version, updatedWorkflow)
- const latestOperation = deployment.latest_operation
- const targetVersion = syncWorkflowVersionMetadata(
- latestOperation?.target_version,
- updatedWorkflow,
- )
- const currentVersionChanged = currentVersion !== deployment.current_version
- const targetVersionChanged = targetVersion !== latestOperation?.target_version
-
- if (!currentVersionChanged && !targetVersionChanged) return environmentDeployment
-
- return {
- ...environmentDeployment,
- deployment: {
- ...deployment,
- current_version: currentVersion,
- latest_operation:
- latestOperation && targetVersionChanged
- ? {
- ...latestOperation,
- target_version: targetVersion,
- }
- : latestOperation,
- },
- }
+type UpdateVersionParams = {
+ resource:
+ | Omit<Extract<EditorResource, { kind: 'app' }>, 'mode'>
+ | Exclude<EditorResource, { kind: 'app' }>
+ versionId: string
+ title: string
+ releaseNotes: string
}
-function syncWorkflowVersionPages(
- data: InfiniteData<WorkflowPaginationResponse> | undefined,
- updatedWorkflow: WorkflowResponse,
-) {
- if (!data) return data
-
- let changed = false
- const pages = data.pages.map((page) => {
- let pageChanged = false
- const items = page.items.map((workflow) => {
- if (workflow.id !== updatedWorkflow.id) return workflow
-
- changed = true
- pageChanged = true
- return updatedWorkflow
- })
-
- return pageChanged ? { ...page, items } : page
- })
-
- return changed ? { ...data, pages } : data
-}
-
-function syncEnvironmentDeployments(
- data: ListEnvironmentDeploymentsResponse | undefined,
- updatedWorkflow: WorkflowResponse,
-) {
- if (!data) return data
-
- let changed = false
- const environmentDeployments = data.environment_deployments.map((deployment) => {
- const updatedDeployment = syncEnvironmentDeploymentVersion(deployment, updatedWorkflow)
- if (updatedDeployment !== deployment) changed = true
- return updatedDeployment
- })
-
- return changed ? { ...data, environment_deployments: environmentDeployments } : data
-}
-
-function syncAppWorkflowVersionCaches(
- queryClient: QueryClient,
- appId: string,
- updatedWorkflow: WorkflowResponse,
-) {
- const publishedWorkflowQuery = appWorkflowQueryOptions(appId)
-
- queryClient.setQueryData<WorkflowResponse>(publishedWorkflowQuery.queryKey, (workflow) =>
- workflow?.id === updatedWorkflow.id ? updatedWorkflow : workflow,
+export const useUpdateWorkflow = () => {
+ const { mutateAsync: updateAppVersion } = useMutation(
+ consoleQuery.apps.byAppId.workflows.byWorkflowId.patch.mutationOptions(),
)
- queryClient.setQueriesData<InfiniteData<WorkflowPaginationResponse>>(
- { queryKey: appWorkflowVersionsInfiniteQueryKey() },
- (data) => syncWorkflowVersionPages(data, updatedWorkflow),
+ const { mutateAsync: updatePipelineVersion } = useMutation(
+ consoleQuery.rag.pipelines.byPipelineId.workflows.byWorkflowId.patch.mutationOptions(),
)
-}
-
-function syncWorkflowDeploymentCaches(
- queryClient: QueryClient,
- appId: string,
- updatedWorkflow: WorkflowResponse,
-) {
- const environmentDeploymentsQuery =
- consoleQuery.enterprise.appDeploy.deploymentService.listEnvironmentDeployments.queryOptions({
- input: {
- params: {
- app_id: appId,
- },
- },
- })
-
- queryClient.setQueryData<ListEnvironmentDeploymentsResponse>(
- environmentDeploymentsQuery.queryKey,
- (data) => syncEnvironmentDeployments(data, updatedWorkflow),
+ const { mutateAsync: updateSnippetVersion } = useMutation(
+ consoleQuery.snippets.bySnippetId.workflows.byWorkflowId.patch.mutationOptions(),
)
- queryClient.setQueriesData<GetEnvironmentDeploymentResponse>(
- {
- queryKey: consoleQuery.enterprise.appDeploy.deploymentService.getEnvironmentDeployment.key({
- type: 'query',
- }),
- },
- (data) => {
- if (!data) return data
-
- const environmentDeployment = syncEnvironmentDeploymentVersion(
- data.environment_deployment,
- updatedWorkflow,
- )
- return environmentDeployment === data.environment_deployment
- ? data
- : { ...data, environment_deployment: environmentDeployment }
+ const mutateAsync = useCallback(
+ ({ resource, versionId, title, releaseNotes }: UpdateVersionParams) => {
+ const body = { marked_name: title, marked_comment: releaseNotes }
+ switch (resource.kind) {
+ case 'app':
+ return updateAppVersion({
+ params: { app_id: resource.appId, workflow_id: versionId },
+ body,
+ })
+ case 'knowledge-pipeline':
+ return updatePipelineVersion({
+ params: { pipeline_id: resource.pipelineId, workflow_id: versionId },
+ body,
+ })
+ case 'snippet':
+ return updateSnippetVersion({
+ params: { snippet_id: resource.snippetId, workflow_id: versionId },
+ body,
+ })
+ }
},
+ [updateAppVersion, updatePipelineVersion, updateSnippetVersion],
)
-
- return environmentDeploymentsQuery.queryKey
+ return { mutateAsync }
}
-export const useUpdateWorkflow = () => {
- const queryClient = useQueryClient()
- return useMutation({
- mutationKey: [NAME_SPACE, 'update'],
- mutationFn: (params: UpdateWorkflowParams) =>
- patch<WorkflowResponse>(params.url, {
- body: {
- marked_name: params.title,
- marked_comment: params.releaseNotes,
- },
- }),
- onSuccess: (updatedWorkflow, params) => {
- if (params.appId) syncAppWorkflowVersionCaches(queryClient, params.appId, updatedWorkflow)
-
- const environmentDeploymentsQueryKey =
- params.appId && (params.appMode === 'workflow' || params.appMode === 'advanced-chat')
- ? syncWorkflowDeploymentCaches(queryClient, params.appId, updatedWorkflow)
- : undefined
- const invalidations = [
- queryClient.invalidateQueries({ queryKey: [...WorkflowVersionHistoryKey] }),
- queryClient.invalidateQueries({ queryKey: appWorkflowVersionsInfiniteQueryKey() }),
- ]
+export const useDeleteWorkflow = (resource: EditorResource) => {
+ const { mutateAsync: deleteAppVersion } = useMutation(
+ consoleQuery.apps.byAppId.workflows.byWorkflowId.delete.mutationOptions(),
+ )
+ const { mutateAsync: deletePipelineVersion } = useMutation(
+ consoleQuery.rag.pipelines.byPipelineId.workflows.byWorkflowId.delete.mutationOptions(),
+ )
+ const { mutateAsync: deleteSnippetVersion } = useMutation(
+ consoleQuery.snippets.bySnippetId.workflows.byWorkflowId.delete.mutationOptions(),
+ )
- if (environmentDeploymentsQueryKey) {
- invalidations.push(
- queryClient.invalidateQueries({ queryKey: environmentDeploymentsQueryKey }),
- )
+ return useCallback(
+ (versionId: string) => {
+ switch (resource.kind) {
+ case 'app':
+ return deleteAppVersion({ params: { app_id: resource.appId, workflow_id: versionId } })
+ case 'knowledge-pipeline':
+ return deletePipelineVersion({
+ params: { pipeline_id: resource.pipelineId, workflow_id: versionId },
+ })
+ case 'snippet':
+ return deleteSnippetVersion({
+ params: { snippet_id: resource.snippetId, workflow_id: versionId },
+ })
}
-
- return Promise.all(invalidations)
},
- })
-}
-
-export const useDeleteWorkflow = () => {
- return useMutation({
- mutationKey: [NAME_SPACE, 'delete'],
- mutationFn: (url: string) => del(url),
- })
+ [resource, deleteAppVersion, deletePipelineVersion, deleteSnippetVersion],
+ )
}
export const useRestoreWorkflow = (resource: EditorResource) => {
@@ -331,19 +190,6 @@ export const useRestoreWorkflow = (resource: EditorResource) => {
})
}
-export const usePublishWorkflow = () => {
- return useMutation({
- mutationKey: [NAME_SPACE, 'publish'],
- mutationFn: (params: PublishWorkflowParams) =>
- post<WorkflowPublishResponse>(params.url, {
- body: {
- marked_name: params.title,
- marked_comment: params.releaseNotes,
- },
- }),
- })
-}
-
function lastRunQueryOptions(resource: EditorResource, nodeId: string, enabled: boolean) {
switch (resource.kind) {
case 'app':
diff --git a/web/service/workflow.ts b/web/service/workflow.ts
index 9c682430cd7..f229e1611df 100644
--- a/web/service/workflow.ts
+++ b/web/service/workflow.ts
@@ -8,53 +8,19 @@ import type {
ConversationVariable,
EnvironmentVariable,
} from '@/app/components/workflow/types'
-import type { CommonResponse } from '@/models/common'
-import type {
- ConversationVariableResponse,
- FetchWorkflowDraftResponse,
- HumanInputFormData,
- NodesDefaultConfigsResponse,
- VarInInspect,
-} from '@/types/workflow'
+import type { FetchWorkflowDraftResponse, VarInInspect } from '@/types/workflow'
import { consoleClient } from '@/service/console'
-import { get, post } from './base'
+import { get } from './base'
export type EnvironmentVariablePatch = {
environmentVariables: EnvironmentVariable[]
deletedEnvironmentVariableIds: string[]
}
-type EnvironmentVariablePatchPayload = {
- environment_variables: EnvironmentVariable[]
- deleted_environment_variable_ids: string[]
-}
-
export const fetchWorkflowDraft = (url: string) => {
return get(url, {}, { silent: true }) as Promise<FetchWorkflowDraftResponse>
}
-export const syncWorkflowDraft = ({
- url,
- params,
-}: {
- url: string
- params: Pick<FetchWorkflowDraftResponse, 'graph' | 'features' | 'conversation_variables'> &
- Partial<Pick<FetchWorkflowDraftResponse, 'environment_variables'>> & {
- environment_variable_patch?: EnvironmentVariablePatchPayload
- force?: boolean
- }
-}) => {
- return post<CommonResponse & { updated_at: number; hash: string }>(
- url,
- { body: params },
- { silent: true },
- )
-}
-
-export const fetchNodesDefaultConfigs = (url: string) => {
- return get<NodesDefaultConfigsResponse>(url)
-}
-
export const singleNodeRun = (
resource: EditorResource,
nodeId: string,
@@ -79,10 +45,6 @@ export const singleNodeRun = (
}
}
-export const stopWorkflowRun = (url: string) => {
- return post<CommonResponse>(url)
-}
-
export const fetchNodeDefault = (appId: string, blockType: BlockEnum, query = {}) => {
return consoleClient.apps.byAppId.workflows.defaultWorkflowBlockConfigs.byBlockType.get({
params: { app_id: appId, block_type: blockType },
@@ -99,16 +61,6 @@ export const fetchPipelineNodeDefault = (pipelineId: string, blockType: BlockEnu
)
}
-export const fetchCurrentValueOfConversationVariable = ({
- url,
- params,
-}: {
- url: string
- params: { conversation_id: string }
-}) => {
- return get<ConversationVariableResponse>(url, { params })
-}
-
const fetchAllInspectVarsOnePage = (resource: EditorResource, page: number) => {
switch (resource.kind) {
case 'app':
@@ -225,23 +177,3 @@ export const submitHumanInputForm = (
body: data,
})
}
-
-export const fetchHumanInputNodeStepRunForm = (
- url: string,
- data: {
- inputs: Record<string, unknown>
- },
-) => {
- return post<HumanInputFormData>(`${url}/preview`, { body: data })
-}
-
-export const submitHumanInputNodeStepRunForm = (
- url: string,
- data: {
- inputs: Record<string, unknown> | undefined
- form_inputs: Record<string, unknown> | undefined
- action: string
- },
-) => {
- return post<CommonResponse>(`${url}/run`, { body: data })
-}
diff --git a/web/types/app.ts b/web/types/app.ts
index 4e91ac918fd..955cd27dcf7 100644
--- a/web/types/app.ts
+++ b/web/types/app.ts
@@ -275,6 +275,7 @@ export type ModelConfig = {
model: Model
dataset_configs: DatasetConfigs
file_upload?: {
+ enabled?: boolean
image: VisionSettings
} & UploadFileSetting
files?: VisionFile[]
diff --git a/web/types/workflow.ts b/web/types/workflow.ts
index 92ce9a31166..a3493041074 100644
--- a/web/types/workflow.ts
+++ b/web/types/workflow.ts
@@ -1,5 +1,4 @@
import type {
- AppMode,
WorkflowDraftVariableResponse,
WorkflowDraftVariableWithoutValueResponse,
} from '@dify/contracts/api/console/apps/types.gen'
@@ -352,7 +351,7 @@ export type HumanInputFormData = {
inputs: FormInputItem[]
actions: UserAction[]
form_token: string | null
- resolved_default_values: Record<string, HumanInputResolvedValue>
+ resolved_default_values: Record<string, unknown>
display_in_ui: boolean
expiration_time: number | null
}
@@ -428,37 +427,11 @@ export type WorkflowRunHistoryResponse = {
data: WorkflowRunHistory[]
}
-export type NodesDefaultConfigsResponse = {
- type: string
- config: any
-}[]
-
-export type ConversationVariableResponse = {
- data: (ConversationVariable & { updated_at: number; created_at: number })[]
- has_more: boolean
- limit: number
- total: number
- page: number
-}
-
export type IterationDurationMap = Record<string, number>
export type LoopDurationMap = Record<string, number>
export type LoopVariableMap = Record<string, any>
-export type WorkflowConfigResponse = {
- parallel_depth_limit: number
-}
-
export type PublishWorkflowParams = {
- url: string
- title: string
- releaseNotes: string
-}
-
-export type UpdateWorkflowParams = {
- appId?: string
- appMode?: AppMode
- url: string
title: string
releaseNotes: string
}