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(plugins): migrate agent strategy queries to generated contracts (#42696)

yyh4192299ad436
diff --git a/api/controllers/console/workspace/agent_providers.py b/api/controllers/console/workspace/agent_providers.py
index 4ba2faefc74..77bcbac19fb 100644
--- a/api/controllers/console/workspace/agent_providers.py
+++ b/api/controllers/console/workspace/agent_providers.py
@@ -1,5 +1,3 @@
-from typing import Any
-
from flask_restx import Resource
from pydantic import RootModel
@@ -11,18 +9,20 @@ from controllers.console.wraps import (
with_current_tenant_id,
with_current_user,
)
-from graphon.model_runtime.utils.encoders import jsonable_encoder
+from core.plugin.entities.plugin_daemon import PluginAgentProviderEntity
+from fields.base import ResponseModel
+from libs.helper import dump_response
from libs.login import login_required
from models import Account
from services.agent_service import AgentService
-class AgentProviderListResponse(RootModel[list[dict[str, Any]]]):
- root: list[dict[str, Any]]
+class AgentProviderResponse(PluginAgentProviderEntity, ResponseModel):
+ pass
-class AgentProviderResponse(RootModel[dict[str, Any]]):
- root: dict[str, Any]
+class AgentProviderListResponse(RootModel[list[AgentProviderResponse]]):
+ pass
register_response_schema_models(console_ns, AgentProviderListResponse, AgentProviderResponse)
@@ -43,7 +43,8 @@ class AgentProviderListApi(Resource):
@with_current_user
@with_current_tenant_id
def get(self, current_tenant_id: str, current_user: Account):
- return jsonable_encoder(AgentService.list_agent_providers(current_user.id, current_tenant_id))
+ providers = AgentService.list_agent_providers(current_user.id, current_tenant_id)
+ return AgentProviderListResponse.model_validate(providers, from_attributes=True).model_dump(mode="json")
@console_ns.route("/workspaces/current/agent-provider/<path:provider_name>")
@@ -62,4 +63,5 @@ class AgentProviderApi(Resource):
@with_current_user
@with_current_tenant_id
def get(self, current_tenant_id: str, current_user: Account, provider_name: str):
- return jsonable_encoder(AgentService.get_agent_provider(current_user.id, current_tenant_id, provider_name))
+ provider = AgentService.get_agent_provider(current_user.id, current_tenant_id, provider_name)
+ return dump_response(AgentProviderResponse, provider)
diff --git a/api/core/plugin/entities/parameters.py b/api/core/plugin/entities/parameters.py
index 1fed886850c..8d66376f7ec 100644
--- a/api/core/plugin/entities/parameters.py
+++ b/api/core/plugin/entities/parameters.py
@@ -258,7 +258,7 @@ def init_frontend_parameter(rule: PluginParameter, type: StrEnum, value: Any):
if not is_empty_tools_selection and not parameter_value and parameter_value != 0:
# get default value
parameter_value = rule.default
- if not parameter_value and rule.required:
+ if not parameter_value and parameter_value != 0 and rule.required:
raise ValueError(f"tool parameter {rule.name} not found in tool config")
if type == PluginParameterType.SELECT:
diff --git a/api/openapi/markdown/console-openapi.md b/api/openapi/markdown/console-openapi.md
index f3c94c3b05c..3d079fb12f8 100644
--- a/api/openapi/markdown/console-openapi.md
+++ b/api/openapi/markdown/console-openapi.md
@@ -14397,6 +14397,14 @@ Stable Agent Soul reference to one normalized skill archive.
| value | string<br>integer<br>number<br>boolean<br>[ string ]<br>[ integer ]<br>[ number ]<br>[ boolean ] | | No |
| variable | string | | No |
+#### AgentFeature
+
+Agent Feature, used to describe the features of the agent strategy.
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| AgentFeature | string | Agent Feature, used to describe the features of the agent strategy. | |
+
#### AgentFeatureToggleConfig
| Name | Type | Description | Required |
@@ -14856,6 +14864,14 @@ section may be empty, which is how callers express "no knowledge layer".
| state | string | | No |
| status | string | | No |
+#### AgentProviderEntityWithPlugin
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| identity | [AgentStrategyProviderIdentity](#agentstrategyprovideridentity) | | Yes |
+| plugin_id | string | The id of the plugin | No |
+| strategies | [ [AgentStrategyEntity](#agentstrategyentity) ] | | No |
+
#### AgentProviderListResponse
| Name | Type | Description | Required |
@@ -14866,7 +14882,11 @@ section may be empty, which is how callers express "no knowledge layer".
| Name | Type | Description | Required |
| ---- | ---- | ----------- | -------- |
-| AgentProviderResponse | object | | |
+| declaration | [AgentProviderEntityWithPlugin](#agentproviderentitywithplugin) | | Yes |
+| meta | [Meta](#meta) | | Yes |
+| plugin_id | string | | Yes |
+| plugin_unique_identifier | string | | Yes |
+| provider | string | | Yes |
#### AgentPublicationCountsResponse
@@ -15288,6 +15308,56 @@ Soft lifecycle state for Agent records.
| ---- | ---- | ----------- | -------- |
| AgentStatus | string | Soft lifecycle state for Agent records. | |
+#### AgentStrategyEntity
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| description | [I18nObject](#i18nobject) | The description of the agent strategy | Yes |
+| features | [ [AgentFeature](#agentfeature) ] | | No |
+| identity | [AgentStrategyIdentity](#agentstrategyidentity) | | Yes |
+| meta_version | string | | No |
+| output_schema | object | | No |
+| parameters | [ [AgentStrategyParameter](#agentstrategyparameter) ] | | No |
+
+#### AgentStrategyIdentity
+
+Inherits from ToolIdentity, without any additional fields.
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| author | string | The author of the tool | Yes |
+| icon | string | | No |
+| label | [I18nObject](#i18nobject) | The label of the tool | Yes |
+| name | string | The name of the tool | Yes |
+| provider | string | The provider of the tool | Yes |
+
+#### AgentStrategyParameter
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| auto_generate | [PluginParameterAutoGenerate](#pluginparameterautogenerate) | | No |
+| default | number<br>integer<br>string<br>boolean<br>[ object ]<br>object | | No |
+| help | [I18nObject](#i18nobject) | | No |
+| label | [I18nObject](#i18nobject) | The label presented to the user | Yes |
+| max | number<br>integer | | No |
+| min | number<br>integer | | No |
+| name | string | The name of the parameter | Yes |
+| options | [ [PluginParameterOption](#pluginparameteroption) ] | | No |
+| placeholder | [I18nObject](#i18nobject) | The placeholder presented to the user | No |
+| precision | integer | | No |
+| required | boolean | | No |
+| scope | string | | No |
+| template | [PluginParameterTemplate](#pluginparametertemplate) | | No |
+| type | [AgentStrategyParameterType](#agentstrategyparametertype) | The type of the parameter | Yes |
+
+#### AgentStrategyParameterType
+
+Keep all the types from PluginParameterType
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| AgentStrategyParameterType | string | Keep all the types from PluginParameterType | |
+
#### AgentStrategyProviderEntity
| Name | Type | Description | Required |
diff --git a/api/services/agent_service.py b/api/services/agent_service.py
index e065e1f978b..bcc2539ab93 100644
--- a/api/services/agent_service.py
+++ b/api/services/agent_service.py
@@ -7,6 +7,7 @@ from sqlalchemy.orm import Session
import contexts
from core.app.app_config.easy_ui_based_app.agent.manager import AgentConfigManager
+from core.plugin.entities.plugin_daemon import PluginAgentProviderEntity
from core.plugin.impl.agent import PluginAgentClient
from core.plugin.impl.exc import PluginDaemonClientSideError
from core.tools.entities.tool_entities import EmojiIconDict
@@ -165,7 +166,7 @@ class AgentService:
return result
@classmethod
- def list_agent_providers(cls, user_id: str, tenant_id: str):
+ def list_agent_providers(cls, user_id: str, tenant_id: str) -> list[PluginAgentProviderEntity]:
"""
List agent providers
"""
@@ -173,7 +174,7 @@ class AgentService:
return manager.fetch_agent_strategy_providers(tenant_id)
@classmethod
- def get_agent_provider(cls, user_id: str, tenant_id: str, provider_name: str):
+ def get_agent_provider(cls, user_id: str, tenant_id: str, provider_name: str) -> PluginAgentProviderEntity:
"""
Get agent provider
"""
diff --git a/api/tests/unit_tests/controllers/console/workspace/test_agent_providers.py b/api/tests/unit_tests/controllers/console/workspace/test_agent_providers.py
index 462d0e3bb32..47d7d00bab4 100644
--- a/api/tests/unit_tests/controllers/console/workspace/test_agent_providers.py
+++ b/api/tests/unit_tests/controllers/console/workspace/test_agent_providers.py
@@ -1,12 +1,19 @@
from inspect import unwrap
from unittest.mock import patch
+import pytest
from flask import Flask
+from pydantic import ValidationError
from controllers.console.workspace.agent_providers import (
AgentProviderApi,
AgentProviderListApi,
+ AgentProviderListResponse,
+ AgentProviderResponse,
)
+from core.agent.plugin_entities import AgentStrategyParameter
+from core.plugin.entities.plugin_daemon import PluginAgentProviderEntity
+from core.plugin.impl.exc import PluginNotFoundError
from models.account import Account
from tests.unit_tests.model_factories import make_account
@@ -15,27 +22,65 @@ def _account() -> Account:
return make_account(account_id="user1", name="Agent Provider Tester", email="[email protected]")
+def _provider() -> PluginAgentProviderEntity:
+ return PluginAgentProviderEntity.model_validate(
+ {
+ "provider": "agent",
+ "plugin_id": "langgenius/agent",
+ "plugin_unique_identifier": "langgenius/agent:0.0.2@checksum",
+ "meta": {},
+ "declaration": {
+ "identity": {
+ "author": "langgenius",
+ "name": "langgenius/agent/agent",
+ "label": {"en_US": "Agent"},
+ "description": {"en_US": "Agent strategies"},
+ "icon": "icon.svg",
+ },
+ "strategies": [
+ {
+ "identity": {
+ "author": "langgenius",
+ "name": "reasoning",
+ "provider": "langgenius/agent/agent",
+ "label": {"en_US": "Reasoning"},
+ },
+ "description": {"en_US": "Reason with tools"},
+ "parameters": [
+ {"name": "tools", "type": "array[tools]", "label": {"en_US": "Tools"}},
+ {"name": "limit", "type": "number", "label": {"en_US": "Limit"}, "default": 0},
+ {"name": "enabled", "type": "boolean", "label": {"en_US": "Enabled"}, "default": False},
+ ],
+ }
+ ],
+ },
+ }
+ )
+
+
class TestAgentProviderListApi:
- def test_get_success(self, app: Flask):
+ def test_get_success(self, app: Flask) -> None:
api = AgentProviderListApi()
method = unwrap(api.get)
user = _account()
tenant_id = "tenant1"
- providers = [{"name": "openai"}, {"name": "anthropic"}]
+ provider = _provider()
with (
app.test_request_context("/"),
patch(
"controllers.console.workspace.agent_providers.AgentService.list_agent_providers",
- return_value=providers,
- ),
+ return_value=[provider],
+ ) as list_providers,
):
result = method(api, tenant_id, user)
- assert result == providers
+ assert result == [provider.model_dump(mode="json")]
+ assert result[0]["declaration"]["identity"]["name"] == "langgenius/agent/agent"
+ list_providers.assert_called_once_with(user.id, tenant_id)
- def test_get_empty_list(self, app: Flask):
+ def test_get_empty_list(self, app: Flask) -> None:
api = AgentProviderListApi()
method = unwrap(api.get)
@@ -55,41 +100,70 @@ class TestAgentProviderListApi:
class TestAgentProviderApi:
- def test_get_success(self, app: Flask):
+ def test_get_success(self, app: Flask) -> None:
api = AgentProviderApi()
method = unwrap(api.get)
user = _account()
tenant_id = "tenant1"
- provider_name = "openai"
- provider_data = {"name": "openai", "models": ["gpt-4"]}
+ provider_name = "langgenius/agent/agent"
+ provider = _provider()
with (
app.test_request_context("/"),
patch(
"controllers.console.workspace.agent_providers.AgentService.get_agent_provider",
- return_value=provider_data,
- ),
+ return_value=provider,
+ ) as get_provider,
):
result = method(api, tenant_id, user, provider_name)
- assert result == provider_data
-
- def test_get_provider_not_found(self, app: Flask):
+ assert result == provider.model_dump(mode="json")
+ assert result["meta"]["version"] is None
+ strategy = result["declaration"]["strategies"][0]
+ assert strategy["identity"]["provider"] == provider_name
+ assert strategy["identity"]["icon"] is None
+ assert strategy["features"] is None
+ assert strategy["output_schema"] is None
+ assert strategy["parameters"][0]["type"] == "array[tools]"
+ assert strategy["parameters"][1]["default"] == 0
+ assert strategy["parameters"][2]["default"] is False
+ get_provider.assert_called_once_with(user.id, tenant_id, provider_name)
+
+ def test_get_provider_not_found(self, app: Flask) -> None:
api = AgentProviderApi()
method = unwrap(api.get)
user = _account()
tenant_id = "tenant1"
- provider_name = "unknown"
+ provider_name = "langgenius/missing/agent"
with (
app.test_request_context("/"),
patch(
- "controllers.console.workspace.agent_providers.AgentService.get_agent_provider",
- return_value=None,
+ "services.agent_service.PluginAgentClient.fetch_agent_strategy_provider",
+ side_effect=PluginNotFoundError("Agent provider is not installed"),
),
):
- result = method(api, tenant_id, user, provider_name)
+ with pytest.raises(ValueError, match="Agent provider is not installed"):
+ method(api, tenant_id, user, provider_name)
+
+
+class TestAgentProviderResponseContract:
+ def test_list_and_detail_share_the_plugin_declaration_schema(self) -> None:
+ schema = AgentProviderListResponse.model_json_schema(mode="serialization")
+
+ assert schema["type"] == "array"
+ assert schema["items"] == {"$ref": "#/$defs/AgentProviderResponse"}
+ declaration_schema = schema["$defs"]["AgentProviderResponse"]["properties"]["declaration"]
+ assert declaration_schema == {"$ref": "#/$defs/AgentProviderEntityWithPlugin"}
+ assert schema["$defs"]["AgentStrategyParameterType"]["enum"] == [
+ value.value for value in AgentStrategyParameter.AgentStrategyParameterType
+ ]
+
+ def test_response_rejects_unsupported_single_tool_parameters(self) -> None:
+ provider_data = _provider().model_dump(mode="json")
+ provider_data["declaration"]["strategies"][0]["parameters"][0]["type"] = "tool-selector"
- assert result is None
+ with pytest.raises(ValidationError, match="array\\[tools\\]"):
+ AgentProviderResponse.model_validate(provider_data)
diff --git a/api/tests/unit_tests/core/plugin/test_plugin_entities.py b/api/tests/unit_tests/core/plugin/test_plugin_entities.py
index cb4eaf1cd88..ca85d75f8c5 100644
--- a/api/tests/unit_tests/core/plugin/test_plugin_entities.py
+++ b/api/tests/unit_tests/core/plugin/test_plugin_entities.py
@@ -276,6 +276,33 @@ class TestPluginParameterEntities:
with pytest.raises(ValueError, match="not found in tool config"):
init_frontend_parameter(tools_rule, PluginParameterType.TOOLS_SELECTOR, None)
+ @pytest.mark.parametrize(
+ ("parameter_type", "default"),
+ [
+ (PluginParameterType.NUMBER, 0),
+ (PluginParameterType.NUMBER, 0.0),
+ (PluginParameterType.BOOLEAN, False),
+ ],
+ )
+ def test_required_parameter_accepts_zero_and_false_defaults(
+ self, parameter_type: PluginParameterType, default: int | float | bool
+ ) -> None:
+ rule = PluginParameter(name="required", label=self._label(), required=True, default=default)
+
+ value = init_frontend_parameter(rule, parameter_type, None)
+
+ assert value == default
+ assert type(value) is type(default)
+
+ @pytest.mark.parametrize("default", [None, "", [], {}])
+ def test_required_parameter_rejects_empty_defaults(
+ self, default: str | list[object] | dict[str, object] | None
+ ) -> None:
+ rule = PluginParameter(name="required", label=self._label(), required=True, default=default)
+
+ with pytest.raises(ValueError, match="tool parameter required not found in tool config"):
+ init_frontend_parameter(rule, PluginParameterType.ANY, None)
+
class TestPluginDaemonEntities:
def test_credential_type_helpers(self):
diff --git a/oxlint-suppressions.json b/oxlint-suppressions.json
index b711df6f0a8..368f2d60b24 100644
--- a/oxlint-suppressions.json
+++ b/oxlint-suppressions.json
@@ -2552,11 +2552,6 @@
"count": 2
}
},
- "web/app/components/plugins/plugin-detail-panel/agent-strategy-list.tsx": {
- "typescript/no-explicit-any": {
- "count": 1
- }
- },
"web/app/components/plugins/plugin-detail-panel/app-selector/app-inputs-form.tsx": {
"typescript/no-explicit-any": {
"count": 8
@@ -2598,9 +2593,6 @@
},
"jsx-a11y/no-static-element-interactions": {
"count": 1
- },
- "typescript/no-explicit-any": {
- "count": 2
}
},
"web/app/components/plugins/plugin-detail-panel/strategy-item.tsx": {
@@ -2679,7 +2671,7 @@
},
"web/app/components/plugins/types.ts": {
"typescript/no-explicit-any": {
- "count": 24
+ "count": 20
}
},
"web/app/components/rag-pipeline/components/panel/input-field/editor/form/__tests__/hidden-fields.spec.tsx": {
@@ -3149,14 +3141,6 @@
"count": 2
}
},
- "web/app/components/workflow/nodes/_base/components/agent-strategy.tsx": {
- "typescript/no-empty-object-type": {
- "count": 1
- },
- "typescript/no-explicit-any": {
- "count": 3
- }
- },
"web/app/components/workflow/nodes/_base/components/before-run-form/form-item.tsx": {
"jsx-a11y/no-autofocus": {
"count": 3
@@ -3452,32 +3436,17 @@
},
"web/app/components/workflow/nodes/agent/__tests__/integration.spec.tsx": {
"typescript/no-explicit-any": {
- "count": 20
+ "count": 17
}
},
"web/app/components/workflow/nodes/agent/default.ts": {
- "typescript/no-explicit-any": {
- "count": 3
- }
- },
- "web/app/components/workflow/nodes/agent/node.tsx": {
"typescript/no-explicit-any": {
"count": 2
}
},
- "web/app/components/workflow/nodes/agent/panel.tsx": {
- "typescript/no-explicit-any": {
- "count": 1
- }
- },
- "web/app/components/workflow/nodes/agent/types.ts": {
- "typescript/no-explicit-any": {
- "count": 1
- }
- },
"web/app/components/workflow/nodes/agent/use-config.ts": {
"typescript/no-explicit-any": {
- "count": 7
+ "count": 5
}
},
"web/app/components/workflow/nodes/assigner/__tests__/integration.spec.tsx": {
@@ -3999,9 +3968,6 @@
}
},
"web/app/components/workflow/nodes/tool/types.ts": {
- "no-barrel-files/no-barrel-files": {
- "count": 1
- },
"typescript/no-explicit-any": {
"count": 3
}
@@ -5002,11 +4968,6 @@
"count": 1
}
},
- "web/service/strategy.ts": {
- "no-restricted-imports": {
- "count": 1
- }
- },
"web/service/tools.ts": {
"no-restricted-imports": {
"count": 1
@@ -5096,11 +5057,6 @@
"count": 1
}
},
- "web/service/use-strategy.ts": {
- "@tanstack/query/prefer-query-options": {
- "count": 2
- }
- },
"web/service/use-tools.ts": {
"@tanstack/query/prefer-query-options": {
"count": 15
diff --git a/packages/contracts/generated/api/console/workspaces/types.gen.ts b/packages/contracts/generated/api/console/workspaces/types.gen.ts
index 450ace9e1fa..4db1ebc6d91 100644
--- a/packages/contracts/generated/api/console/workspaces/types.gen.ts
+++ b/packages/contracts/generated/api/console/workspaces/types.gen.ts
@@ -9,12 +9,14 @@ export type TenantListResponse = {
}
export type AgentProviderResponse = {
- [key: string]: unknown
+ declaration: AgentProviderEntityWithPlugin
+ meta: Meta
+ plugin_id: string
+ plugin_unique_identifier: string
+ provider: string
}
-export type AgentProviderListResponse = Array<{
- [key: string]: unknown
-}>
+export type AgentProviderListResponse = Array<AgentProviderResponse>
export type AgentSkillBindingsResponse = {
agent_id: string
@@ -1256,6 +1258,17 @@ export type TenantListItemResponse = {
status?: string | null
}
+export type AgentProviderEntityWithPlugin = {
+ identity: AgentStrategyProviderIdentity
+ plugin_id?: string | null
+ strategies?: Array<AgentStrategyEntity>
+}
+
+export type Meta = {
+ minimum_dify_version?: string | null
+ version?: string | null
+}
+
export type AgentSkillBindingItemResponse = {
description: string
display_name: string
@@ -2039,6 +2052,27 @@ export type TenantInfoResponse = {
trial_end_reason?: string | null
}
+export type AgentStrategyProviderIdentity = {
+ author: string
+ description: CoreToolsEntitiesCommonEntitiesI18nObject
+ icon: string
+ icon_dark?: string | null
+ label: CoreToolsEntitiesCommonEntitiesI18nObject
+ name: string
+ tags?: Array<ToolLabelEnum> | null
+}
+
+export type AgentStrategyEntity = {
+ description: I18nObject
+ features?: Array<AgentFeature> | null
+ identity: AgentStrategyIdentity
+ meta_version?: string | null
+ output_schema?: {
+ [key: string]: unknown
+ } | null
+ parameters?: Array<AgentStrategyParameter>
+}
+
export type PluginDependencyType = 'github' | 'marketplace' | 'package'
export type Github = {
@@ -2229,11 +2263,6 @@ export type EndpointProviderDeclaration = {
settings?: Array<ProviderConfig>
}
-export type Meta = {
- minimum_dify_version?: string | null
- version?: string | null
-}
-
export type ProviderEntity = {
background?: string | null
configurate_methods: Array<ConfigurateMethod>
@@ -2468,6 +2497,61 @@ export type OAuthSchema = {
credentials_schema?: Array<ProviderConfig>
}
+export type ToolLabelEnum =
+ | 'business'
+ | 'design'
+ | 'education'
+ | 'entertainment'
+ | 'finance'
+ | 'image'
+ | 'medical'
+ | 'news'
+ | 'other'
+ | 'productivity'
+ | 'rag'
+ | 'search'
+ | 'social'
+ | 'travel'
+ | 'utilities'
+ | 'videos'
+ | 'weather'
+
+export type AgentFeature = 'history-messages'
+
+export type AgentStrategyIdentity = {
+ author: string
+ icon?: string | null
+ label: I18nObject
+ name: string
+ provider: string
+}
+
+export type AgentStrategyParameter = {
+ auto_generate?: PluginParameterAutoGenerate | null
+ default?:
+ | number
+ | number
+ | string
+ | boolean
+ | Array<unknown>
+ | {
+ [key: string]: unknown
+ }
+ | null
+ help?: I18nObject | null
+ label: I18nObject
+ max?: number | number | null
+ min?: number | number | null
+ name: string
+ options?: Array<PluginParameterOption>
+ placeholder?: I18nObject | null
+ precision?: number | null
+ required?: boolean
+ scope?: string | null
+ template?: PluginParameterTemplate | null
+ type: AgentStrategyParameterType
+}
+
export type AiModelEntityResponse = {
deprecated?: boolean
features?: Array<ModelFeature> | null
@@ -2547,16 +2631,6 @@ export type QuotaConfiguration = {
restrict_models?: Array<RestrictModel>
}
-export type AgentStrategyProviderIdentity = {
- author: string
- description: CoreToolsEntitiesCommonEntitiesI18nObject
- icon: string
- icon_dark?: string | null
- label: CoreToolsEntitiesCommonEntitiesI18nObject
- name: string
- tags?: Array<ToolLabelEnum> | null
-}
-
export type DatasourceProviderIdentity = {
author: string
description: CoreToolsEntitiesCommonEntitiesI18nObject
@@ -2689,6 +2763,20 @@ export type EventParameterType =
| 'select'
| 'string'
+export type AgentStrategyParameterType =
+ | 'any'
+ | 'app-selector'
+ | 'array[tools]'
+ | 'boolean'
+ | 'file'
+ | 'files'
+ | 'model-selector'
+ | 'number'
+ | 'secret-input'
+ | 'select'
+ | 'string'
+ | 'system-files'
+
export type PriceConfigResponse = {
currency: string
input: string
@@ -2744,25 +2832,6 @@ export type RestrictModel = {
model_type: ModelType
}
-export type ToolLabelEnum =
- | 'business'
- | 'design'
- | 'education'
- | 'entertainment'
- | 'finance'
- | 'image'
- | 'medical'
- | 'news'
- | 'other'
- | 'productivity'
- | 'rag'
- | 'search'
- | 'social'
- | 'travel'
- | 'utilities'
- | 'videos'
- | 'weather'
-
export type PriceConfig = {
currency: string
input: string
diff --git a/packages/contracts/generated/api/console/workspaces/zod.gen.ts b/packages/contracts/generated/api/console/workspaces/zod.gen.ts
index 4b3f8d6b1e2..f21f6696403 100644
--- a/packages/contracts/generated/api/console/workspaces/zod.gen.ts
+++ b/packages/contracts/generated/api/console/workspaces/zod.gen.ts
@@ -2,16 +2,6 @@
import * as z from 'zod'
-/**
- * AgentProviderResponse
- */
-export const zAgentProviderResponse = z.record(z.string(), z.unknown())
-
-/**
- * AgentProviderListResponse
- */
-export const zAgentProviderListResponse = z.array(z.record(z.string(), z.unknown()))
-
/**
* AgentSkillBindingsPayload
*/
@@ -787,6 +777,14 @@ export const zSwitchWorkspacePayload = z.object({
tenant_id: z.string(),
})
+/**
+ * Meta
+ */
+export const zMeta = z.object({
+ minimum_dify_version: z.string().nullish(),
+ version: z.string().nullish(),
+})
+
/**
* AgentSkillBindingItemResponse
*/
@@ -2375,14 +2373,6 @@ export const zCoreToolsEntitiesCommonEntitiesI18nObject = z.object({
zh_Hans: z.string().nullish(),
})
-/**
- * Meta
- */
-export const zMeta = z.object({
- minimum_dify_version: z.string().nullish(),
- version: z.string().nullish(),
-})
-
/**
* Plugins
*/
@@ -2814,6 +2804,72 @@ export const zOAuthSchema = z.object({
credentials_schema: z.array(zProviderConfig).optional(),
})
+/**
+ * ToolLabelEnum
+ */
+export const zToolLabelEnum = z.enum([
+ 'business',
+ 'design',
+ 'education',
+ 'entertainment',
+ 'finance',
+ 'image',
+ 'medical',
+ 'news',
+ 'other',
+ 'productivity',
+ 'rag',
+ 'search',
+ 'social',
+ 'travel',
+ 'utilities',
+ 'videos',
+ 'weather',
+])
+
+/**
+ * AgentStrategyProviderIdentity
+ *
+ * Inherits from ToolProviderIdentity, without any additional fields.
+ */
+export const zAgentStrategyProviderIdentity = z.object({
+ author: z.string(),
+ description: zCoreToolsEntitiesCommonEntitiesI18nObject,
+ icon: z.string(),
+ icon_dark: z.string().nullish(),
+ label: zCoreToolsEntitiesCommonEntitiesI18nObject,
+ name: z.string(),
+ tags: z.array(zToolLabelEnum).nullish().default([]),
+})
+
+/**
+ * AgentStrategyProviderEntity
+ */
+export const zAgentStrategyProviderEntity = z.object({
+ identity: zAgentStrategyProviderIdentity,
+ plugin_id: z.string().nullish(),
+})
+
+/**
+ * AgentFeature
+ *
+ * Agent Feature, used to describe the features of the agent strategy.
+ */
+export const zAgentFeature = z.enum(['history-messages'])
+
+/**
+ * AgentStrategyIdentity
+ *
+ * Inherits from ToolIdentity, without any additional fields.
+ */
+export const zAgentStrategyIdentity = z.object({
+ author: z.string(),
+ icon: z.string().nullish(),
+ label: zI18nObject,
+ name: z.string(),
+ provider: z.string(),
+})
+
/**
* EndpointDeclarationResponse
*/
@@ -2875,6 +2931,18 @@ export const zFieldModelSchema = z.object({
*/
export const zProviderQuotaType = z.enum(['free', 'paid', 'trial'])
+/**
+ * DatasourceProviderIdentity
+ */
+export const zDatasourceProviderIdentity = z.object({
+ author: z.string(),
+ description: zCoreToolsEntitiesCommonEntitiesI18nObject,
+ icon: z.string(),
+ label: zCoreToolsEntitiesCommonEntitiesI18nObject,
+ name: z.string(),
+ tags: z.array(zToolLabelEnum).nullish().default([]),
+})
+
/**
* DatasourceProviderType
*
@@ -2887,6 +2955,18 @@ export const zDatasourceProviderType = z.enum([
'website_crawl',
])
+/**
+ * DatasourceProviderEntity
+ *
+ * Datasource provider entity
+ */
+export const zDatasourceProviderEntity = z.object({
+ credentials_schema: z.array(zProviderConfig).optional(),
+ identity: zDatasourceProviderIdentity,
+ oauth_schema: zOAuthSchema.nullish(),
+ provider_type: zDatasourceProviderType,
+})
+
/**
* EndpointDeclaration
*
@@ -2908,6 +2988,29 @@ export const zEndpointProviderDeclaration = z.object({
settings: z.array(zProviderConfig).optional(),
})
+/**
+ * ToolProviderIdentity
+ */
+export const zToolProviderIdentity = z.object({
+ author: z.string(),
+ description: zCoreToolsEntitiesCommonEntitiesI18nObject,
+ icon: z.string(),
+ icon_dark: z.string().nullish(),
+ label: zCoreToolsEntitiesCommonEntitiesI18nObject,
+ name: z.string(),
+ tags: z.array(zToolLabelEnum).nullish().default([]),
+})
+
+/**
+ * ToolProviderEntity
+ */
+export const zToolProviderEntity = z.object({
+ credentials_schema: z.array(zProviderConfig).optional(),
+ identity: zToolProviderIdentity,
+ oauth_schema: zOAuthSchema.nullish(),
+ plugin_id: z.string().nullish(),
+})
+
/**
* TriggerProviderIdentity
*
@@ -2975,6 +3078,26 @@ export const zEventParameterType = z.enum([
'string',
])
+/**
+ * AgentStrategyParameterType
+ *
+ * Keep all the types from PluginParameterType
+ */
+export const zAgentStrategyParameterType = z.enum([
+ 'any',
+ 'app-selector',
+ 'array[tools]',
+ 'boolean',
+ 'file',
+ 'files',
+ 'model-selector',
+ 'number',
+ 'secret-input',
+ 'select',
+ 'string',
+ 'system-files',
+])
+
/**
* PriceConfigResponse
*
@@ -3392,99 +3515,6 @@ export const zModelProviderListResponse = z.object({
data: z.array(zProviderResponse),
})
-/**
- * ToolLabelEnum
- */
-export const zToolLabelEnum = z.enum([
- 'business',
- 'design',
- 'education',
- 'entertainment',
- 'finance',
- 'image',
- 'medical',
- 'news',
- 'other',
- 'productivity',
- 'rag',
- 'search',
- 'social',
- 'travel',
- 'utilities',
- 'videos',
- 'weather',
-])
-
-/**
- * AgentStrategyProviderIdentity
- *
- * Inherits from ToolProviderIdentity, without any additional fields.
- */
-export const zAgentStrategyProviderIdentity = z.object({
- author: z.string(),
- description: zCoreToolsEntitiesCommonEntitiesI18nObject,
- icon: z.string(),
- icon_dark: z.string().nullish(),
- label: zCoreToolsEntitiesCommonEntitiesI18nObject,
- name: z.string(),
- tags: z.array(zToolLabelEnum).nullish().default([]),
-})
-
-/**
- * AgentStrategyProviderEntity
- */
-export const zAgentStrategyProviderEntity = z.object({
- identity: zAgentStrategyProviderIdentity,
- plugin_id: z.string().nullish(),
-})
-
-/**
- * DatasourceProviderIdentity
- */
-export const zDatasourceProviderIdentity = z.object({
- author: z.string(),
- description: zCoreToolsEntitiesCommonEntitiesI18nObject,
- icon: z.string(),
- label: zCoreToolsEntitiesCommonEntitiesI18nObject,
- name: z.string(),
- tags: z.array(zToolLabelEnum).nullish().default([]),
-})
-
-/**
- * DatasourceProviderEntity
- *
- * Datasource provider entity
- */
-export const zDatasourceProviderEntity = z.object({
- credentials_schema: z.array(zProviderConfig).optional(),
- identity: zDatasourceProviderIdentity,
- oauth_schema: zOAuthSchema.nullish(),
- provider_type: zDatasourceProviderType,
-})
-
-/**
- * ToolProviderIdentity
- */
-export const zToolProviderIdentity = z.object({
- author: z.string(),
- description: zCoreToolsEntitiesCommonEntitiesI18nObject,
- icon: z.string(),
- icon_dark: z.string().nullish(),
- label: zCoreToolsEntitiesCommonEntitiesI18nObject,
- name: z.string(),
- tags: z.array(zToolLabelEnum).nullish().default([]),
-})
-
-/**
- * ToolProviderEntity
- */
-export const zToolProviderEntity = z.object({
- credentials_schema: z.array(zProviderConfig).optional(),
- identity: zToolProviderIdentity,
- oauth_schema: zOAuthSchema.nullish(),
- plugin_id: z.string().nullish(),
-})
-
/**
* PriceConfig
*
@@ -3836,6 +3866,72 @@ export const zTriggerProviderApiEntity = z.object({
*/
export const zTriggerProviderListResponse = z.array(zTriggerProviderApiEntity)
+/**
+ * AgentStrategyParameter
+ */
+export const zAgentStrategyParameter = z.object({
+ auto_generate: zPluginParameterAutoGenerate.nullish(),
+ default: z
+ .union([
+ z.number(),
+ z.int(),
+ z.string(),
+ z.boolean(),
+ z.array(z.unknown()),
+ z.record(z.string(), z.unknown()),
+ ])
+ .nullish(),
+ help: zI18nObject.nullish(),
+ label: zI18nObject,
+ max: z.union([z.number(), z.int()]).nullish(),
+ min: z.union([z.number(), z.int()]).nullish(),
+ name: z.string(),
+ options: z.array(zPluginParameterOption).optional(),
+ placeholder: zI18nObject.nullish(),
+ precision: z.int().nullish(),
+ required: z.boolean().optional().default(false),
+ scope: z.string().nullish(),
+ template: zPluginParameterTemplate.nullish(),
+ type: zAgentStrategyParameterType,
+})
+
+/**
+ * AgentStrategyEntity
+ */
+export const zAgentStrategyEntity = z.object({
+ description: zI18nObject,
+ features: z.array(zAgentFeature).nullish(),
+ identity: zAgentStrategyIdentity,
+ meta_version: z.string().nullish(),
+ output_schema: z.record(z.string(), z.unknown()).nullish(),
+ parameters: z.array(zAgentStrategyParameter).optional(),
+})
+
+/**
+ * AgentProviderEntityWithPlugin
+ */
+export const zAgentProviderEntityWithPlugin = z.object({
+ identity: zAgentStrategyProviderIdentity,
+ plugin_id: z.string().nullish(),
+ strategies: z.array(zAgentStrategyEntity).optional(),
+})
+
+/**
+ * AgentProviderResponse
+ */
+export const zAgentProviderResponse = z.object({
+ declaration: zAgentProviderEntityWithPlugin,
+ meta: zMeta,
+ plugin_id: z.string(),
+ plugin_unique_identifier: z.string(),
+ provider: z.string(),
+})
+
+/**
+ * AgentProviderListResponse
+ */
+export const zAgentProviderListResponse = z.array(zAgentProviderResponse)
+
/**
* EventEntity
*
diff --git a/web/app/components/header/account-setting/data-source-page-new/__tests__/index.spec.tsx b/web/app/components/header/account-setting/data-source-page-new/__tests__/index.spec.tsx
index 1fdb022ce29..5a5fb93bf22 100644
--- a/web/app/components/header/account-setting/data-source-page-new/__tests__/index.spec.tsx
+++ b/web/app/components/header/account-setting/data-source-page-new/__tests__/index.spec.tsx
@@ -179,9 +179,7 @@ describe('DataSourcePage Component', () => {
vi.mocked(useTheme).mockReturnValue({ theme: 'light' } as unknown as ReturnType<
typeof useTheme
>)
- vi.mocked(useRenderI18nObject).mockReturnValue(
- (obj: Record<string, string>) => obj?.en_US || '',
- )
+ vi.mocked(useRenderI18nObject).mockReturnValue((obj) => obj?.en_US || '')
vi.mocked(useGetDataSourceOAuthUrl).mockReturnValue({
mutateAsync: vi.fn(),
} as unknown as ReturnType<typeof useGetDataSourceOAuthUrl>)
diff --git a/web/app/components/plugins/install-plugin/__tests__/utils.spec.ts b/web/app/components/plugins/install-plugin/__tests__/utils.spec.ts
index f5f988bd89a..9c6dc233178 100644
--- a/web/app/components/plugins/install-plugin/__tests__/utils.spec.ts
+++ b/web/app/components/plugins/install-plugin/__tests__/utils.spec.ts
@@ -36,7 +36,7 @@ describe('pluginManifestToCardPluginProps', () => {
endpoint: { settings: [], endpoints: [] },
model: {},
tags: ['search', 'api'],
- agent_strategy: {},
+ agent_strategy: null,
meta: { version: '1.0.0' },
trigger: {} as PluginDeclaration['trigger'],
...overrides,
diff --git a/web/app/components/plugins/install-plugin/hooks/__tests__/use-refresh-plugin-list.spec.ts b/web/app/components/plugins/install-plugin/hooks/__tests__/use-refresh-plugin-list.spec.ts
index 269214d2032..d091a69b898 100644
--- a/web/app/components/plugins/install-plugin/hooks/__tests__/use-refresh-plugin-list.spec.ts
+++ b/web/app/components/plugins/install-plugin/hooks/__tests__/use-refresh-plugin-list.spec.ts
@@ -1,223 +1,166 @@
-import type { GetWorkspacesCurrentModelsModelTypesByModelTypeData } from '@dify/contracts/api/console/workspaces/types.gen'
-import type { OperationKey } from '@orpc/tanstack-query'
-import { renderHook } from '@testing-library/react'
-import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import type { PropsWithChildren } from 'react'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { act, renderHook, waitFor } from '@testing-library/react'
+import { createElement } from 'react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import { consoleQuery } from '@/service/console'
import { commonQueryKeys } from '@/service/use-common'
import { PluginCategoryEnum } from '../../../types'
-
-// Mock invalidation / refresh functions
-const mockInvalidateInstalledPluginList = vi.fn()
-const mockInvalidateCheckInstalled = vi.fn()
-const mockRefetchLLMModelList = vi.fn()
-const mockRefetchEmbeddingModelList = vi.fn()
-const mockRefetchRerankModelList = vi.fn()
-const mockRefetchSpeech2textModelList = vi.fn()
-const mockRefetchTTSModelList = vi.fn()
-const mockInvalidateDefaultModel = vi.fn()
-const mockInvalidateQueries = vi.fn()
-const mockInvalidateAllToolProviders = vi.fn()
-const mockInvalidateAllBuiltInTools = vi.fn()
-const mockInvalidateAllDataSources = vi.fn()
-const mockInvalidateDataSourceListAuth = vi.fn()
-const mockInvalidateStrategyProviders = vi.fn()
-const mockInvalidateAllTriggerPlugins = vi.fn()
-const mockInvalidateRAGRecommendedPlugins = vi.fn()
-
-vi.mock('@/service/use-plugins', () => ({
- useInvalidateCheckInstalled: () => mockInvalidateCheckInstalled,
- useInvalidateInstalledPluginList: () => mockInvalidateInstalledPluginList,
+import useRefreshPluginList from '../use-refresh-plugin-list'
+
+const mocks = vi.hoisted(() => ({
+ request: vi.fn<(url: string) => Promise<Response>>(),
+ installed: vi.fn(),
+ checkInstalled: vi.fn(),
+ defaultModel: vi.fn(),
+ toolProviders: vi.fn(),
+ builtInTools: vi.fn(),
+ dataSources: vi.fn(),
+ dataSourceAuth: vi.fn(),
+ triggers: vi.fn(),
+ recommended: vi.fn(),
}))
-vi.mock('@/app/components/header/account-setting/model-provider-page/declarations', () => ({
- ModelTypeEnum: {
- textGeneration: 'llm',
- textEmbedding: 'text-embedding',
- rerank: 'rerank',
- speech2text: 'speech2text',
- tts: 'tts',
- },
+vi.mock('@/service/base', () => ({ request: mocks.request }))
+vi.mock('@/service/use-plugins', () => ({
+ useInvalidateCheckInstalled: () => mocks.checkInstalled,
+ useInvalidateInstalledPluginList: () => mocks.installed,
}))
-
vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({
- useInvalidateDefaultModel: () => mockInvalidateDefaultModel,
+ useInvalidateDefaultModel: () => mocks.defaultModel,
}))
-
vi.mock('@/service/use-tools', () => ({
- useInvalidateAllToolProviders: () => mockInvalidateAllToolProviders,
- useInvalidateAllBuiltInTools: () => mockInvalidateAllBuiltInTools,
- useInvalidateRAGRecommendedPlugins: () => mockInvalidateRAGRecommendedPlugins,
+ useInvalidateAllToolProviders: () => mocks.toolProviders,
+ useInvalidateAllBuiltInTools: () => mocks.builtInTools,
+ useInvalidateRAGRecommendedPlugins: () => mocks.recommended,
}))
-
vi.mock('@/service/use-pipeline', () => ({
- useInvalidDataSourceList: () => mockInvalidateAllDataSources,
+ useInvalidDataSourceList: () => mocks.dataSources,
}))
-
vi.mock('@/service/use-datasource', () => ({
- useInvalidDataSourceListAuth: () => mockInvalidateDataSourceListAuth,
-}))
-
-vi.mock('@/service/use-strategy', () => ({
- useInvalidateStrategyProviders: () => mockInvalidateStrategyProviders,
+ useInvalidDataSourceListAuth: () => mocks.dataSourceAuth,
}))
-
vi.mock('@/service/use-triggers', () => ({
- useInvalidateAllTriggerPlugins: () => mockInvalidateAllTriggerPlugins,
+ useInvalidateAllTriggerPlugins: () => mocks.triggers,
}))
-const { default: useRefreshPluginList } = await import('../use-refresh-plugin-list')
+const current = consoleQuery.workspaces.current
+const strategyKeys = [
+ current.agentProviders.get.queryKey(),
+ current.agentProvider.byProviderName.get.queryKey({
+ input: { params: { provider_name: 'langgenius/agent/react' } },
+ }),
+ current.agentProvider.byProviderName.get.queryKey({
+ input: { params: { provider_name: 'langgenius/agent/function-calling' } },
+ }),
+]
+const providerKeys = [
+ current.modelProviders.summary.get.key(),
+ commonQueryKeys.modelProviderDetails,
+]
+const unrelatedKey = consoleQuery.account.profile.get.key()
+const modelTypes = ['llm', 'text-embedding', 'rerank', 'speech2text', 'tts']
+
+describe('plugin installation refresh', () => {
+ let client: QueryClient
+
+ const wrapper = ({ children }: PropsWithChildren) =>
+ createElement(QueryClientProvider, { client }, children)
-describe('useRefreshPluginList', () => {
beforeEach(() => {
vi.clearAllMocks()
- })
-
- it('should always invalidate installed plugin list and installation checks', () => {
- const { result } = renderHook(() => useRefreshPluginList())
-
- result.current.refreshPluginList()
-
- expect(mockInvalidateInstalledPluginList).toHaveBeenCalledTimes(1)
- expect(mockInvalidateCheckInstalled).toHaveBeenCalledTimes(1)
- })
-
- it('should refresh tool providers for tool category manifest', () => {
- const { result } = renderHook(() => useRefreshPluginList())
-
- result.current.refreshPluginList({ category: PluginCategoryEnum.tool } as never)
-
- expect(mockInvalidateInstalledPluginList).toHaveBeenCalledWith(PluginCategoryEnum.tool)
- expect(mockInvalidateAllToolProviders).toHaveBeenCalledTimes(1)
- expect(mockInvalidateAllBuiltInTools).toHaveBeenCalledTimes(1)
- expect(mockInvalidateRAGRecommendedPlugins).toHaveBeenCalledWith('tool')
- })
-
- it('should refresh model lists for model category manifest', () => {
- const { result } = renderHook(() => useRefreshPluginList())
-
- result.current.refreshPluginList({ category: PluginCategoryEnum.model } as never)
-
- expect(mockInvalidateInstalledPluginList).toHaveBeenCalledWith(PluginCategoryEnum.model)
- expect(mockInvalidateQueries).toHaveBeenCalledWith({
- queryKey: consoleQuery.workspaces.current.modelProviders.summary.get.key(),
+ client = new QueryClient({
+ defaultOptions: { queries: { retry: false, staleTime: Infinity } },
})
- expect(mockInvalidateQueries).toHaveBeenCalledWith({
- queryKey: commonQueryKeys.modelProviderDetails,
- })
- expect(mockRefetchLLMModelList).toHaveBeenCalledTimes(1)
- expect(mockRefetchEmbeddingModelList).toHaveBeenCalledTimes(1)
- expect(mockRefetchRerankModelList).toHaveBeenCalledTimes(1)
- expect(mockRefetchSpeech2textModelList).toHaveBeenCalledTimes(1)
- expect(mockRefetchTTSModelList).toHaveBeenCalledTimes(1)
- expect(mockInvalidateDefaultModel).toHaveBeenCalledTimes(5)
- expect(mockInvalidateDefaultModel).toHaveBeenCalledWith('llm')
- expect(mockInvalidateDefaultModel).toHaveBeenCalledWith('text-embedding')
- expect(mockInvalidateDefaultModel).toHaveBeenCalledWith('rerank')
- expect(mockInvalidateDefaultModel).toHaveBeenCalledWith('speech2text')
- expect(mockInvalidateDefaultModel).toHaveBeenCalledWith('tts')
- })
-
- it('should refresh datasource lists for datasource category manifest', () => {
- const { result } = renderHook(() => useRefreshPluginList())
-
- result.current.refreshPluginList({ category: PluginCategoryEnum.datasource } as never)
-
- expect(mockInvalidateAllDataSources).toHaveBeenCalledTimes(1)
- expect(mockInvalidateDataSourceListAuth).toHaveBeenCalledTimes(1)
+ for (const key of [...strategyKeys, ...providerKeys, unrelatedKey])
+ client.setQueryData(key, { cached: true })
+ for (const model_type of modelTypes) {
+ client.setQueryData(
+ current.models.modelTypes.byModelType.get.queryKey({ input: { params: { model_type } } }),
+ { data: [] },
+ )
+ }
+ mocks.request.mockImplementation(async () => Response.json({ data: [] }))
})
- it('should refresh trigger plugins for trigger category manifest', () => {
- const { result } = renderHook(() => useRefreshPluginList())
-
- result.current.refreshPluginList({ category: PluginCategoryEnum.trigger } as never)
+ afterEach(() => client.clear())
- expect(mockInvalidateAllTriggerPlugins).toHaveBeenCalledTimes(1)
- })
-
- it('should refresh strategy providers for agent category manifest', () => {
- const { result } = renderHook(() => useRefreshPluginList())
+ it('invalidates the strategy catalog and every provider detail after an agent plugin changes', () => {
+ const { result } = renderHook(useRefreshPluginList, { wrapper })
- result.current.refreshPluginList({ category: PluginCategoryEnum.agent } as never)
+ act(() => result.current.refreshPluginList({ category: PluginCategoryEnum.agent }))
- expect(mockInvalidateStrategyProviders).toHaveBeenCalledTimes(1)
+ expect(mocks.installed).toHaveBeenCalledWith(PluginCategoryEnum.agent)
+ expect(mocks.checkInstalled).toHaveBeenCalledOnce()
+ for (const key of strategyKeys) expect(client.getQueryState(key)?.isInvalidated).toBe(true)
+ for (const key of [...providerKeys, unrelatedKey])
+ expect(client.getQueryState(key)?.isInvalidated).toBe(false)
+ expect(mocks.request).not.toHaveBeenCalled()
})
- it('should refresh all types when refreshAllType is true', () => {
- const { result } = renderHook(() => useRefreshPluginList())
-
- result.current.refreshPluginList(undefined, true)
+ it.each([PluginCategoryEnum.tool, PluginCategoryEnum.datasource, PluginCategoryEnum.trigger])(
+ 'keeps strategy caches fresh when a %s plugin changes',
+ (category) => {
+ const { result } = renderHook(useRefreshPluginList, { wrapper })
- expect(mockInvalidateInstalledPluginList).toHaveBeenCalledWith()
- expect(mockInvalidateAllToolProviders).toHaveBeenCalledTimes(1)
- expect(mockInvalidateAllBuiltInTools).toHaveBeenCalledTimes(1)
- expect(mockInvalidateRAGRecommendedPlugins).toHaveBeenCalledWith('tool')
- expect(mockInvalidateAllTriggerPlugins).toHaveBeenCalledTimes(1)
- expect(mockInvalidateAllDataSources).toHaveBeenCalledTimes(1)
- expect(mockInvalidateDataSourceListAuth).toHaveBeenCalledTimes(1)
- expect(mockInvalidateQueries).toHaveBeenCalledWith({
- queryKey: consoleQuery.workspaces.current.modelProviders.summary.get.key(),
- })
- expect(mockInvalidateQueries).toHaveBeenCalledWith({
- queryKey: commonQueryKeys.modelProviderDetails,
- })
- expect(mockRefetchLLMModelList).toHaveBeenCalledTimes(1)
- expect(mockRefetchEmbeddingModelList).toHaveBeenCalledTimes(1)
- expect(mockRefetchRerankModelList).toHaveBeenCalledTimes(1)
- expect(mockRefetchSpeech2textModelList).toHaveBeenCalledTimes(1)
- expect(mockRefetchTTSModelList).toHaveBeenCalledTimes(1)
- expect(mockInvalidateDefaultModel).toHaveBeenCalledTimes(5)
- expect(mockInvalidateStrategyProviders).toHaveBeenCalledTimes(1)
- })
+ act(() => result.current.refreshPluginList({ category }))
- it('should not refresh category-specific lists when manifest is null', () => {
- const { result } = renderHook(() => useRefreshPluginList())
-
- result.current.refreshPluginList(null)
-
- expect(mockInvalidateInstalledPluginList).toHaveBeenCalledTimes(1)
- expect(mockInvalidateAllToolProviders).not.toHaveBeenCalled()
- expect(mockInvalidateQueries).not.toHaveBeenCalled()
- expect(mockInvalidateAllDataSources).not.toHaveBeenCalled()
- expect(mockInvalidateAllTriggerPlugins).not.toHaveBeenCalled()
- expect(mockInvalidateStrategyProviders).not.toHaveBeenCalled()
- })
-
- it('should not refresh unrelated categories for a specific manifest', () => {
- const { result } = renderHook(() => useRefreshPluginList())
-
- result.current.refreshPluginList({ category: PluginCategoryEnum.tool } as never)
-
- expect(mockInvalidateAllToolProviders).toHaveBeenCalledTimes(1)
- expect(mockInvalidateQueries).not.toHaveBeenCalled()
- expect(mockInvalidateAllDataSources).not.toHaveBeenCalled()
- expect(mockInvalidateAllTriggerPlugins).not.toHaveBeenCalled()
- expect(mockInvalidateStrategyProviders).not.toHaveBeenCalled()
+ expect(mocks.installed).toHaveBeenCalledWith(category)
+ for (const key of strategyKeys) expect(client.getQueryState(key)?.isInvalidated).toBe(false)
+ if (category === PluginCategoryEnum.tool) {
+ expect(mocks.toolProviders).toHaveBeenCalledOnce()
+ expect(mocks.builtInTools).toHaveBeenCalledOnce()
+ expect(mocks.recommended).toHaveBeenCalledWith('tool')
+ }
+ if (category === PluginCategoryEnum.datasource) {
+ expect(mocks.dataSources).toHaveBeenCalledOnce()
+ expect(mocks.dataSourceAuth).toHaveBeenCalledOnce()
+ }
+ if (category === PluginCategoryEnum.trigger) expect(mocks.triggers).toHaveBeenCalledOnce()
+ },
+ )
+
+ it.each([false, true])('refreshes model data and defaults; all categories = %s', async (all) => {
+ const { result } = renderHook(useRefreshPluginList, { wrapper })
+
+ act(() => result.current.refreshPluginList({ category: PluginCategoryEnum.model }, all))
+
+ await waitFor(() => expect(mocks.request).toHaveBeenCalledTimes(modelTypes.length))
+ for (const modelType of modelTypes) {
+ expect(
+ mocks.request.mock.calls.some(([url]) => url.endsWith(`/model-types/${modelType}`)),
+ ).toBe(true)
+ expect(mocks.defaultModel).toHaveBeenCalledWith(modelType)
+ }
+ for (const key of providerKeys) expect(client.getQueryState(key)?.isInvalidated).toBe(true)
+ for (const key of strategyKeys) expect(client.getQueryState(key)?.isInvalidated).toBe(all)
+ expect(client.getQueryState(unrelatedKey)?.isInvalidated).toBe(false)
+ if (all) {
+ expect(mocks.installed).toHaveBeenCalledWith()
+ expect(mocks.toolProviders).toHaveBeenCalledOnce()
+ expect(mocks.builtInTools).toHaveBeenCalledOnce()
+ expect(mocks.dataSources).toHaveBeenCalledOnce()
+ expect(mocks.dataSourceAuth).toHaveBeenCalledOnce()
+ expect(mocks.triggers).toHaveBeenCalledOnce()
+ expect(mocks.recommended).toHaveBeenCalledWith('tool')
+ }
})
-})
-vi.mock('@tanstack/react-query', async (importOriginal) => {
- const actual = await importOriginal<typeof import('@tanstack/react-query')>()
- return {
- ...actual,
- useQueryClient: () => ({ invalidateQueries: mockInvalidateQueries }),
- useQuery: (options: {
- queryKey: OperationKey<
- 'query',
- { params: GetWorkspacesCurrentModelsModelTypesByModelTypeData['path'] }
- >
- }) => {
- if (!options.queryKey[0].includes('modelTypes')) return actual.useQuery(options)
-
- const type = options.queryKey[1].input?.params?.model_type
- if (!type) throw new Error('Missing model type in query')
- const map: Record<string, { refetch: ReturnType<typeof vi.fn> }> = {
- llm: { refetch: mockRefetchLLMModelList },
- 'text-embedding': { refetch: mockRefetchEmbeddingModelList },
- rerank: { refetch: mockRefetchRerankModelList },
- speech2text: { refetch: mockRefetchSpeech2textModelList },
- tts: { refetch: mockRefetchTTSModelList },
- }
- return map[type] ?? { refetch: vi.fn() }
+ it.each([null, undefined])(
+ 'only refreshes installation caches without a manifest (%s)',
+ (manifest) => {
+ const { result } = renderHook(useRefreshPluginList, { wrapper })
+
+ act(() => result.current.refreshPluginList(manifest))
+
+ expect(mocks.installed).toHaveBeenCalledWith()
+ expect(mocks.checkInstalled).toHaveBeenCalledOnce()
+ for (const key of [...strategyKeys, ...providerKeys])
+ expect(client.getQueryState(key)?.isInvalidated).toBe(false)
+ expect(mocks.toolProviders).not.toHaveBeenCalled()
+ expect(mocks.dataSources).not.toHaveBeenCalled()
+ expect(mocks.triggers).not.toHaveBeenCalled()
+ expect(mocks.request).not.toHaveBeenCalled()
},
- }
+ )
})
diff --git a/web/app/components/plugins/install-plugin/hooks/use-refresh-plugin-list.tsx b/web/app/components/plugins/install-plugin/hooks/use-refresh-plugin-list.tsx
index 06841cfc43b..dfb18177b3c 100644
--- a/web/app/components/plugins/install-plugin/hooks/use-refresh-plugin-list.tsx
+++ b/web/app/components/plugins/install-plugin/hooks/use-refresh-plugin-list.tsx
@@ -10,7 +10,6 @@ import {
useInvalidateCheckInstalled,
useInvalidateInstalledPluginList,
} from '@/service/use-plugins'
-import { useInvalidateStrategyProviders } from '@/service/use-strategy'
import {
useInvalidateAllBuiltInTools,
useInvalidateAllToolProviders,
@@ -68,8 +67,6 @@ const useRefreshPluginList = () => {
const invalidateDataSourceListAuth = useInvalidDataSourceListAuth()
- const invalidateStrategyProviders = useInvalidateStrategyProviders()
-
const invalidateAllTriggerPlugins = useInvalidateAllTriggerPlugins()
const invalidateRAGRecommendedPlugins = useInvalidateRAGRecommendedPlugins()
@@ -117,8 +114,14 @@ const useRefreshPluginList = () => {
}
// agent select
- if ((manifest && PluginCategoryEnum.agent.includes(manifest.category)) || refreshAllType)
- invalidateStrategyProviders()
+ if ((manifest && PluginCategoryEnum.agent.includes(manifest.category)) || refreshAllType) {
+ queryClient.invalidateQueries({
+ queryKey: consoleQuery.workspaces.current.agentProviders.get.key(),
+ })
+ queryClient.invalidateQueries({
+ queryKey: consoleQuery.workspaces.current.agentProvider.byProviderName.get.key(),
+ })
+ }
},
}
}
diff --git a/web/app/components/plugins/plugin-detail-panel/__tests__/strategy-detail.spec.tsx b/web/app/components/plugins/plugin-detail-panel/__tests__/strategy-detail.spec.tsx
index 414d418b2f7..a2f7a13b170 100644
--- a/web/app/components/plugins/plugin-detail-panel/__tests__/strategy-detail.spec.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/__tests__/strategy-detail.spec.tsx
@@ -1,221 +1,97 @@
-import type { StrategyDetail as StrategyDetailType } from '@/app/components/plugins/types'
-import { fireEvent, render, screen } from '@testing-library/react'
-import userEvent from '@testing-library/user-event'
-import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import type {
+ AgentStrategyEntity,
+ AgentStrategyProviderIdentity,
+} from '@dify/contracts/api/console/workspaces/types.gen'
+import { render, screen, within } from '@testing-library/react'
+import { describe, expect, it, vi } from 'vite-plus/test'
import StrategyDetail from '../strategy-detail'
-vi.mock('@/hooks/use-i18n', () => ({
- useRenderI18nObject: () => (obj: Record<string, string>) => obj?.en_US || '',
-}))
-
-vi.mock('@langgenius/dify-ui/cn', () => ({
- cn: (...args: (string | undefined | false | null)[]) => args.filter(Boolean).join(' '),
-}))
-
-vi.mock('@/app/components/plugins/card/base/card-icon', () => ({
- default: () => <span data-testid="card-icon" />,
-}))
-
-vi.mock('@/app/components/plugins/card/base/description', () => ({
- default: ({ text }: { text: string }) => <div data-testid="description">{text}</div>,
-}))
-
-type ProviderType = Parameters<typeof StrategyDetail>[0]['provider']
-
-const mockProvider = {
+const provider: AgentStrategyProviderIdentity = {
author: 'test-author',
name: 'test-provider',
- description: { en_US: 'Provider desc' },
- tenant_id: 'tenant-1',
+ description: { en_US: 'Provider description' },
icon: 'icon.png',
label: { en_US: 'Test Provider' },
- tags: [],
-} as unknown as ProviderType
+}
-const mockDetail = {
+const createStrategy = (): AgentStrategyEntity => ({
identity: {
author: 'author-1',
name: 'strategy-1',
- icon: 'icon.png',
label: { en_US: 'Strategy Label' },
provider: 'provider-1',
},
+ description: { en_US: 'Strategy description' },
parameters: [
{
- name: 'param1',
- label: { en_US: 'Parameter 1' },
- type: 'text-input',
+ name: 'query',
+ label: { en_US: 'Search query' },
+ type: 'string',
required: true,
- human_description: { en_US: 'A text parameter' },
+ help: { en_US: 'A text parameter' },
},
+ { name: 'count', label: { en_US: 'Result count' }, type: 'number' },
+ { name: 'enabled', label: { en_US: 'Enabled' }, type: 'boolean', help: null },
+ { name: 'file', label: { en_US: 'Input file' }, type: 'file' },
+ { name: 'tools', label: { en_US: 'Tools' }, type: 'array[tools]' },
],
- description: { en_US: 'Strategy description' },
output_schema: {
properties: {
result: { type: 'string', description: 'Result output' },
items: { type: 'array', items: { type: 'string' }, description: 'Array items' },
},
},
- features: [],
-} as unknown as StrategyDetailType
-
-describe('StrategyDetail', () => {
- const mockOnHide = vi.fn()
-
- beforeEach(() => {
- vi.clearAllMocks()
- })
-
- describe('Rendering', () => {
- it('should render drawer', () => {
- render(<StrategyDetail provider={mockProvider} detail={mockDetail} onHide={mockOnHide} />)
-
- const dialog = screen.getByRole('dialog')
-
- expect(dialog)!.toBeInTheDocument()
- expect(dialog).toHaveClass(
- 'data-[swipe-direction=right]:top-2',
- 'data-[swipe-direction=right]:bottom-2',
- 'data-[swipe-direction=right]:h-[calc(100dvh-16px)]',
- 'data-[swipe-direction=right]:w-100',
- 'data-[swipe-direction=right]:max-w-[calc(100vw-1rem)]',
- )
- })
-
- it('should render provider label', () => {
- render(<StrategyDetail provider={mockProvider} detail={mockDetail} onHide={mockOnHide} />)
-
- expect(screen.getByText('Test Provider'))!.toBeInTheDocument()
- })
-
- it('should render strategy label', () => {
- render(<StrategyDetail provider={mockProvider} detail={mockDetail} onHide={mockOnHide} />)
-
- expect(screen.getByText('Strategy Label'))!.toBeInTheDocument()
- })
-
- it('should render parameters section', () => {
- render(<StrategyDetail provider={mockProvider} detail={mockDetail} onHide={mockOnHide} />)
-
- expect(screen.getByText('tools.setBuiltInTools.parameters'))!.toBeInTheDocument()
- expect(screen.getByText('Parameter 1'))!.toBeInTheDocument()
- })
-
- it('should render output schema section', () => {
- render(<StrategyDetail provider={mockProvider} detail={mockDetail} onHide={mockOnHide} />)
-
- expect(screen.getByText('OUTPUT'))!.toBeInTheDocument()
- expect(screen.getByText('result'))!.toBeInTheDocument()
- expect(screen.getByText('String'))!.toBeInTheDocument()
- })
-
- it('should render BACK button', () => {
- render(<StrategyDetail provider={mockProvider} detail={mockDetail} onHide={mockOnHide} />)
-
- expect(screen.getByText('BACK'))!.toBeInTheDocument()
- })
- })
-
- describe('User Interactions', () => {
- it('should call onHide when close button clicked', async () => {
- const user = userEvent.setup()
-
- render(<StrategyDetail provider={mockProvider} detail={mockDetail} onHide={mockOnHide} />)
-
- await user.click(screen.getByRole('button', { name: /operation\.close|close/i }))
-
- expect(mockOnHide).toHaveBeenCalledTimes(1)
- })
-
- it('should call onHide when BACK clicked', () => {
- render(<StrategyDetail provider={mockProvider} detail={mockDetail} onHide={mockOnHide} />)
-
- fireEvent.click(screen.getByText('BACK'))
+})
- expect(mockOnHide).toHaveBeenCalledTimes(1)
- })
+const renderDetails = (detail: AgentStrategyEntity) =>
+ render(
+ <StrategyDetail provider={provider} tenantId="tenant-1" detail={detail} onHide={vi.fn()} />,
+ )
+
+describe('Strategy details contract', () => {
+ it('displays API parameter types and help alongside output schema descriptions', () => {
+ renderDetails(createStrategy())
+ const drawer = within(screen.getByRole('dialog', { name: 'Strategy Label' }))
+
+ expect(drawer.getByText('Search query')).toBeInTheDocument()
+ expect(drawer.getByText('tools.setBuiltInTools.string')).toBeInTheDocument()
+ expect(drawer.getByText('tools.setBuiltInTools.required')).toBeInTheDocument()
+ expect(drawer.getByText('A text parameter')).toBeInTheDocument()
+ expect(drawer.getByText('tools.setBuiltInTools.number')).toBeInTheDocument()
+ expect(drawer.getByText('boolean')).toBeInTheDocument()
+ expect(drawer.getByText('tools.setBuiltInTools.file')).toBeInTheDocument()
+ expect(drawer.getByText('multiple-tool-select')).toBeInTheDocument()
+ expect(drawer.getByText('String')).toBeInTheDocument()
+ expect(drawer.getByText('Array[String]')).toBeInTheDocument()
+ expect(drawer.getByText('Result output')).toBeInTheDocument()
+ expect(drawer.getByText('Array items')).toBeInTheDocument()
})
- describe('Parameter Types', () => {
- it('should display correct type for number-input', () => {
- const detailWithNumber = {
- ...mockDetail,
- parameters: [{ ...mockDetail.parameters[0]!, type: 'number-input' }],
- }
- render(
- <StrategyDetail provider={mockProvider} detail={detailWithNumber} onHide={mockOnHide} />,
- )
-
- expect(screen.getByText('tools.setBuiltInTools.number'))!.toBeInTheDocument()
- })
-
- it('should display correct type for checkbox', () => {
- const detailWithCheckbox = {
- ...mockDetail,
- parameters: [{ ...mockDetail.parameters[0]!, type: 'checkbox' }],
- }
- render(
- <StrategyDetail provider={mockProvider} detail={detailWithCheckbox} onHide={mockOnHide} />,
- )
+ it('accepts optional parameters and a null output schema', () => {
+ renderDetails({ ...createStrategy(), parameters: undefined, output_schema: null })
- expect(screen.getByText('boolean'))!.toBeInTheDocument()
- })
-
- it('should display correct type for file', () => {
- const detailWithFile = {
- ...mockDetail,
- parameters: [{ ...mockDetail.parameters[0]!, type: 'file' }],
- }
- render(<StrategyDetail provider={mockProvider} detail={detailWithFile} onHide={mockOnHide} />)
-
- expect(screen.getByText('tools.setBuiltInTools.file'))!.toBeInTheDocument()
- })
-
- it('should display correct type for array[tools]', () => {
- const detailWithArrayTools = {
- ...mockDetail,
- parameters: [{ ...mockDetail.parameters[0]!, type: 'array[tools]' }],
- }
- render(
- <StrategyDetail
- provider={mockProvider}
- detail={detailWithArrayTools}
- onHide={mockOnHide}
- />,
- )
-
- expect(screen.getByText('multiple-tool-select'))!.toBeInTheDocument()
- })
-
- it('should display original type for unknown types', () => {
- const detailWithUnknown = {
- ...mockDetail,
- parameters: [{ ...mockDetail.parameters[0]!, type: 'custom-type' }],
- }
- render(
- <StrategyDetail provider={mockProvider} detail={detailWithUnknown} onHide={mockOnHide} />,
- )
-
- expect(screen.getByText('custom-type'))!.toBeInTheDocument()
- })
+ expect(screen.getByRole('dialog', { name: 'Strategy Label' })).toBeInTheDocument()
+ expect(screen.queryByText('Search query')).not.toBeInTheDocument()
+ expect(screen.queryByText('OUTPUT')).not.toBeInTheDocument()
})
- describe('Edge Cases', () => {
- it('should handle empty parameters', () => {
- const detailEmpty = { ...mockDetail, parameters: [] }
- render(<StrategyDetail provider={mockProvider} detail={detailEmpty} onHide={mockOnHide} />)
-
- expect(screen.getByText('tools.setBuiltInTools.parameters'))!.toBeInTheDocument()
+ it('safely displays JSON schema properties that do not declare a simple type', () => {
+ renderDetails({
+ ...createStrategy(),
+ output_schema: {
+ properties: {
+ unconstrained: true,
+ reference: { $ref: '#/$defs/result' },
+ union: { type: ['string', 'null'] },
+ tuple: { type: 'array', prefixItems: [{ type: 'number' }] },
+ },
+ },
})
- it('should handle no output schema', () => {
- const detailNoOutput = {
- ...mockDetail,
- output_schema: undefined as unknown as Record<string, unknown>,
- }
- render(<StrategyDetail provider={mockProvider} detail={detailNoOutput} onHide={mockOnHide} />)
-
- expect(screen.queryByText('OUTPUT')).not.toBeInTheDocument()
- })
+ expect(screen.getByText('unconstrained')).toBeInTheDocument()
+ expect(screen.getByText('reference')).toBeInTheDocument()
+ expect(screen.getByText('union')).toBeInTheDocument()
+ expect(screen.getAllByText('Unknown')).toHaveLength(3)
+ expect(screen.getByText('Array[Unknown]')).toBeInTheDocument()
})
})
diff --git a/web/app/components/plugins/plugin-detail-panel/__tests__/strategy-item.spec.tsx b/web/app/components/plugins/plugin-detail-panel/__tests__/strategy-item.spec.tsx
index c6b61ccccc3..b434a219202 100644
--- a/web/app/components/plugins/plugin-detail-panel/__tests__/strategy-item.spec.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/__tests__/strategy-item.spec.tsx
@@ -1,60 +1,138 @@
-import type { ComponentProps } from 'react'
-import type { StrategyDetail } from '@/app/components/plugins/types'
-import { fireEvent, render, screen } from '@testing-library/react'
-import { describe, expect, it, vi } from 'vite-plus/test'
-import StrategyItem from '../strategy-item'
-
-vi.mock('@/hooks/use-i18n', () => ({
- useRenderI18nObject: () => (value: Record<string, string>) => value.en_US || '',
-}))
+import type {
+ AgentProviderResponse,
+ AgentStrategyEntity,
+ AgentStrategyProviderIdentity,
+} from '@dify/contracts/api/console/workspaces/types.gen'
+import { screen, waitFor, within } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import { normalizeInstalledPluginDetail } from '@/service/use-plugins'
+import { renderWithConsoleQuery as render } from '@/test/console/query-data'
+import AgentStrategyList from '../agent-strategy-list'
-vi.mock('../strategy-detail', () => ({
- default: ({ onHide }: { onHide: () => void }) => (
- <div data-testid="strategy-detail-panel">
- <button onClick={onHide}>Close details</button>
- </div>
- ),
+const { request } = vi.hoisted(() => ({ request: vi.fn() }))
+vi.mock('@/service/base', () => ({ request }))
+vi.mock('#i18n', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('#i18n')>()),
+ useLocale: () => 'zh-Hans',
}))
-const provider = {
+const provider: AgentStrategyProviderIdentity = {
author: 'test-author',
name: 'test-provider',
- description: { en_US: 'Provider description' },
- tenant_id: 'tenant-1',
+ description: { en_US: 'Provider description', zh_Hans: null },
icon: 'icon.png',
- label: { en_US: 'Test Provider' },
- tags: [],
-} as unknown as ComponentProps<typeof StrategyItem>['provider']
+ label: { en_US: 'Test Provider', zh_Hans: null },
+ tags: null,
+}
-const detail = {
+const strategy: AgentStrategyEntity = {
identity: {
author: 'author-1',
name: 'strategy-1',
- icon: 'icon.png',
- label: { en_US: 'Strategy Label' },
+ label: { en_US: 'Strategy Label', zh_Hans: null },
provider: 'provider-1',
},
- parameters: [],
- description: { en_US: 'Strategy description' },
- output_schema: {},
- features: [],
-} as unknown as StrategyDetail
-
-describe('StrategyItem', () => {
- it('shows the localized strategy summary', () => {
- render(<StrategyItem provider={provider} detail={detail} />)
-
- expect(screen.getByText('Strategy Label')).toBeInTheDocument()
- expect(screen.getByText('Strategy description')).toBeInTheDocument()
+ description: { en_US: 'Strategy description', zh_Hans: null },
+ parameters: [
+ { name: 'query', type: 'string', label: { en_US: 'Query' }, help: { en_US: 'Search text' } },
+ ],
+}
+
+const plugin = normalizeInstalledPluginDetail({
+ id: 'test-id',
+ created_at: '2024-01-01',
+ updated_at: '2024-01-02',
+ plugin_id: 'test-plugin',
+ plugin_unique_identifier: 'test-uid',
+ tenant_id: 'tenant-1',
+ endpoints_setups: 0,
+ endpoints_active: 0,
+ version: '1.0.0',
+ source: 'marketplace',
+ runtime_type: 'local',
+ checksum: 'checksum',
+ meta: {},
+ declaration: {
+ version: '1.0.0',
+ author: 'Dify',
+ name: 'Test Plugin',
+ category: 'agent-strategy',
+ created_at: '2024-01-01',
+ icon: 'plugin.svg',
+ label: { en_US: 'Test Plugin' },
+ description: { en_US: 'Strategy plugin' },
+ resource: {},
+ plugins: {},
+ meta: {},
+ agent_strategy: { identity: provider },
+ },
+})
+
+const createResponse = (): AgentProviderResponse => ({
+ declaration: {
+ identity: { ...provider, name: 'test-plugin/test-provider' },
+ strategies: [
+ { ...strategy, identity: { ...strategy.identity, provider: 'test-plugin/test-provider' } },
+ ],
+ },
+ meta: {},
+ plugin_id: 'test-plugin',
+ plugin_unique_identifier: 'test-uid',
+ provider: 'test-provider',
+})
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ request.mockImplementation(async () => Response.json(createResponse()))
+})
+
+describe('Plugin agent strategies', () => {
+ it('loads the provider and opens and closes its real strategy drawer with localized fallback', async () => {
+ const user = userEvent.setup()
+ const requests: string[] = []
+ request.mockImplementation(async (url: string) => {
+ requests.push(decodeURIComponent(new URL(url).pathname))
+ return Response.json(createResponse())
+ })
+ render(<AgentStrategyList detail={plugin} />)
+
+ await user.click(await screen.findByText('Strategy Label'))
+ const drawer = await screen.findByRole('dialog', { name: 'Strategy Label' })
+ expect(within(drawer).getByText('Test Provider')).toBeInTheDocument()
+ expect(within(drawer).getByText('Query')).toBeInTheDocument()
+ expect(within(drawer).getByText('Search text')).toBeInTheDocument()
+ expect(requests).toEqual([
+ expect.stringMatching(/\/workspaces\/current\/agent-provider\/test-plugin\/test-provider$/),
+ ])
+
+ await user.click(within(drawer).getByRole('button', { name: 'common.operation.close' }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ await user.click(screen.getByText('Strategy Label'))
+ await user.click(screen.getByText('BACK'))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
})
- it('opens and closes the strategy details', () => {
- render(<StrategyItem provider={provider} detail={detail} />)
+ it('allows an empty provider declaration without fabricating strategies', async () => {
+ const response = createResponse()
+ response.declaration.strategies = undefined
+ request.mockImplementation(async () => Response.json(response))
+ render(<AgentStrategyList detail={plugin} />)
+
+ expect(
+ await screen.findByText('plugin.detailPanel.strategyNum:{"num":0,"strategy":"strategy"}'),
+ ).toBeInTheDocument()
+ expect(screen.queryByText('Strategy Label')).not.toBeInTheDocument()
+ })
- fireEvent.click(screen.getByText('Strategy Label'))
- expect(screen.getByTestId('strategy-detail-panel')).toBeInTheDocument()
+ it('does not request a provider when the plugin has no strategy declaration', () => {
+ render(
+ <AgentStrategyList
+ detail={{ ...plugin, declaration: { ...plugin.declaration, agent_strategy: null } }}
+ />,
+ )
- fireEvent.click(screen.getByRole('button', { name: 'Close details' }))
- expect(screen.queryByTestId('strategy-detail-panel')).not.toBeInTheDocument()
+ expect(request).not.toHaveBeenCalled()
+ expect(screen.queryByText(/plugin.detailPanel.strategyNum/)).not.toBeInTheDocument()
})
})
diff --git a/web/app/components/plugins/plugin-detail-panel/agent-strategies.md b/web/app/components/plugins/plugin-detail-panel/agent-strategies.md
new file mode 100644
index 00000000000..cf781517cc1
--- /dev/null
+++ b/web/app/components/plugins/plugin-detail-panel/agent-strategies.md
@@ -0,0 +1,96 @@
+# Agent strategies
+
+The plugin detail panel, workflow strategy selector, and agent node configuration
+consume generated Console options directly. The agent provider list and detail
+share the backend contract across these surfaces; neither a service hook nor a
+frontend response DTO owns a second version of that contract.
+
+## API and type ownership
+
+[Agent provider controllers] own the HTTP list and detail schemas, authentication,
+and tenant admission. Their response models use `PluginAgentProviderEntity`, the
+[plugin daemon model] already returned by `AgentService`. The generated
+`AgentProviderResponse`, `AgentStrategyEntity`, and `AgentStrategyParameter` types
+flow to their consumers without assertions that widen or narrow the response.
+When this API changes, update its Python owner and regenerate TypeScript, Zod,
+and OpenAPI Markdown together. The installed-plugin response contains a dynamic
+manifest; its strategy declaration is parsed once with the generated Zod schema
+at that existing boundary, so the plugin detail query never takes its provider
+name from `any`.
+
+Generated optional and nullable fields remain optional and nullable. Rendering
+owners supply display fallbacks; they do not rewrite cached responses into a
+second DTO. Localized labels use the i18n renderer. The generic credential form
+accepts its own presentation schema, so the agent form owns that conversion and
+retains typed parameter defaults, constraints, and field behavior, including
+one-sided numeric bounds. Open JSON schema values are narrowed at their rendering
+boundary; properties with boolean or unresolved schemas still display as unknown.
+
+[Parameter initialization] owns execution-time defaults: missing, null, and empty
+string inputs use the declaration default, while explicit `0` and `false` remain
+values. Required defaults of `0` and `false` are valid too. Workflow validation
+follows that rule. Editing may temporarily contain an empty input; do not force a
+default back into every keystroke or lose the existing field's clearing behavior.
+
+Strategy selection passes the fetched provider and strategy directly to the
+agent-owned list. Only presentation helpers such as alphabetical grouping are
+shared with other provider catalogs. Workflow state keeps the selected strategy's
+output schema and the provider's plugin metadata without a Tool DTO intermediary. Saved nodes can lack a
+plugin installation identifier; they still display and edit their selected
+provider/strategy. Only installation and version-switch actions require that
+identifier.
+
+## Queries and freshness
+
+| Call site | Decision |
+| ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Plugin detail | Query the selected provider using its generated route input; disable the query when the provider is absent. Inherit normal query retries. |
+| Strategy selector | Query the generated provider list while mounted; pass raw providers to the agent-owned list for display and selection. |
+| Workflow checklist | Use the same provider list cache when checking installed strategies. |
+| Agent node configuration | Query provider detail only when a provider is selected. Keep `retry: false` here because the error state participates in the node's installation status. |
+
+All these queries inherit the existing QueryClient's five-minute freshness.
+There is no strategy-specific `query-policies.ts` override, redundant locale key,
+or custom polling policy. Provider names, including names containing slashes,
+are part of generated route input and therefore cache identity. A missing
+provider uses `skipToken`; an empty identifier is not a substitute request.
+
+## Installation invalidation
+
+There is no strategy mutation in this API. [Plugin installation refresh] owns the
+completion event from install, upgrade, and uninstall workflows. For an agent
+plugin, or an explicit refresh of every category, it invalidates both the provider
+list and every provider detail using their generated keys. Refreshing only the
+list would leave an open agent node or plugin detail using an outdated declaration.
+Other categories do not invalidate strategy data. An absent manifest retains the
+existing installed-list-only behavior unless the caller requests all categories.
+
+This event hook owns category orchestration. It is not a forwarding wrapper
+around a strategy query, and no additional invalidation helper is needed.
+
+## Persisted workflow boundary
+
+A current fetched declaration determines available parameter types. The backend
+contract does not support `tool-selector`; it is not a valid strategy API variant.
+Persisted workflow values have a separate lifecycle: existing `array[tools]`
+conversion and `tool_node_version` handling remain at the agent node owner.
+Removing obsolete response DTOs must not discard legitimate saved values.
+
+Workflow variable discovery uses the existing JSON Schema-to-`VarType` resolver.
+Display labels such as `String` and `Unknown` are not internal variable types:
+string outputs use `VarType.string`, and unconstrained properties use `VarType.any`.
+This keeps the variable picker's type filters consistent with strategy outputs.
+
+## Verification
+
+Controller and schema tests protect real daemon response serialization, nullable
+fields, scalar defaults, and invalid parameter variants. Consumer tests exercise
+generated requests, missing-provider behavior, selection, and form state.
+Installation refresh tests use a real QueryClient to check both list and detail
+invalidation and isolation from unrelated categories. Coverage percentage is not
+an acceptance criterion.
+
+[Agent provider controllers]: ../../../../../api/controllers/console/workspace/agent_providers.py
+[Parameter initialization]: ../../../../../api/core/plugin/entities/parameters.py
+[Plugin installation refresh]: ../install-plugin/hooks/use-refresh-plugin-list.tsx
+[plugin daemon model]: ../../../../../api/core/plugin/entities/plugin_daemon.py
diff --git a/web/app/components/plugins/plugin-detail-panel/agent-strategy-list.tsx b/web/app/components/plugins/plugin-detail-panel/agent-strategy-list.tsx
index 417afddc753..884a3cec0c5 100644
--- a/web/app/components/plugins/plugin-detail-panel/agent-strategy-list.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/agent-strategy-list.tsx
@@ -1,9 +1,9 @@
import type { PluginDetail } from '@/app/components/plugins/types'
+import { skipToken, useQuery } from '@tanstack/react-query'
import * as React from 'react'
-import { useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import StrategyItem from '@/app/components/plugins/plugin-detail-panel/strategy-item'
-import { useStrategyProviderDetail } from '@/service/use-strategy'
+import { consoleQuery } from '@/service/console'
type Props = Readonly<{
detail: PluginDetail
@@ -11,24 +11,17 @@ type Props = Readonly<{
const AgentStrategyList = ({ detail }: Props) => {
const { t } = useTranslation()
- const providerBriefInfo = detail.declaration.agent_strategy.identity
- const providerKey = `${detail.plugin_id}/${providerBriefInfo.name}`
- const { data: strategyProviderDetail } = useStrategyProviderDetail(providerKey)
-
- const providerDetail = useMemo(() => {
- return {
- ...strategyProviderDetail?.declaration.identity,
- tenant_id: detail.tenant_id,
- }
- }, [detail.tenant_id, strategyProviderDetail?.declaration.identity])
-
- const strategyList = useMemo(() => {
- if (!strategyProviderDetail) return []
-
- return strategyProviderDetail.declaration.strategies
- }, [strategyProviderDetail])
+ const providerName = detail.declaration.agent_strategy?.identity.name
+ const { data: strategyProviderDetail } = useQuery(
+ consoleQuery.workspaces.current.agentProvider.byProviderName.get.queryOptions({
+ input: providerName
+ ? { params: { provider_name: `${detail.plugin_id}/${providerName}` } }
+ : skipToken,
+ }),
+ )
if (!strategyProviderDetail) return null
+ const strategyList = strategyProviderDetail.declaration.strategies ?? []
return (
<div className="px-4 pt-2 pb-4">
@@ -45,7 +38,8 @@ const AgentStrategyList = ({ detail }: Props) => {
{strategyList.map((strategyDetail) => (
<StrategyItem
key={`${strategyDetail.identity.provider}${strategyDetail.identity.name}`}
- provider={providerDetail as any}
+ provider={strategyProviderDetail.declaration.identity}
+ tenantId={detail.tenant_id}
detail={strategyDetail}
/>
))}
diff --git a/web/app/components/plugins/plugin-detail-panel/strategy-detail.tsx b/web/app/components/plugins/plugin-detail-panel/strategy-detail.tsx
index 40eca945b9f..e8a69850a23 100644
--- a/web/app/components/plugins/plugin-detail-panel/strategy-detail.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/strategy-detail.tsx
@@ -1,9 +1,11 @@
'use client'
+import type {
+ AgentStrategyEntity,
+ AgentStrategyParameterType,
+ AgentStrategyProviderIdentity,
+} from '@dify/contracts/api/console/workspaces/types.gen'
import type { FC } from 'react'
-import type { StrategyDetail as StrategyDetailType } from '@/app/components/plugins/types'
-import type { Locale } from '@/i18n/locale'
-import type { PluginLanguage } from '@/i18n/metadata'
import { cn } from '@langgenius/dify-ui/cn'
import {
Drawer,
@@ -11,6 +13,7 @@ import {
DrawerContent,
DrawerPopup,
DrawerPortal,
+ DrawerTitle,
DrawerViewport,
} from '@langgenius/dify-ui/drawer'
import { IconButton } from '@langgenius/dify-ui/icon-button'
@@ -25,44 +28,42 @@ import { API_PREFIX } from '@/config'
import { useRenderI18nObject } from '@/hooks/use-i18n'
type Props = Readonly<{
- provider: {
- author: string
- name: string
- description: Record<Locale | PluginLanguage, string>
- tenant_id: string
- icon: string
- label: Record<Locale | PluginLanguage, string>
- tags: string[]
- }
- detail: StrategyDetailType
+ provider: AgentStrategyProviderIdentity
+ tenantId: string
+ detail: AgentStrategyEntity
onHide: () => void
}>
-const StrategyDetail: FC<Props> = ({ provider, detail, onHide }) => {
+const isSchemaObject = (value: unknown): value is Record<string, unknown> =>
+ typeof value === 'object' && value !== null && !Array.isArray(value)
+
+const getOutputType = (schema: unknown): string => {
+ if (!isSchemaObject(schema)) return 'Unknown'
+ if (schema.type === 'array') return `Array[${getOutputType(schema.items)}]`
+ if (typeof schema.type !== 'string' || !schema.type) return 'Unknown'
+ return schema.type.slice(0, 1).toLocaleUpperCase() + schema.type.slice(1)
+}
+
+const StrategyDetail: FC<Props> = ({ provider, tenantId, detail, onHide }) => {
const getValueFromI18nObject = useRenderI18nObject()
const { t } = useTranslation()
const outputSchema = useMemo(() => {
- const res: any[] = []
- if (!detail.output_schema || !detail.output_schema.properties) return []
- Object.keys(detail.output_schema.properties).forEach((outputKey) => {
- const output = detail.output_schema.properties[outputKey]
- res.push({
- name: outputKey,
- type:
- output.type === 'array'
- ? `Array[${output.items?.type ? output.items.type.slice(0, 1).toLocaleUpperCase() + output.items.type.slice(1) : 'Unknown'}]`
- : `${output.type ? output.type.slice(0, 1).toLocaleUpperCase() + output.type.slice(1) : 'Unknown'}`,
- description: output.description,
- })
- })
- return res
+ const properties = detail.output_schema?.properties
+ if (!isSchemaObject(properties)) return []
+ return Object.entries(properties).map(([name, output]) => ({
+ name,
+ type: getOutputType(output),
+ description:
+ isSchemaObject(output) && typeof output.description === 'string'
+ ? output.description
+ : undefined,
+ }))
}, [detail.output_schema])
- const getType = (type: string) => {
- if (type === 'number-input') return t(($) => $['setBuiltInTools.number'], { ns: 'tools' })
- if (type === 'text-input') return t(($) => $['setBuiltInTools.string'], { ns: 'tools' })
- if (type === 'checkbox') return 'boolean'
+ const getType = (type: AgentStrategyParameterType) => {
+ if (type === 'number') return t(($) => $['setBuiltInTools.number'], { ns: 'tools' })
+ if (type === 'string') return t(($) => $['setBuiltInTools.string'], { ns: 'tools' })
if (type === 'file') return t(($) => $['setBuiltInTools.file'], { ns: 'tools' })
if (type === 'array[tools]') return 'multiple-tool-select'
return type
@@ -107,13 +108,13 @@ const StrategyDetail: FC<Props> = ({ provider, detail, onHide }) => {
<Icon
size="tiny"
className="size-6"
- src={`${API_PREFIX}/workspaces/current/plugin/icon?tenant_id=${provider.tenant_id}&filename=${provider.icon}`}
+ src={`${API_PREFIX}/workspaces/current/plugin/icon?tenant_id=${tenantId}&filename=${provider.icon}`}
/>
<div className="">{getValueFromI18nObject(provider.label)}</div>
</div>
- <div className="mt-1 system-md-semibold text-text-primary">
+ <DrawerTitle className="mt-1 system-md-semibold text-text-primary">
{getValueFromI18nObject(detail.identity.label)}
- </div>
+ </DrawerTitle>
<Description
className="mt-3"
text={getValueFromI18nObject(detail.description)}
@@ -127,10 +128,10 @@ const StrategyDetail: FC<Props> = ({ provider, detail, onHide }) => {
{t(($) => $['setBuiltInTools.parameters'], { ns: 'tools' })}
</div>
<div className="px-4">
- {detail.parameters.length > 0 && (
+ {detail.parameters && detail.parameters.length > 0 && (
<div className="space-y-1 py-2">
- {detail.parameters.map((item: any, index) => (
- <div key={index} className="py-1">
+ {detail.parameters.map((item) => (
+ <div key={item.name} className="py-1">
<div className="flex items-center gap-2">
<div className="code-sm-semibold text-text-secondary">
{getValueFromI18nObject(item.label)}
@@ -144,9 +145,9 @@ const StrategyDetail: FC<Props> = ({ provider, detail, onHide }) => {
</div>
)}
</div>
- {item.human_description && (
+ {item.help && (
<div className="mt-0.5 system-xs-regular text-text-tertiary">
- {getValueFromI18nObject(item.human_description)}
+ {getValueFromI18nObject(item.help)}
</div>
)}
</div>
@@ -164,8 +165,8 @@ const StrategyDetail: FC<Props> = ({ provider, detail, onHide }) => {
</div>
{outputSchema.length > 0 && (
<div className="space-y-1 px-4 py-2">
- {outputSchema.map((outputItem, index) => (
- <div key={index} className="py-1">
+ {outputSchema.map((outputItem) => (
+ <div key={outputItem.name} className="py-1">
<div className="flex items-center gap-2">
<div className="code-sm-semibold text-text-secondary">
{outputItem.name}
diff --git a/web/app/components/plugins/plugin-detail-panel/strategy-item.tsx b/web/app/components/plugins/plugin-detail-panel/strategy-item.tsx
index 8201618dd62..b25fa81586f 100644
--- a/web/app/components/plugins/plugin-detail-panel/strategy-item.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/strategy-item.tsx
@@ -1,8 +1,9 @@
'use client'
-import type { StrategyDetail } from '@/app/components/plugins/types'
-import type { Locale } from '@/i18n/locale'
-import type { PluginLanguage } from '@/i18n/metadata'
+import type {
+ AgentStrategyEntity,
+ AgentStrategyProviderIdentity,
+} from '@dify/contracts/api/console/workspaces/types.gen'
import { cn } from '@langgenius/dify-ui/cn'
import * as React from 'react'
import { useState } from 'react'
@@ -10,19 +11,12 @@ import { useRenderI18nObject } from '@/hooks/use-i18n'
import StrategyDetailPanel from './strategy-detail'
type Props = Readonly<{
- provider: {
- author: string
- name: string
- description: Record<Locale | PluginLanguage, string>
- tenant_id: string
- icon: string
- label: Record<Locale | PluginLanguage, string>
- tags: string[]
- }
- detail: StrategyDetail
+ provider: AgentStrategyProviderIdentity
+ tenantId: string
+ detail: AgentStrategyEntity
}>
-const StrategyItem = ({ provider, detail }: Props) => {
+const StrategyItem = ({ provider, tenantId, detail }: Props) => {
const getValueFromI18nObject = useRenderI18nObject()
const [showDetail, setShowDetail] = useState(false)
@@ -44,6 +38,7 @@ const StrategyItem = ({ provider, detail }: Props) => {
{showDetail && (
<StrategyDetailPanel
provider={provider}
+ tenantId={tenantId}
detail={detail}
onHide={() => setShowDetail(false)}
/>
diff --git a/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/__tests__/index.spec.tsx b/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/__tests__/index.spec.tsx
index 75033df8f4b..a14ce189761 100644
--- a/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/__tests__/index.spec.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/subscription-list/edit/__tests__/index.spec.tsx
@@ -224,7 +224,7 @@ const createPluginDetail = (overrides: Partial<PluginDetail> = {}): PluginDetail
endpoint: { settings: [], endpoints: [] },
model: {},
tags: [],
- agent_strategy: {},
+ agent_strategy: null,
meta: { version: '1.0.0' },
trigger: {
events: [],
diff --git a/web/app/components/plugins/plugin-detail-panel/tool-selector/components/__tests__/reasoning-config-form.helpers.spec.ts b/web/app/components/plugins/plugin-detail-panel/tool-selector/components/__tests__/reasoning-config-form.helpers.spec.ts
index 3b49e1fea4a..478bd3cb19c 100644
--- a/web/app/components/plugins/plugin-detail-panel/tool-selector/components/__tests__/reasoning-config-form.helpers.spec.ts
+++ b/web/app/components/plugins/plugin-detail-panel/tool-selector/components/__tests__/reasoning-config-form.helpers.spec.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vite-plus/test'
import { FormTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
-import { VarType as VarKindType } from '@/app/components/workflow/nodes/tool/types'
+import { VarKindType } from '@/app/components/workflow/nodes/_base/types'
import { VarType } from '@/app/components/workflow/types'
import {
createFilterVar,
diff --git a/web/app/components/plugins/plugin-detail-panel/tool-selector/components/__tests__/reasoning-config-form.spec.tsx b/web/app/components/plugins/plugin-detail-panel/tool-selector/components/__tests__/reasoning-config-form.spec.tsx
index 998fdbee152..d876b89c007 100644
--- a/web/app/components/plugins/plugin-detail-panel/tool-selector/components/__tests__/reasoning-config-form.spec.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/tool-selector/components/__tests__/reasoning-config-form.spec.tsx
@@ -5,8 +5,8 @@ import { fireEvent, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import { FormTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
+import { VarKindType } from '@/app/components/workflow/nodes/_base/types'
import { Type } from '@/app/components/workflow/nodes/llm/types'
-import { VarType as VarKindType } from '@/app/components/workflow/nodes/tool/types'
import { renderWithAccountProfile as render } from '@/test/console/account-profile'
import ReasoningConfigForm from '../reasoning-config-form'
diff --git a/web/app/components/plugins/plugin-detail-panel/tool-selector/components/reasoning-config-form.helpers.ts b/web/app/components/plugins/plugin-detail-panel/tool-selector/components/reasoning-config-form.helpers.ts
index 7cf92a4bb58..b85df1eb2b4 100644
--- a/web/app/components/plugins/plugin-detail-panel/tool-selector/components/reasoning-config-form.helpers.ts
+++ b/web/app/components/plugins/plugin-detail-panel/tool-selector/components/reasoning-config-form.helpers.ts
@@ -3,7 +3,7 @@ import type { ToolFormSchema } from '@/app/components/tools/utils/to-form-schema
import type { ValueSelector, Var } from '@/app/components/workflow/types'
import { produce } from 'immer'
import { FormTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
-import { VarType as VarKindType } from '@/app/components/workflow/nodes/tool/types'
+import { VarKindType } from '@/app/components/workflow/nodes/_base/types'
import { VarType } from '@/app/components/workflow/types'
type ReasoningConfigInputValue = {
diff --git a/web/app/components/plugins/plugin-detail-panel/tool-selector/components/reasoning-config-form.tsx b/web/app/components/plugins/plugin-detail-panel/tool-selector/components/reasoning-config-form.tsx
index 64baa5b6b5d..562279343d1 100644
--- a/web/app/components/plugins/plugin-detail-panel/tool-selector/components/reasoning-config-form.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/tool-selector/components/reasoning-config-form.tsx
@@ -28,11 +28,11 @@ import CodeEditor from '@/app/components/workflow/nodes/_base/components/editor/
import FormInputBoolean from '@/app/components/workflow/nodes/_base/components/form-input-boolean'
import FormInputTypeSwitch from '@/app/components/workflow/nodes/_base/components/form-input-type-switch'
import VarReferencePicker from '@/app/components/workflow/nodes/_base/components/variable/var-reference-picker'
+import { VarKindType } from '@/app/components/workflow/nodes/_base/types'
import { CodeLanguage } from '@/app/components/workflow/nodes/code/types'
import MixedVariableTextInput from '@/app/components/workflow/nodes/tool/components/mixed-variable-text-input'
import ToolDatePicker from '@/app/components/workflow/nodes/tool/components/tool-date-picker'
import ToolDateRangePicker from '@/app/components/workflow/nodes/tool/components/tool-date-range-picker'
-import { VarType as VarKindType } from '@/app/components/workflow/nodes/tool/types'
import { userProfileQueryOptions } from '@/features/account-profile/client'
import {
createPickerProps,
diff --git a/web/app/components/plugins/plugin-detail-panel/tool-selector/components/tool-settings-panel.tsx b/web/app/components/plugins/plugin-detail-panel/tool-selector/components/tool-settings-panel.tsx
index ac2a84cd7dc..f350412bf36 100644
--- a/web/app/components/plugins/plugin-detail-panel/tool-selector/components/tool-settings-panel.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/tool-selector/components/tool-settings-panel.tsx
@@ -5,7 +5,7 @@ import type { ReasoningConfigValue } from './reasoning-config-form'
import type { CredentialFormSchema } from '@/app/components/header/account-setting/model-provider-page/declarations'
import type { ToolFormSchema } from '@/app/components/tools/utils/to-form-schema'
import type { ToolValue } from '@/app/components/workflow/block-selector/types'
-import type { ToolVarInputs } from '@/app/components/workflow/nodes/tool/types'
+import type { ResourceVarInputs } from '@/app/components/workflow/nodes/_base/types'
import type { NodeOutPutVar, ToolWithProvider } from '@/app/components/workflow/types'
import { Separator } from '@langgenius/dify-ui/separator'
import { Tabs, TabsList, TabsPanel, TabsTab } from '@langgenius/dify-ui/tabs'
@@ -20,14 +20,14 @@ type ToolSettingsPanelProps = {
currType: TabType
settingsFormSchemas: ToolFormSchema[]
paramsFormSchemas: ToolFormSchema[]
- settingsValue: ToolVarInputs
+ settingsValue: ResourceVarInputs
showTabSlider: boolean
userSettingsOnly: boolean
reasoningConfigOnly: boolean
nodeOutputVars: NodeOutPutVar[]
availableNodes: Node[]
onCurrTypeChange: (type: TabType) => void
- onSettingsFormChange: (v: ToolVarInputs) => void
+ onSettingsFormChange: (v: ResourceVarInputs) => void
onParamsFormChange: (v: ReasoningConfigValue) => void
}
diff --git a/web/app/components/plugins/types.ts b/web/app/components/plugins/types.ts
index 5a117d98335..21ff7784ace 100644
--- a/web/app/components/plugins/types.ts
+++ b/web/app/components/plugins/types.ts
@@ -1,4 +1,7 @@
-import type { EndpointProviderDeclarationResponse } from '@dify/contracts/api/console/workspaces/types.gen'
+import type {
+ AgentStrategyProviderEntity,
+ EndpointProviderDeclarationResponse,
+} from '@dify/contracts/api/console/workspaces/types.gen'
import type { FormTypeEnum } from '../base/form/types'
import type { CredentialFormSchemaBase } from '../header/account-setting/model-provider-page/declarations'
import type { AutoUpdateConfig } from './reference-setting-modal/auto-update-setting/types'
@@ -64,7 +67,7 @@ export type PluginDeclaration = {
datasource?: PluginToolDeclaration
model: any
tags: string[]
- agent_strategy: any
+ agent_strategy?: AgentStrategyProviderEntity | null
meta: PluginDeclarationMeta
trigger: PluginTriggerDefinition
}
@@ -477,44 +480,6 @@ export type VersionProps = {
toInstallVersion: string
}
-export type StrategyParamItem = {
- name: string
- label: Record<Locale | PluginLanguage, string>
- help: Record<Locale | PluginLanguage, string>
- placeholder: Record<Locale | PluginLanguage, string>
- type: string
- scope: string
- required: boolean
- default: any
- options: any[]
- template: {
- enabled: boolean
- }
- auto_generate: {
- type: string
- }
-}
-
-export type StrategyDetail = {
- identity: {
- author: string
- name: string
- icon: string
- label: Record<Locale | PluginLanguage, string>
- provider: string
- }
- parameters: StrategyParamItem[]
- description: Record<Locale | PluginLanguage, string>
- output_schema: Record<string, any>
- features: AgentFeature[]
-}
-
-const AgentFeature = {
- HISTORY_MESSAGES: 'history-messages',
-} as const
-
-type AgentFeature = (typeof AgentFeature)[keyof typeof AgentFeature]
-
type Identity = {
author: string
name: string
@@ -525,20 +490,6 @@ type Identity = {
tags: string[]
}
-type StrategyDeclaration = {
- identity: Identity
- plugin_id: string
- strategies: StrategyDetail[]
-}
-
export type PluginMeta = {
version: string // the version of dify sdk
}
-
-export type StrategyPluginDetail = {
- provider: string
- plugin_unique_identifier: string
- plugin_id: string
- declaration: StrategyDeclaration
- meta: PluginMeta
-}
diff --git a/web/app/components/plugins/update-plugin/__tests__/index.spec.tsx b/web/app/components/plugins/update-plugin/__tests__/index.spec.tsx
index 4f42635a1e9..1d0846cb192 100644
--- a/web/app/components/plugins/update-plugin/__tests__/index.spec.tsx
+++ b/web/app/components/plugins/update-plugin/__tests__/index.spec.tsx
@@ -131,7 +131,7 @@ const createMockPluginDeclaration = (
endpoint: { settings: [], endpoints: [] },
model: {},
tags: [],
- agent_strategy: {},
+ agent_strategy: null,
meta: { version: '1.0.0' },
trigger: {
events: [],
diff --git a/web/app/components/tools/utils/to-form-schema.ts b/web/app/components/tools/utils/to-form-schema.ts
index 25a50e7547e..bdaa5fe2e3e 100644
--- a/web/app/components/tools/utils/to-form-schema.ts
+++ b/web/app/components/tools/utils/to-form-schema.ts
@@ -3,7 +3,7 @@ import type { ToolCredential, ToolParameter } from '../types'
import type { TypeWithI18N } from '@/app/components/header/account-setting/model-provider-page/declarations'
import type { SchemaRoot } from '@/app/components/workflow/nodes/llm/types'
import { FormTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
-import { VarType as VarKindType } from '@/app/components/workflow/nodes/tool/types'
+import { VarKindType } from '@/app/components/workflow/nodes/_base/types'
// Type for form value input with type and value properties
type FormValueInput = {
diff --git a/web/app/components/workflow/__tests__/service-mock-factory.ts b/web/app/components/workflow/__tests__/service-mock-factory.ts
index 7998c154813..6129fe3fe77 100644
--- a/web/app/components/workflow/__tests__/service-mock-factory.ts
+++ b/web/app/components/workflow/__tests__/service-mock-factory.ts
@@ -49,10 +49,6 @@ type TriggerMockData = {
triggerPlugins?: unknown[]
}
-type StrategyMockData = {
- strategyProviders?: unknown[]
-}
-
export function createToolServiceMock(data?: ToolMockData) {
return {
useAllBuiltInTools: vi.fn(() => ({ data: data?.buildInTools ?? [] })),
@@ -67,9 +63,3 @@ export function createTriggerServiceMock(data?: TriggerMockData) {
useAllTriggerPlugins: vi.fn(() => ({ data: data?.triggerPlugins ?? [] })),
}
}
-
-export function createStrategyServiceMock(data?: StrategyMockData) {
- return {
- useStrategyProviders: vi.fn(() => ({ data: data?.strategyProviders ?? [] })),
- }
-}
diff --git a/web/app/components/workflow/block-selector/tool-list-data.ts b/web/app/components/workflow/block-selector/tool-list-data.ts
index 3b9a7e03707..035315a9c85 100644
--- a/web/app/components/workflow/block-selector/tool-list-data.ts
+++ b/web/app/components/workflow/block-selector/tool-list-data.ts
@@ -1,7 +1,7 @@
import type { DatasourceProviderType } from '@dify/contracts/api/console/workspaces/types.gen'
import type { ToolWithProvider } from '../types'
-import { pinyin } from 'pinyin-pro'
import { CollectionType } from '../../tools/types'
+import { compareProviderLetters, getProviderLetter } from './utils'
type ToolCategoryGroup = 'custom' | 'data-source' | 'mcp' | 'workflow'
@@ -48,16 +48,14 @@ export function createToolListData(
const firstChar = getFirstChar(tool)
if (!firstChar) continue
- const letter = normalizeLetter(firstChar)
+ const letter = getProviderLetter(firstChar)
const bucket = getOrCreateBucket(buckets, letter)
addToolToBucket(bucket, tool)
}
- const sortedBuckets = [...buckets.entries()].sort(([left], [right]) => {
- if (left === '#') return 1
- if (right === '#') return -1
- return left.localeCompare(right)
- })
+ const sortedBuckets = [...buckets.entries()].sort(([left], [right]) =>
+ compareProviderLetters(left, right),
+ )
const letters = sortedBuckets.map(([letter]) => letter)
const flatTools = sortedBuckets.flatMap(([letter, bucket]) =>
bucket.groups.flatMap((group) => group.tools.map((tool) => ({ ...tool, letter }))),
@@ -67,15 +65,6 @@ export function createToolListData(
return { letters, flatTools, treeGroups }
}
-function normalizeLetter(firstChar: string) {
- const pinyinInitial = /[\u4E00-\u9FA5]/.test(firstChar)
- ? pinyin(firstChar, { pattern: 'first', toneType: 'none' })[0]
- : firstChar
- const letter = (pinyinInitial || firstChar).toUpperCase()
-
- return /[A-Z]/.test(letter) ? letter : '#'
-}
-
function getOrCreateBucket(buckets: Map<string, LetterBucket>, letter: string) {
const existingBucket = buckets.get(letter)
if (existingBucket) return existingBucket
diff --git a/web/app/components/workflow/block-selector/utils.ts b/web/app/components/workflow/block-selector/utils.ts
index f4a0baf05b4..1263fe31f07 100644
--- a/web/app/components/workflow/block-selector/utils.ts
+++ b/web/app/components/workflow/block-selector/utils.ts
@@ -1,5 +1,6 @@
import type { DataSourceItem } from './types'
import type { Tool } from '@/app/components/tools/types'
+import { pinyin } from 'pinyin-pro'
export const transformDataSourceToTool = (dataSourceItem: DataSourceItem) => {
return {
@@ -35,3 +36,19 @@ export const transformDataSourceToTool = (dataSourceItem: DataSourceItem) => {
},
}
}
+
+export function getProviderLetter(firstChar: string) {
+ const pinyinInitial = /[\u4E00-\u9FA5]/.test(firstChar)
+ ? pinyin(firstChar, { pattern: 'first', toneType: 'none' })[0]
+ : firstChar
+ const letter = (pinyinInitial || firstChar).toUpperCase()
+
+ return /[A-Z]/.test(letter) ? letter : '#'
+}
+
+export function compareProviderLetters(left: string, right: string) {
+ if (left === right) return 0
+ if (left === '#') return 1
+ if (right === '#') return -1
+ return left.localeCompare(right)
+}
diff --git a/web/app/components/workflow/hooks/__tests__/use-checklist.spec.ts b/web/app/components/workflow/hooks/__tests__/use-checklist.spec.ts
index 90234cf1bec..5c70a4c1545 100644
--- a/web/app/components/workflow/hooks/__tests__/use-checklist.spec.ts
+++ b/web/app/components/workflow/hooks/__tests__/use-checklist.spec.ts
@@ -6,7 +6,7 @@ import type { ChecklistItem } from '../use-checklist'
import type { ToolWithProvider } from '@/app/components/workflow/types'
import { zWorkflowAgentComposerResponse } from '@dify/contracts/api/console/apps/zod.gen'
import { QueryClient } from '@tanstack/react-query'
-import { act, screen, waitFor } from '@testing-library/react'
+import { screen, waitFor } from '@testing-library/react'
import { createElement, Fragment } from 'react'
import { CollectionType } from '@/app/components/tools/types'
import { consoleQuery } from '@/service/console'
@@ -22,6 +22,15 @@ import { useChecklist, useChecklistBeforePublish, useWorkflowRunValidation } fro
// Mocks
// ---------------------------------------------------------------------------
+vi.mock('@/service/base', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/service/base')>()),
+ request: vi.fn((url: string) => {
+ if (url.endsWith('/workspaces/current/agent-providers'))
+ return Promise.resolve(Response.json([]))
+ throw new Error(`Unexpected request: ${url}`)
+ }),
+}))
+
const toolServiceState = vi.hoisted(() => ({
buildInTools: [] as ToolWithProvider[] | undefined,
customTools: [] as ToolWithProvider[] | undefined,
@@ -77,10 +86,6 @@ vi.mock('@/service/use-triggers', async () =>
(await import('../../__tests__/service-mock-factory')).createTriggerServiceMock(),
)
-vi.mock('@/service/use-strategy', () => ({
- useStrategyProviders: () => ({ data: [] }),
-}))
-
type CheckValidFn = (data: CommonNodeType, t: unknown, extra?: unknown) => { errorMessage: string }
const mockNodesMap: Record<
string,
@@ -255,6 +260,7 @@ function buildInlineAgentGraph({
})
const appId = 'app-id'
const nodeId = 'inline-agent-node'
+ queryClient.setQueryData(consoleQuery.workspaces.current.agentProviders.get.queryKey(), [])
queryClient.setQueryData(
consoleQuery.apps.byAppId.workflows.draft.nodes.byNodeId.agentComposer.get.queryKey({
input: {
@@ -413,17 +419,19 @@ describe('useChecklist', () => {
expect(warning!.errorMessages).toContain('Model not configured')
})
- it('should validate legacy Agent nodes when their metadata is hidden by Agent v2', () => {
+ it('should validate legacy Agent nodes when their metadata is hidden by Agent v2', async () => {
const { nodes, edges } = buildLegacyAgentGraph()
const { result } = renderWorkflowHook(() => useChecklist(nodes, edges))
- expect(result.current).toEqual([
- expect.objectContaining({
- id: 'legacy-agent',
- errorMessages: ['workflow.nodes.agent.checkList.strategyNotSelected'],
- }),
- ])
+ await waitFor(() =>
+ expect(result.current).toEqual([
+ expect.objectContaining({
+ id: 'legacy-agent',
+ errorMessages: ['workflow.nodes.agent.checkList.strategyNotSelected'],
+ }),
+ ]),
+ )
})
it.each([
@@ -806,13 +814,7 @@ describe('useChecklistBeforePublish', () => {
rfState.edges = edges as unknown as typeof rfState.edges
const { result } = renderWorkflowHook(() => useChecklistBeforePublish())
- let isValid: boolean | undefined
-
- await act(async () => {
- isValid = await result.current.handleCheckBeforePublish()
- })
-
- expect(isValid).toBe(false)
+ await waitFor(async () => expect(await result.current.handleCheckBeforePublish()).toBe(false))
})
})
diff --git a/web/app/components/workflow/hooks/use-checklist.ts b/web/app/components/workflow/hooks/use-checklist.ts
index 2782d19d818..36d65a30178 100644
--- a/web/app/components/workflow/hooks/use-checklist.ts
+++ b/web/app/components/workflow/hooks/use-checklist.ts
@@ -38,7 +38,6 @@ import {
} from '@/features/agent-v2/agent-detail/configure/tool-provider-catalog'
import { consoleQuery } from '@/service/console'
import { fetchDatasets } from '@/service/datasets'
-import { useStrategyProviders } from '@/service/use-strategy'
import {
useAllBuiltInTools,
useAllCustomTools,
@@ -178,7 +177,9 @@ export const useChecklist = (nodes: Node[], edges: Edge[], options?: { flowType?
const dataSourceList = useStore((s) => s.dataSourceList)
const environmentVariables =
useStore((s) => s.environmentVariables) ?? EMPTY_ENVIRONMENT_VARIABLES
- const { data: strategyProviders } = useStrategyProviders()
+ const { data: strategyProviders } = useQuery(
+ consoleQuery.workspaces.current.agentProviders.get.queryOptions(),
+ )
const { data: triggerPlugins } = useAllTriggerPlugins()
const datasetsDetail = useDatasetsDetailStore((s) => s.datasetsDetail)
const getToolIcon = useGetToolIcon()
@@ -622,7 +623,9 @@ export const useChecklistBeforePublish = () => {
const queryClient = useQueryClient()
const store = useStoreApi()
const { nodesMap: nodesExtraData } = useNodesMetaData()
- const { data: strategyProviders } = useStrategyProviders()
+ const { data: strategyProviders } = useQuery(
+ consoleQuery.workspaces.current.agentProviders.get.queryOptions(),
+ )
const { data: modelProviders = EMPTY_MODEL_PROVIDERS } = useQuery(
consoleQuery.workspaces.current.modelProviders.summary.get.queryOptions({
select: (response) => response.data,
diff --git a/web/app/components/workflow/nodes/_base/components/__tests__/agent-strategy-selector.spec.tsx b/web/app/components/workflow/nodes/_base/components/__tests__/agent-strategy-selector.spec.tsx
index 85d5f5960d3..ce738b1a2b8 100644
--- a/web/app/components/workflow/nodes/_base/components/__tests__/agent-strategy-selector.spec.tsx
+++ b/web/app/components/workflow/nodes/_base/components/__tests__/agent-strategy-selector.spec.tsx
@@ -1,402 +1,278 @@
-import type { ReactNode } from 'react'
-import type { StrategyPluginDetail } from '@/app/components/plugins/types'
-import { render, screen, waitFor } from '@testing-library/react'
+import type { AgentProviderResponse } from '@dify/contracts/api/console/workspaces/types.gen'
+import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import { PluginCategoryEnum } from '@/app/components/plugins/types'
+import { createPlugin } from '@/app/components/workflow/block-selector/__tests__/factories'
+import { renderWithConsoleQuery as render } from '@/test/console/query-data'
+import { createProvider, createStrategy } from '../../../agent/__tests__/strategy-fixture'
import { AgentStrategySelector } from '../agent-strategy-selector'
-const mocks = vi.hoisted(() => ({
- useSuspenseQuery: vi.fn(),
- useStrategyProviders: vi.fn(),
- useMarketplacePlugins: vi.fn(),
- useStrategyInfo: vi.fn(),
- refetchStrategyInfo: vi.fn(),
- queryPluginsWithDebounced: vi.fn(),
+const { request, searchMarketplace, marketplaceResults, marketplace, install } = vi.hoisted(() => ({
+ request: vi.fn(),
+ searchMarketplace: vi.fn(),
+ marketplaceResults: vi.fn(),
+ marketplace: vi.fn(),
+ install: vi.fn(),
}))
-
-vi.mock('@tanstack/react-query', () => ({
- useSuspenseQuery: mocks.useSuspenseQuery,
-}))
-
-vi.mock('@/service/use-strategy', () => ({
- useStrategyProviders: mocks.useStrategyProviders,
-}))
-
+vi.mock('@/service/base', () => ({ request }))
vi.mock('@/app/components/plugins/marketplace/hooks', () => ({
- useMarketplacePlugins: mocks.useMarketplacePlugins,
-}))
-
-vi.mock('@/app/components/workflow/nodes/agent/use-config', () => ({
- useStrategyInfo: mocks.useStrategyInfo,
-}))
-
-vi.mock('@/app/components/plugins/install-plugin/base/use-get-icon', () => ({
- default: () => ({
- getIconUrl: (icon: string) => `https://example.com/${icon}`,
+ useMarketplacePlugins: () => ({
+ queryPluginsWithDebounced: searchMarketplace,
+ plugins: marketplaceResults(),
}),
}))
-
-vi.mock('@/app/components/base/search-input', () => ({
- SearchInput: ({
- value,
- onValueChange,
- placeholder,
- }: {
- value: string
- onValueChange: (value: string) => void
- placeholder?: string
- className?: string
- }) => (
- <input aria-label={placeholder} value={value} onChange={(e) => onValueChange(e.target.value)} />
- ),
-}))
-
-vi.mock('@/app/components/workflow/block-selector/view-type-select', () => ({
- default: ({ onChange }: { viewType: string; onChange: (value: string) => void }) => (
- <button type="button" onClick={() => onChange('grid')}>
- view-type
- </button>
- ),
- ViewType: {
- flat: 'flat',
- grid: 'grid',
- },
-}))
-
-vi.mock('@/app/components/workflow/block-selector/tools', () => ({
- default: ({
- tools,
- onSelect,
- }: {
- tools: Array<{
- id: string
- name: string
- meta?: unknown
- tools: Array<{
- name: string
- label: string | { en_US?: string }
- output_schema?: Record<string, unknown>
- }>
- }>
- onSelect: (
- value: unknown,
- tool: {
- tool_name: string
- provider_name: string
- tool_label: string
- output_schema?: Record<string, unknown>
- provider_id: string
- meta?: unknown
- },
- ) => void
- }) => (
- <div data-testid="tools-list">
- {tools.map((tool) => (
- <div key={tool.id}>
- <span>{tool.name}</span>
- <button
- type="button"
- onClick={() =>
- onSelect(undefined, {
- tool_name: tool.tools[0]!.name,
- provider_name: tool.id,
- tool_label:
- typeof tool.tools[0]!.label === 'string'
- ? tool.tools[0]!.label
- : tool.tools[0]!.label.en_US || '',
- output_schema: tool.tools[0]!.output_schema,
- provider_id: tool.id,
- meta: tool.meta,
- })
- }
- >
- {`select-${tool.name}`}
- </button>
- </div>
- ))}
- </div>
- ),
+vi.mock('@/service/use-plugins', () => ({
+ useFetchPluginsInMarketPlaceByIds: marketplace,
+ useCheckInstalled: () => ({ data: { plugins: [] }, isLoading: false, refetch: vi.fn() }),
+ useInstallPackageFromMarketPlace: () => ({ mutate: install, isPending: false }),
}))
-vi.mock('@/app/components/workflow/block-selector/marketplace-plugin/list', () => ({
- default: ({ list, searchText }: { list: Array<{ plugin_id: string }>; searchText: string }) => (
- <div data-testid="plugin-list">
- {`${searchText}:${list.map((item) => item.plugin_id).join(',')}`}
- </div>
- ),
-}))
-
-vi.mock('@/app/components/workflow/nodes/_base/components/install-plugin-button', () => ({
- InstallPluginButton: ({
- onClick,
- }: {
- onClick?: (event: { stopPropagation: () => void }) => void
- uniqueIdentifier: string
- size: string
- }) => (
- <button
- type="button"
- data-testid="install-plugin-button"
- onClick={() => onClick?.({ stopPropagation: vi.fn() })}
- >
- install-plugin
- </button>
- ),
-}))
-
-vi.mock('@/app/components/workflow/nodes/_base/components/switch-plugin-version', () => ({
- SwitchPluginVersion: ({
- onChange,
- }: {
- onChange: () => void
- uniqueIdentifier: string
- tooltip: ReactNode
- }) => (
- <button type="button" data-testid="switch-plugin-version" onClick={onChange}>
- switch-plugin-version
- </button>
- ),
-}))
-
-vi.mock('@/next/link', () => ({
- default: ({
- href,
- children,
- className,
- }: {
- href: string
- children: ReactNode
- className?: string
- }) => (
- <a href={href} className={className}>
- {children}
- </a>
- ),
-}))
+vi.mock(
+ '@/app/components/plugins/install-plugin/hooks/use-workspace-plugin-install-permission',
+ () => ({
+ default: () => ({ canInstallPlugin: true, canUpdatePlugin: true }),
+ }),
+)
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ marketplaceResults.mockReturnValue([])
+ marketplace.mockReturnValue({
+ isLoading: false,
+ data: { data: { plugins: [] } },
+ refetch: vi.fn(),
+ })
+})
-const createStrategyDetail = (
- name: string,
- strategyName: string,
- strategyLabel: string,
-): StrategyPluginDetail =>
- ({
- plugin_unique_identifier: `provider/${name}`,
- plugin_id: `plugin-${name}`,
+function namedProvider(name: string, label: string, author: string): AgentProviderResponse {
+ const provider = createProvider()
+ return {
+ ...provider,
+ plugin_unique_identifier: `${name}:1.0.0@hash`,
declaration: {
+ ...provider.declaration,
identity: {
- author: 'Dify',
+ ...provider.declaration.identity,
name,
- description: { en_US: `${name} description` },
- icon: `${name}.png`,
- label: { en_US: `${name} label` },
- tags: [],
+ author,
+ label: { en_US: label, zh_Hans: null },
},
- strategies: [
- {
- identity: {
- name: strategyName,
- author: 'Dify',
- label: { en_US: strategyLabel },
- },
- description: { en_US: `${strategyLabel} description` },
- parameters: [],
- output_schema: { result: { type: 'string' } },
- },
- ],
},
- meta: { version: '1.0.0' },
- }) as unknown as StrategyPluginDetail
-
-describe('AgentStrategySelector', () => {
- const alphaDetail = createStrategyDetail('alpha', 'alpha-strategy', 'Alpha Strategy')
- const betaDetail = createStrategyDetail('beta', 'beta-strategy', 'Beta Strategy')
-
- beforeEach(() => {
- vi.clearAllMocks()
-
- mocks.useSuspenseQuery.mockReturnValue({ data: true })
- mocks.useStrategyProviders.mockReturnValue({ data: [alphaDetail, betaDetail] })
- mocks.useMarketplacePlugins.mockReturnValue({
- queryPluginsWithDebounced: mocks.queryPluginsWithDebounced,
- plugins: [{ plugin_id: 'market-agent' }],
- })
- mocks.useStrategyInfo.mockReturnValue({
- strategyStatus: undefined,
- refetch: mocks.refetchStrategyInfo,
- })
+ }
+}
+
+it('selects the generated strategy output and metadata through the real provider list', async () => {
+ const user = userEvent.setup()
+ const onChange = vi.fn()
+ const provider = createProvider([
+ createStrategy({
+ output_schema: { type: 'object', properties: { answer: { type: 'string' } } },
+ }),
+ ])
+ request.mockImplementation(() => Promise.resolve(Response.json([provider])))
+ render(<AgentStrategySelector onChange={onChange} />, {
+ systemFeatures: { enable_marketplace: false },
})
- it('filters strategies and queries marketplace when searching', async () => {
- const user = userEvent.setup()
-
- render(<AgentStrategySelector onChange={vi.fn()} />)
-
- await user.click(
- screen
- .getByText(/(?:^|\.)nodes\.agent\.strategy\.selectTip(?=$|:)/)
- .closest('[aria-haspopup]')!,
- )
-
- expect(screen.getByText('alpha')).toBeInTheDocument()
- expect(screen.getByText('beta')).toBeInTheDocument()
- expect(screen.getByTestId('plugin-list')).toHaveTextContent(':market-agent')
-
- await user.type(
- screen.getByRole('textbox', {
- name: /(?:^|\.)nodes\.agent\.strategy\.searchPlaceholder(?=$|:)/,
- }),
- 'alp',
- )
-
- await waitFor(() => {
- expect(mocks.queryPluginsWithDebounced).toHaveBeenLastCalledWith({
- query: 'alp',
- category: PluginCategoryEnum.agent,
- })
- })
-
- expect(screen.getByText('alpha')).toBeInTheDocument()
- expect(screen.queryByText('beta')).not.toBeInTheDocument()
+ await user.click(screen.getByText('workflow.nodes.agent.strategy.selectTip'))
+ await user.click(await screen.findByRole('button', { name: 'Agent provider' }))
+ await user.click(await screen.findByRole('button', { name: 'ReAct' }))
+ expect(onChange).toHaveBeenCalledWith({
+ agent_strategy_name: 'react',
+ agent_strategy_provider_name: 'langgenius/agent/provider',
+ agent_strategy_label: 'ReAct',
+ agent_output_schema: provider.declaration.strategies?.[0]?.output_schema,
+ plugin_unique_identifier: 'langgenius/agent:1.0.0@hash',
+ meta: { version: null },
})
+ await waitFor(() =>
+ expect(screen.queryByRole('button', { name: 'ReAct' })).not.toBeInTheDocument(),
+ )
+})
- it('maps the selected tool and closes the popover', async () => {
- const user = userEvent.setup()
- const onChange = vi.fn()
-
- render(<AgentStrategySelector onChange={onChange} />)
-
- await user.click(
- screen
- .getByText(/(?:^|\.)nodes\.agent\.strategy\.selectTip(?=$|:)/)
- .closest('[aria-haspopup]')!,
- )
- await user.click(screen.getByRole('button', { name: 'select-alpha' }))
-
- expect(onChange).toHaveBeenCalledWith({
- agent_strategy_name: 'alpha-strategy',
- agent_strategy_provider_name: 'provider/alpha',
- agent_strategy_label: 'Alpha Strategy',
- agent_output_schema: { result: { type: 'string' } },
- plugin_unique_identifier: 'provider/alpha',
- meta: { version: '1.0.0' },
- })
- expect(screen.queryByTestId('tools-list')).not.toBeInTheDocument()
+it('preserves a nullable output schema when selecting a strategy', async () => {
+ const user = userEvent.setup()
+ const onChange = vi.fn()
+ request.mockImplementation(() => Promise.resolve(Response.json([createProvider()])))
+ render(<AgentStrategySelector onChange={onChange} />, {
+ systemFeatures: { enable_marketplace: false },
})
+ await user.click(screen.getByText('workflow.nodes.agent.strategy.selectTip'))
+ await user.click(await screen.findByRole('button', { name: 'Agent provider' }))
+ await user.click(await screen.findByRole('button', { name: 'ReAct' }))
+ expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ agent_output_schema: null }))
+})
- it('renders the plugin-not-installed warning for external strategies', async () => {
- const user = userEvent.setup()
- mocks.useStrategyInfo.mockReturnValue({
- strategyStatus: {
- plugin: {
- source: 'external',
- installed: false,
- },
- isExistInPlugin: true,
- },
- refetch: mocks.refetchStrategyInfo,
- })
-
- render(
- <AgentStrategySelector
- value={{
- agent_strategy_provider_name: 'provider/alpha',
- agent_strategy_name: 'alpha-strategy',
- agent_strategy_label: 'Alpha Strategy',
- agent_output_schema: {},
- plugin_unique_identifier: 'provider/alpha',
- }}
- onChange={vi.fn()}
- />,
- )
-
- await user.click(
- screen.getByRole('button', { name: /(?:^|\.)nodes\.agent\.pluginNotInstalled(?=$|:)/ }),
- )
-
- expect(
- await screen.findByText(/(?:^|\.)nodes\.agent\.pluginNotInstalled(?=$|:)/),
- ).toBeInTheDocument()
- expect(
- screen.getByText(/(?:^|\.)nodes\.agent\.pluginNotInstalledDesc(?=$|:)/),
- ).toBeInTheDocument()
- expect(screen.getByRole('link', { name: /nodes\.agent\.linkToPlugin/ })).toHaveAttribute(
- 'href',
- '/plugins',
- )
- expect(screen.getAllByRole('dialog')).toHaveLength(1)
-
- for (const key of ['{Enter}', ' ']) {
- await user.keyboard('{Escape}')
- await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
- expect(
- screen.getByRole('button', { name: /(?:^|\.)nodes\.agent\.pluginNotInstalled(?=$|:)/ }),
- ).toHaveFocus()
- await user.keyboard(key)
- expect(await screen.findByRole('dialog')).toBeInTheDocument()
- expect(screen.queryByTestId('tools-list')).not.toBeInTheDocument()
- expect(screen.getByRole('link', { name: /nodes\.agent\.linkToPlugin/ })).toHaveAttribute(
- 'href',
- '/plugins',
- )
- }
+it('preserves letter ordering and author groups across flat and tree views', async () => {
+ const user = userEvent.setup()
+ const providers = [
+ namedProvider('zed', 'Zed', 'First author'),
+ namedProvider('apple', 'Apple', 'Second author'),
+ namedProvider('azure', 'Azure', 'First author'),
+ namedProvider('apricot', 'Apricot', 'Second author'),
+ namedProvider('symbol', '# Other', 'Third author'),
+ ]
+ request.mockImplementation(() => Promise.resolve(Response.json(providers)))
+ render(<AgentStrategySelector onChange={vi.fn()} />, {
+ systemFeatures: { enable_marketplace: false },
})
+ await user.click(screen.getByText('workflow.nodes.agent.strategy.selectTip'))
+ await screen.findByRole('button', { name: 'Apple' })
+ const providerNames = () =>
+ screen
+ .getAllByRole('button')
+ .map((button) => button.textContent)
+ .filter((name) => ['Zed', 'Apple', 'Azure', 'Apricot', '# Other'].includes(name ?? ''))
+ expect(providerNames()).toEqual(['Apple', 'Apricot', 'Azure', 'Zed', '# Other'])
+ await user.click(screen.getByRole('radio', { name: 'workflow.tabs.treeView' }))
+ expect(screen.getByText('First author')).toBeInTheDocument()
+ expect(screen.getByText('Second author')).toBeInTheDocument()
+ expect(providerNames()).toEqual(['Zed', 'Azure', 'Apple', 'Apricot', '# Other'])
+ await user.click(screen.getByRole('button', { name: 'Zed' }))
+ expect(await screen.findByRole('button', { name: 'ReAct' })).toHaveAccessibleDescription(
+ 'Reason and use tools',
+ )
+})
- it('renders install and switch-version actions for marketplace strategies', async () => {
- const user = userEvent.setup()
-
- mocks.useStrategyInfo.mockReturnValueOnce({
- strategyStatus: {
- plugin: {
- source: 'marketplace',
- installed: false,
- },
- isExistInPlugin: false,
- },
- refetch: mocks.refetchStrategyInfo,
- })
-
- const { rerender } = render(
- <AgentStrategySelector
- value={{
- agent_strategy_provider_name: 'provider/alpha',
- agent_strategy_name: 'alpha-strategy',
- agent_strategy_label: 'Alpha Strategy',
- agent_output_schema: {},
- plugin_unique_identifier: 'provider/alpha',
- }}
- onChange={vi.fn()}
- />,
- )
-
- expect(screen.getByTestId('install-plugin-button')).toBeInTheDocument()
+it('filters by provider identity without changing the saved selection or opening strategy rows', async () => {
+ const user = userEvent.setup()
+ const onChange = vi.fn()
+ const providers = [
+ namedProvider('org/target/provider', 'Display name', 'Author'),
+ namedProvider('org/other/provider', 'Other', 'Author'),
+ ]
+ request.mockImplementation(() => Promise.resolve(Response.json(providers)))
+ render(<AgentStrategySelector onChange={onChange} />, {
+ systemFeatures: { enable_marketplace: false },
+ })
+ await user.click(screen.getByText('workflow.nodes.agent.strategy.selectTip'))
+ await screen.findByRole('button', { name: 'Display name' })
+ const search = screen.getByPlaceholderText('workflow.nodes.agent.strategy.searchPlaceholder')
+ await user.type(search, 'TARGET')
+ expect(screen.getByRole('button', { name: 'Display name' })).toHaveAttribute(
+ 'aria-expanded',
+ 'false',
+ )
+ expect(screen.queryByRole('button', { name: 'Other' })).not.toBeInTheDocument()
+ await user.clear(search)
+ await user.type(search, 'Display name')
+ expect(screen.queryByRole('button', { name: 'Display name' })).not.toBeInTheDocument()
+ expect(screen.getByText('tools.addToolModal.agent.title')).toBeInTheDocument()
+ expect(onChange).not.toHaveBeenCalled()
+ expect(searchMarketplace).not.toHaveBeenCalled()
+})
- mocks.useStrategyInfo.mockReturnValue({
- strategyStatus: {
- plugin: {
- source: 'marketplace',
- installed: true,
- },
- isExistInPlugin: false,
- },
- refetch: mocks.refetchStrategyInfo,
- })
+it('keeps letter navigation for long catalogs and removes it in tree view', async () => {
+ const user = userEvent.setup()
+ const scrollIntoView = vi.spyOn(HTMLElement.prototype, 'scrollIntoView')
+ const providers = Array.from({ length: 11 }, (_, index) =>
+ namedProvider(`provider-${index}`, `${String.fromCharCode(65 + index)} provider`, 'Author'),
+ )
+ request.mockImplementation(() => Promise.resolve(Response.json(providers)))
+ render(<AgentStrategySelector onChange={vi.fn()} />, {
+ systemFeatures: { enable_marketplace: false },
+ })
+ await user.click(screen.getByText('workflow.nodes.agent.strategy.selectTip'))
+ const letter = await screen.findByRole('button', { name: 'K' })
+ await user.click(letter)
+ expect(scrollIntoView).toHaveBeenCalledExactlyOnceWith({ behavior: 'smooth' })
+ expect(scrollIntoView.mock.contexts[0]).toContainElement(
+ screen.getByRole('button', { name: 'K provider' }),
+ )
+ scrollIntoView.mockRestore()
+ await user.click(screen.getByRole('radio', { name: 'workflow.tabs.treeView' }))
+ expect(screen.queryByRole('button', { name: 'K' })).not.toBeInTheDocument()
+})
- rerender(
- <AgentStrategySelector
- value={{
- agent_strategy_provider_name: 'provider/alpha',
- agent_strategy_name: 'alpha-strategy',
- agent_strategy_label: 'Alpha Strategy',
- agent_output_schema: {},
- plugin_unique_identifier: 'provider/alpha',
- }}
- onChange={vi.fn()}
- />,
- )
+it('keeps marketplace search and its category link alongside the installed catalog', async () => {
+ const user = userEvent.setup()
+ marketplaceResults.mockReturnValue([
+ createPlugin({ label: { en_US: 'Marketplace strategy', zh_Hans: 'Marketplace strategy' } }),
+ ])
+ request.mockImplementation(() => Promise.resolve(Response.json([createProvider()])))
+ render(<AgentStrategySelector onChange={vi.fn()} />, {
+ systemFeatures: { enable_marketplace: true },
+ })
+ await user.click(screen.getByText('workflow.nodes.agent.strategy.selectTip'))
+ const link = screen.getByRole('link', { name: 'plugin.findMoreInMarketplace' })
+ expect(link.getAttribute('href')).toContain('/plugins/agent-strategy')
+ await user.type(
+ screen.getByPlaceholderText('workflow.nodes.agent.strategy.searchPlaceholder'),
+ 'react',
+ )
+ expect(searchMarketplace).toHaveBeenLastCalledWith({
+ query: 'react',
+ category: PluginCategoryEnum.agent,
+ })
+ expect(screen.getByText('Marketplace strategy')).toBeInTheDocument()
+})
- await user.click(screen.getByTestId('switch-plugin-version'))
+it('preserves an older saved selection with no plugin identifier until the user chooses a replacement', async () => {
+ const user = userEvent.setup()
+ const onChange = vi.fn()
+ const provider = createProvider()
+ request.mockImplementation((url: string) =>
+ Promise.resolve(Response.json(url.includes('agent-providers') ? [provider] : provider)),
+ )
+ render(
+ <AgentStrategySelector
+ value={{
+ agent_strategy_provider_name: provider.declaration.identity.name,
+ agent_strategy_name: 'react',
+ agent_strategy_label: 'Saved label',
+ agent_output_schema: null,
+ }}
+ onChange={onChange}
+ />,
+ { systemFeatures: { enable_marketplace: false } },
+ )
+ expect(screen.getByText('Saved label')).toBeInTheDocument()
+ await user.click(screen.getByText('Saved label'))
+ await user.click(await screen.findByRole('button', { name: 'Agent provider' }))
+ expect(onChange).not.toHaveBeenCalled()
+ await user.click(screen.getByRole('button', { name: 'ReAct' }))
+ expect(onChange).toHaveBeenCalledWith(
+ expect.objectContaining({
+ plugin_unique_identifier: provider.plugin_unique_identifier,
+ meta: { version: null },
+ agent_output_schema: null,
+ }),
+ )
+})
- expect(mocks.refetchStrategyInfo).toHaveBeenCalled()
+it('keeps the install action for a saved marketplace strategy that is no longer installed', async () => {
+ const user = userEvent.setup()
+ marketplace.mockReturnValue({
+ isLoading: false,
+ data: { data: { plugins: [createPlugin()] } },
+ refetch: vi.fn(),
})
+ request.mockImplementation((url: string) =>
+ Promise.resolve(
+ url.includes('agent-providers')
+ ? Response.json([])
+ : Response.json({ message: 'Provider not installed' }, { status: 404 }),
+ ),
+ )
+ render(
+ <AgentStrategySelector
+ value={{
+ agent_strategy_provider_name: 'langgenius/agent/provider',
+ agent_strategy_name: 'react',
+ agent_strategy_label: 'Saved label',
+ agent_output_schema: null,
+ plugin_unique_identifier: 'langgenius/agent:1.0.0@hash',
+ }}
+ onChange={vi.fn()}
+ />,
+ { systemFeatures: { enable_marketplace: true } },
+ )
+ await user.click(
+ await screen.findByRole('button', { name: 'workflow.nodes.agent.pluginInstaller.install' }),
+ )
+ expect(install).toHaveBeenCalledWith('langgenius/agent:1.0.0@hash', expect.any(Object))
+ expect(
+ screen.queryByPlaceholderText('workflow.nodes.agent.strategy.searchPlaceholder'),
+ ).not.toBeInTheDocument()
+ expect(screen.getByText('Saved label')).toBeInTheDocument()
})
diff --git a/web/app/components/workflow/nodes/_base/components/__tests__/agent-strategy.spec.tsx b/web/app/components/workflow/nodes/_base/components/__tests__/agent-strategy.spec.tsx
index 4a63df68892..f6a0650ad7b 100644
--- a/web/app/components/workflow/nodes/_base/components/__tests__/agent-strategy.spec.tsx
+++ b/web/app/components/workflow/nodes/_base/components/__tests__/agent-strategy.spec.tsx
@@ -1,199 +1,170 @@
-import type { ReactNode } from 'react'
-import type {
- CredentialFormSchema,
- CredentialFormSchemaNumberInput,
- CredentialFormSchemaTextInput,
-} from '@/app/components/header/account-setting/model-provider-page/declarations'
-import { render, screen } from '@testing-library/react'
-import { FormTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
-import { createDocLinkMock } from '../../../../__tests__/i18n'
+import type { AgentStrategyParameter } from '@dify/contracts/api/console/workspaces/types.gen'
+import { screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { useState } from 'react'
+import { WorkflowContext } from '@/app/components/workflow/context'
+import { createWorkflowStore } from '@/app/components/workflow/store'
+import { renderWithConsoleQuery as render } from '@/test/console/query-data'
+import { createProvider, createStrategy } from '../../../agent/__tests__/strategy-fixture'
import { AgentStrategy } from '../agent-strategy'
-const createI18nLabel = (text: string) => ({ en_US: text, zh_Hans: text })
-const mockDocLink = createDocLinkMock('/docs')
-
-vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({
- useDefaultModel: () => ({ data: null }),
-}))
-
-vi.mock('@/context/i18n', () => ({
- useDocLink: () => mockDocLink,
-}))
-
-vi.mock('@/hooks/use-i18n', () => ({
- useRenderI18nObject: () => (value: unknown) => {
- if (typeof value === 'string') return value
- if (value && typeof value === 'object' && 'en_US' in value) return value.en_US
- return 'label'
- },
-}))
-
-vi.mock('../../../../store', () => ({
- useWorkflowStore: () => ({
- getState: () => ({
- setControlPromptEditorRerenderKey: vi.fn(),
- }),
+const { request } = vi.hoisted(() => ({ request: vi.fn() }))
+vi.mock('@/service/base', () => ({ request }))
+vi.mock(
+ '@/app/components/header/account-setting/model-provider-page/hooks',
+ async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import('@/app/components/header/account-setting/model-provider-page/hooks')
+ >()),
+ useDefaultModel: () => ({ data: null }),
}),
+)
+vi.mock('@/app/components/workflow/hooks/use-workflow-variables', () => ({
+ useWorkflowVariableType: () => vi.fn(),
}))
-
-vi.mock('../agent-strategy-selector', () => ({
- AgentStrategySelector: () => <div data-testid="agent-strategy-selector" />,
+vi.mock('@/app/components/plugins/marketplace/hooks', () => ({
+ useMarketplacePlugins: () => ({ queryPluginsWithDebounced: vi.fn(), plugins: [] }),
}))
-
-vi.mock('../field', () => ({
- default: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
-}))
-
-vi.mock('../prompt/editor', () => ({
- default: ({ value }: { value: string }) => <div data-testid="agent-strategy-editor">{value}</div>,
+vi.mock('@/service/use-plugins', () => ({
+ useFetchPluginsInMarketPlaceByIds: () => ({
+ isLoading: false,
+ data: { data: { plugins: [] } },
+ refetch: vi.fn(),
+ }),
}))
-type MockFormRenderProps = {
- value: Record<string, unknown>
- onChange: (value: Record<string, unknown>) => void
- nodeId?: string
- nodeOutputVars?: unknown[]
- availableNodes?: unknown[]
+const strategy = {
+ agent_strategy_provider_name: 'langgenius/agent/provider',
+ agent_strategy_name: 'react',
+ agent_strategy_label: 'ReAct',
+ agent_output_schema: null,
}
-
-type MockFormProps = {
- formSchemas: Array<{ variable: string }>
- value: Record<string, unknown>
- onChange: (value: Record<string, unknown>) => void
- override?: [unknown, (schema: unknown, props: MockFormRenderProps) => ReactNode]
- nodeId?: string
- nodeOutputVars?: unknown[]
- availableNodes?: unknown[]
-}
-
-vi.mock('@/app/components/header/account-setting/model-provider-page/model-modal/Form', () => ({
- default: ({
- formSchemas,
- value,
- onChange,
- override,
- nodeId,
- nodeOutputVars,
- availableNodes,
- }: MockFormProps) => {
- const renderOverride = override?.[1]
-
+const createParameter = (overrides: Partial<AgentStrategyParameter>): AgentStrategyParameter => ({
+ name: 'count',
+ type: 'number',
+ label: { en_US: 'Count' },
+ default: '3',
+ min: 0,
+ max: 10,
+ ...overrides,
+})
+const renderForm = (
+ parameters: AgentStrategyParameter[],
+ initialValue: Record<string, unknown> = {},
+) => {
+ const onChange = vi.fn()
+ request.mockImplementation((url: string) =>
+ Promise.resolve(
+ Response.json(
+ url.endsWith('/agent-providers')
+ ? [createProvider()]
+ : createProvider([createStrategy({ parameters })]),
+ ),
+ ),
+ )
+ const workflowStore = createWorkflowStore({})
+ function Harness() {
+ const [value, setValue] = useState(initialValue)
return (
- <div data-testid="mock-form">
- {formSchemas.map((schema) => (
- <div key={schema.variable}>
- {renderOverride?.(schema, {
- value,
- onChange,
- nodeId,
- nodeOutputVars,
- availableNodes,
- })}
- </div>
- ))}
- </div>
+ <WorkflowContext value={workflowStore}>
+ <AgentStrategy
+ strategy={strategy}
+ onStrategyChange={vi.fn()}
+ formSchema={parameters}
+ formValue={value}
+ onFormValueChange={(next) => {
+ setValue(next)
+ onChange(next)
+ }}
+ />
+ </WorkflowContext>
)
- },
-}))
-
-describe('AgentStrategy', () => {
- const defaultProps = {
- strategy: {
- agent_strategy_provider_name: 'provider',
- agent_strategy_name: 'strategy',
- agent_strategy_label: 'Strategy',
- agent_output_schema: {},
- plugin_unique_identifier: 'plugin',
- },
- onStrategyChange: vi.fn(),
- formValue: {},
- onFormValueChange: vi.fn(),
- nodeOutputVars: [],
- availableNodes: [],
- nodeId: 'node-1',
}
+ const result = render(<Harness />, { systemFeatures: { enable_marketplace: false } })
+ return { ...result, onChange }
+}
- beforeEach(() => {
- vi.clearAllMocks()
- })
-
- const createTextNumberSchema = (
- overrides: Partial<CredentialFormSchemaNumberInput> = {},
- ): CredentialFormSchema =>
- ({
- name: 'count',
- variable: 'count',
- label: createI18nLabel('Count'),
- type: FormTypeEnum.textNumber,
- required: false,
- show_on: [],
- default: '1',
- ...overrides,
- }) as unknown as CredentialFormSchema
-
- const createTextInputSchema = (
- overrides: Partial<CredentialFormSchemaTextInput> = {},
- ): CredentialFormSchema => ({
- name: 'prompt',
- variable: 'prompt',
- label: createI18nLabel('Prompt'),
- type: FormTypeEnum.textInput,
- required: false,
- show_on: [],
- default: 'hello',
- ...overrides,
- })
-
- it('should render text-number schemas when min and max are zero', () => {
- render(
- <AgentStrategy
- {...defaultProps}
- formSchema={[
- createTextNumberSchema({
- min: 0,
- max: 0,
- default: '0',
- }),
- ]}
- />,
- )
+beforeEach(() => vi.clearAllMocks())
+
+it('renders typed number and boolean defaults through the real form without requiring an installation identifier', async () => {
+ const user = userEvent.setup()
+ const { onChange } = renderForm([
+ createParameter({ default: 0 }),
+ createParameter({
+ name: 'enabled',
+ type: 'boolean',
+ label: { en_US: 'Enabled' },
+ default: false,
+ }),
+ ])
+ expect(screen.getByRole('textbox', { name: 'Count' })).toHaveValue('0')
+ expect(screen.getByRole('radio', { name: 'False' })).toBeChecked()
+ await user.click(screen.getByRole('radio', { name: 'True' }))
+ expect(onChange).toHaveBeenLastCalledWith({ count: 0, enabled: true })
+})
- expect(screen.getByRole('textbox', { name: 'Count' })).toBeInTheDocument()
- })
+it.each([
+ { value: undefined, expected: '3' },
+ { value: '4', expected: '4' },
+ { value: 0, expected: '0' },
+])('preserves numeric strings and zero: $value', ({ value, expected }) => {
+ renderForm([createParameter({})], value === undefined ? {} : { count: value })
+ expect(screen.getByRole('textbox', { name: 'Count' })).toHaveValue(expected)
+})
- it('should skip text-number schemas when min is missing', () => {
- render(
- <AgentStrategy
- {...defaultProps}
- formSchema={[
- createTextNumberSchema({
- max: 5,
- }),
- ]}
- />,
- )
+it('preserves a one-sided numeric constraint through fallback input and blur', async () => {
+ const user = userEvent.setup()
+ const { onChange } = renderForm([createParameter({ min: 0, max: null })])
+ const input = screen.getByRole('spinbutton')
+ await user.clear(input)
+ await user.type(input, '-2')
+ await user.tab()
+ expect(input).toHaveValue(0)
+ expect(onChange).toHaveBeenLastCalledWith({ count: '0' })
+})
- expect(screen.queryByRole('textbox')).not.toBeInTheDocument()
- })
+it('does not select a boolean value when the declaration default is null', () => {
+ renderForm([
+ createParameter({
+ name: 'enabled',
+ type: 'boolean',
+ label: { en_US: 'Enabled' },
+ default: null,
+ }),
+ ])
+ expect(screen.getByRole('radio', { name: 'False' })).not.toBeChecked()
+ expect(screen.getByRole('radio', { name: 'True' })).not.toBeChecked()
+})
- it('should skip text-number schemas when max is missing', () => {
- render(
- <AgentStrategy
- {...defaultProps}
- formSchema={[
- createTextNumberSchema({
- min: 0,
- }),
- ]}
- />,
+it.each(['', null])(
+ 'displays the declared default for a cleared prompt %s, matching runtime initialization',
+ async (prompt) => {
+ renderForm(
+ [
+ createParameter({
+ name: 'prompt',
+ type: 'string',
+ label: { en_US: 'Prompt' },
+ default: 'Default prompt',
+ }),
+ ],
+ { prompt },
)
-
- expect(screen.queryByRole('textbox')).not.toBeInTheDocument()
- })
-
- it('should render text-input schemas through the editor override', () => {
- render(<AgentStrategy {...defaultProps} formSchema={[createTextInputSchema()]} />)
-
- expect(screen.getByTestId('agent-strategy-editor')).toHaveTextContent('hello')
- })
+ await waitFor(() => expect(screen.getByRole('textbox')).toHaveTextContent('Default prompt'))
+ },
+)
+
+it('uses the declaration default for an explicitly undefined form value', async () => {
+ renderForm(
+ [
+ createParameter({
+ name: 'prompt',
+ type: 'string',
+ label: { en_US: 'Prompt' },
+ default: 'Default prompt',
+ }),
+ ],
+ { prompt: undefined },
+ )
+ await waitFor(() => expect(screen.getByRole('textbox')).toHaveTextContent('Default prompt'))
})
diff --git a/web/app/components/workflow/nodes/_base/components/__tests__/form-input-type-switch.spec.tsx b/web/app/components/workflow/nodes/_base/components/__tests__/form-input-type-switch.spec.tsx
index 07c40cd3238..564df51725d 100644
--- a/web/app/components/workflow/nodes/_base/components/__tests__/form-input-type-switch.spec.tsx
+++ b/web/app/components/workflow/nodes/_base/components/__tests__/form-input-type-switch.spec.tsx
@@ -1,13 +1,13 @@
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import { VarType } from '@/app/components/workflow/nodes/tool/types'
+import { VarKindType } from '@/app/components/workflow/nodes/_base/types'
import FormInputTypeSwitch from '../form-input-type-switch'
describe('FormInputTypeSwitch', () => {
it('changes the required input type selection', async () => {
const user = userEvent.setup()
const onChange = vi.fn()
- render(<FormInputTypeSwitch value={VarType.variable} onChange={onChange} />)
+ render(<FormInputTypeSwitch value={VarKindType.variable} onChange={onChange} />)
expect(
screen.getByRole('radio', { name: 'workflow.nodes.common.typeSwitch.variable' }),
@@ -15,11 +15,11 @@ describe('FormInputTypeSwitch', () => {
await user.click(screen.getByRole('radio', { name: 'workflow.nodes.common.typeSwitch.input' }))
- expect(onChange).toHaveBeenCalledWith(VarType.constant)
+ expect(onChange).toHaveBeenCalledWith(VarKindType.constant)
})
it('disables both input type options when read-only', () => {
- render(<FormInputTypeSwitch value={VarType.constant} onChange={vi.fn()} readonly />)
+ render(<FormInputTypeSwitch value={VarKindType.constant} onChange={vi.fn()} readonly />)
expect(
screen.getByRole('radio', { name: 'workflow.nodes.common.typeSwitch.variable' }),
diff --git a/web/app/components/workflow/nodes/_base/components/agent-strategy-list.tsx b/web/app/components/workflow/nodes/_base/components/agent-strategy-list.tsx
new file mode 100644
index 00000000000..315a598d887
--- /dev/null
+++ b/web/app/components/workflow/nodes/_base/components/agent-strategy-list.tsx
@@ -0,0 +1,259 @@
+import type {
+ AgentProviderResponse,
+ AgentStrategyEntity,
+} from '@dify/contracts/api/console/workspaces/types.gen'
+import type { PreviewCardHandle } from '@langgenius/dify-ui/preview-card'
+import { Button } from '@langgenius/dify-ui/button'
+import { cn } from '@langgenius/dify-ui/cn'
+import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from '@langgenius/dify-ui/collapsible'
+import {
+ createPreviewCardHandle,
+ PreviewCard,
+ PreviewCardTrigger,
+} from '@langgenius/dify-ui/preview-card'
+import { useId, useMemo, useRef, useState } from 'react'
+import { trackEvent } from '@/app/components/base/amplitude'
+import useGetIcon from '@/app/components/plugins/install-plugin/base/use-get-icon'
+import Empty from '@/app/components/tools/provider/empty'
+import { useGetLanguage } from '@/context/i18n'
+import { renderI18nObject } from '@/i18n/metadata'
+import BlockIcon from '../../../block-icon'
+import { IndexBar } from '../../../block-selector/index-bar'
+import { BlockSelectorPreviewCardContent } from '../../../block-selector/preview-card'
+import { ViewType } from '../../../block-selector/types'
+import { compareProviderLetters, getProviderLetter } from '../../../block-selector/utils'
+import { BlockEnum } from '../../../types'
+
+type StrategyPreview = {
+ provider: AgentProviderResponse
+ strategy: AgentStrategyEntity
+}
+type OnSelectStrategy = (provider: AgentProviderResponse, strategy: AgentStrategyEntity) => void
+
+function StrategyAction({
+ provider,
+ strategy,
+ previewCardHandle,
+ onSelect,
+}: StrategyPreview & {
+ previewCardHandle: PreviewCardHandle<StrategyPreview>
+ onSelect: OnSelectStrategy
+}) {
+ const language = useGetLanguage()
+ const descriptionId = useId()
+ const description = renderI18nObject(strategy.description, language)
+ return (
+ <>
+ <PreviewCardTrigger
+ delay={150}
+ closeDelay={150}
+ handle={previewCardHandle}
+ payload={{ provider, strategy }}
+ render={
+ <Button
+ variant="ghost"
+ size="medium"
+ aria-describedby={description ? descriptionId : undefined}
+ className="w-full justify-between pr-1 pl-5.25 text-left focus-visible:ring-inset"
+ onClick={() => {
+ onSelect(provider, strategy)
+ trackEvent('tool_selected', {
+ tool_name: strategy.identity.name,
+ plugin_id: provider.plugin_id,
+ })
+ }}
+ >
+ <div className="truncate border-l-2 border-divider-subtle py-2 pl-4 system-sm-medium text-text-secondary">
+ {renderI18nObject(strategy.identity.label, language)}
+ </div>
+ </Button>
+ }
+ />
+ {description && (
+ <span id={descriptionId} className="sr-only">
+ {description}
+ </span>
+ )}
+ </>
+ )
+}
+
+function StrategyProvider({
+ provider,
+ previewCardHandle,
+ onSelect,
+}: {
+ provider: AgentProviderResponse
+ previewCardHandle: PreviewCardHandle<StrategyPreview>
+ onSelect: OnSelectStrategy
+}) {
+ const language = useGetLanguage()
+ const { getIconUrl } = useGetIcon()
+ const panelId = useId()
+ return (
+ <Collapsible className="mb-1 last-of-type:mb-0">
+ <div className="group/item relative flex w-full items-center rounded-lg">
+ <CollapsibleTrigger
+ aria-controls={panelId}
+ className="group/collapsible flex h-8 min-h-8 w-full min-w-0 touch-manipulation items-center justify-start gap-0 rounded-lg bg-transparent pr-2 pl-3 text-start system-sm-medium text-text-secondary outline-hidden select-none group-hover/item:bg-state-base-hover hover:bg-state-base-hover hover:text-text-primary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:ring-inset data-panel-open:text-text-primary"
+ >
+ <BlockIcon
+ className="shrink-0"
+ type={BlockEnum.Tool}
+ toolIcon={
+ provider.declaration.identity.icon
+ ? getIconUrl(provider.declaration.identity.icon)
+ : ''
+ }
+ />
+ <div className="ml-2 flex w-0 grow items-center text-sm text-text-primary">
+ <span className="max-w-62.5 truncate">
+ {renderI18nObject(provider.declaration.identity.label, language)}
+ </span>
+ </div>
+ <span
+ aria-hidden
+ className="ml-2 i-ri-arrow-right-s-line size-4 shrink-0 text-text-quaternary transition-transform group-data-panel-open/collapsible:rotate-90 motion-reduce:transition-none"
+ />
+ </CollapsibleTrigger>
+ </div>
+ <CollapsiblePanel id={panelId}>
+ {provider.declaration.strategies?.map((strategy) => (
+ <StrategyAction
+ key={strategy.identity.name}
+ provider={provider}
+ strategy={strategy}
+ previewCardHandle={previewCardHandle}
+ onSelect={onSelect}
+ />
+ ))}
+ </CollapsiblePanel>
+ </Collapsible>
+ )
+}
+
+export function AgentStrategyList({
+ providers,
+ viewType,
+ onSelect,
+ className,
+}: {
+ providers: AgentProviderResponse[]
+ viewType: ViewType
+ onSelect: OnSelectStrategy
+ className?: string
+}) {
+ const language = useGetLanguage()
+ const { getIconUrl } = useGetIcon()
+ const [previewCardHandle] = useState(() => createPreviewCardHandle<StrategyPreview>())
+ const itemRefsRef = useRef<Record<string, HTMLDivElement | null>>({})
+ const { letters, flatGroups, authorGroups } = useMemo(() => {
+ const buckets = new Map<string, Map<string, AgentProviderResponse[]>>()
+ for (const provider of providers) {
+ const identity = provider.declaration.identity
+ const label = renderI18nObject(identity.label, language) || identity.name
+ const letter = getProviderLetter(label[0] || '#')
+ const bucket = buckets.get(letter) ?? new Map<string, AgentProviderResponse[]>()
+ const group = bucket.get(identity.author) ?? []
+ group.push(provider)
+ bucket.set(identity.author, group)
+ buckets.set(letter, bucket)
+ }
+ const sortedBuckets = [...buckets].sort(([left], [right]) =>
+ compareProviderLetters(left, right),
+ )
+ const authorGroups = new Map<string, AgentProviderResponse[]>()
+ for (const bucket of buckets.values()) {
+ for (const [author, providers] of bucket) {
+ const group = authorGroups.get(author) ?? []
+ group.push(...providers)
+ authorGroups.set(author, group)
+ }
+ }
+ return {
+ letters: sortedBuckets.map(([letter]) => letter),
+ flatGroups: sortedBuckets.map(([letter, groups]) => ({
+ letter,
+ providers: [...groups.values()].flat(),
+ })),
+ authorGroups: [...authorGroups],
+ }
+ }, [providers, language])
+
+ return (
+ <div className={cn('max-w-full p-1', className)}>
+ {!providers.length && (
+ <div className="py-10">
+ <Empty isAgent />
+ </div>
+ )}
+ {viewType === ViewType.flat ? (
+ <div className="flex w-full min-w-0">
+ <div className="mr-1 min-w-0 grow">
+ {flatGroups.flatMap(({ letter, providers }) =>
+ providers.map((provider, index) => (
+ <div
+ key={provider.declaration.identity.name}
+ ref={(element) => {
+ if (index === 0) itemRefsRef.current[letter] = element
+ }}
+ >
+ <StrategyProvider
+ provider={provider}
+ previewCardHandle={previewCardHandle}
+ onSelect={onSelect}
+ />
+ </div>
+ )),
+ )}
+ </div>
+ {providers.length > 10 && (
+ <IndexBar letters={letters} itemRefs={itemRefsRef} className="top-0 xl:top-36" />
+ )}
+ </div>
+ ) : (
+ <div>
+ {authorGroups.map(([author, providers]) => (
+ <div key={author}>
+ <div className="flex h-5.5 items-center px-3 text-xs font-medium text-text-tertiary">
+ {author}
+ </div>
+ {providers.map((provider) => (
+ <StrategyProvider
+ key={provider.declaration.identity.name}
+ provider={provider}
+ previewCardHandle={previewCardHandle}
+ onSelect={onSelect}
+ />
+ ))}
+ </div>
+ ))}
+ </div>
+ )}
+ <PreviewCard handle={previewCardHandle}>
+ {({ payload }) =>
+ payload && (
+ <BlockSelectorPreviewCardContent>
+ <BlockIcon
+ size="md"
+ className="mb-2"
+ type={BlockEnum.Tool}
+ toolIcon={
+ payload.provider.declaration.identity.icon
+ ? getIconUrl(payload.provider.declaration.identity.icon)
+ : ''
+ }
+ />
+ <div className="mb-1 text-sm/5 wrap-break-word text-text-primary">
+ {renderI18nObject(payload.strategy.identity.label, language)}
+ </div>
+ <div className="text-xs leading-4.5 wrap-break-word text-text-secondary">
+ {renderI18nObject(payload.strategy.description, language)}
+ </div>
+ </BlockSelectorPreviewCardContent>
+ )
+ }
+ </PreviewCard>
+ </div>
+ )
+}
diff --git a/web/app/components/workflow/nodes/_base/components/agent-strategy-selector.tsx b/web/app/components/workflow/nodes/_base/components/agent-strategy-selector.tsx
index 3057b2715ef..055eaaf46d7 100644
--- a/web/app/components/workflow/nodes/_base/components/agent-strategy-selector.tsx
+++ b/web/app/components/workflow/nodes/_base/components/agent-strategy-selector.tsx
@@ -1,7 +1,5 @@
import type { ReactNode } from 'react'
-import type { ToolWithProvider } from '../../../types'
import type { Strategy } from './agent-strategy'
-import type { StrategyPluginDetail } from '@/app/components/plugins/types'
import type {
ListProps,
ListRef,
@@ -9,22 +7,23 @@ import type {
import { cn } from '@langgenius/dify-ui/cn'
import { Infotip, InfotipContent, InfotipTrigger } from '@langgenius/dify-ui/infotip'
import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'
-import { useSuspenseQuery } from '@tanstack/react-query'
+import { useQuery, useSuspenseQuery } from '@tanstack/react-query'
import { memo, useEffect, useId, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { SearchInput } from '@/app/components/base/search-input'
import useGetIcon from '@/app/components/plugins/install-plugin/base/use-get-icon'
import { useMarketplacePlugins } from '@/app/components/plugins/marketplace/hooks'
import { PluginCategoryEnum } from '@/app/components/plugins/types'
-import { CollectionType } from '@/app/components/tools/types'
import PluginList from '@/app/components/workflow/block-selector/marketplace-plugin/list'
+import { useGetLanguage } from '@/context/i18n'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
+import { renderI18nObject } from '@/i18n/metadata'
import Link from '@/next/link'
-import { useStrategyProviders } from '@/service/use-strategy'
-import Tools from '../../../block-selector/tools'
+import { consoleQuery } from '@/service/console'
import { ViewType } from '../../../block-selector/types'
import ViewTypeSelect from '../../../block-selector/view-type-select'
import { useStrategyInfo } from '../../agent/use-config'
+import { AgentStrategyList } from './agent-strategy-list'
import { InstallPluginButton } from './install-plugin-button'
import { SwitchPluginVersion } from './switch-plugin-version'
@@ -60,40 +59,6 @@ const NotFoundWarn = (props: { title: string; description: ReactNode }) => {
)
}
-function formatStrategy(
- input: StrategyPluginDetail[],
- getIcon: (i: string) => string,
-): ToolWithProvider[] {
- return input.map((item) => {
- const res: ToolWithProvider = {
- id: item.plugin_unique_identifier,
- author: item.declaration.identity.author,
- name: item.declaration.identity.name,
- description: item.declaration.identity.description as ToolWithProvider['description'],
- plugin_id: item.plugin_id,
- icon: getIcon(item.declaration.identity.icon),
- label: item.declaration.identity.label as ToolWithProvider['label'],
- type: CollectionType.all,
- meta: item.meta,
- tools: item.declaration.strategies.map((strategy) => ({
- name: strategy.identity.name,
- author: strategy.identity.author,
- label: strategy.identity.label as ToolWithProvider['tools'][number]['label'],
- description: strategy.description,
- parameters:
- strategy.parameters as unknown as ToolWithProvider['tools'][number]['parameters'],
- output_schema: strategy.output_schema,
- labels: [],
- })),
- team_credentials: {},
- is_team_authorization: true,
- allow_delete: false,
- labels: [],
- }
- return res
- })
-}
-
type AgentStrategySelectorProps = {
value?: Strategy
onChange: (value?: Strategy) => void
@@ -109,13 +74,14 @@ export const AgentStrategySelector = memo((props: AgentStrategySelectorProps) =>
const [open, setOpen] = useState(false)
const [viewType, setViewType] = useState<ViewType>(ViewType.flat)
const [query, setQuery] = useState('')
- const stra = useStrategyProviders()
+ const providers = useQuery(consoleQuery.workspaces.current.agentProviders.get.queryOptions())
+ const language = useGetLanguage()
const { getIconUrl } = useGetIcon()
- const list = stra.data ? formatStrategy(stra.data, getIconUrl) : undefined
- const filteredTools = useMemo(() => {
- if (!list) return []
- return list.filter((tool) => tool.name.toLowerCase().includes(query.toLowerCase()))
- }, [query, list])
+ const filteredProviders = useMemo(() => {
+ return (providers.data ?? []).filter((provider) =>
+ provider.declaration.identity.name.toLowerCase().includes(query.toLowerCase()),
+ )
+ }, [query, providers.data])
const { strategyStatus, refetch: refetchStrategyInfo } = useStrategyInfo(
value?.agent_strategy_provider_name,
value?.agent_strategy_name,
@@ -139,9 +105,12 @@ export const AgentStrategySelector = memo((props: AgentStrategySelectorProps) =>
!strategyStatus.plugin.installed &&
!!value
- const icon = list?.find((coll) =>
- coll.tools?.find((tool) => tool.name === value?.agent_strategy_name),
- )?.icon as string | undefined
+ const selectedProvider = providers.data?.find(
+ (provider) => provider.declaration.identity.name === value?.agent_strategy_provider_name,
+ )
+ const icon = selectedProvider?.declaration.identity.icon
+ ? getIconUrl(selectedProvider.declaration.identity.icon)
+ : undefined
const { t } = useTranslation()
const wrapElemRef = useRef<HTMLDivElement>(null)
@@ -189,7 +158,7 @@ export const AgentStrategySelector = memo((props: AgentStrategySelectorProps) =>
t(($) => $['nodes.agent.strategy.selectTip'], { ns: 'workflow' })}
</p>
<div className="ml-auto flex items-center gap-1">
- {showInstallButton && value && (
+ {showInstallButton && value?.plugin_unique_identifier && (
<InstallPluginButton
onClick={(e) => e.stopPropagation()}
size="small"
@@ -214,7 +183,7 @@ export const AgentStrategySelector = memo((props: AgentStrategySelectorProps) =>
aria-hidden="true"
/>
)}
- {showSwitchVersion && value && (
+ {showSwitchVersion && value?.plugin_unique_identifier && (
<SwitchPluginVersion
uniqueIdentifier={value.plugin_unique_identifier}
tooltip={
@@ -259,25 +228,21 @@ export const AgentStrategySelector = memo((props: AgentStrategySelectorProps) =>
className="relative flex w-full flex-col overflow-hidden md:max-h-75 xl:max-h-100 2xl:max-h-141"
ref={wrapElemRef}
>
- <Tools
- tools={filteredTools}
+ <AgentStrategyList
+ providers={filteredProviders}
viewType={viewType}
- onSelect={(_, tool) => {
+ onSelect={(provider, strategy) => {
onChange({
- agent_strategy_name: tool!.tool_name,
- agent_strategy_provider_name: tool!.provider_name,
- agent_strategy_label: tool!.tool_label,
- agent_output_schema: tool!.output_schema || {},
- plugin_unique_identifier: tool!.provider_id,
- meta: tool!.meta,
+ agent_strategy_name: strategy.identity.name,
+ agent_strategy_provider_name: provider.declaration.identity.name,
+ agent_strategy_label: renderI18nObject(strategy.identity.label, language),
+ agent_output_schema: strategy.output_schema,
+ plugin_unique_identifier: provider.plugin_unique_identifier,
+ meta: provider.meta,
})
setOpen(false)
}}
className="h-full max-h-full max-w-none overflow-y-auto"
- indexBarClassName="top-0 xl:top-36"
- hasSearchText={false}
- canNotSelectMultiple
- isAgent
/>
{enable_marketplace && (
<PluginList
diff --git a/web/app/components/workflow/nodes/_base/components/agent-strategy.tsx b/web/app/components/workflow/nodes/_base/components/agent-strategy.tsx
index e0061a6d776..d6c8de42013 100644
--- a/web/app/components/workflow/nodes/_base/components/agent-strategy.tsx
+++ b/web/app/components/workflow/nodes/_base/components/agent-strategy.tsx
@@ -1,13 +1,13 @@
+import type {
+ AgentStrategyEntity,
+ AgentStrategyParameter,
+ AgentStrategyParameterType,
+ Meta,
+} from '@dify/contracts/api/console/workspaces/types.gen'
import type { ComponentProps } from 'react'
import type { Node } from 'reactflow'
import type { NodeOutPutVar } from '../../../types'
-import type { ToolVarInputs } from '../../tool/types'
-import type {
- CredentialFormSchema,
- CredentialFormSchemaNumberInput,
- CredentialFormSchemaTextInput,
-} from '@/app/components/header/account-setting/model-provider-page/declarations'
-import type { PluginMeta } from '@/app/components/plugins/types'
+import type { CredentialFormSchema } from '@/app/components/header/account-setting/model-provider-page/declarations'
import { Fieldset, FieldsetLegend } from '@langgenius/dify-ui/fieldset'
import {
NumberField,
@@ -25,7 +25,6 @@ import {
SliderThumb,
SliderTrack,
} from '@langgenius/dify-ui/slider'
-import { noop } from 'es-toolkit/function'
import { memo } from 'react'
import { useTranslation } from 'react-i18next'
import { Agent } from '@/app/components/base/icons/src/vender/workflow'
@@ -36,8 +35,6 @@ import {
} from '@/app/components/header/account-setting/model-provider-page/declarations'
import { useDefaultModel } from '@/app/components/header/account-setting/model-provider-page/hooks'
import Form from '@/app/components/header/account-setting/model-provider-page/model-modal/Form'
-import MultipleToolSelector from '@/app/components/plugins/plugin-detail-panel/multiple-tool-selector'
-import ToolSelector from '@/app/components/plugins/plugin-detail-panel/tool-selector'
import { useDocLink } from '@/context/i18n'
import { useRenderI18nObject } from '@/hooks/use-i18n'
import Link from '@/next/link'
@@ -51,28 +48,36 @@ export type Strategy = {
agent_strategy_provider_name: string
agent_strategy_name: string
agent_strategy_label: string
- agent_output_schema: Record<string, any>
- plugin_unique_identifier: string
- meta?: PluginMeta
+ agent_output_schema: AgentStrategyEntity['output_schema']
+ plugin_unique_identifier?: string
+ meta?: Meta
}
type AgentStrategyProps = {
strategy?: Strategy
onStrategyChange: (strategy?: Strategy) => void
- formSchema: CredentialFormSchema[]
- formValue: ToolVarInputs
- onFormValueChange: (value: ToolVarInputs) => void
+ formSchema: AgentStrategyParameter[]
+ formValue: Record<string, unknown>
+ onFormValueChange: (value: Record<string, unknown>) => void
nodeOutputVars?: NodeOutPutVar[]
availableNodes?: Node[]
nodeId?: string
}
-type CustomSchema<Type, Field = {}> = Omit<CredentialFormSchema, 'type'> & { type: Type } & Field
-
-type ToolSelectorSchema = CustomSchema<'tool-selector'>
-type MultipleToolSelectorSchema = CustomSchema<'array[tools]'>
-
-type CustomField = ToolSelectorSchema | MultipleToolSelectorSchema
+const fieldTypes: Record<AgentStrategyParameterType, FormTypeEnum> = {
+ string: FormTypeEnum.textInput,
+ number: FormTypeEnum.textNumber,
+ boolean: FormTypeEnum.checkbox,
+ select: FormTypeEnum.select,
+ 'secret-input': FormTypeEnum.secretInput,
+ file: FormTypeEnum.file,
+ files: FormTypeEnum.files,
+ 'system-files': FormTypeEnum.files,
+ 'app-selector': FormTypeEnum.appSelector,
+ 'model-selector': FormTypeEnum.modelSelector,
+ 'array[tools]': FormTypeEnum.multiToolSelector,
+ any: FormTypeEnum.any,
+}
export const AgentStrategy = memo((props: AgentStrategyProps) => {
const {
@@ -92,13 +97,51 @@ export const AgentStrategy = memo((props: AgentStrategyProps) => {
const workflowStore = useWorkflowStore()
const { setControlPromptEditorRerenderKey } = workflowStore.getState()
- const override: ComponentProps<typeof Form<CustomField>>['override'] = [
+ const formSchemas: CredentialFormSchema[] = formSchema.map((parameter) => ({
+ name: parameter.name,
+ variable: parameter.name,
+ type: fieldTypes[parameter.type],
+ label: { en_US: renderI18nObject(parameter.label), zh_Hans: renderI18nObject(parameter.label) },
+ required: parameter.required ?? false,
+ show_on: [],
+ tooltip: parameter.help
+ ? { en_US: renderI18nObject(parameter.help), zh_Hans: renderI18nObject(parameter.help) }
+ : undefined,
+ placeholder: parameter.placeholder
+ ? {
+ en_US: renderI18nObject(parameter.placeholder),
+ zh_Hans: renderI18nObject(parameter.placeholder),
+ }
+ : undefined,
+ scope: parameter.scope ?? undefined,
+ min: parameter.min ?? undefined,
+ max: parameter.max ?? undefined,
+ options: (parameter.options ?? []).map((option) => ({
+ value: option.value,
+ label: { en_US: renderI18nObject(option.label), zh_Hans: renderI18nObject(option.label) },
+ show_on: [],
+ })),
+ }))
+ const values = { ...formValue }
+ for (const parameter of formSchema) {
+ if (values[parameter.name] === undefined && parameter.default !== undefined)
+ values[parameter.name] = parameter.default
+ }
+
+ const override: ComponentProps<typeof Form>['override'] = [
[FormTypeEnum.textNumber, FormTypeEnum.textInput],
(schema, props) => {
+ const parameter = formSchema.find((item) => item.name === schema.variable)
+ if (!parameter) return false
switch (schema.type) {
case FormTypeEnum.textInput: {
- const def = schema as CredentialFormSchemaTextInput
- const value = props.value[schema.variable] || schema.default
+ const fieldValue: unknown = props.value[schema.variable]
+ const value =
+ typeof fieldValue === 'string' && fieldValue !== ''
+ ? fieldValue
+ : typeof parameter.default === 'string'
+ ? parameter.default
+ : ''
const instanceId = schema.variable
const onChange = (value: string) => {
props.onChange({ ...props.value, [schema.variable]: value })
@@ -119,13 +162,13 @@ export const AgentStrategy = memo((props: AgentStrategyProps) => {
containerBackgroundClassName="bg-transparent"
gradientBorder={false}
nodeId={nodeId}
- isSupportPromptGenerator={!!def.auto_generate?.type}
+ isSupportPromptGenerator={!!parameter.auto_generate?.type}
titleTooltip={schema.tooltip && renderI18nObject(schema.tooltip)}
editorContainerClassName="px-0 bg-components-input-bg-normal focus-within:bg-components-input-bg-active rounded-lg"
availableNodes={availableNodes}
nodesOutputVars={nodeOutputVars}
- isSupportJinja={def.template?.enabled}
- required={def.required}
+ isSupportJinja={parameter.template?.enabled}
+ required={parameter.required}
varList={[]}
modelConfig={
defaultModel.data
@@ -144,12 +187,19 @@ export const AgentStrategy = memo((props: AgentStrategyProps) => {
)
}
case FormTypeEnum.textNumber: {
- const def = schema as CredentialFormSchemaNumberInput
- if (def.max == null || def.min == null) return false
+ if (parameter.max == null || parameter.min == null) return false
- const defaultValue = schema.default ? Number.parseInt(schema.default) : 1
- const value = props.value[schema.variable] ?? defaultValue
- const label = renderI18nObject(def.label)
+ const defaultValue =
+ typeof parameter.default === 'number' ||
+ (typeof parameter.default === 'string' && parameter.default !== '')
+ ? Number(parameter.default)
+ : 1
+ const fieldValue: unknown = props.value[schema.variable]
+ const value =
+ typeof fieldValue === 'number' || (typeof fieldValue === 'string' && fieldValue !== '')
+ ? Number(fieldValue)
+ : defaultValue
+ const label = renderI18nObject(parameter.label)
const onChange = (value: number) => {
props.onChange({ ...props.value, [schema.variable]: value })
}
@@ -157,11 +207,11 @@ export const AgentStrategy = memo((props: AgentStrategyProps) => {
<Field
title={
<>
- {label} {def.required && <span className="text-red-500">*</span>}
+ {label} {parameter.required && <span className="text-red-500">*</span>}
</>
}
- key={def.variable}
- tooltip={def.tooltip && renderI18nObject(def.tooltip)}
+ key={schema.variable}
+ tooltip={schema.tooltip && renderI18nObject(schema.tooltip)}
inline
>
<Fieldset className="flex w-50 items-center gap-3">
@@ -170,8 +220,8 @@ export const AgentStrategy = memo((props: AgentStrategyProps) => {
value={value}
onValueChange={onChange}
className="w-full"
- min={def.min}
- max={def.max}
+ min={parameter.min}
+ max={parameter.max}
>
<SliderLabel className="sr-only">{label}</SliderLabel>
<SliderControl>
@@ -183,8 +233,8 @@ export const AgentStrategy = memo((props: AgentStrategyProps) => {
</Slider>
<NumberField
value={value}
- min={def.min}
- max={def.max}
+ min={parameter.min}
+ max={parameter.max}
onValueChange={(nextValue) => onChange(nextValue ?? defaultValue)}
>
<NumberFieldGroup>
@@ -202,75 +252,19 @@ export const AgentStrategy = memo((props: AgentStrategyProps) => {
}
},
]
- const renderField: ComponentProps<typeof Form<CustomField>>['customRenderField'] = (
- schema,
- props,
- ) => {
- switch (schema.type) {
- case FormTypeEnum.toolSelector: {
- const value = props.value[schema.variable]
- const onChange = (value: any) => {
- props.onChange({ ...props.value, [schema.variable]: value })
- }
- return (
- <Field
- title={
- <>
- {renderI18nObject(schema.label)}{' '}
- {schema.required && <span className="text-red-500">*</span>}
- </>
- }
- tooltip={schema.tooltip && renderI18nObject(schema.tooltip)}
- >
- <ToolSelector
- nodeId={props.nodeId || ''}
- nodeOutputVars={props.nodeOutputVars || []}
- availableNodes={props.availableNodes || []}
- scope={schema.scope}
- value={value}
- onSelect={(item) => onChange(item)}
- onDelete={() => onChange(null)}
- onSelectMultiple={noop}
- />
- </Field>
- )
- }
- case FormTypeEnum.multiToolSelector: {
- const value = props.value[schema.variable]
- const onChange = (value: any) => {
- props.onChange({ ...props.value, [schema.variable]: value })
- }
- return (
- <MultipleToolSelector
- nodeId={props.nodeId || ''}
- nodeOutputVars={props.nodeOutputVars || []}
- availableNodes={props.availableNodes || []}
- scope={schema.scope}
- value={value || []}
- label={renderI18nObject(schema.label)}
- tooltip={schema.tooltip && renderI18nObject(schema.tooltip)}
- onChange={onChange}
- supportCollapse
- required={schema.required}
- />
- )
- }
- }
- }
return (
<div className="space-y-2">
<AgentStrategySelector value={strategy} onChange={onStrategyChange} />
{strategy ? (
<div>
- <Form<CustomField>
- formSchemas={[...formSchema]}
- value={formValue}
+ <Form
+ formSchemas={formSchemas}
+ value={values}
onChange={onFormValueChange}
validating={false}
showOnVariableMap={{}}
isEditMode={true}
fieldLabelClassName="uppercase"
- customRenderField={renderField}
override={override}
nodeId={nodeId}
nodeOutputVars={nodeOutputVars || []}
diff --git a/web/app/components/workflow/nodes/_base/components/form-input-type-switch.tsx b/web/app/components/workflow/nodes/_base/components/form-input-type-switch.tsx
index 1bf0cca6395..37834102bd8 100644
--- a/web/app/components/workflow/nodes/_base/components/form-input-type-switch.tsx
+++ b/web/app/components/workflow/nodes/_base/components/form-input-type-switch.tsx
@@ -3,11 +3,11 @@ import type { FC, ReactNode } from 'react'
import { SegmentedControl, SegmentedControlItem } from '@langgenius/dify-ui/segmented-control'
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
import { useTranslation } from 'react-i18next'
-import { VarType } from '@/app/components/workflow/nodes/tool/types'
+import { VarKindType } from '@/app/components/workflow/nodes/_base/types'
type Props = Readonly<{
- value: VarType
- onChange: (value: VarType) => void
+ value: VarKindType
+ onChange: (value: VarKindType) => void
readonly?: boolean
}>
@@ -15,7 +15,7 @@ type TypeOptionProps = {
children: ReactNode
label: string
selected: boolean
- value: VarType
+ value: VarKindType
}
const optionClassName =
@@ -23,7 +23,7 @@ const optionClassName =
function TypeOption({ children, label, selected, value }: TypeOptionProps) {
const option = (
- <SegmentedControlItem<VarType> value={value} aria-label={label} className={optionClassName}>
+ <SegmentedControlItem<VarKindType> value={value} aria-label={label} className={optionClassName}>
{children}
</SegmentedControlItem>
)
@@ -44,7 +44,7 @@ const FormInputTypeSwitch: FC<Props> = ({ value, onChange, readonly = false }) =
const inputLabel = t(($) => $['nodes.common.typeSwitch.input'], { ns: 'workflow' })
return (
- <SegmentedControl<VarType>
+ <SegmentedControl<VarKindType>
value={value}
onValueChange={(value) => onChange(value)}
disabled={readonly}
@@ -52,13 +52,17 @@ const FormInputTypeSwitch: FC<Props> = ({ value, onChange, readonly = false }) =
className="h-8 shrink-0"
>
<TypeOption
- value={VarType.variable}
+ value={VarKindType.variable}
label={variableLabel}
- selected={value === VarType.variable}
+ selected={value === VarKindType.variable}
>
<span aria-hidden className="i-custom-vender-solid-development-variable-02 size-4" />
</TypeOption>
- <TypeOption value={VarType.constant} label={inputLabel} selected={value === VarType.constant}>
+ <TypeOption
+ value={VarKindType.constant}
+ label={inputLabel}
+ selected={value === VarKindType.constant}
+ >
<span aria-hidden className="i-ri-edit-line size-4" />
</TypeOption>
</SegmentedControl>
diff --git a/web/app/components/workflow/nodes/_base/components/variable/__tests__/utils.spec.ts b/web/app/components/workflow/nodes/_base/components/variable/__tests__/utils.spec.ts
index f768e74b567..3353a6771a2 100644
--- a/web/app/components/workflow/nodes/_base/components/variable/__tests__/utils.spec.ts
+++ b/web/app/components/workflow/nodes/_base/components/variable/__tests__/utils.spec.ts
@@ -1,4 +1,5 @@
import type { AgentV2NodeType } from '@/app/components/workflow/nodes/agent-v2/types'
+import type { AgentNodeType } from '@/app/components/workflow/nodes/agent/types'
import type { AnswerNodeType } from '@/app/components/workflow/nodes/answer/types'
import type { HumanInputNodeType } from '@/app/components/workflow/nodes/human-input/types'
import type { LLMNodeType } from '@/app/components/workflow/nodes/llm/types'
@@ -81,6 +82,71 @@ describe('variable utils', () => {
])
})
+ it.each([null, undefined])(
+ 'keeps the built-in legacy Agent outputs without an output schema: %s',
+ (output_schema) => {
+ const node = createNode<AgentNodeType>({
+ type: BlockEnum.Agent,
+ title: 'Agent',
+ desc: '',
+ output_schema,
+ })
+ const availableVars = toNodeAvailableVars({
+ beforeNodes: [node],
+ isChatMode: false,
+ filterVar: () => true,
+ allPluginInfoList: {},
+ })
+ expect(availableVars.find((item) => item.nodeId === node.id)?.vars).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ variable: 'text', type: VarType.string }),
+ expect.objectContaining({ variable: 'json', type: VarType.arrayObject }),
+ ]),
+ )
+ },
+ )
+
+ it('keeps legacy Agent JSON Schema outputs selectable with canonical variable types', () => {
+ const node = createNode<AgentNodeType>({
+ type: BlockEnum.Agent,
+ title: 'Agent',
+ desc: '',
+ output_schema: {
+ properties: {
+ answer: { type: 'string' },
+ scores: { type: 'array', items: { type: 'number' } },
+ allowed: true,
+ forbidden: false,
+ unspecified: {},
+ emptyType: { type: '' },
+ },
+ },
+ })
+ const options = { beforeNodes: [node], isChatMode: false, allPluginInfoList: {} }
+ const availableVars = toNodeAvailableVars({ ...options, filterVar: () => true })
+ expect(availableVars.find((item) => item.nodeId === node.id)?.vars).toEqual(
+ expect.arrayContaining([
+ { variable: 'answer', type: VarType.string },
+ { variable: 'scores', type: VarType.arrayNumber },
+ { variable: 'allowed', type: VarType.any },
+ { variable: 'forbidden', type: VarType.any },
+ { variable: 'unspecified', type: VarType.any },
+ { variable: 'emptyType', type: VarType.any },
+ ]),
+ )
+ const stringVars = toNodeAvailableVars({
+ ...options,
+ filterVar: (variable) => variable.type === VarType.string,
+ })
+ expect(stringVars.find((item) => item.nodeId === node.id)?.vars).toContainEqual({
+ variable: 'answer',
+ type: VarType.string,
+ })
+ expect(stringVars.find((item) => item.nodeId === node.id)?.vars).not.toContainEqual(
+ expect.objectContaining({ variable: 'scores' }),
+ )
+ })
+
it('uses Agent v2 default declared outputs for agent nodes', () => {
const node = createNode<AgentV2NodeType>({
type: BlockEnum.Agent,
diff --git a/web/app/components/workflow/nodes/_base/components/variable/__tests__/var-reference-picker.branches.spec.tsx b/web/app/components/workflow/nodes/_base/components/variable/__tests__/var-reference-picker.branches.spec.tsx
index 875763a3d1c..df425ac511e 100644
--- a/web/app/components/workflow/nodes/_base/components/variable/__tests__/var-reference-picker.branches.spec.tsx
+++ b/web/app/components/workflow/nodes/_base/components/variable/__tests__/var-reference-picker.branches.spec.tsx
@@ -8,8 +8,8 @@ import {
resetFixtureCounters,
} from '@/app/components/workflow/__tests__/fixtures'
import { renderWorkflowFlowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'
+import { VarKindType } from '@/app/components/workflow/nodes/_base/types'
import { BlockEnum, InputVarType, VarType } from '@/app/components/workflow/types'
-import { VarType as VarKindType } from '../../../../tool/types'
import VarReferencePicker from '../var-reference-picker'
const { mockFetchDynamicOptions } = vi.hoisted(() => ({
diff --git a/web/app/components/workflow/nodes/_base/components/variable/__tests__/var-reference-picker.trigger.spec.tsx b/web/app/components/workflow/nodes/_base/components/variable/__tests__/var-reference-picker.trigger.spec.tsx
index 0fa96b3bbb0..8e1812c487b 100644
--- a/web/app/components/workflow/nodes/_base/components/variable/__tests__/var-reference-picker.trigger.spec.tsx
+++ b/web/app/components/workflow/nodes/_base/components/variable/__tests__/var-reference-picker.trigger.spec.tsx
@@ -1,8 +1,8 @@
import type { ComponentProps } from 'react'
import { Popover, PopoverContent } from '@langgenius/dify-ui/popover'
import { fireEvent, render, screen } from '@testing-library/react'
+import { VarKindType } from '@/app/components/workflow/nodes/_base/types'
import { BlockEnum, VarType } from '@/app/components/workflow/types'
-import { VarType as VarKindType } from '../../../../tool/types'
import VarReferencePickerTrigger from '../var-reference-picker.trigger'
const createProps = (
diff --git a/web/app/components/workflow/nodes/_base/components/variable/constant-field.tsx b/web/app/components/workflow/nodes/_base/components/variable/constant-field.tsx
index 8bad60e2f8a..9e5510f7b66 100644
--- a/web/app/components/workflow/nodes/_base/components/variable/constant-field.tsx
+++ b/web/app/components/workflow/nodes/_base/components/variable/constant-field.tsx
@@ -18,7 +18,7 @@ import * as React from 'react'
import { useCallback, useMemo } from 'react'
import { FormTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
import { useLanguage } from '@/app/components/header/account-setting/model-provider-page/hooks'
-import { VarType as VarKindType } from '@/app/components/workflow/nodes/tool/types'
+import { VarKindType } from '@/app/components/workflow/nodes/_base/types'
type Props = Readonly<{
schema: Partial<CredentialFormSchema>
diff --git a/web/app/components/workflow/nodes/_base/components/variable/utils.ts b/web/app/components/workflow/nodes/_base/components/variable/utils.ts
index 052fa87c980..ed227b53a95 100644
--- a/web/app/components/workflow/nodes/_base/components/variable/utils.ts
+++ b/web/app/components/workflow/nodes/_base/components/variable/utils.ts
@@ -53,19 +53,20 @@ import {
TEMPLATE_TRANSFORM_OUTPUT_STRUCT,
TOOL_OUTPUT_STRUCT,
} from '@/app/components/workflow/constants'
+import { VarKindType } from '@/app/components/workflow/nodes/_base/types'
import { getAgentV2OutputVars } from '@/app/components/workflow/nodes/agent-v2/output-variables'
import { isAgentV2NodeData } from '@/app/components/workflow/nodes/agent-v2/types'
import DataSourceNodeDefault from '@/app/components/workflow/nodes/data-source/default'
import HumanInputNodeDefault from '@/app/components/workflow/nodes/human-input/default'
import { DeliveryMethodType } from '@/app/components/workflow/nodes/human-input/types'
import ToolNodeDefault from '@/app/components/workflow/nodes/tool/default'
+import { resolveVarType } from '@/app/components/workflow/nodes/tool/output-schema-utils'
import PluginTriggerNodeDefault from '@/app/components/workflow/nodes/trigger-plugin/default'
import { BlockEnum, InputVarType, VarType } from '@/app/components/workflow/types'
import { VAR_REGEX } from '@/config'
import { AppModeEnum } from '@/types/app'
import { OUTPUT_FILE_SUB_VARIABLES } from '../../../constants'
import { Type } from '../../../llm/types'
-import { VarType as ToolVarType } from '../../../tool/types'
type WorkflowTranslate = <const Selector extends SelectorParam<'workflow'>>(
selector: Selector,
@@ -571,16 +572,14 @@ const formatItem = (
const payload = data as AgentNodeType
const outputs: Var[] = []
- Object.keys(payload.output_schema?.properties || {}).forEach((outputKey) => {
- const output = payload.output_schema.properties[outputKey]
- outputs.push({
- variable: outputKey,
- type:
- output.type === 'array'
- ? (`Array[${output.items?.type ? output.items.type.slice(0, 1).toLocaleUpperCase() + output.items.type.slice(1) : 'Unknown'}]` as VarType)
- : (`${output.type ? output.type.slice(0, 1).toLocaleUpperCase() + output.type.slice(1) : 'Unknown'}` as VarType),
+ const properties = payload.output_schema?.properties
+ if (properties && typeof properties === 'object' && !Array.isArray(properties)) {
+ Object.entries(properties).forEach(([variable, output]: [string, unknown]) => {
+ const schema =
+ output && typeof output === 'object' && !Array.isArray(output) ? output : {}
+ outputs.push({ variable, type: resolveVarType(schema).type })
})
- })
+ }
res.vars = [...outputs, ...TOOL_OUTPUT_STRUCT, ...AGENT_OUTPUT_STRUCT]
break
}
@@ -1329,12 +1328,12 @@ export const getNodeUsedVars = (node: Node): ValueSelector[] => {
const payload = data as ToolNodeType
const mixVars = matchNotSystemVars(
Object.keys(payload.tool_parameters)
- ?.filter((key) => payload.tool_parameters[key]!.type === ToolVarType.mixed)
+ ?.filter((key) => payload.tool_parameters[key]!.type === VarKindType.mixed)
.map((key) => payload.tool_parameters[key]!.value) as string[],
)
const vars =
Object.keys(payload.tool_parameters)
- .filter((key) => payload.tool_parameters[key]!.type === ToolVarType.variable)
+ .filter((key) => payload.tool_parameters[key]!.type === VarKindType.variable)
.map((key) => payload.tool_parameters[key]!.value as string) || []
res = [...(mixVars as ValueSelector[]), ...(vars as any)]
break
@@ -1366,12 +1365,12 @@ export const getNodeUsedVars = (node: Node): ValueSelector[] => {
const payload = data as DataSourceNodeType
const mixVars = matchNotSystemVars(
Object.keys(payload.datasource_parameters)
- ?.filter((key) => payload.datasource_parameters[key]!.type === ToolVarType.mixed)
+ ?.filter((key) => payload.datasource_parameters[key]!.type === VarKindType.mixed)
.map((key) => payload.datasource_parameters[key]!.value) as string[],
)
const vars =
Object.keys(payload.datasource_parameters)
- .filter((key) => payload.datasource_parameters[key]!.type === ToolVarType.variable)
+ .filter((key) => payload.datasource_parameters[key]!.type === VarKindType.variable)
.map((key) => payload.datasource_parameters[key]!.value as string) || []
res = [...(mixVars as ValueSelector[]), ...(vars as any)]
break
@@ -1697,14 +1696,14 @@ export const updateNodeVars = (
case BlockEnum.Tool: {
const payload = data as ToolNodeType
const hasShouldRenameVar = Object.keys(payload.tool_parameters)?.filter(
- (key) => payload.tool_parameters[key]!.type !== ToolVarType.constant,
+ (key) => payload.tool_parameters[key]!.type !== VarKindType.constant,
)
if (hasShouldRenameVar) {
Object.keys(payload.tool_parameters).forEach((key) => {
const value = payload.tool_parameters[key]!
const { type } = value!
if (
- type === ToolVarType.variable &&
+ type === VarKindType.variable &&
value!.value.join('.') === oldVarSelector.join('.')
) {
payload.tool_parameters[key] = {
@@ -1713,7 +1712,7 @@ export const updateNodeVars = (
}
}
- if (type === ToolVarType.mixed) {
+ if (type === VarKindType.mixed) {
payload.tool_parameters[key] = {
...value,
value: replaceOldVarInText(
@@ -1745,7 +1744,7 @@ export const updateNodeVars = (
const { type } = value!
if (
- type === ToolVarType.variable &&
+ type === VarKindType.variable &&
Array.isArray(value!.value) &&
value!.value.join('.') === oldVarSelector.join('.')
) {
@@ -1755,7 +1754,7 @@ export const updateNodeVars = (
}
}
- if (type === ToolVarType.mixed && typeof value!.value === 'string') {
+ if (type === VarKindType.mixed && typeof value!.value === 'string') {
payload.agent_parameters![key] = {
...value,
value: replaceOldVarInText(value!.value, oldVarSelector, newVarSelector),
@@ -1785,14 +1784,14 @@ export const updateNodeVars = (
case BlockEnum.DataSource: {
const payload = data as DataSourceNodeType
const hasShouldRenameVar = Object.keys(payload.datasource_parameters)?.filter(
- (key) => payload.datasource_parameters[key]!.type !== ToolVarType.constant,
+ (key) => payload.datasource_parameters[key]!.type !== VarKindType.constant,
)
if (hasShouldRenameVar) {
Object.keys(payload.datasource_parameters).forEach((key) => {
const value = payload.datasource_parameters[key]!
const { type } = value!
if (
- type === ToolVarType.variable &&
+ type === VarKindType.variable &&
value!.value.join('.') === oldVarSelector.join('.')
) {
payload.datasource_parameters[key] = {
@@ -1801,7 +1800,7 @@ export const updateNodeVars = (
}
}
- if (type === ToolVarType.mixed) {
+ if (type === VarKindType.mixed) {
payload.datasource_parameters[key] = {
...value,
value: replaceOldVarInText(
diff --git a/web/app/components/workflow/nodes/_base/components/variable/var-list.tsx b/web/app/components/workflow/nodes/_base/components/variable/var-list.tsx
index eaae1ba5fbf..65d4feeb276 100644
--- a/web/app/components/workflow/nodes/_base/components/variable/var-list.tsx
+++ b/web/app/components/workflow/nodes/_base/components/variable/var-list.tsx
@@ -11,7 +11,7 @@ import { useCallback, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import { ReactSortable } from 'react-sortablejs'
import { useKeyboardSortable } from '@/app/components/base/keyboard-sortable/use-keyboard-sortable'
-import { VarType as VarKindType } from '@/app/components/workflow/nodes/tool/types'
+import { VarKindType } from '@/app/components/workflow/nodes/_base/types'
import { toast } from '@/app/notifications'
import { checkKeys, replaceSpaceWithUnderscoreInVarNameInput } from '@/utils/var'
import RemoveButton from '../remove-button'
diff --git a/web/app/components/workflow/nodes/_base/components/variable/var-reference-picker.helpers.ts b/web/app/components/workflow/nodes/_base/components/variable/var-reference-picker.helpers.ts
index 602134d7a2f..c739346120b 100644
--- a/web/app/components/workflow/nodes/_base/components/variable/var-reference-picker.helpers.ts
+++ b/web/app/components/workflow/nodes/_base/components/variable/var-reference-picker.helpers.ts
@@ -1,10 +1,10 @@
'use client'
-import type { VarType as VarKindType } from '../../../tool/types'
import type {
CredentialFormSchema,
FormOption,
} from '@/app/components/header/account-setting/model-provider-page/declarations'
+import type { VarKindType } from '@/app/components/workflow/nodes/_base/types'
import type {
CommonNodeType,
Node,
diff --git a/web/app/components/workflow/nodes/_base/components/variable/var-reference-picker.trigger.tsx b/web/app/components/workflow/nodes/_base/components/variable/var-reference-picker.trigger.tsx
index 77957713a61..85f12317087 100644
--- a/web/app/components/workflow/nodes/_base/components/variable/var-reference-picker.trigger.tsx
+++ b/web/app/components/workflow/nodes/_base/components/variable/var-reference-picker.trigger.tsx
@@ -1,13 +1,13 @@
'use client'
import type { FC, ReactElement } from 'react'
-import type { VarType as VarKindType } from '../../../tool/types'
import type {
CredentialFormSchema,
CredentialFormSchemaSelect,
} from '@/app/components/header/account-setting/model-provider-page/declarations'
import type { Tool } from '@/app/components/tools/types'
import type { TriggerWithProvider } from '@/app/components/workflow/block-selector/types'
+import type { VarKindType } from '@/app/components/workflow/nodes/_base/types'
import type { Node, ToolWithProvider, ValueSelector, Var } from '@/app/components/workflow/types'
import { cn } from '@langgenius/dify-ui/cn'
import { PopoverTrigger } from '@langgenius/dify-ui/popover'
diff --git a/web/app/components/workflow/nodes/_base/components/variable/var-reference-picker.tsx b/web/app/components/workflow/nodes/_base/components/variable/var-reference-picker.tsx
index 668f7f20d3f..f6653bb7847 100644
--- a/web/app/components/workflow/nodes/_base/components/variable/var-reference-picker.tsx
+++ b/web/app/components/workflow/nodes/_base/components/variable/var-reference-picker.tsx
@@ -26,7 +26,7 @@ import { useTranslation } from 'react-i18next'
import { useNodes, useReactFlow, useStoreApi } from 'reactflow'
import { FormTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
// import type { BaseResource, BaseResourceProvider } from '@/app/components/workflow/nodes/_base/types'
-import { VarType as VarKindType } from '@/app/components/workflow/nodes/tool/types'
+import { VarKindType } from '@/app/components/workflow/nodes/_base/types'
import { useStore as useWorkflowStore } from '@/app/components/workflow/store'
import { BlockEnum } from '@/app/components/workflow/types'
import { isExceptionVariable } from '@/app/components/workflow/utils'
diff --git a/web/app/components/workflow/nodes/agent/__tests__/default.spec.ts b/web/app/components/workflow/nodes/agent/__tests__/default.spec.ts
new file mode 100644
index 00000000000..be128eaddff
--- /dev/null
+++ b/web/app/components/workflow/nodes/agent/__tests__/default.spec.ts
@@ -0,0 +1,70 @@
+import type { AgentStrategyParameter } from '@dify/contracts/api/console/workspaces/types.gen'
+import type { AgentNodeType } from '../types'
+import { VarKindType } from '@/app/components/workflow/nodes/_base/types'
+import { BlockEnum } from '@/app/components/workflow/types'
+import { withSelectorKey } from '@/test/i18n-mock'
+import nodeDefault from '../default'
+import { createStrategy } from './strategy-fixture'
+
+const t = withSelectorKey((key: string) => key, 'workflow')
+const check = (parameter: AgentStrategyParameter, value?: unknown) => {
+ const payload: AgentNodeType = {
+ title: 'Agent',
+ desc: '',
+ type: BlockEnum.Agent,
+ output_schema: null,
+ agent_parameters: value === undefined ? {} : { input: { type: VarKindType.constant, value } },
+ }
+ return nodeDefault.checkValid(payload, t, {
+ strategy: createStrategy({ parameters: [parameter] }),
+ language: 'en_US',
+ isReadyForCheckValid: true,
+ })
+}
+
+it.each([
+ { type: 'number', value: 0 },
+ { type: 'boolean', value: false },
+] satisfies { type: AgentStrategyParameter['type']; value: unknown }[])(
+ 'accepts required $type zero values from saved inputs and declaration defaults',
+ ({ type, value }) => {
+ const parameter: AgentStrategyParameter = {
+ name: 'input',
+ type,
+ label: { en_US: 'Input' },
+ required: true,
+ }
+ expect(check(parameter, value).isValid).toBe(true)
+ expect(check({ ...parameter, default: value === false ? false : 0 }).isValid).toBe(true)
+ },
+)
+
+it.each(['', null])(
+ 'accepts a cleared input %s with a declaration default, matching runtime initialization',
+ (value) => {
+ expect(
+ check(
+ {
+ name: 'input',
+ type: 'string',
+ label: { en_US: 'Input' },
+ required: true,
+ default: 'Default prompt',
+ },
+ value,
+ ).isValid,
+ ).toBe(true)
+ },
+)
+
+it('rejects an absent required input with a nullable default', () => {
+ expect(
+ check({
+ name: 'input',
+ type: 'string',
+ label: { en_US: 'Input' },
+ required: true,
+ default: null,
+ }).isValid,
+ ).toBe(false)
+})
diff --git a/web/app/components/workflow/nodes/agent/__tests__/integration.spec.tsx b/web/app/components/workflow/nodes/agent/__tests__/integration.spec.tsx
index 1a5aab8de39..e3bf432f6bd 100644
--- a/web/app/components/workflow/nodes/agent/__tests__/integration.spec.tsx
+++ b/web/app/components/workflow/nodes/agent/__tests__/integration.spec.tsx
@@ -1,21 +1,23 @@
-import type { GetWorkspacesCurrentModelsModelTypesByModelTypeData } from '@dify/contracts/api/console/workspaces/types.gen'
+import type {
+ AgentStrategyParameter,
+ GetWorkspacesCurrentModelsModelTypesByModelTypeData,
+} from '@dify/contracts/api/console/workspaces/types.gen'
import type { OperationKey } from '@orpc/tanstack-query'
import type { AgentNodeType } from '../types'
-import type { StrategyParamItem } from '@/app/components/plugins/types'
import type { PanelProps } from '@/types/workflow'
+import { zAgentStrategyParameter } from '@dify/contracts/api/console/workspaces/zod.gen'
import { fireEvent, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import {
FormTypeEnum,
ModelTypeEnum,
} from '@/app/components/header/account-setting/model-provider-page/declarations'
+import { VarKindType } from '@/app/components/workflow/nodes/_base/types'
import { BlockEnum } from '@/app/components/workflow/types'
-import { VarType as ToolVarType } from '../../tool/types'
import { ModelBar } from '../components/model-bar'
import { ToolIcon } from '../components/tool-icon'
import Node from '../node'
import Panel from '../panel'
-import { AgentFeature } from '../types'
import useConfig from '../use-config'
let mockTextGenerationModels:
@@ -172,21 +174,22 @@ const mockUseConfig = vi.mocked(useConfig)
const createStrategyParam = (
name: string,
- type: FormTypeEnum,
+ type: AgentStrategyParameter['type'],
required: boolean,
-): StrategyParamItem => ({
- name,
- type,
- required,
- label: { en_US: name } as StrategyParamItem['label'],
- help: { en_US: `${name} help` } as StrategyParamItem['help'],
- placeholder: { en_US: `${name} placeholder` } as StrategyParamItem['placeholder'],
- scope: 'global',
- default: null,
- options: [],
- template: { enabled: false },
- auto_generate: { type: 'none' },
-})
+) =>
+ zAgentStrategyParameter.parse({
+ name,
+ type,
+ required,
+ label: { en_US: name },
+ help: { en_US: `${name} help` },
+ placeholder: { en_US: `${name} placeholder` },
+ scope: 'global',
+ default: null,
+ options: [],
+ template: { enabled: false },
+ auto_generate: null,
+ })
const createData = (overrides: Partial<AgentNodeType> = {}): AgentNodeType => ({
title: 'Agent',
@@ -197,11 +200,11 @@ const createData = (overrides: Partial<AgentNodeType> = {}): AgentNodeType => ({
agent_strategy_name: 'react',
agent_strategy_label: 'React Agent',
agent_parameters: {
- modelParam: { type: ToolVarType.constant, value: { provider: 'openai', model: 'gpt-4o' } },
- toolParam: { type: ToolVarType.constant, value: { provider_name: 'author/tool-a' } },
- multiToolParam: { type: ToolVarType.constant, value: [{ provider_name: 'author/tool-b' }] },
+ modelParam: { type: VarKindType.constant, value: { provider: 'openai', model: 'gpt-4o' } },
+ toolParam: { type: VarKindType.constant, value: { provider_name: 'author/tool-a' } },
+ multiToolParam: { type: VarKindType.constant, value: [{ provider_name: 'author/tool-b' }] },
},
- meta: { version: '1.0.0' } as any,
+ meta: { version: '1.0.0' },
plugin_unique_identifier: 'provider/agent:1.0.0',
...overrides,
})
@@ -219,18 +222,17 @@ const createConfigResult = (
author: 'provider',
name: 'react',
icon: 'icon',
- label: { en_US: 'React Agent' } as any,
+ label: { en_US: 'React Agent' },
provider: 'provider/agent',
},
parameters: [
createStrategyParam('modelParam', FormTypeEnum.modelSelector, true),
createStrategyParam('optionalModel', FormTypeEnum.modelSelector, false),
- createStrategyParam('toolParam', FormTypeEnum.toolSelector, false),
createStrategyParam('multiToolParam', FormTypeEnum.multiToolSelector, false),
],
- description: { en_US: 'agent description' } as any,
+ description: { en_US: 'agent description' },
output_schema: {},
- features: [AgentFeature.HISTORY_MESSAGES],
+ features: ['history-messages'],
},
formData: {},
onFormChange: vi.fn(),
diff --git a/web/app/components/workflow/nodes/agent/__tests__/node.spec.tsx b/web/app/components/workflow/nodes/agent/__tests__/node.spec.tsx
index a7bf9947a23..27ec24d598e 100644
--- a/web/app/components/workflow/nodes/agent/__tests__/node.spec.tsx
+++ b/web/app/components/workflow/nodes/agent/__tests__/node.spec.tsx
@@ -1,11 +1,12 @@
+import type { AgentStrategyParameter } from '@dify/contracts/api/console/workspaces/types.gen'
import type { ReactNode } from 'react'
import type { AgentNodeType } from '../types'
import type useConfig from '../use-config'
-import type { StrategyParamItem } from '@/app/components/plugins/types'
+import { zAgentStrategyParameter } from '@dify/contracts/api/console/workspaces/zod.gen'
import { render, screen } from '@testing-library/react'
import { FormTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
+import { VarKindType } from '@/app/components/workflow/nodes/_base/types'
import { BlockEnum } from '@/app/components/workflow/types'
-import { VarType } from '../../tool/types'
import Node from '../node'
const mockUseConfig = vi.hoisted(() => vi.fn())
@@ -73,20 +74,21 @@ vi.mock('../../_base/components/setting-item', () => ({
),
}))
-const createStrategyParam = (overrides: Partial<StrategyParamItem> = {}): StrategyParamItem => ({
- name: 'requiredModel',
- type: FormTypeEnum.modelSelector,
- required: true,
- label: { en_US: 'Required Model' } as StrategyParamItem['label'],
- help: { en_US: 'Required model help' } as StrategyParamItem['help'],
- placeholder: { en_US: 'Required model placeholder' } as StrategyParamItem['placeholder'],
- scope: 'global',
- default: null,
- options: [],
- template: { enabled: false },
- auto_generate: { type: 'none' },
- ...overrides,
-})
+const createStrategyParam = (overrides: Partial<AgentStrategyParameter> = {}) =>
+ zAgentStrategyParameter.parse({
+ name: 'requiredModel',
+ type: FormTypeEnum.modelSelector,
+ required: true,
+ label: { en_US: 'Required Model' },
+ help: { en_US: 'Required model help' },
+ placeholder: { en_US: 'Required model placeholder' },
+ scope: 'global',
+ default: null,
+ options: [],
+ template: { enabled: false },
+ auto_generate: null,
+ ...overrides,
+ })
const createData = (overrides: Partial<AgentNodeType> = {}): AgentNodeType => ({
title: 'Agent',
@@ -99,15 +101,15 @@ const createData = (overrides: Partial<AgentNodeType> = {}): AgentNodeType => ({
plugin_unique_identifier: 'provider/agent:1.0.0',
agent_parameters: {
optionalModel: {
- type: VarType.constant,
+ type: VarKindType.constant,
value: { provider: 'openai', model: 'gpt-4o' },
},
toolParam: {
- type: VarType.constant,
+ type: VarKindType.constant,
value: { provider_name: 'author/tool-a' },
},
multiToolParam: {
- type: VarType.constant,
+ type: VarKindType.constant,
value: [{ provider_name: 'author/tool-b' }, { provider_name: 'author/tool-c' }],
},
},
@@ -127,7 +129,7 @@ const createConfigResult = (
author: 'provider',
name: 'react',
icon: 'icon',
- label: { en_US: 'React Agent' } as StrategyParamItem['label'],
+ label: { en_US: 'React Agent' },
provider: 'provider/agent',
},
parameters: [
@@ -136,18 +138,13 @@ const createConfigResult = (
name: 'optionalModel',
required: false,
}),
- createStrategyParam({
- name: 'toolParam',
- type: FormTypeEnum.toolSelector,
- required: false,
- }),
createStrategyParam({
name: 'multiToolParam',
type: FormTypeEnum.multiToolSelector,
required: false,
}),
],
- description: { en_US: 'agent description' } as StrategyParamItem['label'],
+ description: { en_US: 'agent description' },
output_schema: {},
features: [],
},
@@ -207,11 +204,10 @@ describe('agent/node', () => {
)
expect(screen.getByText('requiredModel:empty-model')).toBeInTheDocument()
expect(screen.getByText('optionalModel:openai/gpt-4o')).toBeInTheDocument()
- expect(screen.getByText('tool:author/tool-a')).toBeInTheDocument()
expect(screen.getByText('tool:author/tool-b')).toBeInTheDocument()
expect(screen.getByText('tool:author/tool-c')).toBeInTheDocument()
expect(mockModelBar).toHaveBeenCalledTimes(2)
- expect(mockToolIcon).toHaveBeenCalledTimes(3)
+ expect(mockToolIcon).toHaveBeenCalledTimes(2)
})
it('skips optional models and empty tool values when no configuration is provided', () => {
@@ -227,11 +223,6 @@ describe('agent/node', () => {
name: 'optionalModel',
required: false,
}),
- createStrategyParam({
- name: 'toolParam',
- type: FormTypeEnum.toolSelector,
- required: false,
- }),
],
},
currentStrategyStatus: {
diff --git a/web/app/components/workflow/nodes/agent/__tests__/panel.spec.tsx b/web/app/components/workflow/nodes/agent/__tests__/panel.spec.tsx
index 4966bbea2ae..48a79dd7591 100644
--- a/web/app/components/workflow/nodes/agent/__tests__/panel.spec.tsx
+++ b/web/app/components/workflow/nodes/agent/__tests__/panel.spec.tsx
@@ -1,14 +1,14 @@
+import type { AgentStrategyParameter } from '@dify/contracts/api/console/workspaces/types.gen'
import type { ReactNode } from 'react'
import type { AgentNodeType } from '../types'
import type useConfig from '../use-config'
-import type { StrategyParamItem } from '@/app/components/plugins/types'
import type { NodePanelProps } from '@/app/components/workflow/types'
+import { zAgentStrategyParameter } from '@dify/contracts/api/console/workspaces/zod.gen'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { FormTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
import { BlockEnum } from '@/app/components/workflow/types'
import Panel from '../panel'
-import { AgentFeature } from '../types'
const mockUseConfig = vi.hoisted(() => vi.fn())
const mockResetEditor = vi.hoisted(() => vi.fn())
@@ -36,17 +36,17 @@ vi.mock('../../_base/components/agent-strategy', () => ({
agent_strategy_name: string
agent_strategy_label: string
agent_output_schema: AgentNodeType['output_schema']
- plugin_unique_identifier: string
+ plugin_unique_identifier?: string
meta?: AgentNodeType['meta']
}
- formSchema: Array<{ variable: string; tooltip?: StrategyParamItem['help'] }>
+ formSchema: AgentStrategyParameter[]
formValue: Record<string, unknown>
onStrategyChange: (strategy: {
agent_strategy_provider_name: string
agent_strategy_name: string
agent_strategy_label: string
agent_output_schema: AgentNodeType['output_schema']
- plugin_unique_identifier: string
+ plugin_unique_identifier?: string
meta?: AgentNodeType['meta']
}) => void
onFormValueChange: (value: Record<string, unknown>) => void
@@ -124,20 +124,21 @@ vi.mock('../../_base/components/output-vars', () => ({
),
}))
-const createStrategyParam = (overrides: Partial<StrategyParamItem> = {}): StrategyParamItem => ({
- name: 'instruction',
- type: FormTypeEnum.any,
- required: true,
- label: { en_US: 'Instruction' } as StrategyParamItem['label'],
- help: { en_US: 'Instruction help' } as StrategyParamItem['help'],
- placeholder: { en_US: 'Instruction placeholder' } as StrategyParamItem['placeholder'],
- scope: 'global',
- default: null,
- options: [],
- template: { enabled: false },
- auto_generate: { type: 'none' },
- ...overrides,
-})
+const createStrategyParam = (overrides: Partial<AgentStrategyParameter> = {}) =>
+ zAgentStrategyParameter.parse({
+ name: 'instruction',
+ type: FormTypeEnum.any,
+ required: true,
+ label: { en_US: 'Instruction' },
+ help: { en_US: 'Instruction help' },
+ placeholder: { en_US: 'Instruction placeholder' },
+ scope: 'global',
+ default: null,
+ options: [],
+ template: { enabled: false },
+ auto_generate: null,
+ ...overrides,
+ })
const createData = (overrides: Partial<AgentNodeType> = {}): AgentNodeType => ({
title: 'Agent',
@@ -179,7 +180,7 @@ const createConfigResult = (
author: 'provider',
name: 'react',
icon: 'icon',
- label: { en_US: 'React Agent' } as StrategyParamItem['label'],
+ label: { en_US: 'React Agent' },
provider: 'provider/agent',
},
parameters: [
@@ -190,9 +191,9 @@ const createConfigResult = (
required: false,
}),
],
- description: { en_US: 'agent description' } as StrategyParamItem['label'],
+ description: { en_US: 'agent description' },
output_schema: {},
- features: [AgentFeature.HISTORY_MESSAGES],
+ features: ['history-messages'],
},
formData: {
instruction: 'Plan and answer',
@@ -257,11 +258,11 @@ describe('agent/panel', () => {
expect.objectContaining({
formSchema: expect.arrayContaining([
expect.objectContaining({
- variable: 'instruction',
- tooltip: { en_US: 'Instruction help' },
+ name: 'instruction',
+ help: { en_US: 'Instruction help' },
}),
expect.objectContaining({
- variable: 'modelParam',
+ name: 'modelParam',
}),
]),
formValue: {
@@ -296,6 +297,21 @@ describe('agent/panel', () => {
expect(mockResetEditor).toHaveBeenCalledTimes(1)
})
+ it('keeps a saved strategy selected without optional plugin installation metadata', () => {
+ const inputs = createData({ plugin_unique_identifier: undefined })
+ mockUseConfig.mockReturnValue(createConfigResult({ inputs }))
+ render(<Panel id="agent-node" data={inputs} panelProps={panelProps} />)
+ expect(mockAgentStrategy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ strategy: expect.objectContaining({
+ agent_strategy_name: 'react',
+ plugin_unique_identifier: undefined,
+ }),
+ formValue: { instruction: 'Plan and answer' },
+ }),
+ )
+ })
+
it('hides memory config when chat mode support is unavailable', () => {
mockUseConfig.mockReturnValue(
createConfigResult({
diff --git a/web/app/components/workflow/nodes/agent/__tests__/strategy-fixture.ts b/web/app/components/workflow/nodes/agent/__tests__/strategy-fixture.ts
new file mode 100644
index 00000000000..9de48fd81f4
--- /dev/null
+++ b/web/app/components/workflow/nodes/agent/__tests__/strategy-fixture.ts
@@ -0,0 +1,48 @@
+import type {
+ AgentProviderResponse,
+ AgentStrategyEntity,
+} from '@dify/contracts/api/console/workspaces/types.gen'
+
+export const createStrategy = (
+ overrides: Partial<AgentStrategyEntity> = {},
+): AgentStrategyEntity => ({
+ identity: {
+ author: 'Dify',
+ name: 'react',
+ label: { en_US: 'ReAct' },
+ provider: 'langgenius/agent/provider',
+ },
+ description: { en_US: 'Reason and use tools', zh_Hans: null },
+ parameters: [
+ {
+ name: 'instruction',
+ type: 'string',
+ label: { en_US: 'Instruction' },
+ default: 'Default prompt',
+ },
+ ],
+ output_schema: null,
+ features: null,
+ ...overrides,
+})
+
+export const createProvider = (
+ strategies: AgentStrategyEntity[] = [createStrategy()],
+): AgentProviderResponse => ({
+ provider: 'provider',
+ plugin_id: 'langgenius/agent',
+ plugin_unique_identifier: 'langgenius/agent:1.0.0@hash',
+ meta: { version: null },
+ declaration: {
+ identity: {
+ author: 'Dify',
+ name: 'langgenius/agent/provider',
+ icon: 'agent.svg',
+ label: { en_US: 'Agent provider' },
+ description: { en_US: 'Agent strategies' },
+ tags: null,
+ },
+ plugin_id: 'langgenius/agent',
+ strategies,
+ },
+})
diff --git a/web/app/components/workflow/nodes/agent/__tests__/use-config.spec.ts b/web/app/components/workflow/nodes/agent/__tests__/use-config.spec.ts
index 4013aa34dd6..426e05f6778 100644
--- a/web/app/components/workflow/nodes/agent/__tests__/use-config.spec.ts
+++ b/web/app/components/workflow/nodes/agent/__tests__/use-config.spec.ts
@@ -1,455 +1,199 @@
import type { AgentNodeType } from '../types'
-import type { StrategyParamItem } from '@/app/components/plugins/types'
-import { act, renderHook, waitFor } from '@testing-library/react'
-import { FormTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
-import { BlockEnum, VarType as WorkflowVarType } from '@/app/components/workflow/types'
-import { VarType } from '../../tool/types'
+import { QueryClient } from '@tanstack/react-query'
+import { act, waitFor } from '@testing-library/react'
+import { VarKindType } from '@/app/components/workflow/nodes/_base/types'
+import { BlockEnum } from '@/app/components/workflow/types'
+import { renderHookWithConsoleQuery as renderHook } from '@/test/console/query-data'
import useConfig, { useStrategyInfo } from '../use-config'
+import { createProvider, createStrategy } from './strategy-fixture'
-const mockUseNodesReadOnly = vi.hoisted(() => vi.fn())
-const mockUseIsChatMode = vi.hoisted(() => vi.fn())
-const mockUseNodeCrud = vi.hoisted(() => vi.fn())
-const mockUseVarList = vi.hoisted(() => vi.fn())
-const mockUseAvailableVarList = vi.hoisted(() => vi.fn())
-const mockUseStrategyProviderDetail = vi.hoisted(() => vi.fn())
-const mockUseFetchPluginsInMarketPlaceByIds = vi.hoisted(() => vi.fn())
-const mockUseCheckInstalled = vi.hoisted(() => vi.fn())
-const mockGenerateAgentToolValue = vi.hoisted(() => vi.fn())
-const mockToolParametersToFormSchemas = vi.hoisted(() => vi.fn())
-
-vi.mock('../../../hooks/use-workflow', async (importOriginal) => {
- const actual = await importOriginal<typeof import('../../../hooks/use-workflow')>()
-
- return {
- ...actual,
- useNodesReadOnly: (...args: unknown[]) => mockUseNodesReadOnly(...args),
- useIsChatMode: (...args: unknown[]) => mockUseIsChatMode(...args),
- }
-})
-
-vi.mock('@/app/components/workflow/nodes/_base/hooks/use-node-crud', () => ({
- __esModule: true,
- default: (...args: unknown[]) => mockUseNodeCrud(...args),
+const { request, setInputs, marketplaceRefetch, marketplaceQuery } = vi.hoisted(() => ({
+ request: vi.fn(),
+ setInputs: vi.fn(),
+ marketplaceRefetch: vi.fn(),
+ marketplaceQuery: vi.fn(),
}))
-
-vi.mock('@/app/components/workflow/nodes/_base/hooks/use-var-list', () => ({
- __esModule: true,
- default: (...args: unknown[]) => mockUseVarList(...args),
+vi.mock('@/service/base', () => ({ request }))
+vi.mock('../../../hooks/use-workflow', () => ({
+ useNodesReadOnly: () => ({ nodesReadOnly: false }),
+ useIsChatMode: () => true,
}))
-
-vi.mock('@/app/components/workflow/nodes/_base/hooks/use-available-var-list', () => ({
- __esModule: true,
- default: (...args: unknown[]) => mockUseAvailableVarList(...args),
+vi.mock('../../_base/hooks/use-node-crud', () => ({
+ default: (_id: string, inputs: AgentNodeType) => ({ inputs, setInputs }),
}))
-
-vi.mock('@/service/use-strategy', () => ({
- useStrategyProviderDetail: (...args: unknown[]) => mockUseStrategyProviderDetail(...args),
+vi.mock('../../_base/hooks/use-var-list', () => ({
+ default: () => ({ handleVarListChange: vi.fn(), handleAddVariable: vi.fn() }),
}))
-
-vi.mock('@/service/use-plugins', () => ({
- useFetchPluginsInMarketPlaceByIds: (...args: unknown[]) =>
- mockUseFetchPluginsInMarketPlaceByIds(...args),
- useCheckInstalled: (...args: unknown[]) => mockUseCheckInstalled(...args),
+vi.mock('../../_base/hooks/use-available-var-list', () => ({
+ default: () => ({ availableVars: [], availableNodesWithParent: [] }),
}))
-
-vi.mock('@/app/components/tools/utils/to-form-schema', () => ({
- generateAgentToolValue: (...args: unknown[]) => mockGenerateAgentToolValue(...args),
- toolParametersToFormSchemas: (...args: unknown[]) => mockToolParametersToFormSchemas(...args),
+vi.mock('@/service/use-plugins', () => ({
+ useFetchPluginsInMarketPlaceByIds: marketplaceQuery,
+ useCheckInstalled: () => ({ data: { plugins: [] } }),
}))
-const createStrategyParam = (overrides: Partial<StrategyParamItem> = {}): StrategyParamItem => ({
- name: 'instruction',
- type: FormTypeEnum.any,
- required: true,
- label: { en_US: 'Instruction' } as StrategyParamItem['label'],
- help: { en_US: 'Instruction help' } as StrategyParamItem['help'],
- placeholder: { en_US: 'Instruction placeholder' } as StrategyParamItem['placeholder'],
- scope: 'global',
- default: null,
- options: [],
- template: { enabled: false },
- auto_generate: { type: 'none' },
- ...overrides,
-})
-
-const createToolValue = () => ({
- settings: {
- api_key: 'secret',
- },
- parameters: {
- query: 'weather',
- },
- schemas: [
- {
- variable: 'api_key',
- form: 'form',
- },
- {
- variable: 'query',
- form: 'llm',
- },
- ],
-})
-
const createData = (overrides: Partial<AgentNodeType> = {}): AgentNodeType => ({
title: 'Agent',
desc: '',
type: BlockEnum.Agent,
- output_schema: {
- properties: {
- summary: {
- type: 'string',
- description: 'summary output',
- },
- items: {
- type: 'array',
- items: {
- type: 'number',
- },
- description: 'items output',
- },
- },
- },
- agent_strategy_provider_name: 'provider/agent',
+ output_schema: null,
+ agent_strategy_provider_name: 'langgenius/agent/provider',
agent_strategy_name: 'react',
- agent_strategy_label: 'React Agent',
- plugin_unique_identifier: 'provider/agent:1.0.0',
- agent_parameters: {
- instruction: {
- type: VarType.variable,
- value: '#start.topic#',
- },
- modelParam: {
- type: VarType.constant,
- value: {
- provider: 'openai',
- model: 'gpt-4o',
- },
- },
- },
- meta: { version: '1.0.0' } as AgentNodeType['meta'],
+ agent_parameters: { instruction: { type: VarKindType.constant, value: '' } },
+ tool_node_version: '2',
...overrides,
})
-describe('agent/use-config', () => {
- const providerRefetch = vi.fn()
- const marketplaceRefetch = vi.fn()
- const setInputs = vi.fn()
- const handleVarListChange = vi.fn()
- const handleAddVariable = vi.fn()
- let currentInputs: AgentNodeType
-
- beforeEach(() => {
- vi.clearAllMocks()
- currentInputs = createData({
- tool_node_version: '2',
- })
-
- mockUseNodesReadOnly.mockReturnValue({ nodesReadOnly: false, getNodesReadOnly: () => false })
- mockUseIsChatMode.mockReturnValue(true)
- mockUseNodeCrud.mockImplementation(() => ({
- inputs: currentInputs,
- setInputs,
- }))
- mockUseVarList.mockReturnValue({
- handleVarListChange,
- handleAddVariable,
- } as never)
- mockUseAvailableVarList.mockReturnValue({
- availableVars: [
- {
- nodeId: 'node-1',
- title: 'Start',
- vars: [
- {
- variable: 'topic',
- type: WorkflowVarType.string,
- },
- ],
- },
- ],
- availableNodesWithParent: [
- {
- nodeId: 'node-1',
- title: 'Start',
- },
- ],
- } as never)
- mockUseStrategyProviderDetail.mockReturnValue({
- isLoading: false,
- isError: false,
- data: {
- declaration: {
- strategies: [
- {
- identity: {
- name: 'react',
- },
- parameters: [
- createStrategyParam(),
- createStrategyParam({
- name: 'modelParam',
- type: FormTypeEnum.modelSelector,
- required: false,
- }),
- ],
- },
- ],
- },
- },
- refetch: providerRefetch,
- } as never)
- mockUseFetchPluginsInMarketPlaceByIds.mockReturnValue({
- isLoading: false,
- data: {
- data: {
- plugins: [{ id: 'provider/agent' }],
- },
- },
- refetch: marketplaceRefetch,
- } as never)
- mockUseCheckInstalled.mockReturnValue({
- data: {
- plugins: [
- {
- declaration: {
- label: { en_US: 'Installed Agent Plugin' },
- },
- },
- ],
- },
- } as never)
- mockToolParametersToFormSchemas.mockImplementation((value) => value as never)
- mockGenerateAgentToolValue.mockImplementation(
- (_value, schemas, isLLM) =>
- ({
- kind: isLLM ? 'llm' : 'setting',
- fields: (schemas as Array<{ variable: string }>).map((item) => item.variable),
- }) as never,
- )
+beforeEach(() => {
+ vi.clearAllMocks()
+ request.mockImplementation(() => Promise.resolve(Response.json(createProvider())))
+ marketplaceRefetch.mockResolvedValue({ data: undefined })
+ marketplaceQuery.mockReturnValue({
+ isLoading: false,
+ data: { data: { plugins: [] } },
+ refetch: marketplaceRefetch,
})
+})
- it('returns an undefined strategy status while strategy data is still loading and can refetch dependencies', () => {
- mockUseStrategyProviderDetail.mockReturnValue({
- isLoading: true,
- isError: false,
- data: undefined,
- refetch: providerRefetch,
- } as never)
-
- const { result } = renderHook(() => useStrategyInfo('provider/agent', 'react'))
-
+describe('agent strategy query and configuration', () => {
+ it('does not request or refetch a missing provider', () => {
+ const { result } = renderHook(() => useStrategyInfo())
expect(result.current.strategyStatus).toBeUndefined()
- expect(result.current.strategy).toBeUndefined()
-
- act(() => {
- result.current.refetch()
- })
-
- expect(providerRefetch).toHaveBeenCalledTimes(1)
- expect(marketplaceRefetch).toHaveBeenCalledTimes(1)
+ act(() => result.current.refetch())
+ expect(request).not.toHaveBeenCalled()
+ expect(marketplaceRefetch).not.toHaveBeenCalled()
+ expect(marketplaceQuery).toHaveBeenCalledWith([], { retry: false })
})
- it('resolves strategy status for external plugins that are missing or not installed', () => {
- mockUseStrategyProviderDetail.mockReturnValue({
- isLoading: false,
- isError: true,
- data: {
- declaration: {
- strategies: [],
- },
- },
- refetch: providerRefetch,
- } as never)
- mockUseFetchPluginsInMarketPlaceByIds.mockReturnValue({
- isLoading: false,
- data: {
- data: {
- plugins: [],
- },
- },
- refetch: marketplaceRefetch,
- } as never)
-
- const { result } = renderHook(() => useStrategyInfo('provider/agent', 'react'))
-
+ it('treats a failed provider lookup as missing without retrying', async () => {
+ request.mockImplementation(() =>
+ Promise.resolve(Response.json({ message: 'Missing provider' }, { status: 404 })),
+ )
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: 2, retryDelay: 0 } },
+ })
+ const { result } = renderHook(() => useStrategyInfo('langgenius/agent/missing', 'react'), {
+ queryClient,
+ })
+ await waitFor(() => expect(result.current.strategyProvider.isError).toBe(true))
expect(result.current.strategyStatus).toEqual({
- plugin: {
- source: 'external',
- installed: false,
- },
+ plugin: { source: 'external', installed: false },
isExistInPlugin: false,
})
+ expect(request).toHaveBeenCalledTimes(1)
})
- it('exposes derived form data, strategy state, output schema, and setter helpers', () => {
- const { result } = renderHook(() => useConfig('agent-node', currentInputs))
-
- expect(result.current.readOnly).toBe(false)
- expect(result.current.isChatMode).toBe(true)
- expect(result.current.formData).toEqual({
- instruction: '#start.topic#',
- modelParam: {
- provider: 'openai',
- model: 'gpt-4o',
- },
- })
- expect(result.current.currentStrategyStatus).toEqual({
- plugin: {
- source: 'marketplace',
- installed: true,
- },
- isExistInPlugin: true,
- })
- expect(result.current.availableVars).toHaveLength(1)
- expect(result.current.availableNodesWithParent).toEqual([
- {
- nodeId: 'node-1',
- title: 'Start',
+ it('keeps cleared form values and unknown persisted parameters when editing', async () => {
+ const inputs = createData({
+ agent_parameters: {
+ instruction: { type: VarKindType.constant, value: '' },
+ unknown_parameter: { type: VarKindType.constant, value: { count: 0, enabled: false } },
},
- ])
- expect(result.current.outputSchema).toEqual([
- { name: 'summary', type: 'String', description: 'summary output' },
- { name: 'items', type: 'Array[Number]', description: 'items output' },
- ])
-
- setInputs.mockClear()
-
- act(() => {
- result.current.onFormChange({
- instruction: '#start.updated#',
- modelParam: {
- provider: 'anthropic',
- model: 'claude-sonnet',
- },
- })
- result.current.handleMemoryChange({
- window: {
- enabled: true,
- size: 6,
- },
- query_prompt_template: 'history',
- } as AgentNodeType['memory'])
})
-
- expect(setInputs).toHaveBeenNthCalledWith(
- 1,
+ const { result } = renderHook(() => useConfig('agent', inputs))
+ await waitFor(() => expect(result.current.currentStrategy?.identity.name).toBe('react'))
+ expect(result.current.formData).toEqual({ instruction: '' })
+ expect(result.current.outputSchema).toEqual([])
+ expect(result.current.currentStrategyStatus?.plugin.installed).toBe(true)
+ act(() => result.current.onFormChange({ instruction: 'Changed' }))
+ expect(setInputs).toHaveBeenLastCalledWith(
expect.objectContaining({
agent_parameters: {
- instruction: {
- type: VarType.variable,
- value: '#start.updated#',
- },
- modelParam: {
- type: VarType.constant,
- value: {
- provider: 'anthropic',
- model: 'claude-sonnet',
- },
- },
- },
- }),
- )
- expect(setInputs).toHaveBeenNthCalledWith(
- 2,
- expect.objectContaining({
- memory: {
- window: {
- enabled: true,
- size: 6,
- },
- query_prompt_template: 'history',
+ instruction: { type: VarKindType.constant, value: 'Changed' },
+ unknown_parameter: { type: VarKindType.constant, value: { count: 0, enabled: false } },
},
}),
)
- expect(result.current.handleVarListChange).toBe(handleVarListChange)
- expect(result.current.handleAddVariable).toBe(handleAddVariable)
- expect(result.current.pluginDetail).toEqual({
- declaration: {
- label: { en_US: 'Installed Agent Plugin' },
- },
- })
})
- it('formats legacy tool selector values before exposing the node config', async () => {
- currentInputs = createData({
+ it('converts legacy arrays of tools once and preserves unknown persisted values', async () => {
+ const provider = createProvider([
+ createStrategy({
+ parameters: [{ name: 'tools', type: 'array[tools]', label: { en_US: 'Tools' } }],
+ }),
+ ])
+ request.mockImplementation(() => Promise.resolve(Response.json(provider)))
+ const legacyTool = {
+ provider_name: 'langgenius/weather/provider',
+ tool_name: 'weather',
+ tool_label: 'Weather',
+ enabled: true,
+ settings: { api_key: { value: 'secret' } },
+ parameters: { query: { value: 'weather', auto: 0 } },
+ schemas: [
+ {
+ name: 'api_key',
+ type: 'secret-input',
+ form: 'form',
+ label: { en_US: 'API key', zh_Hans: 'API key' },
+ },
+ { name: 'query', type: 'string', form: 'llm', label: { en_US: 'Query', zh_Hans: 'Query' } },
+ ],
+ }
+ const inputs = createData({
tool_node_version: undefined,
agent_parameters: {
- toolParam: {
- type: VarType.constant,
- value: createToolValue(),
- },
- multiToolParam: {
- type: VarType.constant,
- value: [createToolValue()],
- },
+ tools: { type: VarKindType.constant, value: [legacyTool] },
+ unrecognized: { type: VarKindType.constant, value: { untouched: true } },
},
})
- mockUseStrategyProviderDetail.mockReturnValue({
- isLoading: false,
- isError: false,
- data: {
- declaration: {
- strategies: [
- {
- identity: {
- name: 'react',
- },
- parameters: [
- createStrategyParam({
- name: 'toolParam',
- type: FormTypeEnum.toolSelector,
- required: false,
- }),
- createStrategyParam({
- name: 'multiToolParam',
- type: FormTypeEnum.multiToolSelector,
- required: false,
- }),
- ],
- },
- ],
- },
- },
- refetch: providerRefetch,
- } as never)
-
- renderHook(() => useConfig('agent-node', currentInputs))
-
- await waitFor(() => {
+ renderHook(() => useConfig('agent', inputs))
+ await waitFor(() =>
expect(setInputs).toHaveBeenCalledWith(
expect.objectContaining({
tool_node_version: '2',
- agent_parameters: expect.objectContaining({
- toolParam: expect.objectContaining({
- value: expect.objectContaining({
- settings: {
- kind: 'setting',
- fields: ['api_key'],
- },
- parameters: {
- kind: 'llm',
- fields: ['query'],
- },
- }),
- }),
- multiToolParam: expect.objectContaining({
+ agent_parameters: {
+ tools: {
+ type: VarKindType.constant,
value: [
expect.objectContaining({
- settings: {
- kind: 'setting',
- fields: ['api_key'],
- },
- parameters: {
- kind: 'llm',
- fields: ['query'],
- },
+ settings: { api_key: { value: { type: 'mixed', value: 'secret' } } },
+ parameters: { query: { auto: 0, value: 'weather' } },
}),
],
- }),
- }),
+ },
+ unrecognized: { type: VarKindType.constant, value: { untouched: true } },
+ },
}),
- )
+ ),
+ )
+ expect(inputs.agent_parameters?.tools?.value).toEqual([legacyTool])
+ })
+
+ it('keeps JSON Schema boolean outputs and displays unknown or empty types', () => {
+ const { result } = renderHook(() =>
+ useConfig(
+ 'agent',
+ createData({
+ output_schema: {
+ properties: {
+ allowed: true,
+ forbidden: false,
+ empty: { type: '' },
+ array: { type: 'array', items: { type: '' } },
+ },
+ },
+ }),
+ ),
+ )
+ expect(result.current.outputSchema).toEqual([
+ { name: 'allowed', type: 'Unknown', description: '' },
+ { name: 'forbidden', type: 'Unknown', description: '' },
+ { name: 'empty', type: 'Unknown', description: '' },
+ { name: 'array', type: 'Array[Unknown]', description: '' },
+ ])
+ })
+
+ it('does not convert tools with an existing tool node version', async () => {
+ const inputs = createData({
+ agent_parameters: {
+ tools: {
+ type: VarKindType.constant,
+ value: [{ settings: { secret: { value: 'existing' } } }],
+ },
+ },
})
+ renderHook(() => useConfig('agent', inputs))
+ await waitFor(() => expect(setInputs).toHaveBeenCalledWith(inputs))
})
})
diff --git a/web/app/components/workflow/nodes/agent/default.ts b/web/app/components/workflow/nodes/agent/default.ts
index 1e0bf856519..ccb4a0af8a7 100644
--- a/web/app/components/workflow/nodes/agent/default.ts
+++ b/web/app/components/workflow/nodes/agent/default.ts
@@ -1,7 +1,10 @@
+import type {
+ AgentProviderResponse,
+ AgentStrategyEntity,
+} from '@dify/contracts/api/console/workspaces/types.gen'
import type { TFunction } from 'i18next'
import type { NodeDefault } from '../../types'
import type { AgentNodeType } from './types'
-import type { StrategyDetail, StrategyPluginDetail } from '@/app/components/plugins/types'
import { FormTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
import { renderI18nObject } from '@/i18n/metadata'
import { BlockEnum } from '../../types'
@@ -22,8 +25,8 @@ const nodeDefault: NodeDefault<AgentNodeType> = {
payload,
t: TFunction<'workflow'>,
moreDataForCheckValid: {
- strategyProvider?: StrategyPluginDetail
- strategy?: StrategyDetail
+ strategyProvider?: AgentProviderResponse
+ strategy?: AgentStrategyEntity
language: string
isReadyForCheckValid: boolean
},
@@ -41,98 +44,7 @@ const nodeDefault: NodeDefault<AgentNodeType> = {
errorMessage: t(($) => $['nodes.agent.checkList.strategyNotSelected'], { ns: 'workflow' }),
}
}
- for (const param of strategy.parameters) {
- // single tool
- if (param.required && param.type === FormTypeEnum.toolSelector) {
- // no value
- const toolValue = payload.agent_parameters?.[param.name]?.value
- if (!toolValue) {
- return {
- isValid: false,
- errorMessage: t(($) => $['errorMsg.fieldRequired'], {
- ns: 'workflow',
- field: renderI18nObject(param.label, language),
- }),
- }
- }
- // not enabled
- else if (!toolValue.enabled) {
- return {
- isValid: false,
- errorMessage: t(($) => $['errorMsg.noValidTool'], {
- ns: 'workflow',
- field: renderI18nObject(param.label, language),
- }),
- }
- }
- // check form of tool
- else {
- const schemas = toolValue.schemas || []
- const userSettings = toolValue.settings
- const reasoningConfig = toolValue.parameters
- const version = payload.version
- const toolNodeVersion = payload.tool_node_version
- const mergeVersion = version || toolNodeVersion
- schemas.forEach((schema: any) => {
- if (schema?.required) {
- if (schema.form === 'form' && !mergeVersion && !userSettings[schema.name]?.value) {
- return {
- isValid: false,
- errorMessage: t(($) => $['errorMsg.toolParameterRequired'], {
- ns: 'workflow',
- field: renderI18nObject(param.label, language),
- param: renderI18nObject(schema.label, language),
- }),
- }
- }
- if (
- schema.form === 'form' &&
- mergeVersion &&
- !userSettings[schema.name]?.value.value
- ) {
- return {
- isValid: false,
- errorMessage: t(($) => $['errorMsg.toolParameterRequired'], {
- ns: 'workflow',
- field: renderI18nObject(param.label, language),
- param: renderI18nObject(schema.label, language),
- }),
- }
- }
- if (
- schema.form === 'llm' &&
- !mergeVersion &&
- reasoningConfig[schema.name].auto === 0 &&
- !reasoningConfig[schema.name]?.value
- ) {
- return {
- isValid: false,
- errorMessage: t(($) => $['errorMsg.toolParameterRequired'], {
- ns: 'workflow',
- field: renderI18nObject(param.label, language),
- param: renderI18nObject(schema.label, language),
- }),
- }
- }
- if (
- schema.form === 'llm' &&
- mergeVersion &&
- reasoningConfig[schema.name].auto === 0 &&
- !reasoningConfig[schema.name]?.value.value
- ) {
- return {
- isValid: false,
- errorMessage: t(($) => $['errorMsg.toolParameterRequired'], {
- ns: 'workflow',
- field: renderI18nObject(param.label, language),
- param: renderI18nObject(schema.label, language),
- }),
- }
- }
- }
- })
- }
- }
+ for (const param of strategy.parameters ?? []) {
// multiple tools
if (param.required && param.type === FormTypeEnum.multiToolSelector) {
const tools = payload.agent_parameters?.[param.name]?.value || []
@@ -199,7 +111,12 @@ const nodeDefault: NodeDefault<AgentNodeType> = {
}
}
// common params
- if (param.required && !(payload.agent_parameters?.[param.name]?.value || param.default)) {
+ const savedValue = payload.agent_parameters?.[param.name]?.value
+ const value =
+ savedValue === undefined || savedValue === null || savedValue === ''
+ ? param.default
+ : savedValue
+ if (param.required && (value === undefined || value === null || value === '')) {
return {
isValid: false,
errorMessage: t(($) => $['errorMsg.fieldRequired'], {
diff --git a/web/app/components/workflow/nodes/agent/node.tsx b/web/app/components/workflow/nodes/agent/node.tsx
index ba0e790808a..810a9cf664f 100644
--- a/web/app/components/workflow/nodes/agent/node.tsx
+++ b/web/app/components/workflow/nodes/agent/node.tsx
@@ -26,7 +26,7 @@ const AgentNode: FC<NodeProps<AgentNodeType>> = (props) => {
// if not required and not selected, show nothing
const models =
currentStrategy?.parameters
- .filter((param) => param.type === FormTypeEnum.modelSelector)
+ ?.filter((param) => param.type === FormTypeEnum.modelSelector)
.reduce(
(acc, param) => {
const item = inputs.agent_parameters?.[param.name]?.value
@@ -48,22 +48,12 @@ const AgentNode: FC<NodeProps<AgentNodeType>> = (props) => {
const tools = useMemo(() => {
const tools: Array<ToolIconProps> = []
- currentStrategy?.parameters.forEach((param, i) => {
- if (param.type === FormTypeEnum.toolSelector) {
- const field = param.name
- const value = inputs.agent_parameters?.[field]?.value
- if (value) {
- tools.push({
- id: `${param.name}-${i}`,
- providerName: value.provider_name as any,
- })
- }
- }
+ currentStrategy?.parameters?.forEach((param) => {
if (param.type === FormTypeEnum.multiToolSelector) {
const field = param.name
const value = inputs.agent_parameters?.[field]?.value
- if (value) {
- ;(value as unknown as any[]).forEach((item, idx) => {
+ if (Array.isArray(value)) {
+ value.forEach((item, idx) => {
tools.push({
id: `${param.name}-${idx}`,
providerName: item.provider_name,
diff --git a/web/app/components/workflow/nodes/agent/panel.tsx b/web/app/components/workflow/nodes/agent/panel.tsx
index 1971a22da78..1d56774e750 100644
--- a/web/app/components/workflow/nodes/agent/panel.tsx
+++ b/web/app/components/workflow/nodes/agent/panel.tsx
@@ -1,11 +1,8 @@
import type { FC } from 'react'
import type { NodePanelProps } from '../../types'
import type { AgentNodeType } from './types'
-import type { CredentialFormSchema } from '@/app/components/header/account-setting/model-provider-page/declarations'
-import type { StrategyParamItem } from '@/app/components/plugins/types'
import { memo } from 'react'
import { useTranslation } from 'react-i18next'
-import { toType } from '@/app/components/tools/utils/to-form-schema'
import { isSupportMCP } from '@/utils/plugin-version-feature'
import { useStore } from '../../store'
import { AgentStrategy } from '../_base/components/agent-strategy'
@@ -14,21 +11,10 @@ import { MCPToolAvailabilityProvider } from '../_base/components/mcp-tool-availa
import MemoryConfig from '../_base/components/memory-config'
import OutputVars, { VarItem } from '../_base/components/output-vars'
import Split from '../_base/components/split'
-import { AgentFeature } from './types'
import useConfig from './use-config'
const i18nPrefix = 'nodes.agent'
-function strategyParamToCredientialForm(param: StrategyParamItem): CredentialFormSchema {
- return {
- ...(param as any),
- variable: param.name,
- show_on: [],
- type: toType(param.type),
- tooltip: param.help,
- }
-}
-
const AgentPanel: FC<NodePanelProps<AgentNodeType>> = (props) => {
const {
inputs,
@@ -44,7 +30,7 @@ const AgentPanel: FC<NodePanelProps<AgentNodeType>> = (props) => {
handleMemoryChange,
} = useConfig(props.id, props.data)
const { t } = useTranslation()
- const isMCPVersionSupported = isSupportMCP(inputs.meta?.version)
+ const isMCPVersionSupported = isSupportMCP(inputs.meta?.version ?? undefined)
const resetEditor = useStore((s) => s.setControlPromptEditorRerenderKey)
return (
@@ -58,13 +44,13 @@ const AgentPanel: FC<NodePanelProps<AgentNodeType>> = (props) => {
<MCPToolAvailabilityProvider versionSupported={isMCPVersionSupported}>
<AgentStrategy
strategy={
- inputs.agent_strategy_name
+ inputs.agent_strategy_name && inputs.agent_strategy_provider_name
? {
- agent_strategy_provider_name: inputs.agent_strategy_provider_name!,
- agent_strategy_name: inputs.agent_strategy_name!,
- agent_strategy_label: inputs.agent_strategy_label!,
+ agent_strategy_provider_name: inputs.agent_strategy_provider_name,
+ agent_strategy_name: inputs.agent_strategy_name,
+ agent_strategy_label: inputs.agent_strategy_label ?? inputs.agent_strategy_name,
agent_output_schema: inputs.output_schema,
- plugin_unique_identifier: inputs.plugin_unique_identifier!,
+ plugin_unique_identifier: inputs.plugin_unique_identifier,
meta: inputs.meta,
}
: undefined
@@ -75,13 +61,13 @@ const AgentPanel: FC<NodePanelProps<AgentNodeType>> = (props) => {
agent_strategy_provider_name: strategy?.agent_strategy_provider_name,
agent_strategy_name: strategy?.agent_strategy_name,
agent_strategy_label: strategy?.agent_strategy_label,
- output_schema: strategy!.agent_output_schema,
- plugin_unique_identifier: strategy!.plugin_unique_identifier,
+ output_schema: strategy?.agent_output_schema,
+ plugin_unique_identifier: strategy?.plugin_unique_identifier,
meta: strategy?.meta,
})
resetEditor(Date.now())
}}
- formSchema={currentStrategy?.parameters?.map(strategyParamToCredientialForm) || []}
+ formSchema={currentStrategy?.parameters ?? []}
formValue={formData}
onFormValueChange={onFormChange}
nodeOutputVars={availableVars}
@@ -91,7 +77,7 @@ const AgentPanel: FC<NodePanelProps<AgentNodeType>> = (props) => {
</MCPToolAvailabilityProvider>
</Field>
<div className="px-4 py-2">
- {isChatMode && currentStrategy?.features?.includes(AgentFeature.HISTORY_MESSAGES) && (
+ {isChatMode && currentStrategy?.features?.includes('history-messages') && (
<>
<Split />
<MemoryConfig
diff --git a/web/app/components/workflow/nodes/agent/types.ts b/web/app/components/workflow/nodes/agent/types.ts
index c2d53b29b4f..11e9c22791e 100644
--- a/web/app/components/workflow/nodes/agent/types.ts
+++ b/web/app/components/workflow/nodes/agent/types.ts
@@ -1,20 +1,16 @@
-import type { ToolVarInputs } from '../tool/types'
-import type { PluginMeta } from '@/app/components/plugins/types'
+import type { AgentStrategyEntity, Meta } from '@dify/contracts/api/console/workspaces/types.gen'
+import type { ResourceVarInputs } from '@/app/components/workflow/nodes/_base/types'
import type { CommonNodeType, Memory } from '@/app/components/workflow/types'
export type AgentNodeType = CommonNodeType & {
agent_strategy_provider_name?: string
agent_strategy_name?: string
agent_strategy_label?: string
- agent_parameters?: ToolVarInputs
- meta?: PluginMeta
- output_schema: Record<string, any>
+ agent_parameters?: ResourceVarInputs
+ meta?: Meta
+ output_schema: AgentStrategyEntity['output_schema']
plugin_unique_identifier?: string
memory?: Memory
version?: string
tool_node_version?: string
}
-
-export const AgentFeature = {
- HISTORY_MESSAGES: 'history-messages',
-} as const
diff --git a/web/app/components/workflow/nodes/agent/use-config.ts b/web/app/components/workflow/nodes/agent/use-config.ts
index e8fd23c8a37..b8330be6880 100644
--- a/web/app/components/workflow/nodes/agent/use-config.ts
+++ b/web/app/components/workflow/nodes/agent/use-config.ts
@@ -1,6 +1,7 @@
import type { Memory, Var } from '../../types'
-import type { ToolVarInputs } from '../tool/types'
import type { AgentNodeType } from './types'
+import type { ResourceVarInputs } from '@/app/components/workflow/nodes/_base/types'
+import { skipToken, useQuery } from '@tanstack/react-query'
import { produce } from 'immer'
import { useCallback, useEffect, useMemo } from 'react'
import { FormTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
@@ -8,14 +9,14 @@ import {
generateAgentToolValue,
toolParametersToFormSchemas,
} from '@/app/components/tools/utils/to-form-schema'
+import { VarKindType } from '@/app/components/workflow/nodes/_base/types'
+import { consoleQuery } from '@/service/console'
import { useCheckInstalled, useFetchPluginsInMarketPlaceByIds } from '@/service/use-plugins'
-import { useStrategyProviderDetail } from '@/service/use-strategy'
import { useIsChatMode, useNodesReadOnly } from '../../hooks/use-workflow'
-import { VarType as VarKindType } from '../../types'
+import { VarType } from '../../types'
import useAvailableVarList from '../_base/hooks/use-available-var-list'
import useNodeCrud from '../_base/hooks/use-node-crud'
import useVarList from '../_base/hooks/use-var-list'
-import { VarType } from '../tool/types'
type StrategyStatus = {
plugin: {
@@ -26,17 +27,26 @@ type StrategyStatus = {
}
export const useStrategyInfo = (strategyProviderName?: string, strategyName?: string) => {
- const strategyProvider = useStrategyProviderDetail(strategyProviderName || '', { retry: false })
- const strategy = strategyProvider.data?.declaration.strategies.find(
+ const strategyProvider = useQuery(
+ consoleQuery.workspaces.current.agentProvider.byProviderName.get.queryOptions({
+ input: strategyProviderName ? { params: { provider_name: strategyProviderName } } : skipToken,
+ retry: false,
+ }),
+ )
+ const strategy = strategyProvider.data?.declaration.strategies?.find(
(str) => str.identity.name === strategyName,
)
- const marketplace = useFetchPluginsInMarketPlaceByIds([strategyProviderName!], {
- retry: false,
- })
+ const marketplace = useFetchPluginsInMarketPlaceByIds(
+ strategyProviderName ? [strategyProviderName] : [],
+ {
+ retry: false,
+ },
+ )
const strategyStatus: StrategyStatus | undefined = useMemo(() => {
- if (strategyProvider.isLoading || marketplace.isLoading) return undefined
+ if (!strategyProviderName || strategyProvider.isLoading || marketplace.isLoading)
+ return undefined
const strategyExist = !!strategy
- const isPluginInstalled = !strategyProvider.isError
+ const isPluginInstalled = strategyProvider.isSuccess
const isInMarketplace = !!marketplace.data?.data.plugins.at(0)
return {
plugin: {
@@ -45,11 +55,19 @@ export const useStrategyInfo = (strategyProviderName?: string, strategyName?: st
},
isExistInPlugin: strategyExist,
}
- }, [strategy, marketplace, strategyProvider.isError, strategyProvider.isLoading])
+ }, [
+ strategy,
+ strategyProviderName,
+ marketplace,
+ strategyProvider.isSuccess,
+ strategyProvider.isLoading,
+ ])
+ const { refetch: refetchProvider } = strategyProvider
+ const { refetch: refetchMarketplace } = marketplace
const refetch = useCallback(() => {
- strategyProvider.refetch()
- marketplace.refetch()
- }, [marketplace, strategyProvider])
+ if (!strategyProviderName) return
+ return Promise.all([refetchProvider(), refetchMarketplace()])
+ }, [refetchMarketplace, refetchProvider, strategyProviderName])
return {
strategyProvider,
strategy,
@@ -73,7 +91,7 @@ const useConfig = (id: string, payload: AgentNodeType) => {
} = useStrategyInfo(inputs.agent_strategy_provider_name, inputs.agent_strategy_name)
const pluginId = inputs.agent_strategy_provider_name?.split('/').splice(0, 2).join('/')
const pluginDetail = useCheckInstalled({
- pluginIds: [pluginId!],
+ pluginIds: pluginId ? [pluginId] : [],
enabled: Boolean(pluginId),
})
const formData = useMemo(() => {
@@ -90,17 +108,17 @@ const useConfig = (id: string, payload: AgentNodeType) => {
const getParamVarType = useCallback(
(paramName: string) => {
- const isVariable = currentStrategy?.parameters.some(
+ const isVariable = currentStrategy?.parameters?.some(
(param) => param.name === paramName && param.type === FormTypeEnum.any,
)
- if (isVariable) return VarType.variable
- return VarType.constant
+ if (isVariable) return VarKindType.variable
+ return VarKindType.constant
},
[currentStrategy?.parameters],
)
- const onFormChange = (value: Record<string, any>) => {
- const res: ToolVarInputs = {}
+ const onFormChange = (value: Record<string, unknown>) => {
+ const res: ResourceVarInputs = { ...inputs.agent_parameters }
Object.entries(value).forEach(([key, val]) => {
res[key] = {
type: getParamVarType(key),
@@ -140,10 +158,6 @@ const useConfig = (id: string, payload: AgentNodeType) => {
const schemas = currentStrategy?.parameters || []
Object.keys(draft.agent_parameters || {}).forEach((key) => {
const targetSchema = schemas.find((schema) => schema.name === key)
- if (targetSchema?.type === FormTypeEnum.toolSelector)
- draft.agent_parameters![key]!.value = formattingToolData(
- draft.agent_parameters![key]!.value,
- )
if (targetSchema?.type === FormTypeEnum.multiToolSelector)
draft.agent_parameters![key]!.value = draft.agent_parameters![key]!.value.map(
(tool: any) => formattingToolData(tool),
@@ -164,16 +178,16 @@ const useConfig = (id: string, payload: AgentNodeType) => {
// vars
const filterMemoryPromptVar = useCallback((varPayload: Var) => {
- const supportedVariableTypes: readonly VarKindType[] = [
- VarKindType.arrayObject,
- VarKindType.array,
- VarKindType.number,
- VarKindType.string,
- VarKindType.secret,
- VarKindType.arrayString,
- VarKindType.arrayNumber,
- VarKindType.file,
- VarKindType.arrayFile,
+ const supportedVariableTypes: readonly VarType[] = [
+ VarType.arrayObject,
+ VarType.array,
+ VarType.number,
+ VarType.string,
+ VarType.secret,
+ VarType.arrayString,
+ VarType.arrayNumber,
+ VarType.file,
+ VarType.arrayFile,
]
return supportedVariableTypes.includes(varPayload.type)
@@ -187,20 +201,33 @@ const useConfig = (id: string, payload: AgentNodeType) => {
// single run
const outputSchema = useMemo(() => {
- const res: any[] = []
- if (!inputs.output_schema || !inputs.output_schema.properties) return []
- Object.keys(inputs.output_schema.properties).forEach((outputKey) => {
- const output = inputs.output_schema.properties[outputKey]
- res.push({
- name: outputKey,
+ const properties = inputs.output_schema?.properties
+ if (!properties || typeof properties !== 'object' || Array.isArray(properties)) return []
+ return Object.entries(properties).map(([name, output]: [string, unknown]) => {
+ const schema = output && typeof output === 'object' && !Array.isArray(output) ? output : {}
+ const type =
+ 'type' in schema && typeof schema.type === 'string' && schema.type ? schema.type : 'unknown'
+ const items = 'items' in schema ? schema.items : undefined
+ const itemType =
+ items &&
+ typeof items === 'object' &&
+ 'type' in items &&
+ typeof items.type === 'string' &&
+ items.type
+ ? items.type
+ : 'unknown'
+ return {
+ name,
type:
- output.type === 'array'
- ? `Array[${output.items?.type ? output.items.type.slice(0, 1).toLocaleUpperCase() + output.items.type.slice(1) : 'Unknown'}]`
- : `${output.type ? output.type.slice(0, 1).toLocaleUpperCase() + output.type.slice(1) : 'Unknown'}`,
- description: output.description,
- })
+ type === 'array'
+ ? `Array[${itemType.charAt(0).toUpperCase()}${itemType.slice(1)}]`
+ : `${type.charAt(0).toUpperCase()}${type.slice(1)}`,
+ description:
+ 'description' in schema && typeof schema.description === 'string'
+ ? schema.description
+ : '',
+ }
})
- return res
}, [inputs.output_schema])
const handleMemoryChange = useCallback(
diff --git a/web/app/components/workflow/nodes/data-source/default.ts b/web/app/components/workflow/nodes/data-source/default.ts
index 2540edd0aad..4718847aa38 100644
--- a/web/app/components/workflow/nodes/data-source/default.ts
+++ b/web/app/components/workflow/nodes/data-source/default.ts
@@ -1,7 +1,7 @@
import type { TFunction } from 'i18next'
import type { NodeDefault } from '../../types'
import type { DataSourceNodeType } from './types'
-import { VarType as VarKindType } from '@/app/components/workflow/nodes/tool/types'
+import { VarKindType } from '@/app/components/workflow/nodes/_base/types'
import { BlockEnum } from '@/app/components/workflow/types'
import { genNodeMetaData } from '@/app/components/workflow/utils'
import { getMatchedSchemaType } from '../_base/components/variable/use-match-schema-type'
diff --git a/web/app/components/workflow/nodes/data-source/hooks/__tests__/use-config.spec.ts b/web/app/components/workflow/nodes/data-source/hooks/__tests__/use-config.spec.ts
index 73937c024bd..e56123aa39f 100644
--- a/web/app/components/workflow/nodes/data-source/hooks/__tests__/use-config.spec.ts
+++ b/web/app/components/workflow/nodes/data-source/hooks/__tests__/use-config.spec.ts
@@ -1,6 +1,6 @@
import type { DataSourceNodeType } from '../../types'
import { renderHook } from '@testing-library/react'
-import { VarType as VarKindType } from '../../../tool/types'
+import { VarKindType } from '@/app/components/workflow/nodes/_base/types'
import { useConfig } from '../use-config'
const mockUseStoreApi = vi.hoisted(() => vi.fn())
diff --git a/web/app/components/workflow/nodes/if-else/__tests__/integration.spec.tsx b/web/app/components/workflow/nodes/if-else/__tests__/integration.spec.tsx
index 3a686730d19..49544ef7255 100644
--- a/web/app/components/workflow/nodes/if-else/__tests__/integration.spec.tsx
+++ b/web/app/components/workflow/nodes/if-else/__tests__/integration.spec.tsx
@@ -3,8 +3,8 @@ import type { IfElseNodeType } from '../types'
import type { PanelProps } from '@/types/workflow'
import { fireEvent, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { VarKindType } from '@/app/components/workflow/nodes/_base/types'
import { BlockEnum, VarType } from '../../../types'
-import { VarType as NumberVarType } from '../../tool/types'
import ConditionAdd from '../components/condition-add'
import ConditionFilesListValue from '../components/condition-files-list-value'
import ConditionList from '../components/condition-list'
@@ -243,7 +243,7 @@ describe('if-else path', () => {
/>
<ConditionNumberInput
value="12"
- numberVarType={NumberVarType.constant}
+ numberVarType={VarKindType.constant}
onNumberVarTypeChange={onNumberVarTypeChange}
onValueChange={onValueChange}
variables={[]}
@@ -259,7 +259,7 @@ describe('if-else path', () => {
fireEvent.change(screen.getByDisplayValue('12'), { target: { value: '42' } })
expect(onSelect.mock.calls[0]?.[0]).toBe(ComparisonOperator.is)
- expect(onNumberVarTypeChange.mock.calls[0]?.[0]).toBe(NumberVarType.variable)
+ expect(onNumberVarTypeChange.mock.calls[0]?.[0]).toBe(VarKindType.variable)
expect(onValueChange).toHaveBeenCalledWith('42')
})
diff --git a/web/app/components/workflow/nodes/if-else/components/condition-list/condition-item.tsx b/web/app/components/workflow/nodes/if-else/components/condition-list/condition-item.tsx
index 59f35cfc016..fd83f9067f0 100644
--- a/web/app/components/workflow/nodes/if-else/components/condition-list/condition-item.tsx
+++ b/web/app/components/workflow/nodes/if-else/components/condition-list/condition-item.tsx
@@ -1,4 +1,3 @@
-import type { VarType as NumberVarType } from '../../../tool/types'
import type {
Condition,
HandleAddSubVariableCondition,
@@ -8,6 +7,7 @@ import type {
HandleUpdateCondition,
HandleUpdateSubVariableCondition,
} from '../../types'
+import type { VarKindType } from '@/app/components/workflow/nodes/_base/types'
import type { Node, NodeOutPutVar, ValueSelector, Var } from '@/app/components/workflow/types'
import { cn } from '@langgenius/dify-ui/cn'
import {
@@ -148,7 +148,7 @@ const ConditionItem = ({
)
const handleUpdateConditionNumberVarType = useCallback(
- (numberVarType: NumberVarType) => {
+ (numberVarType: VarKindType) => {
const newCondition = {
...condition,
numberVarType,
diff --git a/web/app/components/workflow/nodes/if-else/components/condition-number-input.tsx b/web/app/components/workflow/nodes/if-else/components/condition-number-input.tsx
index ef99e14071b..57c1fee9063 100644
--- a/web/app/components/workflow/nodes/if-else/components/condition-number-input.tsx
+++ b/web/app/components/workflow/nodes/if-else/components/condition-number-input.tsx
@@ -16,16 +16,16 @@ import { memo, useCallback, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { Variable02 } from '@/app/components/base/icons/src/vender/solid/development'
import VarReferenceVars from '@/app/components/workflow/nodes/_base/components/variable/var-reference-vars'
+import { VarKindType } from '@/app/components/workflow/nodes/_base/types'
import { VarType } from '@/app/components/workflow/types'
import { variableTransformer } from '@/app/components/workflow/utils'
import VariableTag from '../../_base/components/variable-tag'
-import { VarType as NumberVarType } from '../../tool/types'
-const options = [NumberVarType.variable, NumberVarType.constant]
+const options = [VarKindType.variable, VarKindType.constant]
type ConditionNumberInputProps = {
- numberVarType?: NumberVarType
- onNumberVarTypeChange: (v: NumberVarType) => void
+ numberVarType?: VarKindType
+ onNumberVarTypeChange: (v: VarKindType) => void
value: string
onValueChange: (v: string) => void
variables: NodeOutPutVar[]
@@ -33,7 +33,7 @@ type ConditionNumberInputProps = {
unit?: string
}
const ConditionNumberInput = ({
- numberVarType = NumberVarType.constant,
+ numberVarType = VarKindType.constant,
onNumberVarTypeChange,
value,
onValueChange,
@@ -86,7 +86,7 @@ const ConditionNumberInput = ({
</DropdownMenu>
<div className="mx-1 h-4 w-px bg-divider-regular"></div>
<div className="ml-0.5 w-0 grow">
- {numberVarType === NumberVarType.variable && (
+ {numberVarType === VarKindType.variable && (
<Popover open={variableSelectorVisible} onOpenChange={setVariableSelectorVisible}>
<PopoverTrigger nativeButton={false} render={<div className="w-full" />}>
{value && (
@@ -126,7 +126,7 @@ const ConditionNumberInput = ({
</PopoverContent>
</Popover>
)}
- {numberVarType === NumberVarType.constant && (
+ {numberVarType === VarKindType.constant && (
<div className="relative">
<input
className={cn(
diff --git a/web/app/components/workflow/nodes/if-else/types.ts b/web/app/components/workflow/nodes/if-else/types.ts
index 6917091eca3..1d1f20219f1 100644
--- a/web/app/components/workflow/nodes/if-else/types.ts
+++ b/web/app/components/workflow/nodes/if-else/types.ts
@@ -1,4 +1,4 @@
-import type { VarType as NumberVarType } from '../tool/types'
+import type { VarKindType } from '@/app/components/workflow/nodes/_base/types'
import type { CommonNodeType, ValueSelector, Var, VarType } from '@/app/components/workflow/types'
export const LogicalOperator = {
@@ -41,7 +41,7 @@ export type Condition = {
key?: string // sub variable key
comparison_operator?: ComparisonOperator
value: string | string[] | boolean
- numberVarType?: NumberVarType
+ numberVarType?: VarKindType
sub_variable_condition?: CaseItem
}
diff --git a/web/app/components/workflow/nodes/iteration/__tests__/use-config.spec.ts b/web/app/components/workflow/nodes/iteration/__tests__/use-config.spec.ts
index e0b19e6fb10..564ed804d75 100644
--- a/web/app/components/workflow/nodes/iteration/__tests__/use-config.spec.ts
+++ b/web/app/components/workflow/nodes/iteration/__tests__/use-config.spec.ts
@@ -1,7 +1,7 @@
import type { IterationNodeType } from '../types'
import type { Var } from '@/app/components/workflow/types'
import { act, renderHook } from '@testing-library/react'
-import { VarType as VarKindType } from '@/app/components/workflow/nodes/tool/types'
+import { VarKindType } from '@/app/components/workflow/nodes/_base/types'
import { BlockEnum, ErrorHandleMode, VarType } from '@/app/components/workflow/types'
import useConfig from '../use-config'
diff --git a/web/app/components/workflow/nodes/iteration/use-config.ts b/web/app/components/workflow/nodes/iteration/use-config.ts
index d3db60e588d..4aa1d471c26 100644
--- a/web/app/components/workflow/nodes/iteration/use-config.ts
+++ b/web/app/components/workflow/nodes/iteration/use-config.ts
@@ -1,6 +1,6 @@
import type { ErrorHandleMode, ValueSelector, Var } from '../../types'
import type { IterationNodeType } from './types'
-import type { VarType as VarKindType } from '@/app/components/workflow/nodes/tool/types'
+import type { VarKindType } from '@/app/components/workflow/nodes/_base/types'
import { isEqual } from 'es-toolkit/predicate'
import { produce } from 'immer'
import { useCallback } from 'react'
diff --git a/web/app/components/workflow/nodes/llm/panel.tsx b/web/app/components/workflow/nodes/llm/panel.tsx
index 97c66c5be0b..854e1ffd9ed 100644
--- a/web/app/components/workflow/nodes/llm/panel.tsx
+++ b/web/app/components/workflow/nodes/llm/panel.tsx
@@ -19,6 +19,7 @@ import Field from '@/app/components/workflow/nodes/_base/components/field'
import FormInputTypeSwitch from '@/app/components/workflow/nodes/_base/components/form-input-type-switch'
import Split from '@/app/components/workflow/nodes/_base/components/split'
import VarList from '@/app/components/workflow/nodes/_base/components/variable/var-list'
+import { VarKindType } from '@/app/components/workflow/nodes/_base/types'
import { toast } from '@/app/notifications'
import { consoleQuery } from '@/service/console'
import { FlowType } from '@/types/common'
@@ -26,7 +27,6 @@ import { fetchAndMergeValidCompletionParams } from '@/utils/completion-params'
import { extractPluginId } from '../../utils/plugin'
import ConfigVision from '../_base/components/config-vision'
import VarReferencePicker from '../_base/components/variable/var-reference-picker'
-import { VarType } from '../tool/types'
import ConfigPrompt from './components/config-prompt'
import PanelMemorySection from './components/panel-memory-section'
import PanelOutputSection from './components/panel-output-section'
@@ -215,10 +215,10 @@ const Panel: FC<NodePanelProps<LLMNodeType>> = ({ id, data }) => {
operations={
flowType === FlowType.snippet && !isEnvironmentModelSource ? undefined : (
<FormInputTypeSwitch
- value={isEnvironmentModelSource ? VarType.variable : VarType.constant}
+ value={isEnvironmentModelSource ? VarKindType.variable : VarKindType.constant}
readonly={readOnly}
onChange={(value) => {
- const useEnvironmentVariable = value === VarType.variable
+ const useEnvironmentVariable = value === VarKindType.variable
if (useEnvironmentVariable === isEnvironmentModelSource) return
modelSelectionRequestGenerationRef.current++
handleModelSourceChange(useEnvironmentVariable)
diff --git a/web/app/components/workflow/nodes/loop/__tests__/variable-selectors.spec.tsx b/web/app/components/workflow/nodes/loop/__tests__/variable-selectors.spec.tsx
index 943649ad1bb..3ad11f95899 100644
--- a/web/app/components/workflow/nodes/loop/__tests__/variable-selectors.spec.tsx
+++ b/web/app/components/workflow/nodes/loop/__tests__/variable-selectors.spec.tsx
@@ -3,7 +3,7 @@ import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useState } from 'react'
import { ReactFlowProvider } from 'reactflow'
-import { VarType as NumberVarType } from '@/app/components/workflow/nodes/tool/types'
+import { VarKindType } from '@/app/components/workflow/nodes/_base/types'
import { VarType } from '@/app/components/workflow/types'
import ConditionAdd from '../components/condition-add'
import ConditionVarSelector from '../components/condition-list/condition-var-selector'
@@ -28,7 +28,7 @@ it('writes a variable expression when selecting a numeric comparison value', asy
const onValueChange = vi.fn()
render(
<ConditionNumberInput
- numberVarType={NumberVarType.variable}
+ numberVarType={VarKindType.variable}
value=""
variables={variables}
onNumberVarTypeChange={vi.fn()}
diff --git a/web/app/components/workflow/nodes/loop/components/condition-list/condition-item.tsx b/web/app/components/workflow/nodes/loop/components/condition-list/condition-item.tsx
index 6939492b2c8..91fd6bb89d3 100644
--- a/web/app/components/workflow/nodes/loop/components/condition-list/condition-item.tsx
+++ b/web/app/components/workflow/nodes/loop/components/condition-list/condition-item.tsx
@@ -1,4 +1,3 @@
-import type { VarType as NumberVarType } from '../../../tool/types'
import type {
Condition,
HandleAddSubVariableCondition,
@@ -8,6 +7,7 @@ import type {
HandleUpdateCondition,
HandleUpdateSubVariableCondition,
} from '../../types'
+import type { VarKindType } from '@/app/components/workflow/nodes/_base/types'
import type { Node, NodeOutPutVar, ValueSelector, Var } from '@/app/components/workflow/types'
import { cn } from '@langgenius/dify-ui/cn'
import {
@@ -119,7 +119,7 @@ const ConditionItem = ({
)
const handleUpdateConditionNumberVarType = useCallback(
- (numberVarType: NumberVarType) => {
+ (numberVarType: VarKindType) => {
const newCondition = {
...condition,
numberVarType,
diff --git a/web/app/components/workflow/nodes/loop/components/condition-number-input.tsx b/web/app/components/workflow/nodes/loop/components/condition-number-input.tsx
index ef99e14071b..57c1fee9063 100644
--- a/web/app/components/workflow/nodes/loop/components/condition-number-input.tsx
+++ b/web/app/components/workflow/nodes/loop/components/condition-number-input.tsx
@@ -16,16 +16,16 @@ import { memo, useCallback, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { Variable02 } from '@/app/components/base/icons/src/vender/solid/development'
import VarReferenceVars from '@/app/components/workflow/nodes/_base/components/variable/var-reference-vars'
+import { VarKindType } from '@/app/components/workflow/nodes/_base/types'
import { VarType } from '@/app/components/workflow/types'
import { variableTransformer } from '@/app/components/workflow/utils'
import VariableTag from '../../_base/components/variable-tag'
-import { VarType as NumberVarType } from '../../tool/types'
-const options = [NumberVarType.variable, NumberVarType.constant]
+const options = [VarKindType.variable, VarKindType.constant]
type ConditionNumberInputProps = {
- numberVarType?: NumberVarType
- onNumberVarTypeChange: (v: NumberVarType) => void
+ numberVarType?: VarKindType
+ onNumberVarTypeChange: (v: VarKindType) => void
value: string
onValueChange: (v: string) => void
variables: NodeOutPutVar[]
@@ -33,7 +33,7 @@ type ConditionNumberInputProps = {
unit?: string
}
const ConditionNumberInput = ({
- numberVarType = NumberVarType.constant,
+ numberVarType = VarKindType.constant,
onNumberVarTypeChange,
value,
onValueChange,
@@ -86,7 +86,7 @@ const ConditionNumberInput = ({
</DropdownMenu>
<div className="mx-1 h-4 w-px bg-divider-regular"></div>
<div className="ml-0.5 w-0 grow">
- {numberVarType === NumberVarType.variable && (
+ {numberVarType === VarKindType.variable && (
<Popover open={variableSelectorVisible} onOpenChange={setVariableSelectorVisible}>
<PopoverTrigger nativeButton={false} render={<div className="w-full" />}>
{value && (
@@ -126,7 +126,7 @@ const ConditionNumberInput = ({
</PopoverContent>
</Popover>
)}
- {numberVarType === NumberVarType.constant && (
+ {numberVarType === VarKindType.constant && (
<div className="relative">
<input
className={cn(
diff --git a/web/app/components/workflow/nodes/loop/types.ts b/web/app/components/workflow/nodes/loop/types.ts
index 0ef69b29115..60c24a73abb 100644
--- a/web/app/components/workflow/nodes/loop/types.ts
+++ b/web/app/components/workflow/nodes/loop/types.ts
@@ -1,4 +1,4 @@
-import type { VarType as NumberVarType } from '../tool/types'
+import type { VarKindType } from '@/app/components/workflow/nodes/_base/types'
import type {
BlockEnum,
CommonNodeType,
@@ -49,7 +49,7 @@ export type Condition = {
key?: string // sub variable key
comparison_operator?: ComparisonOperator
value: string | string[] | boolean
- numberVarType?: NumberVarType
+ numberVarType?: VarKindType
sub_variable_condition?: CaseItem
}
diff --git a/web/app/components/workflow/nodes/tool/components/tool-form/__tests__/index.spec.tsx b/web/app/components/workflow/nodes/tool/components/tool-form/__tests__/index.spec.tsx
index 99705f62c57..59ee2e46819 100644
--- a/web/app/components/workflow/nodes/tool/components/tool-form/__tests__/index.spec.tsx
+++ b/web/app/components/workflow/nodes/tool/components/tool-form/__tests__/index.spec.tsx
@@ -1,16 +1,16 @@
-import type { ToolVarInputs } from '../../../types'
import type { CredentialFormSchema } from '@/app/components/header/account-setting/model-provider-page/declarations'
+import type { ResourceVarInputs } from '@/app/components/workflow/nodes/_base/types'
import { render, screen } from '@testing-library/react'
import { FormTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
-import { VarType } from '../../../types'
+import { VarKindType } from '@/app/components/workflow/nodes/_base/types'
import ToolForm from '../index'
type MockToolFormItemProps = {
readOnly: boolean
nodeId: string
schema: CredentialFormSchema
- value: ToolVarInputs
- onChange: (value: ToolVarInputs) => void
+ value: ResourceVarInputs
+ onChange: (value: ResourceVarInputs) => void
inPanel?: boolean
showManageInputField?: boolean
onManageInputField?: () => void
@@ -50,9 +50,9 @@ describe('tool/tool-form', () => {
it('should render every schema item and forward tool-specific props', () => {
const handleChange = vi.fn()
const handleManageInputField = vi.fn()
- const value: ToolVarInputs = {
+ const value: ResourceVarInputs = {
api_key: {
- type: VarType.constant,
+ type: VarKindType.constant,
value: 'secret',
},
}
diff --git a/web/app/components/workflow/nodes/tool/components/tool-form/index.tsx b/web/app/components/workflow/nodes/tool/components/tool-form/index.tsx
index a842509b88d..ffea65d022b 100644
--- a/web/app/components/workflow/nodes/tool/components/tool-form/index.tsx
+++ b/web/app/components/workflow/nodes/tool/components/tool-form/index.tsx
@@ -1,8 +1,8 @@
'use client'
import type { FC } from 'react'
-import type { ToolVarInputs } from '../../types'
import type { CredentialFormSchema } from '@/app/components/header/account-setting/model-provider-page/declarations'
import type { Tool } from '@/app/components/tools/types'
+import type { ResourceVarInputs } from '@/app/components/workflow/nodes/_base/types'
import type { ToolWithProvider } from '@/app/components/workflow/types'
import ToolFormItem from './item'
@@ -10,8 +10,8 @@ type Props = Readonly<{
readOnly: boolean
nodeId: string
schema: CredentialFormSchema[]
- value: ToolVarInputs
- onChange: (value: ToolVarInputs) => void
+ value: ResourceVarInputs
+ onChange: (value: ResourceVarInputs) => void
onOpen?: (index: number) => void
inPanel?: boolean
currentTool?: Tool
diff --git a/web/app/components/workflow/nodes/tool/components/tool-form/item.tsx b/web/app/components/workflow/nodes/tool/components/tool-form/item.tsx
index 2d69c73fa67..040344c254b 100644
--- a/web/app/components/workflow/nodes/tool/components/tool-form/item.tsx
+++ b/web/app/components/workflow/nodes/tool/components/tool-form/item.tsx
@@ -1,8 +1,8 @@
'use client'
import type { FC, ReactNode } from 'react'
-import type { ToolVarInputs } from '../../types'
import type { CredentialFormSchema } from '@/app/components/header/account-setting/model-provider-page/declarations'
import type { Tool } from '@/app/components/tools/types'
+import type { ResourceVarInputs } from '@/app/components/workflow/nodes/_base/types'
import type { ToolWithProvider } from '@/app/components/workflow/types'
import { Button } from '@langgenius/dify-ui/button'
import { Infotip, InfotipContent, InfotipTrigger } from '@langgenius/dify-ui/infotip'
@@ -52,8 +52,8 @@ type Props = Readonly<{
readOnly: boolean
nodeId: string
schema: CredentialFormSchema
- value: ToolVarInputs
- onChange: (value: ToolVarInputs) => void
+ value: ResourceVarInputs
+ onChange: (value: ResourceVarInputs) => void
inPanel?: boolean
currentTool?: Tool
currentProvider?: ToolWithProvider
diff --git a/web/app/components/workflow/nodes/tool/default.ts b/web/app/components/workflow/nodes/tool/default.ts
index 96880fe5860..dd544b56a32 100644
--- a/web/app/components/workflow/nodes/tool/default.ts
+++ b/web/app/components/workflow/nodes/tool/default.ts
@@ -2,7 +2,7 @@ import type { TFunction } from 'i18next'
import type { NodeDefault, ToolWithProvider, Var } from '../../types'
import type { ToolNodeType } from './types'
import { CollectionType } from '@/app/components/tools/types'
-import { VarType as VarKindType } from '@/app/components/workflow/nodes/tool/types'
+import { VarKindType } from '@/app/components/workflow/nodes/_base/types'
import { BlockEnum } from '@/app/components/workflow/types'
import { genNodeMetaData } from '@/app/components/workflow/utils'
import { matchesProviderReference } from '@/utils/provider-reference'
diff --git a/web/app/components/workflow/nodes/tool/hooks/__tests__/use-config.spec.tsx b/web/app/components/workflow/nodes/tool/hooks/__tests__/use-config.spec.tsx
index 7b26283adc0..4c5eb618e81 100644
--- a/web/app/components/workflow/nodes/tool/hooks/__tests__/use-config.spec.tsx
+++ b/web/app/components/workflow/nodes/tool/hooks/__tests__/use-config.spec.tsx
@@ -1,8 +1,8 @@
import type { ToolNodeType } from '../../types'
import { renderHook } from '@testing-library/react'
import { CollectionType } from '@/app/components/tools/types'
+import { VarKindType } from '@/app/components/workflow/nodes/_base/types'
import { BlockEnum } from '@/app/components/workflow/types'
-import { VarType } from '../../types'
import useConfig from '../use-config'
const mockSetInputs = vi.hoisted(() => vi.fn())
@@ -115,7 +115,7 @@ const currentToolWithoutDefaults = {
}
const createToolVarInput = (value: string) => ({
- type: VarType.mixed,
+ type: VarKindType.mixed,
value,
})
diff --git a/web/app/components/workflow/nodes/tool/hooks/__tests__/use-single-run-form-params.spec.ts b/web/app/components/workflow/nodes/tool/hooks/__tests__/use-single-run-form-params.spec.ts
index bbf936925ee..c45c3e6a4e3 100644
--- a/web/app/components/workflow/nodes/tool/hooks/__tests__/use-single-run-form-params.spec.ts
+++ b/web/app/components/workflow/nodes/tool/hooks/__tests__/use-single-run-form-params.spec.ts
@@ -1,8 +1,9 @@
-import type { ToolNodeType, VarType } from '../../types'
+import type { ToolNodeType } from '../../types'
import type { InputVar } from '@/app/components/workflow/types'
import type { NodeTracing } from '@/types/workflow'
import { act, renderHook } from '@testing-library/react'
import { CollectionType } from '@/app/components/tools/types'
+import { VarKindType } from '@/app/components/workflow/nodes/_base/types'
import { BlockEnum, InputVarType } from '@/app/components/workflow/types'
import useSingleRunFormParams from '../use-single-run-form-params'
@@ -93,13 +94,13 @@ describe('useSingleRunFormParams', () => {
it('should build form inputs from variable params and settings and expose dependent vars', () => {
const payload = createNodeData({
tool_parameters: {
- query: { type: 'variable' as VarType, value: ['start', 'query'] },
- legacy_query: { type: 'variable' as VarType, value: 'legacy.answer' },
- constant_query: { type: 'constant' as VarType, value: 'fixed' },
+ query: { type: VarKindType.variable, value: ['start', 'query'] },
+ legacy_query: { type: VarKindType.variable, value: 'legacy.answer' },
+ constant_query: { type: VarKindType.constant, value: 'fixed' },
},
tool_configurations: {
- prompt: { type: 'mixed' as VarType, value: 'prefix {{#tool.result#}}' },
- api_key: { type: 'constant' as VarType, value: 'secret' },
+ prompt: { type: VarKindType.mixed, value: 'prefix {{#tool.result#}}' },
+ api_key: { type: VarKindType.constant, value: 'secret' },
plainText: 'ignored',
},
})
@@ -147,8 +148,8 @@ describe('useSingleRunFormParams', () => {
it('should update form values and forward run input data on change', () => {
const payload = createNodeData({
tool_parameters: {
- nullable_constant: { type: 'constant' as VarType, value: null },
- query: { type: 'variable' as VarType, value: ['start', 'query'] },
+ nullable_constant: { type: VarKindType.constant, value: null },
+ query: { type: VarKindType.variable, value: ['start', 'query'] },
},
})
const getInputVars = vi.fn(() => [createInputVar('#start.query#')])
diff --git a/web/app/components/workflow/nodes/tool/hooks/use-config.ts b/web/app/components/workflow/nodes/tool/hooks/use-config.ts
index e12b95f93a0..3ad066eb0f6 100644
--- a/web/app/components/workflow/nodes/tool/hooks/use-config.ts
+++ b/web/app/components/workflow/nodes/tool/hooks/use-config.ts
@@ -1,4 +1,5 @@
-import type { ToolNodeType, ToolVarInputs } from '../types'
+import type { ToolNodeType } from '../types'
+import type { ResourceVarInputs } from '@/app/components/workflow/nodes/_base/types'
import type { InputVar } from '@/app/components/workflow/types'
import { capitalize } from 'es-toolkit/string'
import { produce } from 'immer'
@@ -122,7 +123,7 @@ const useConfig = (id: string, payload: ToolNodeType) => {
const configuredToolSettings = getConfiguredValue(
tool_configurations,
toolSettingSchema,
- ) as ToolVarInputs
+ ) as ResourceVarInputs
if (Object.keys(configuredToolSettings).length > 0)
draft.tool_configurations = configuredToolSettings
}
@@ -130,7 +131,7 @@ const useConfig = (id: string, payload: ToolNodeType) => {
const configuredToolParameters = getConfiguredValue(
tool_parameters,
toolInputVarSchema,
- ) as ToolVarInputs
+ ) as ResourceVarInputs
if (Object.keys(configuredToolParameters).length > 0)
draft.tool_parameters = configuredToolParameters
}
@@ -154,7 +155,7 @@ const useConfig = (id: string, payload: ToolNodeType) => {
// setting when call
const setInputVar = useCallback(
- (value: ToolVarInputs) => {
+ (value: ResourceVarInputs) => {
setInputs({
...inputs,
tool_parameters: value,
diff --git a/web/app/components/workflow/nodes/tool/hooks/use-single-run-form-params.ts b/web/app/components/workflow/nodes/tool/hooks/use-single-run-form-params.ts
index c55e2872272..c3c92a0c526 100644
--- a/web/app/components/workflow/nodes/tool/hooks/use-single-run-form-params.ts
+++ b/web/app/components/workflow/nodes/tool/hooks/use-single-run-form-params.ts
@@ -7,9 +7,9 @@ import { produce } from 'immer'
import { useCallback, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import useNodeCrud from '@/app/components/workflow/nodes/_base/hooks/use-node-crud'
+import { VarKindType } from '@/app/components/workflow/nodes/_base/types'
import formatToTracingNodeList from '@/app/components/workflow/run/utils/format-log'
import { useToolIcon } from '../../../hooks/use-tool-icon'
-import { VarType } from '../types'
type Params = {
id: string
@@ -32,7 +32,7 @@ const useSingleRunFormParams = ({
const { inputs } = useNodeCrud<ToolNodeType>(id, payload)
const hadVarParams = Object.keys(inputs.tool_parameters)
- .filter((key) => inputs.tool_parameters[key]!.type !== VarType.constant)
+ .filter((key) => inputs.tool_parameters[key]!.type !== VarKindType.constant)
.map((k) => inputs.tool_parameters[k])
const hadVarSettings = Object.keys(inputs.tool_configurations)
@@ -40,13 +40,13 @@ const useSingleRunFormParams = ({
(key) =>
typeof inputs.tool_configurations[key] === 'object' &&
inputs.tool_configurations[key].type &&
- inputs.tool_configurations[key].type !== VarType.constant,
+ inputs.tool_configurations[key].type !== VarKindType.constant,
)
.map((k) => inputs.tool_configurations[k])
const varInputs = getInputVars(
[...hadVarParams, ...hadVarSettings].map((p) => {
- if (p.type === VarType.variable) {
+ if (p.type === VarKindType.variable) {
// handle the old wrong value not crash the page
if (!(p.value as any).join) return `{{#${p.value}#}}`
@@ -69,7 +69,7 @@ const useSingleRunFormParams = ({
const res = produce(inputVarValues, (draft) => {
Object.keys(inputs.tool_parameters).forEach((key: string) => {
const { type, value } = inputs.tool_parameters[key]!
- if (type === VarType.constant && (value === undefined || value === null)) {
+ if (type === VarKindType.constant && (value === undefined || value === null)) {
if (!draft.tool_parameters || !draft.tool_parameters[key]) return
draft[key] = value
}
diff --git a/web/app/components/workflow/nodes/tool/types.ts b/web/app/components/workflow/nodes/tool/types.ts
index 9a58e8a299d..5a13085eca8 100644
--- a/web/app/components/workflow/nodes/tool/types.ts
+++ b/web/app/components/workflow/nodes/tool/types.ts
@@ -2,17 +2,13 @@ import type { ResourceVarInputs } from '../_base/types'
import type { Collection, CollectionType } from '@/app/components/tools/types'
import type { CommonNodeType } from '@/app/components/workflow/types'
-// Use base types directly
-export { VarKindType as VarType } from '../_base/types'
-export type ToolVarInputs = ResourceVarInputs
-
export type ToolNodeType = CommonNodeType & {
provider_id: string
provider_type: CollectionType
provider_name: string
tool_name: string
tool_label: string
- tool_parameters: ToolVarInputs
+ tool_parameters: ResourceVarInputs
tool_configurations: Record<string, any>
paramSchemas?: Record<string, any>[]
version?: string
diff --git a/web/app/components/workflow/nodes/variable-assigner/components/var-group-item.tsx b/web/app/components/workflow/nodes/variable-assigner/components/var-group-item.tsx
index b275159186e..30342985bd3 100644
--- a/web/app/components/workflow/nodes/variable-assigner/components/var-group-item.tsx
+++ b/web/app/components/workflow/nodes/variable-assigner/components/var-group-item.tsx
@@ -9,7 +9,7 @@ import { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { Folder } from '@/app/components/base/icons/src/vender/line/files'
import Field from '@/app/components/workflow/nodes/_base/components/field'
-import { VarType as VarKindType } from '@/app/components/workflow/nodes/tool/types'
+import { VarKindType } from '@/app/components/workflow/nodes/_base/types'
import { VarType } from '@/app/components/workflow/types'
import { toast } from '@/app/notifications'
import { checkKeys, replaceSpaceWithUnderscoreInVarNameInput } from '@/utils/var'
diff --git a/web/app/components/workflow/nodes/variable-assigner/components/var-list/index.tsx b/web/app/components/workflow/nodes/variable-assigner/components/var-list/index.tsx
index cc97e9b700f..1bd69ac9e67 100644
--- a/web/app/components/workflow/nodes/variable-assigner/components/var-list/index.tsx
+++ b/web/app/components/workflow/nodes/variable-assigner/components/var-list/index.tsx
@@ -7,7 +7,7 @@ import * as React from 'react'
import { useCallback } from 'react'
import { useTranslation } from 'react-i18next'
import VarReferencePicker from '@/app/components/workflow/nodes/_base/components/variable/var-reference-picker'
-import { VarType as VarKindType } from '@/app/components/workflow/nodes/tool/types'
+import { VarKindType } from '@/app/components/workflow/nodes/_base/types'
import ListNoDataPlaceholder from '../../../_base/components/list-no-data-placeholder'
import RemoveButton from '../../../_base/components/remove-button'
diff --git a/web/app/components/workflow/types.ts b/web/app/components/workflow/types.ts
index e4613ddd9df..a019c43765b 100644
--- a/web/app/components/workflow/types.ts
+++ b/web/app/components/workflow/types.ts
@@ -11,8 +11,8 @@ import type {
ErrorHandleTypeEnum,
} from '@/app/components/workflow/nodes/_base/components/error-handle/types'
import type { WorkflowRetryConfig } from '@/app/components/workflow/nodes/_base/components/retry/types'
+import type { VarKindType } from '@/app/components/workflow/nodes/_base/types'
import type { StructuredOutput } from '@/app/components/workflow/nodes/llm/types'
-import type { VarType as VarKindType } from '@/app/components/workflow/nodes/tool/types'
import type { ChatVarType } from '@/app/components/workflow/panel/chat-variable-panel/type'
import type { SchemaTypeDefinition } from '@/service/use-common'
import type { Resolution, TransferMethod } from '@/types/app'
@@ -499,7 +499,7 @@ export type MoreInfo = {
export type ToolWithProvider = Collection & {
tools: Tool[]
- meta: PluginMeta
+ meta?: PluginMeta
plugin_unique_identifier?: string
}
diff --git a/web/hooks/use-i18n.ts b/web/hooks/use-i18n.ts
index 326750562ef..37455ee3fc4 100644
--- a/web/hooks/use-i18n.ts
+++ b/web/hooks/use-i18n.ts
@@ -3,5 +3,5 @@ import { getModelLanguage, renderI18nObject } from '@/i18n/metadata'
export const useRenderI18nObject = () => {
const language = getModelLanguage(useLocale())
- return (obj: Record<string, string>) => renderI18nObject(obj, language)
+ return (obj: Parameters<typeof renderI18nObject>[0]) => renderI18nObject(obj, language)
}
diff --git a/web/service/__tests__/use-plugins.spec.tsx b/web/service/__tests__/use-plugins.spec.tsx
index 57b504a7991..7c4598ee485 100644
--- a/web/service/__tests__/use-plugins.spec.tsx
+++ b/web/service/__tests__/use-plugins.spec.tsx
@@ -312,6 +312,27 @@ describe('normalizeInstalledPluginDetail', () => {
expect(categoryDetail.plugin_id).toBe('langgenius/category-plugin')
})
+ it('preserves the generated agent identity and nullable metadata at the dynamic manifest boundary', () => {
+ const plugin = createPluginInstallation()
+ plugin.declaration.agent_strategy = {
+ identity: {
+ author: 'Dify',
+ name: 'agent',
+ icon: 'agent.svg',
+ icon_dark: null,
+ label: { en_US: 'Agent', zh_Hans: null },
+ description: { en_US: 'Agent strategy' },
+ tags: null,
+ },
+ plugin_id: null,
+ }
+ expect(normalizeInstalledPluginDetail(plugin).declaration.agent_strategy).toEqual(
+ plugin.declaration.agent_strategy,
+ )
+ plugin.declaration.agent_strategy = null
+ expect(normalizeInstalledPluginDetail(plugin).declaration.agent_strategy).toBeNull()
+ })
+
it('preserves endpoint setting types at the dynamic plugin manifest boundary', () => {
const plugin = createPluginInstallation()
plugin.declaration.endpoint = {
diff --git a/web/service/strategy.ts b/web/service/strategy.ts
deleted file mode 100644
index bb032ba286b..00000000000
--- a/web/service/strategy.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import type { StrategyPluginDetail } from '@/app/components/plugins/types'
-import { get } from './base'
-
-export const fetchStrategyList = () => {
- return get<StrategyPluginDetail[]>('/workspaces/current/agent-providers')
-}
-
-export const fetchStrategyDetail = (agentProvider: string) => {
- return get<StrategyPluginDetail>(`/workspaces/current/agent-provider/${agentProvider}`)
-}
diff --git a/web/service/use-plugins.ts b/web/service/use-plugins.ts
index 876faa038c0..6b2dce7a1f2 100644
--- a/web/service/use-plugins.ts
+++ b/web/service/use-plugins.ts
@@ -34,7 +34,10 @@ import type {
VersionListResponse,
} from '@/app/components/plugins/types'
import type { Collection } from '@/app/components/tools/types'
-import { zEndpointProviderDeclarationResponse } from '@dify/contracts/api/console/workspaces/zod.gen'
+import {
+ zAgentStrategyProviderEntity,
+ zEndpointProviderDeclarationResponse,
+} from '@dify/contracts/api/console/workspaces/zod.gen'
import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { cloneDeep } from 'es-toolkit/object'
import { useAtomValue } from 'jotai'
@@ -435,7 +438,10 @@ const normalizePluginDeclaration = (plugin: InstalledPluginResponse): PluginDecl
datasource: normalizePluginToolDeclaration(declaration.datasource),
model: declaration.model,
tags: declaration.tags ?? [],
- agent_strategy: declaration.agent_strategy,
+ agent_strategy:
+ declaration.agent_strategy == null
+ ? declaration.agent_strategy
+ : zAgentStrategyProviderEntity.parse(declaration.agent_strategy),
meta: {
version: getString(declaration.meta.version) || declaration.version,
minimum_dify_version: getString(declaration.meta.minimum_dify_version) || undefined,
diff --git a/web/service/use-strategy.ts b/web/service/use-strategy.ts
deleted file mode 100644
index 4b25fdfad41..00000000000
--- a/web/service/use-strategy.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import type { QueryOptions } from '@tanstack/react-query'
-import type { StrategyPluginDetail } from '@/app/components/plugins/types'
-import { useQuery } from '@tanstack/react-query'
-import { fetchStrategyDetail, fetchStrategyList } from './strategy'
-import { useInvalid } from './use-base'
-
-const NAME_SPACE = 'agent_strategy'
-
-const useStrategyListKey = [NAME_SPACE, 'strategyList']
-export const useStrategyProviders = () => {
- return useQuery<StrategyPluginDetail[]>({
- queryKey: useStrategyListKey,
- queryFn: fetchStrategyList,
- })
-}
-
-export const useInvalidateStrategyProviders = () => {
- return useInvalid(useStrategyListKey)
-}
-
-export const useStrategyProviderDetail = (
- agentProvider: string,
- options?: QueryOptions<StrategyPluginDetail>,
-) => {
- return useQuery<StrategyPluginDetail>({
- ...options,
- queryKey: [NAME_SPACE, 'detail', agentProvider],
- queryFn: () => fetchStrategyDetail(agentProvider),
- enabled: !!agentProvider,
- })
-}