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.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
feat(agent-v2): sync nightly updates to main (#37599)
盐粒 Yanli3f2d22ec0f9a
diff --git a/api/controllers/console/agent/roster.py b/api/controllers/console/agent/roster.pyindex ce75f9f1d06..c45d18ca73e 100644--- a/api/controllers/console/agent/roster.py+++ b/api/controllers/console/agent/roster.py@@ -2,20 +2,28 @@ from uuid import UUIDfrom flask import abort, requestfrom flask_restx import Resource-from pydantic import BaseModel, Field, field_validator+from pydantic import AliasChoices, BaseModel, Field, field_validatorfrom controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_modelsfrom controllers.console import console_nsfrom controllers.console.agent.app_helpers import resolve_agent_app_modelfrom controllers.console.app.app import (- AppDetailWithSite,+ AppDetailWithSite as GenericAppDetailWithSite,+)+from controllers.console.app.app import (AppListQuery,- AppPagination,- AppPartial,CopyAppPayload,- UpdateAppPayload,_normalize_app_list_query_args,)+from controllers.console.app.app import (+ AppPagination as GenericAppPagination,+)+from controllers.console.app.app import (+ AppPartial as GenericAppPartial,+)+from controllers.console.app.app import (+ UpdateAppPayload as GenericUpdateAppPayload,+)from controllers.console.wraps import (account_initialization_required,cloud_edition_billing_resource_check,@@ -80,7 +88,10 @@ class AgentAppCreatePayload(BaseModel):return role-class AgentAppUpdatePayload(UpdateAppPayload):+# Keep agent-app roster DTOs agent-specific instead of reusing the shared+# /apps response/request models. The roster surface needs Agent-only fields such+# as `role`, while the generic console/apps contracts must stay unchanged.+class AgentAppUpdatePayload(GenericUpdateAppPayload):role: str = Field(..., min_length=1, description="Agent role", max_length=255)@field_validator("role")@@ -100,19 +111,6 @@ class AgentAppPublishedReferenceResponse(BaseModel):app_icon_background: str | None = None-class AgentAppPartial(AppPartial):- published_reference_count: int = 0- published_references: list[AgentAppPublishedReferenceResponse] = Field(default_factory=list)---class AgentAppPagination(BaseModel):- page: int- limit: int- total: int- has_more: bool- data: list[AgentAppPartial]--class AgentLogsQuery(BaseModel):page: int = Field(default=1, ge=1, description="Page number")limit: int = Field(default=20, ge=1, le=100, description="Page size")@@ -149,6 +147,26 @@ class AgentStatisticsQuery(BaseModel):return value+class AgentAppPartial(GenericAppPartial):+ app_id: str | None = None+ role: str | None = None+ active_config_is_published: bool = False+ published_reference_count: int = 0+ published_references: list[AgentAppPublishedReferenceResponse] = Field(default_factory=list)+++class AgentAppDetailWithSite(GenericAppDetailWithSite):+ app_id: str | None = None+ role: str | None = None+ active_config_is_published: bool = False+++class AgentAppPagination(GenericAppPagination):+ data: list[AgentAppPartial] = Field( # type: ignore[assignment] # pyrefly: ignore[bad-override-mutable-attribute]+ validation_alias=AliasChoices("items", "data")+ )++register_schema_models(console_ns,AgentAppCreatePayload,@@ -159,14 +177,14 @@ register_schema_models(AgentStatisticsQuery,AgentIdPath,AppListQuery,- UpdateAppPayload,RosterListQuery,)register_response_schema_models(console_ns,- AppDetailWithSite,AgentAppPagination,AgentAppPublishedReferenceResponse,+ AgentAppDetailWithSite,+ AgentAppPartial,AgentConfigSnapshotDetailResponse,AgentConfigSnapshotListResponse,AgentInviteOptionsResponse,@@ -184,16 +202,25 @@ def _agent_roster_service() -> AgentRosterService:def _serialize_agent_app_detail(app_model) -> dict:+ """Serialize an Agent App detail using roster-only DTOs.++ `/agent` responses are roster-shaped rather than raw app-shaped: `id`+ becomes the backing roster Agent id, `app_id` carries the underlying App+ id, and `role` is injected from the backing roster Agent. Keeping that+ remap in this serializer lets generated console/agent contracts expose the+ roster persona fields without widening the shared /apps detail schema.+ """+app_model = AppService().get_app(app_model)if FeatureService.get_system_features().webapp_auth.enabled:app_setting = EnterpriseService.WebAppAuth.get_app_access_mode_by_id(app_id=str(app_model.id))app_model.access_mode = app_setting.access_mode # type: ignore[attr-defined]roster_service = _agent_roster_service()- agent = roster_service.get_app_backing_agent(tenant_id=app_model.tenant_id, app_id=app_model.id)+ payload = AgentAppDetailWithSite.model_validate(app_model, from_attributes=True).model_dump(mode="json")+ agent = roster_service.get_app_backing_agent(tenant_id=app_model.tenant_id, app_id=str(app_model.id))if not agent:raise AgentNotFoundError()- payload = AppDetailWithSite.model_validate(app_model, from_attributes=True).model_dump(mode="json")payload.pop("bound_agent_id", None)payload["app_id"] = str(app_model.id)payload["id"] = agent.id@@ -206,6 +233,14 @@ def _serialize_agent_app_detail(app_model) -> dict:def _serialize_agent_app_pagination(app_pagination, *, tenant_id: str) -> dict:+ """Serialize Agent App lists with roster-shaped items.++ Each item starts from the shared App list shape, then drops+ `bound_agent_id`, rewrites `id` to the backing roster Agent id, stores the+ original App id in `app_id`, and injects roster-only `role` when a backing+ Agent is present.+ """+app_ids = [str(app.id) for app in app_pagination.items]roster_service = _agent_roster_service()agents_by_app_id = roster_service.load_app_backing_agents_by_app_id(@@ -220,7 +255,7 @@ def _serialize_agent_app_pagination(app_pagination, *, tenant_id: str) -> dict:tenant_id=tenant_id,agent_ids=[agent.id for agent in agents_by_app_id.values()],)- payload = AppPagination.model_validate(app_pagination, from_attributes=True).model_dump(mode="json")+ payload = AgentAppPagination.model_validate(app_pagination, from_attributes=True).model_dump(mode="json")for item in payload["data"]:app_id = item["id"]item.pop("bound_agent_id", None)@@ -294,7 +329,7 @@ class AgentAppListApi(Resource):return _serialize_agent_app_pagination(app_pagination, tenant_id=current_tenant_id)@console_ns.expect(console_ns.models[AgentAppCreatePayload.__name__])- @console_ns.response(201, "Agent app created successfully", console_ns.models[AppDetailWithSite.__name__])+ @console_ns.response(201, "Agent app created successfully", console_ns.models[AgentAppDetailWithSite.__name__])@console_ns.response(403, "Insufficient permissions")@console_ns.response(400, "Invalid request parameters")@setup_required@@ -322,7 +357,7 @@ class AgentAppListApi(Resource):@console_ns.route("/agent/<uuid:agent_id>")class AgentAppApi(Resource):- @console_ns.response(200, "Agent app detail", console_ns.models[AppDetailWithSite.__name__])+ @console_ns.response(200, "Agent app detail", console_ns.models[AgentAppDetailWithSite.__name__])@setup_required@login_required@account_initialization_required@@ -333,7 +368,7 @@ class AgentAppApi(Resource):return _serialize_agent_app_detail(app_model)@console_ns.expect(console_ns.models[AgentAppUpdatePayload.__name__])- @console_ns.response(200, "Agent app updated successfully", console_ns.models[AppDetailWithSite.__name__])+ @console_ns.response(200, "Agent app updated successfully", console_ns.models[AgentAppDetailWithSite.__name__])@console_ns.response(403, "Insufficient permissions")@console_ns.response(400, "Invalid request parameters")@setup_required@@ -373,7 +408,7 @@ class AgentAppApi(Resource):@console_ns.route("/agent/<uuid:agent_id>/copy")class AgentAppCopyApi(Resource):@console_ns.expect(console_ns.models[CopyAppPayload.__name__])- @console_ns.response(201, "Agent app copied successfully", console_ns.models[AppDetailWithSite.__name__])+ @console_ns.response(201, "Agent app copied successfully", console_ns.models[AgentAppDetailWithSite.__name__])@console_ns.response(403, "Insufficient permissions")@console_ns.response(400, "Invalid request parameters")@setup_requireddiff --git a/api/controllers/console/app/agent.py b/api/controllers/console/app/agent.pyindex 23ccd28ad6f..6731be67831 100644--- a/api/controllers/console/app/agent.py+++ b/api/controllers/console/app/agent.py@@ -30,7 +30,7 @@ from models import Accountfrom models.agent_config_entities import AgentFileRefConfig, AgentSkillRefConfigfrom models.model import App, AppMode, UploadFilefrom services.agent.composer_service import AgentComposerService-from services.agent.skill_package_service import SkillManifest, SkillPackageError, SkillPackageService+from services.agent.skill_package_service import SkillManifest, SkillPackageErrorfrom services.agent.skill_standardize_service import SkillStandardizeServicefrom services.agent.skill_tool_inference_service import (SkillToolInferenceError,@@ -45,11 +45,18 @@ from services.agent_drive_service import (normalize_drive_key,)from services.agent_service import AgentService-from services.file_service import FileServicelogger = logging.getLogger(__name__)_WORKFLOW_AGENT_DRIVE_APP_MODES = [AppMode.WORKFLOW, AppMode.ADVANCED_CHAT]+_AGENT_SKILL_UPLOAD_PARAMS = {+ "file": {+ "in": "formData",+ "type": "file",+ "required": True,+ "description": "Skill package (.zip or .skill).",+ }+}class AgentLogQuery(BaseModel):@@ -125,11 +132,6 @@ class AgentSkillUploadResponse(ResponseModel):manifest: SkillManifest-class AgentSkillStandardizeResponse(ResponseModel):- skill: AgentSkillRefConfig- manifest: SkillManifest--class AgentDriveFileResponse(ResponseModel):name: strdrive_key: str@@ -156,7 +158,6 @@ register_response_schema_models(AgentDriveFileCommitResponse,AgentDriveFileResponse,AgentLogResponse,- AgentSkillStandardizeResponse,AgentSkillUploadResponse,SkillToolInferenceResult,)@@ -174,30 +175,9 @@ def _agent_not_bound() -> tuple[dict[str, str], int]:return {"code": "agent_not_bound", "message": "no agent is bound for this app/node"}, 400-def _upload_skill_for_app(*, current_user: Account):- if "file" not in request.files:- return {"code": "no_file", "message": "no skill file uploaded"}, 400- if len(request.files) > 1:- return {"code": "too_many_files", "message": "only one skill file is allowed"}, 400-- upload = request.files["file"]- content = upload.stream.read()- try:- manifest = SkillPackageService().validate_and_extract(content=content, filename=upload.filename or "")- except SkillPackageError as exc:- return {"code": exc.code, "message": exc.message}, exc.status_code+def _upload_skill_for_app(*, current_user: Account, app_model: App):+ """Upload one skill package and commit its normalized files into the agent drive."""- upload_file = FileService(db.engine).upload_file(- filename=upload.filename or "skill.zip",- content=content,- mimetype=upload.mimetype or "application/zip",- user=current_user,- )- skill_ref = manifest.to_skill_ref(file_id=upload_file.id)- return {"skill": skill_ref.model_dump(exclude_none=True), "manifest": manifest.model_dump()}, 201---def _standardize_skill_for_app(*, current_user: Account, app_model: App):query = query_params_from_request(AgentDriveMutationQuery)agent_id = _resolve_agent_id(app_model, query.node_id)if not agent_id:@@ -382,72 +362,33 @@ class AgentLogApi(Resource):@console_ns.route("/agent/<uuid:agent_id>/skills/upload")class AgentSkillUploadByAgentApi(Resource):@console_ns.doc("upload_agent_skill_by_agent")- @console_ns.doc(description="Upload + validate a Skill package for an Agent App")- @console_ns.doc(params={"agent_id": "Agent ID"})- @console_ns.response(201, "Skill validated", console_ns.models[AgentSkillUploadResponse.__name__])- @console_ns.response(400, "Invalid skill package")+ @console_ns.doc(description="Upload + standardize a Skill into an Agent App drive")+ @console_ns.doc(consumes=["multipart/form-data"], params={"agent_id": "Agent ID", **_AGENT_SKILL_UPLOAD_PARAMS})+ @console_ns.response(201, "Skill uploaded into drive", console_ns.models[AgentSkillUploadResponse.__name__])+ @console_ns.response(400, "Invalid skill package or no bound agent")@setup_required@login_required@account_initialization_required@with_current_user@with_current_tenant_iddef post(self, tenant_id: str, current_user: Account, agent_id: UUID):- resolve_agent_app_model(tenant_id=tenant_id, agent_id=agent_id)- return _upload_skill_for_app(current_user=current_user)+ app_model = resolve_agent_app_model(tenant_id=tenant_id, agent_id=agent_id)+ return _upload_skill_for_app(current_user=current_user, app_model=app_model)@console_ns.route("/apps/<uuid:app_id>/agent/skills/upload")class AgentSkillUploadApi(Resource):@console_ns.doc("upload_agent_skill")- @console_ns.doc(description="Upload + validate a Skill package (.zip/.skill) and extract its manifest")- @console_ns.doc(params={"app_id": "Application ID"})- @console_ns.response(201, "Skill validated", console_ns.models[AgentSkillUploadResponse.__name__])- @console_ns.response(400, "Invalid skill package")- @setup_required- @login_required- @account_initialization_required- @get_app_model(mode=_WORKFLOW_AGENT_DRIVE_APP_MODES)- @with_current_user- def post(self, current_user: Account, app_model: App):- """Validate an uploaded Skill package and persist the archive.-- Returns a validated skill ref (to bind into the Agent soul config on save)- plus its manifest. Standardizing into the agent drive is ENG-594.- """- return _upload_skill_for_app(current_user=current_user)---@console_ns.route("/agent/<uuid:agent_id>/skills/standardize")-class AgentSkillStandardizeByAgentApi(Resource):- @console_ns.doc("standardize_agent_skill_by_agent")- @console_ns.doc(description="Validate + standardize a Skill into an Agent App drive")- @console_ns.doc(params={"agent_id": "Agent ID"})- @console_ns.response(- 201,- "Skill standardized into drive",- console_ns.models[AgentSkillStandardizeResponse.__name__],- )- @console_ns.response(400, "Invalid skill package or no bound agent")- @setup_required- @login_required- @account_initialization_required- @with_current_user- @with_current_tenant_id- def post(self, tenant_id: str, current_user: Account, agent_id: UUID):- app_model = resolve_agent_app_model(tenant_id=tenant_id, agent_id=agent_id)- return _standardize_skill_for_app(current_user=current_user, app_model=app_model)---@console_ns.route("/apps/<uuid:app_id>/agent/skills/standardize")-class AgentSkillStandardizeApi(Resource):- @console_ns.doc("standardize_agent_skill")- @console_ns.doc(description="Validate + standardize a Skill into the agent drive (ENG-594)")- @console_ns.doc(params={"app_id": "Application ID", **query_params_from_model(AgentDriveMutationQuery)})- @console_ns.response(- 201,- "Skill standardized into drive",- console_ns.models[AgentSkillStandardizeResponse.__name__],+ @console_ns.doc(description="Upload + standardize a Skill into the agent drive")+ @console_ns.doc(+ consumes=["multipart/form-data"],+ params={+ "app_id": "Application ID",+ **query_params_from_model(AgentDriveMutationQuery),+ **_AGENT_SKILL_UPLOAD_PARAMS,+ },)+ @console_ns.response(201, "Skill uploaded into drive", console_ns.models[AgentSkillUploadResponse.__name__])@console_ns.response(400, "Invalid skill package or no bound agent")@setup_required@login_required@@ -455,8 +396,8 @@ class AgentSkillStandardizeApi(Resource):@get_app_model(mode=_WORKFLOW_AGENT_DRIVE_APP_MODES)@with_current_userdef post(self, current_user: Account, app_model: App):- """Upload a Skill, validate it, and standardize it into the app agent's drive."""- return _standardize_skill_for_app(current_user=current_user, app_model=app_model)+ """Upload a Skill, validate it, and commit drive-backed skill files."""+ return _upload_skill_for_app(current_user=current_user, app_model=app_model)@console_ns.route("/agent/<uuid:agent_id>/files")diff --git a/api/controllers/console/app/app.py b/api/controllers/console/app/app.pyindex 3a8d0c1eb56..0e897ac44de 100644--- a/api/controllers/console/app/app.py+++ b/api/controllers/console/app/app.py@@ -402,8 +402,6 @@ class AppPartial(ResponseModel):bound_agent_id: str | None = None# For Agent App responses exposed through /agent.app_id: str | None = None- role: str | None = None- active_config_is_published: bool = Falseis_starred: bool = False@computed_field(return_type=str | None) # type: ignore@@ -457,8 +455,6 @@ class AppDetailWithSite(AppDetail):bound_agent_id: str | None = None# For Agent App responses exposed through /agent.app_id: str | None = None- role: str | None = None- active_config_is_published: bool = False@computed_field(return_type=str | None) # type: ignore@property@@ -541,10 +537,7 @@ register_schema_models(ModelConfig,Site,DeletedTool,- AppPartial,AppDetail,- AppDetailWithSite,- AppPagination,AppExportResponse,Segmentation,PreProcessingRule,@@ -564,6 +557,13 @@ register_schema_models(LoadBalancingPayload,)+register_response_schema_models(+ console_ns,+ AppPartial,+ AppDetailWithSite,+ AppPagination,+)+@console_ns.route("/apps")class AppListApi(Resource):diff --git a/api/openapi/markdown/console-openapi.md b/api/openapi/markdown/console-openapi.mdindex bcbe23d4c3e..ccc4bc12487 100644--- a/api/openapi/markdown/console-openapi.md+++ b/api/openapi/markdown/console-openapi.md@@ -323,7 +323,7 @@ Check if activation token is valid| Code | Description | Schema || ---- | ----------- | ------ |-| 201 | Agent app created successfully | **application/json**: [AppDetailWithSite](#appdetailwithsite)<br> |+| 201 | Agent app created successfully | **application/json**: [AgentAppDetailWithSite](#agentappdetailwithsite)<br> || 400 | Invalid request parameters | || 403 | Insufficient permissions | |@@ -368,7 +368,7 @@ Check if activation token is valid| Code | Description | Schema || ---- | ----------- | ------ |-| 200 | Agent app detail | **application/json**: [AppDetailWithSite](#appdetailwithsite)<br> |+| 200 | Agent app detail | **application/json**: [AgentAppDetailWithSite](#agentappdetailwithsite)<br> |### [PUT] /agent/{agent_id}#### Parameters@@ -387,7 +387,7 @@ Check if activation token is valid| Code | Description | Schema || ---- | ----------- | ------ |-| 200 | Agent app updated successfully | **application/json**: [AppDetailWithSite](#appdetailwithsite)<br> |+| 200 | Agent app updated successfully | **application/json**: [AgentAppDetailWithSite](#agentappdetailwithsite)<br> || 400 | Invalid request parameters | || 403 | Insufficient permissions | |@@ -524,7 +524,7 @@ Stop a running Agent App chat message generation| Code | Description | Schema || ---- | ----------- | ------ |-| 201 | Agent app copied successfully | **application/json**: [AppDetailWithSite](#appdetailwithsite)<br> |+| 201 | Agent app copied successfully | **application/json**: [AgentAppDetailWithSite](#agentappdetailwithsite)<br> || 400 | Invalid request parameters | || 403 | Insufficient permissions | |@@ -800,8 +800,8 @@ Upload one Agent App sandbox file as a Dify ToolFile mapping| ---- | ----------- | ------ || 200 | Uploaded | **application/json**: [SandboxUploadResponse](#sandboxuploadresponse)<br> |-### [POST] /agent/{agent_id}/skills/standardize-Validate + standardize a Skill into an Agent App drive+### [POST] /agent/{agent_id}/skills/upload+Upload + standardize a Skill into an Agent App drive#### Parameters@@ -809,28 +809,18 @@ Validate + standardize a Skill into an Agent App drive| ---- | ---------- | ----------- | -------- | ------ || agent_id | path | Agent ID | Yes | string (uuid) |-#### Responses--| Code | Description | Schema |-| ---- | ----------- | ------ |-| 201 | Skill standardized into drive | **application/json**: [AgentSkillStandardizeResponse](#agentskillstandardizeresponse)<br> |-| 400 | Invalid skill package or no bound agent | |--### [POST] /agent/{agent_id}/skills/upload-Upload + validate a Skill package for an Agent App--#### Parameters+#### Request Body-| Name | Located in | Description | Required | Schema |-| ---- | ---------- | ----------- | -------- | ------ |-| agent_id | path | Agent ID | Yes | string (uuid) |+| Required | Schema |+| -------- | ------ |+| Yes | **multipart/form-data**: { **"file"**: binary }<br> |#### Responses| Code | Description | Schema || ---- | ----------- | ------ |-| 201 | Skill validated | **application/json**: [AgentSkillUploadResponse](#agentskilluploadresponse)<br> |-| 400 | Invalid skill package | |+| 201 | Skill uploaded into drive | **application/json**: [AgentSkillUploadResponse](#agentskilluploadresponse)<br> |+| 400 | Invalid skill package or no bound agent | |### [DELETE] /agent/{agent_id}/skills/{slug}Delete a standardized skill from an Agent App drive@@ -1517,10 +1507,10 @@ Get agent execution logs for an application| 200 | Agent logs retrieved successfully | **application/json**: [AgentLogResponse](#agentlogresponse)<br> || 400 | Invalid request parameters | |-### [POST] /apps/{app_id}/agent/skills/standardize-**Upload a Skill, validate it, and standardize it into the app agent's drive**+### [POST] /apps/{app_id}/agent/skills/upload+**Upload a Skill, validate it, and commit drive-backed skill files**-Validate + standardize a Skill into the agent drive (ENG-594)+Upload + standardize a Skill into the agent drive#### Parameters@@ -1529,32 +1519,18 @@ Validate + standardize a Skill into the agent drive (ENG-594)| app_id | path | Application ID | Yes | string (uuid) || node_id | query | Workflow node ID (workflow composer variant) | No | string |-#### Responses--| Code | Description | Schema |-| ---- | ----------- | ------ |-| 201 | Skill standardized into drive | **application/json**: [AgentSkillStandardizeResponse](#agentskillstandardizeresponse)<br> |-| 400 | Invalid skill package or no bound agent | |--### [POST] /apps/{app_id}/agent/skills/upload-**Validate an uploaded Skill package and persist the archive**--Upload + validate a Skill package (.zip/.skill) and extract its manifest-Returns a validated skill ref (to bind into the Agent soul config on save)-plus its manifest. Standardizing into the agent drive is ENG-594.--#### Parameters+#### Request Body-| Name | Located in | Description | Required | Schema |-| ---- | ---------- | ----------- | -------- | ------ |-| app_id | path | Application ID | Yes | string (uuid) |+| Required | Schema |+| -------- | ------ |+| Yes | **multipart/form-data**: { **"file"**: binary }<br> |#### Responses| Code | Description | Schema || ---- | ----------- | ------ |-| 201 | Skill validated | **application/json**: [AgentSkillUploadResponse](#agentskilluploadresponse)<br> |-| 400 | Invalid skill package | |+| 201 | Skill uploaded into drive | **application/json**: [AgentSkillUploadResponse](#agentskilluploadresponse)<br> |+| 400 | Invalid skill package or no bound agent | |### [DELETE] /apps/{app_id}/agent/skills/{slug}Delete a standardized skill: soul ref first, then the <slug>/ drive prefix (ENG-625 D5)@@ -11378,6 +11354,39 @@ Default namespace| name | string | Agent name | Yes || role | string | Agent role | Yes |+#### AgentAppDetailWithSite++| Name | Type | Description | Required |+| ---- | ---- | ----------- | -------- |+| access_mode | string | | No |+| active_config_is_published | boolean | | No |+| api_base_url | string | | No |+| app_id | string | | No |+| bound_agent_id | string | | No |+| created_at | integer | | No |+| created_by | string | | No |+| deleted_tools | [ [DeletedTool](#deletedtool) ] | | No |+| description | string | | No |+| enable_api | boolean | | Yes |+| enable_site | boolean | | Yes |+| icon | string | | No |+| icon_background | string | | No |+| icon_type | string | | No |+| icon_url | string | | Yes |+| id | string | | Yes |+| max_active_requests | integer | | No |+| mode | string | | Yes |+| model_config | [ModelConfig](#modelconfig) | | No |+| name | string | | Yes |+| role | string | | No |+| site | [Site](#site) | | No |+| tags | [ [Tag](#tag) ] | | No |+| tracing | [JSONValue](#jsonvalue) | | No |+| updated_at | integer | | No |+| updated_by | string | | No |+| use_icon_as_answer_icon | boolean | | No |+| workflow | [WorkflowPartial](#workflowpartial) | | No |+#### AgentAppFeaturesPayloadPresentation features configurable on an Agent App.@@ -12296,13 +12305,6 @@ Visibility and lifecycle scope of an Agent record.| skill_md_file_id | string | | No || skill_md_key | string | | No |-#### AgentSkillStandardizeResponse--| Name | Type | Description | Required |-| ---- | ---- | ----------- | -------- |-| manifest | [SkillManifest](#skillmanifest) | | Yes |-| skill | [AgentSkillRefConfig](#agentskillrefconfig) | | Yes |-#### AgentSkillUploadResponse| Name | Type | Description | Required |@@ -12864,7 +12866,6 @@ Enum class for api provider schema type.| Name | Type | Description | Required || ---- | ---- | ----------- | -------- || access_mode | string | | No |-| active_config_is_published | boolean | | No || api_base_url | string | | No || app_id | string | | No || bound_agent_id | string | | No |@@ -12883,7 +12884,6 @@ Enum class for api provider schema type.| mode | string | | Yes || model_config | [ModelConfig](#modelconfig) | | No || name | string | | Yes |-| role | string | | No || site | [Site](#site) | | No || tags | [ [Tag](#tag) ] | | No || tracing | [JSONValue](#jsonvalue) | | No |@@ -12977,10 +12977,10 @@ AppMCPServer Status Enum| Name | Type | Description | Required || ---- | ---- | ----------- | -------- |-| has_next | boolean | | Yes |-| items | [ [AppPartial](#apppartial) ] | | Yes |+| data | [ [AppPartial](#apppartial) ] | | Yes |+| has_more | boolean | | Yes |+| limit | integer | | Yes || page | integer | | Yes |-| per_page | integer | | Yes || total | integer | | Yes |#### AppPartial@@ -12988,25 +12988,24 @@ AppMCPServer Status Enum| Name | Type | Description | Required || ---- | ---- | ----------- | -------- || access_mode | string | | No |-| active_config_is_published | boolean | | No || app_id | string | | No |-| app_model_config | [ModelConfigPartial](#modelconfigpartial) | | No || author_name | string | | No || bound_agent_id | string | | No || create_user_name | string | | No || created_at | integer | | No || created_by | string | | No |-| desc_or_prompt | string | | No |+| description | string | | No || has_draft_trigger | boolean | | No || icon | string | | No || icon_background | string | | No || icon_type | string | | No |+| icon_url | string | | Yes || id | string | | Yes || is_starred | boolean | | No || max_active_requests | integer | | No |-| mode_compatible_with_agent | string | | Yes |+| mode | string | | Yes |+| model_config | [ModelConfigPartial](#modelconfigpartial) | | No || name | string | | Yes |-| role | string | | No || tags | [ [Tag](#tag) ] | | No || updated_at | integer | | No || updated_by | string | | No |diff --git a/api/services/agent/skill_standardize_service.py b/api/services/agent/skill_standardize_service.pyindex 71bb8daded9..b83004f3c4b 100644--- a/api/services/agent/skill_standardize_service.py+++ b/api/services/agent/skill_standardize_service.py@@ -10,7 +10,9 @@ to the agent drive (Agent Files §5.4 / §4):Both are stored as ``ToolFile`` records and bound via ``AgentDriveService.commit``with ``value_owned_by_drive=True`` (the drive owns their lifecycle). The returnedskill ref records the stable drive paths + file ids (not just the raw upload id),-so the Composer can reload the bound skill list.+so the Composer can reload the bound skill list. The console ``/skills/upload``+endpoints delegate to this service so "upload" now always means drive-backed skill+normalization."""from __future__ import annotations@@ -34,7 +36,7 @@ def slugify_skill_name(name: str) -> str:class SkillStandardizeService:- """Validate + standardize a Skill package into a per-agent drive."""+ """Validate + standardize a Skill package into a per-agent drive upload result."""def __init__(self,diff --git a/api/services/app_service.py b/api/services/app_service.pyindex 18f4e70df4b..cd0d08bf3e7 100644--- a/api/services/app_service.py+++ b/api/services/app_service.py@@ -542,17 +542,21 @@ class AppService:*,name: str | None = None,description: str | None = None,+ role: str | None = None,icon_type: IconType | str | None = None,icon: str | None = None,icon_background: str | None = None,- role: str | None = None,account_id: str | None = None,updated_at: datetime | None = None,) -> None:"""Keep the Roster identity aligned with its Agent App shell.Agent Soul remains versioned through Composer. This helper only mirrors- user-facing identity fields so Roster and Agent Console do not drift.+ user-facing identity fields, including the roster role/persona label,+ so Roster and Agent Console do not drift.++ Role omission is intentional: ``role=None`` preserves the backing+ Agent's current role, while ``role=""`` explicitly clears it."""agent = self._get_backing_agent_for_update(app)if agent is None:@@ -562,14 +566,14 @@ class AppService:agent.name = nameif description is not None:agent.description = description+ if role is not None:+ agent.role = roleif icon_type is not None:agent.icon_type = self._to_agent_icon_type(icon_type)if icon is not None:agent.icon = iconif icon_background is not None:agent.icon_background = icon_background- if role is not None:- agent.role = roleagent.updated_by = account_idif updated_at is not None:agent.updated_at = updated_at@@ -601,10 +605,12 @@ class AppService:app,name=app.name,description=app.description,+ # Omitted role must stay omitted here: None means "preserve current+ # backing-agent role", while an empty string is an explicit clear.+ role=args.get("role"),icon_type=app.icon_type,icon=app.icon,icon_background=app.icon_background,- role=args.get("role"),account_id=current_user.id,updated_at=app.updated_at,)diff --git a/api/services/entities/agent_entities.py b/api/services/entities/agent_entities.pyindex 63ae101533d..e7b5cbd7c6d 100644--- a/api/services/entities/agent_entities.py+++ b/api/services/entities/agent_entities.py@@ -60,6 +60,7 @@ class ComposerSavePayload(BaseModel):class RosterAgentCreatePayload(BaseModel):name: str = Field(min_length=1, max_length=255)+ mode: Literal["agent"] = "agent"description: str = ""role: str = Field(default="", max_length=255)icon_type: AgentIconType | None = Nonediff --git a/api/tests/unit_tests/controllers/console/agent/test_agent_controllers.py b/api/tests/unit_tests/controllers/console/agent/test_agent_controllers.pyindex dfd51f462ea..320d841ca8c 100644--- a/api/tests/unit_tests/controllers/console/agent/test_agent_controllers.py+++ b/api/tests/unit_tests/controllers/console/agent/test_agent_controllers.py@@ -95,6 +95,7 @@ def _agent_app_composer_response() -> dict:def _app_detail_obj(**overrides):data = {"id": "app-1",+ "tenant_id": "tenant-1","name": "Iris","description": "Agent app","mode_compatible_with_agent": "agent",@@ -118,7 +119,6 @@ def _app_detail_obj(**overrides):"deleted_tools": [],"site": None,"bound_agent_id": "00000000-0000-0000-0000-000000000001",- "tenant_id": "tenant-1",}data.update(overrides)return SimpleNamespace(**data)diff --git a/api/tests/unit_tests/controllers/console/app/test_agent_skills.py b/api/tests/unit_tests/controllers/console/app/test_agent_skills.pyindex bcb4aeab462..e94536aa012 100644--- a/api/tests/unit_tests/controllers/console/app/test_agent_skills.py+++ b/api/tests/unit_tests/controllers/console/app/test_agent_skills.py@@ -10,7 +10,7 @@ from __future__ import annotationsimport inspectimport iofrom types import SimpleNamespace-from unittest.mock import MagicMock, patch+from unittest.mock import patchfrom flask import Flask@@ -18,8 +18,6 @@ from controllers.console.app.agent import (AgentDriveFilesByAgentApi,AgentSkillByAgentApi,AgentSkillInferToolsByAgentApi,- AgentSkillStandardizeApi,- AgentSkillStandardizeByAgentApi,AgentSkillUploadApi,AgentSkillUploadByAgentApi,)@@ -45,47 +43,39 @@ _APP = SimpleNamespace(id="app-1", tenant_id="tenant-1", mode=AppMode.AGENT, bou_WORKFLOW_APP = SimpleNamespace(id="app-1", tenant_id="tenant-1", mode=AppMode.WORKFLOW, bound_agent_id=None)-def test_upload_validates_and_returns_skill_ref():+def test_upload_standardizes_into_drive_and_returns_skill_ref():raw = _raw(AgentSkillUploadApi.post)- manifest = MagicMock()- manifest.to_skill_ref.return_value.model_dump.return_value = {"name": "S", "file_id": "uf-1"}- manifest.model_dump.return_value = {"name": "S"}with _file_ctx(files={"file": b"zip-bytes"}):with (- patch(f"{_MOD}.SkillPackageService") as pkg,- patch(f"{_MOD}.FileService") as fs,- patch(f"{_MOD}.db"),+ patch(f"{_MOD}.SkillStandardizeService") as svc,):- pkg.return_value.validate_and_extract.return_value = manifest- fs.return_value.upload_file.return_value = SimpleNamespace(id="uf-1")+ svc.return_value.standardize.return_value = {+ "skill": {"path": "skill-a", "skill_md_key": "skill-a/SKILL.md"},+ "manifest": {"name": "Skill A"},+ }body, status = raw(AgentSkillUploadApi(), _USER, _APP)assert status == 201- assert body["skill"] == {"name": "S", "file_id": "uf-1"}- manifest.to_skill_ref.assert_called_once_with(file_id="uf-1")+ assert body["skill"] == {"path": "skill-a", "skill_md_key": "skill-a/SKILL.md"}+ assert svc.return_value.standardize.call_args.kwargs["agent_id"] == "agent-1"-def test_upload_by_agent_resolves_app_and_returns_skill_ref():+def test_upload_by_agent_resolves_app_and_standardizes_into_drive():raw = _raw(AgentSkillUploadByAgentApi.post)- manifest = MagicMock()- manifest.to_skill_ref.return_value.model_dump.return_value = {"name": "S", "file_id": "uf-1"}- manifest.model_dump.return_value = {"name": "S"}with _file_ctx(files={"file": b"zip-bytes"}):with (patch(f"{_MOD}.resolve_agent_app_model", return_value=_APP) as resolve_app,- patch(f"{_MOD}.SkillPackageService") as pkg,- patch(f"{_MOD}.FileService") as fs,- patch(f"{_MOD}.db"),+ patch(f"{_MOD}.SkillStandardizeService") as svc,):- pkg.return_value.validate_and_extract.return_value = manifest- fs.return_value.upload_file.return_value = SimpleNamespace(id="uf-1")+ svc.return_value.standardize.return_value = {"skill": {"path": "skill-a"}, "manifest": {}}body, status = raw(AgentSkillUploadByAgentApi(), "tenant-1", _USER, "agent-1")assert status == 201- assert body["skill"] == {"name": "S", "file_id": "uf-1"}+ assert body["skill"] == {"path": "skill-a"}resolve_app.assert_called_once_with(tenant_id="tenant-1", agent_id="agent-1")+ assert svc.return_value.standardize.call_args.kwargs["agent_id"] == "agent-1"def test_upload_no_file_is_400():@@ -99,8 +89,8 @@ def test_upload_no_file_is_400():def test_upload_maps_package_error():raw = _raw(AgentSkillUploadApi.post)with _file_ctx(files={"file": b"bad"}):- with patch(f"{_MOD}.SkillPackageService") as pkg:- pkg.return_value.validate_and_extract.side_effect = SkillPackageError(+ with patch(f"{_MOD}.SkillStandardizeService") as svc:+ svc.return_value.standardize.side_effect = SkillPackageError("missing_skill_md", "no SKILL.md", status_code=400)body, status = raw(AgentSkillUploadApi(), _USER, _APP)@@ -108,44 +98,17 @@ def test_upload_maps_package_error():assert body["code"] == "missing_skill_md"-def test_standardize_returns_result():- raw = _raw(AgentSkillStandardizeApi.post)- with _file_ctx(files={"file": b"zip"}):- with patch(f"{_MOD}.SkillStandardizeService") as svc:- svc.return_value.standardize.return_value = {"skill": {"path": "s"}, "manifest": {}}- body, status = raw(AgentSkillStandardizeApi(), _USER, _APP)- assert status == 201- assert body["skill"] == {"path": "s"}- assert svc.return_value.standardize.call_args.kwargs["agent_id"] == "agent-1"---def test_standardize_by_agent_resolves_app():- raw = _raw(AgentSkillStandardizeByAgentApi.post)- with _file_ctx(files={"file": b"zip"}):- with (- patch(f"{_MOD}.resolve_agent_app_model", return_value=_APP) as resolve_app,- patch(f"{_MOD}.SkillStandardizeService") as svc,- ):- svc.return_value.standardize.return_value = {"skill": {"path": "s"}, "manifest": {}}- body, status = raw(AgentSkillStandardizeByAgentApi(), "tenant-1", _USER, "agent-1")-- assert status == 201- assert body["skill"] == {"path": "s"}- resolve_app.assert_called_once_with(tenant_id="tenant-1", agent_id="agent-1")- assert svc.return_value.standardize.call_args.kwargs["agent_id"] == "agent-1"---def test_standardize_no_bound_agent_is_400():- raw = _raw(AgentSkillStandardizeApi.post)+def test_upload_no_bound_agent_is_400():+ raw = _raw(AgentSkillUploadApi.post)app_without_agent = SimpleNamespace(id="app-1", tenant_id="tenant-1", mode=AppMode.AGENT, bound_agent_id=None)with _file_ctx(files={"file": b"zip"}):- body, status = raw(AgentSkillStandardizeApi(), _USER, app_without_agent)+ body, status = raw(AgentSkillUploadApi(), _USER, app_without_agent)assert status == 400assert body["code"] == "agent_not_bound"-def test_standardize_resolves_workflow_node_agent():- raw = _raw(AgentSkillStandardizeApi.post)+def test_upload_resolves_workflow_node_agent():+ raw = _raw(AgentSkillUploadApi.post)with app.test_request_context("/?node_id=agent-node-1", method="POST", data={"file": (io.BytesIO(b"zip"), "skill.zip")}):@@ -155,19 +118,19 @@ def test_standardize_resolves_workflow_node_agent():):composer.resolve_workflow_node_agent_id.return_value = "wf-agent-1"svc.return_value.standardize.return_value = {"skill": {"path": "s"}, "manifest": {}}- body, status = raw(AgentSkillStandardizeApi(), _USER, _WORKFLOW_APP)+ body, status = raw(AgentSkillUploadApi(), _USER, _WORKFLOW_APP)assert status == 201assert body["skill"] == {"path": "s"}assert svc.return_value.standardize.call_args.kwargs["agent_id"] == "wf-agent-1"-def test_standardize_maps_drive_error():- raw = _raw(AgentSkillStandardizeApi.post)+def test_upload_maps_drive_error():+ raw = _raw(AgentSkillUploadApi.post)with _file_ctx(files={"file": b"zip"}):with patch(f"{_MOD}.SkillStandardizeService") as svc:svc.return_value.standardize.side_effect = AgentDriveError("source_not_found", "nope", status_code=404)- body, status = raw(AgentSkillStandardizeApi(), _USER, _APP)+ body, status = raw(AgentSkillUploadApi(), _USER, _APP)assert status == 404assert body["code"] == "source_not_found"diff --git a/api/tests/unit_tests/controllers/console/app/test_app_response_models.py b/api/tests/unit_tests/controllers/console/app/test_app_response_models.pyindex ef8f90e5c9c..9cff0c8d3ee 100644--- a/api/tests/unit_tests/controllers/console/app/test_app_response_models.py+++ b/api/tests/unit_tests/controllers/console/app/test_app_response_models.py@@ -351,6 +351,7 @@ def test_app_partial_serialization_uses_aliases(app_models):create_user_name="Creator",author_name="Author",has_draft_trigger=True,+ role="Should stay agent-only",)serialized = AppPartial.model_validate(app_obj, from_attributes=True).model_dump(mode="json")@@ -363,6 +364,7 @@ def test_app_partial_serialization_uses_aliases(app_models):assert serialized["model_config"]["model"] == {"provider": "openai", "name": "gpt-4o"}assert serialized["workflow"]["id"] == "wf-1"assert serialized["tags"][0]["name"] == "Utilities"+ assert "role" not in serializeddef test_app_detail_with_site_includes_nested_serialization(app_models):@@ -405,6 +407,7 @@ def test_app_detail_with_site_includes_nested_serialization(app_models):deleted_tools=[{"type": "api", "tool_name": "search", "provider_id": "prov"}],site=site,bound_agent_id="agent-1",+ role="Should stay agent-only",)serialized = AppDetailWithSite.model_validate(app_obj, from_attributes=True).model_dump(mode="json")@@ -415,6 +418,7 @@ def test_app_detail_with_site_includes_nested_serialization(app_models):assert serialized["site"]["icon_url"] == "signed:site-icon"assert serialized["site"]["created_at"] == int(timestamp.timestamp())assert serialized["bound_agent_id"] == "agent-1"+ assert "role" not in serializeddef test_app_pagination_aliases_per_page_and_has_next(app_models):diff --git a/api/tests/unit_tests/services/agent/test_agent_services.py b/api/tests/unit_tests/services/agent/test_agent_services.pyindex 41d3d434ba4..b0a099c9bd8 100644--- a/api/tests/unit_tests/services/agent/test_agent_services.py+++ b/api/tests/unit_tests/services/agent/test_agent_services.py@@ -1247,6 +1247,7 @@ class TestAgentAppBackingAgent:app_id="app-1",name="Iris",description="clarifier",+ role="research assistant",)# Agent is bound to the app and is a roster/agent_app entry.@@ -1256,6 +1257,7 @@ class TestAgentAppBackingAgent:assert agent.status == AgentStatus.ACTIVEassert agent.agent_kind == AgentKind.DIFY_AGENTassert agent.name == "Iris"+ assert agent.role == "research assistant"# A v1 snapshot + revision are seeded and wired as the active version.snapshots = [a for a in session.added if isinstance(a, AgentConfigSnapshot)]assert len(snapshots) == 1diff --git a/api/tests/unit_tests/services/test_app_service.py b/api/tests/unit_tests/services/test_app_service.pyindex bb764112640..e595721e169 100644--- a/api/tests/unit_tests/services/test_app_service.py+++ b/api/tests/unit_tests/services/test_app_service.py@@ -168,6 +168,7 @@ class TestAgentAppType:mode=AppMode.AGENT,name="Old",description="old",+ role="draft",icon_type=IconType.EMOJI,icon="robot",icon_background="#fff",@@ -178,6 +179,7 @@ class TestAgentAppType:backing_agent = SimpleNamespace(name="Old",description="old",+ role="draft",icon_type=AgentIconType.EMOJI,icon="robot",icon_background="#fff",@@ -195,6 +197,7 @@ class TestAgentAppType:{"name": "Iris","description": "agent app",+ "role": "research assistant","icon_type": "image","icon": "file-id","icon_background": "#123456",@@ -206,12 +209,114 @@ class TestAgentAppType:assert updated_app.name == "Iris"assert backing_agent.name == "Iris"assert backing_agent.description == "agent app"+ assert backing_agent.role == "research assistant"assert backing_agent.icon_type == AgentIconType.IMAGEassert backing_agent.icon == "file-id"assert backing_agent.icon_background == "#123456"assert backing_agent.updated_by == "account-2"assert backing_agent.updated_at == updated_app.updated_at+ def test_update_agent_app_preserves_role_when_args_omit_it(self):+ from models.agent import AgentIconType+ from models.model import AppMode, IconType+ from services.app_service import AppService++ app = SimpleNamespace(+ id="app-1",+ tenant_id="tenant-1",+ mode=AppMode.AGENT,+ name="Old",+ description="old",+ role="draft",+ icon_type=IconType.EMOJI,+ icon="robot",+ icon_background="#fff",+ use_icon_as_answer_icon=False,+ max_active_requests=None,+ created_by="account-1",+ )+ backing_agent = SimpleNamespace(+ name="Old",+ description="old",+ role="research assistant",+ icon_type=AgentIconType.EMOJI,+ icon="robot",+ icon_background="#fff",+ updated_by=None,+ updated_at=None,+ )++ with (+ patch("services.app_service.db") as mock_db,+ patch("services.app_service.current_user", SimpleNamespace(id="account-2")),+ ):+ mock_db.session.scalar.return_value = backing_agent+ AppService().update_app(+ app, # type: ignore[arg-type]+ {+ "name": "Iris",+ "description": "agent app",+ "icon_type": "image",+ "icon": "file-id",+ "icon_background": "#123456",+ "use_icon_as_answer_icon": False,+ "max_active_requests": 0,+ },+ )++ assert backing_agent.role == "research assistant"++ def test_update_agent_app_clears_role_when_args_set_empty_string(self):+ from models.agent import AgentIconType+ from models.model import AppMode, IconType+ from services.app_service import AppService++ app = SimpleNamespace(+ id="app-1",+ tenant_id="tenant-1",+ mode=AppMode.AGENT,+ name="Old",+ description="old",+ role="draft",+ icon_type=IconType.EMOJI,+ icon="robot",+ icon_background="#fff",+ use_icon_as_answer_icon=False,+ max_active_requests=None,+ created_by="account-1",+ )+ backing_agent = SimpleNamespace(+ name="Old",+ description="old",+ role="research assistant",+ icon_type=AgentIconType.EMOJI,+ icon="robot",+ icon_background="#fff",+ updated_by=None,+ updated_at=None,+ )++ with (+ patch("services.app_service.db") as mock_db,+ patch("services.app_service.current_user", SimpleNamespace(id="account-2")),+ ):+ mock_db.session.scalar.return_value = backing_agent+ AppService().update_app(+ app, # type: ignore[arg-type]+ {+ "name": "Iris",+ "description": "agent app",+ "role": "",+ "icon_type": "image",+ "icon": "file-id",+ "icon_background": "#123456",+ "use_icon_as_answer_icon": False,+ "max_active_requests": 0,+ },+ )++ assert backing_agent.role == ""+def test_delete_agent_app_archives_backing_agent(self):from models.agent import AgentStatusfrom models.model import AppModediff --git a/docker/.env.example b/docker/.env.exampleindex 8daa82d05a1..76b0add67ef 100644--- a/docker/.env.example+++ b/docker/.env.example@@ -150,6 +150,7 @@ NEXT_PUBLIC_ENABLE_SINGLE_DOLLAR_LATEX=false# Enable preview features still in development (currently the /create and# /refine slash commands in the "Go to Anything" command palette).NEXT_PUBLIC_ENABLE_FEATURE_PREVIEW=false+ENABLE_AGENT_V2=falseEXPERIMENTAL_ENABLE_VINEXT=false# Storage and default vector storediff --git a/docker/envs/core-services/web.env.example b/docker/envs/core-services/web.env.exampleindex 4c119106316..bd788a1b16c 100644--- a/docker/envs/core-services/web.env.example+++ b/docker/envs/core-services/web.env.example@@ -25,6 +25,7 @@ ENABLE_WEBSITE_FIRECRAWL=trueENABLE_WEBSITE_WATERCRAWL=trueNEXT_PUBLIC_ENABLE_SINGLE_DOLLAR_LATEX=falseNEXT_PUBLIC_ENABLE_FEATURE_PREVIEW=false+ENABLE_AGENT_V2=falseNEXT_PUBLIC_COOKIE_DOMAIN=NEXT_PUBLIC_BATCH_CONCURRENCY=5CSP_WHITELIST=diff --git a/eslint-suppressions.json b/eslint-suppressions.jsonindex 8a75a82a9da..0641521eb13 100644--- a/eslint-suppressions.json+++ b/eslint-suppressions.json@@ -1089,14 +1089,6 @@"count": 1}},- "web/app/components/base/app-icon/index.tsx": {- "jsx-a11y/click-events-have-key-events": {- "count": 1- },- "jsx-a11y/no-static-element-interactions": {- "count": 1- }- },"web/app/components/base/audio-btn/audio.ts": {"node/prefer-global/buffer": {"count": 1@@ -1529,17 +1521,6 @@"count": 1}},- "web/app/components/base/features/new-feature-panel/moderation/moderation-setting-modal.tsx": {- "jsx-a11y/click-events-have-key-events": {- "count": 2- },- "jsx-a11y/no-static-element-interactions": {- "count": 2- },- "ts/no-explicit-any": {- "count": 2- }- },"web/app/components/base/features/types.ts": {"erasable-syntax-only/enums": {"count": 2@@ -2502,11 +2483,6 @@"count": 2}},- "web/app/components/base/prompt-editor/utils.ts": {- "ts/no-explicit-any": {- "count": 4- }- },"web/app/components/base/prompt-log-modal/index.stories.tsx": {"no-console": {"count": 1@@ -5012,14 +4988,6 @@"count": 1}},- "web/app/components/workflow/block-selector/blocks.tsx": {- "jsx-a11y/click-events-have-key-events": {- "count": 1- },- "jsx-a11y/no-static-element-interactions": {- "count": 1- }- },"web/app/components/workflow/block-selector/featured-tools.tsx": {"jsx-a11y/click-events-have-key-events": {"count": 1@@ -5152,11 +5120,6 @@"count": 1}},- "web/app/components/workflow/candidate-node-main.tsx": {- "ts/no-explicit-any": {- "count": 2- }- },"web/app/components/workflow/comment/comment-input.tsx": {"jsx-a11y/no-autofocus": {"count": 1@@ -5300,11 +5263,6 @@"count": 1}},- "web/app/components/workflow/hooks/use-nodes-interactions.ts": {- "ts/no-explicit-any": {- "count": 8- }- },"web/app/components/workflow/hooks/use-serial-async-callback.ts": {"ts/no-explicit-any": {"count": 1@@ -5704,7 +5662,7 @@"count": 2},"ts/no-explicit-any": {- "count": 6+ "count": 4}},"web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/index.tsx": {@@ -5885,11 +5843,6 @@"count": 5}},- "web/app/components/workflow/nodes/components.ts": {- "ts/no-explicit-any": {- "count": 2- }- },"web/app/components/workflow/nodes/data-source-empty/hooks.ts": {"ts/no-explicit-any": {"count": 1@@ -7060,19 +7013,6 @@"count": 1}},- "web/app/components/workflow/run/agent-log/agent-log-trigger.tsx": {- "jsx-a11y/click-events-have-key-events": {- "count": 1- },- "jsx-a11y/no-static-element-interactions": {- "count": 1- }- },- "web/app/components/workflow/run/agent-log/index.tsx": {- "no-barrel-files/no-barrel-files": {- "count": 2- }- },"web/app/components/workflow/run/hooks.ts": {"ts/no-explicit-any": {"count": 1@@ -7750,11 +7690,6 @@"count": 1}},- "web/service/client.ts": {- "no-restricted-imports": {- "count": 1- }- },"web/service/common.ts": {"no-restricted-imports": {"count": 1diff --git a/packages/contracts/generated/api/console/agent/orpc.gen.ts b/packages/contracts/generated/api/console/agent/orpc.gen.tsindex fcfd3d114fb..fbfca3be118 100644--- a/packages/contracts/generated/api/console/agent/orpc.gen.ts+++ b/packages/contracts/generated/api/console/agent/orpc.gen.ts@@ -83,8 +83,7 @@ import {zPostAgentByAgentIdSandboxFilesUploadResponse,zPostAgentByAgentIdSkillsBySlugInferToolsPath,zPostAgentByAgentIdSkillsBySlugInferToolsResponse,- zPostAgentByAgentIdSkillsStandardizePath,- zPostAgentByAgentIdSkillsStandardizeResponse,+ zPostAgentByAgentIdSkillsUploadBody,zPostAgentByAgentIdSkillsUploadPath,zPostAgentByAgentIdSkillsUploadResponse,zPostAgentResponse,@@ -599,31 +598,11 @@ export const sandbox = {}/**- * Validate + standardize a Skill into an Agent App drive+ * Upload + standardize a Skill into an Agent App drive*/export const post8 = oc.route({- description: 'Validate + standardize a Skill into an Agent App drive',- inputStructure: 'detailed',- method: 'POST',- operationId: 'postAgentByAgentIdSkillsStandardize',- path: '/agent/{agent_id}/skills/standardize',- successStatus: 201,- tags: ['console'],- })- .input(z.object({ params: zPostAgentByAgentIdSkillsStandardizePath }))- .output(zPostAgentByAgentIdSkillsStandardizeResponse)--export const standardize = {- post: post8,-}--/**- * Upload + validate a Skill package for an Agent App- */-export const post9 = oc- .route({- description: 'Upload + validate a Skill package for an Agent App',+ description: 'Upload + standardize a Skill into an Agent App drive',inputStructure: 'detailed',method: 'POST',operationId: 'postAgentByAgentIdSkillsUpload',@@ -631,17 +610,22 @@ export const post9 = ocsuccessStatus: 201,tags: ['console'],})- .input(z.object({ params: zPostAgentByAgentIdSkillsUploadPath }))+ .input(+ z.object({+ body: zPostAgentByAgentIdSkillsUploadBody,+ params: zPostAgentByAgentIdSkillsUploadPath,+ }),+ ).output(zPostAgentByAgentIdSkillsUploadResponse)export const upload2 = {- post: post9,+ post: post8,}/*** Infer CLI tool + ENV suggestions from a standardized Agent App skill*/-export const post10 = oc+export const post9 = oc.route({description: 'Infer CLI tool + ENV suggestions from a standardized Agent App skill',inputStructure: 'detailed',@@ -654,7 +638,7 @@ export const post10 = oc.output(zPostAgentByAgentIdSkillsBySlugInferToolsResponse)export const inferTools = {- post: post10,+ post: post9,}/**@@ -678,7 +662,6 @@ export const bySlug = {}export const skills = {- standardize,upload: upload2,bySlug,}@@ -804,7 +787,7 @@ export const get20 = oc.input(z.object({ query: zGetAgentQuery.optional() })).output(zGetAgentResponse)-export const post11 = oc+export const post10 = oc.route({inputStructure: 'detailed',method: 'POST',@@ -818,7 +801,7 @@ export const post11 = ocexport const agent = {get: get20,- post: post11,+ post: post10,inviteOptions,byAgentId,}diff --git a/packages/contracts/generated/api/console/agent/types.gen.ts b/packages/contracts/generated/api/console/agent/types.gen.tsindex 46cb0545405..19a818cf9a6 100644--- a/packages/contracts/generated/api/console/agent/types.gen.ts+++ b/packages/contracts/generated/api/console/agent/types.gen.ts@@ -21,7 +21,7 @@ export type AgentAppCreatePayload = {role: string}-export type AppDetailWithSite = {+export type AgentAppDetailWithSite = {access_mode?: string | nullactive_config_is_published?: booleanapi_base_url?: string | null@@ -255,11 +255,6 @@ export type SandboxUploadResponse = {path: string}-export type AgentSkillStandardizeResponse = {- manifest: SkillManifest- skill: AgentSkillRefConfig-}-export type AgentSkillUploadResponse = {manifest: SkillManifestskill: AgentSkillRefConfig@@ -1431,7 +1426,7 @@ export type AgentAppPaginationWritable = {total: number}-export type AppDetailWithSiteWritable = {+export type AgentAppDetailWithSiteWritable = {access_mode?: string | nullactive_config_is_published?: booleanapi_base_url?: string | null@@ -1550,7 +1545,7 @@ export type PostAgentErrors = {}export type PostAgentResponses = {- 201: AppDetailWithSite+ 201: AgentAppDetailWithSite}export type PostAgentResponse = PostAgentResponses[keyof PostAgentResponses]@@ -1604,7 +1599,7 @@ export type GetAgentByAgentIdData = {}export type GetAgentByAgentIdResponses = {- 200: AppDetailWithSite+ 200: AgentAppDetailWithSite}export type GetAgentByAgentIdResponse = GetAgentByAgentIdResponses[keyof GetAgentByAgentIdResponses]@@ -1624,7 +1619,7 @@ export type PutAgentByAgentIdErrors = {}export type PutAgentByAgentIdResponses = {- 200: AppDetailWithSite+ 200: AgentAppDetailWithSite}export type PutAgentByAgentIdResponse = PutAgentByAgentIdResponses[keyof PutAgentByAgentIdResponses]@@ -1770,7 +1765,7 @@ export type PostAgentByAgentIdCopyErrors = {}export type PostAgentByAgentIdCopyResponses = {- 201: AppDetailWithSite+ 201: AgentAppDetailWithSite}export type PostAgentByAgentIdCopyResponse@@ -2065,28 +2060,10 @@ export type PostAgentByAgentIdSandboxFilesUploadResponses = {export type PostAgentByAgentIdSandboxFilesUploadResponse= PostAgentByAgentIdSandboxFilesUploadResponses[keyof PostAgentByAgentIdSandboxFilesUploadResponses]-export type PostAgentByAgentIdSkillsStandardizeData = {- body?: never- path: {- agent_id: string- }- query?: never- url: '/agent/{agent_id}/skills/standardize'-}--export type PostAgentByAgentIdSkillsStandardizeErrors = {- 400: unknown-}--export type PostAgentByAgentIdSkillsStandardizeResponses = {- 201: AgentSkillStandardizeResponse-}--export type PostAgentByAgentIdSkillsStandardizeResponse- = PostAgentByAgentIdSkillsStandardizeResponses[keyof PostAgentByAgentIdSkillsStandardizeResponses]-export type PostAgentByAgentIdSkillsUploadData = {- body?: never+ body: {+ file: Blob | File+ }path: {agent_id: string}diff --git a/packages/contracts/generated/api/console/agent/zod.gen.ts b/packages/contracts/generated/api/console/agent/zod.gen.tsindex 6811b8a80bb..fad0a3f0048 100644--- a/packages/contracts/generated/api/console/agent/zod.gen.ts+++ b/packages/contracts/generated/api/console/agent/zod.gen.ts@@ -549,14 +549,6 @@ export const zAgentSkillRefConfig = z.object({skill_md_key: z.string().max(512).nullish(),})-/**- * AgentSkillStandardizeResponse- */-export const zAgentSkillStandardizeResponse = z.object({- manifest: zSkillManifest,- skill: zAgentSkillRefConfig,-})-/*** AgentSkillUploadResponse*/@@ -667,9 +659,9 @@ export const zModelConfig = z.object({})/**- * AppDetailWithSite+ * AgentAppDetailWithSite*/-export const zAppDetailWithSite = z.object({+export const zAgentAppDetailWithSite = z.object({access_mode: z.string().nullish(),active_config_is_published: z.boolean().optional().default(false),api_base_url: z.string().nullish(),@@ -2063,9 +2055,9 @@ export const zSiteWritable = z.object({})/**- * AppDetailWithSite+ * AgentAppDetailWithSite*/-export const zAppDetailWithSiteWritable = z.object({+export const zAgentAppDetailWithSiteWritable = z.object({access_mode: z.string().nullish(),active_config_is_published: z.boolean().optional().default(false),api_base_url: z.string().nullish(),@@ -2131,7 +2123,7 @@ export const zPostAgentBody = zAgentAppCreatePayload/*** Agent app created successfully*/-export const zPostAgentResponse = zAppDetailWithSite+export const zPostAgentResponse = zAgentAppDetailWithSiteexport const zGetAgentInviteOptionsQuery = z.object({app_id: z.string().optional(),@@ -2161,7 +2153,7 @@ export const zGetAgentByAgentIdPath = z.object({/*** Agent app detail*/-export const zGetAgentByAgentIdResponse = zAppDetailWithSite+export const zGetAgentByAgentIdResponse = zAgentAppDetailWithSiteexport const zPutAgentByAgentIdBody = zAgentAppUpdatePayload@@ -2172,7 +2164,7 @@ export const zPutAgentByAgentIdPath = z.object({/*** Agent app updated successfully*/-export const zPutAgentByAgentIdResponse = zAppDetailWithSite+export const zPutAgentByAgentIdResponse = zAgentAppDetailWithSiteexport const zGetAgentByAgentIdChatMessagesPath = z.object({agent_id: z.uuid(),@@ -2259,7 +2251,7 @@ export const zPostAgentByAgentIdCopyPath = z.object({/*** Agent app copied successfully*/-export const zPostAgentByAgentIdCopyResponse = zAppDetailWithSite+export const zPostAgentByAgentIdCopyResponse = zAgentAppDetailWithSiteexport const zGetAgentByAgentIdDriveFilesPath = z.object({agent_id: z.uuid(),@@ -2452,21 +2444,16 @@ export const zPostAgentByAgentIdSandboxFilesUploadPath = z.object({*/export const zPostAgentByAgentIdSandboxFilesUploadResponse = zSandboxUploadResponse-export const zPostAgentByAgentIdSkillsStandardizePath = z.object({- agent_id: z.uuid(),+export const zPostAgentByAgentIdSkillsUploadBody = z.object({+ file: z.custom<Blob | File>(),})-/**- * Skill standardized into drive- */-export const zPostAgentByAgentIdSkillsStandardizeResponse = zAgentSkillStandardizeResponse-export const zPostAgentByAgentIdSkillsUploadPath = z.object({agent_id: z.uuid(),})/**- * Skill validated+ * Skill uploaded into drive*/export const zPostAgentByAgentIdSkillsUploadResponse = zAgentSkillUploadResponsediff --git a/packages/contracts/generated/api/console/apps/orpc.gen.ts b/packages/contracts/generated/api/console/apps/orpc.gen.tsindex 3952812a5a8..eab3c17eb43 100644--- a/packages/contracts/generated/api/console/apps/orpc.gen.ts+++ b/packages/contracts/generated/api/console/apps/orpc.gen.ts@@ -271,10 +271,9 @@ import {zPostAppsByAppIdAgentSkillsBySlugInferToolsPath,zPostAppsByAppIdAgentSkillsBySlugInferToolsQuery,zPostAppsByAppIdAgentSkillsBySlugInferToolsResponse,- zPostAppsByAppIdAgentSkillsStandardizePath,- zPostAppsByAppIdAgentSkillsStandardizeQuery,- zPostAppsByAppIdAgentSkillsStandardizeResponse,+ zPostAppsByAppIdAgentSkillsUploadBody,zPostAppsByAppIdAgentSkillsUploadPath,+ zPostAppsByAppIdAgentSkillsUploadQuery,zPostAppsByAppIdAgentSkillsUploadResponse,zPostAppsByAppIdAnnotationReplyByActionBody,zPostAppsByAppIdAnnotationReplyByActionPath,@@ -939,57 +938,32 @@ export const logs = {}/**- * Upload a Skill, validate it, and standardize it into the app agent's drive+ * Upload a Skill, validate it, and commit drive-backed skill files*- * Validate + standardize a Skill into the agent drive (ENG-594)+ * Upload + standardize a Skill into the agent drive*/export const post10 = oc.route({- description: 'Validate + standardize a Skill into the agent drive (ENG-594)',+ description: 'Upload + standardize a Skill into the agent drive',inputStructure: 'detailed',method: 'POST',- operationId: 'postAppsByAppIdAgentSkillsStandardize',- path: '/apps/{app_id}/agent/skills/standardize',+ operationId: 'postAppsByAppIdAgentSkillsUpload',+ path: '/apps/{app_id}/agent/skills/upload',successStatus: 201,- summary: 'Upload a Skill, validate it, and standardize it into the app agent\'s drive',+ summary: 'Upload a Skill, validate it, and commit drive-backed skill files',tags: ['console'],}).input(z.object({- params: zPostAppsByAppIdAgentSkillsStandardizePath,- query: zPostAppsByAppIdAgentSkillsStandardizeQuery.optional(),+ body: zPostAppsByAppIdAgentSkillsUploadBody,+ params: zPostAppsByAppIdAgentSkillsUploadPath,+ query: zPostAppsByAppIdAgentSkillsUploadQuery.optional(),}),)- .output(zPostAppsByAppIdAgentSkillsStandardizeResponse)--export const standardize = {- post: post10,-}--/**- * Validate an uploaded Skill package and persist the archive- *- * Upload + validate a Skill package (.zip/.skill) and extract its manifest- * Returns a validated skill ref (to bind into the Agent soul config on save)- * plus its manifest. Standardizing into the agent drive is ENG-594.- */-export const post11 = oc- .route({- description:- 'Upload + validate a Skill package (.zip/.skill) and extract its manifest\nReturns a validated skill ref (to bind into the Agent soul config on save)\nplus its manifest. Standardizing into the agent drive is ENG-594.',- inputStructure: 'detailed',- method: 'POST',- operationId: 'postAppsByAppIdAgentSkillsUpload',- path: '/apps/{app_id}/agent/skills/upload',- successStatus: 201,- summary: 'Validate an uploaded Skill package and persist the archive',- tags: ['console'],- })- .input(z.object({ params: zPostAppsByAppIdAgentSkillsUploadPath })).output(zPostAppsByAppIdAgentSkillsUploadResponse)export const upload = {- post: post11,+ post: post10,}/**@@ -998,7 +972,7 @@ export const upload = {* Infer CLI tool + ENV suggestions from a standardized skill's SKILL.md (draft only, ENG-371)* Saving still goes through composer validation.*/-export const post12 = oc+export const post11 = oc.route({description:'Infer CLI tool + ENV suggestions from a standardized skill\'s SKILL.md (draft only, ENG-371)\nSaving still goes through composer validation.',@@ -1018,7 +992,7 @@ export const post12 = oc.output(zPostAppsByAppIdAgentSkillsBySlugInferToolsResponse)export const inferTools = {- post: post12,+ post: post11,}/**@@ -1048,7 +1022,6 @@ export const bySlug = {}export const skills = {- standardize,upload,bySlug,}@@ -1086,7 +1059,7 @@ export const status = {/*** Enable or disable annotation reply for an app*/-export const post13 = oc+export const post12 = oc.route({description: 'Enable or disable annotation reply for an app',inputStructure: 'detailed',@@ -1104,7 +1077,7 @@ export const post13 = oc.output(zPostAppsByAppIdAnnotationReplyByActionResponse)export const byAction = {- post: post13,+ post: post12,status,}@@ -1134,7 +1107,7 @@ export const annotationSetting = {/*** Update annotation settings for an app*/-export const post14 = oc+export const post13 = oc.route({description: 'Update annotation settings for an app',inputStructure: 'detailed',@@ -1152,7 +1125,7 @@ export const post14 = oc.output(zPostAppsByAppIdAnnotationSettingsByAnnotationSettingIdResponse)export const byAnnotationSettingId = {- post: post14,+ post: post13,}export const annotationSettings = {@@ -1162,7 +1135,7 @@ export const annotationSettings = {/*** Batch import annotations from CSV file with rate limiting and security checks*/-export const post15 = oc+export const post14 = oc.route({description: 'Batch import annotations from CSV file with rate limiting and security checks',inputStructure: 'detailed',@@ -1175,7 +1148,7 @@ export const post15 = oc.output(zPostAppsByAppIdAnnotationsBatchImportResponse)export const batchImport = {- post: post15,+ post: post14,}/**@@ -1278,7 +1251,7 @@ export const delete3 = oc/*** Update or delete an annotation*/-export const post16 = oc+export const post15 = oc.route({description: 'Update or delete an annotation',inputStructure: 'detailed',@@ -1297,7 +1270,7 @@ export const post16 = ocexport const byAnnotationId = {delete: delete3,- post: post16,+ post: post15,hitHistories,}@@ -1336,7 +1309,7 @@ export const get15 = oc/*** Create a new annotation for an app*/-export const post17 = oc+export const post16 = oc.route({description: 'Create a new annotation for an app',inputStructure: 'detailed',@@ -1354,7 +1327,7 @@ export const post17 = ocexport const annotations = {delete: delete4,get: get15,- post: post17,+ post: post16,batchImport,batchImportStatus,count: count2,@@ -1365,7 +1338,7 @@ export const annotations = {/*** Enable or disable app API*/-export const post18 = oc+export const post17 = oc.route({description: 'Enable or disable app API',inputStructure: 'detailed',@@ -1378,13 +1351,13 @@ export const post18 = oc.output(zPostAppsByAppIdApiEnableResponse)export const apiEnable = {- post: post18,+ post: post17,}/*** Transcript audio to text for chat messages*/-export const post19 = oc+export const post18 = oc.route({description: 'Transcript audio to text for chat messages',inputStructure: 'detailed',@@ -1397,7 +1370,7 @@ export const post19 = oc.output(zPostAppsByAppIdAudioToTextResponse)export const audioToText = {- post: post19,+ post: post18,}/**@@ -1487,7 +1460,7 @@ export const byMessageId = {/*** Stop a running chat message generation*/-export const post20 = oc+export const post19 = oc.route({description: 'Stop a running chat message generation',inputStructure: 'detailed',@@ -1500,7 +1473,7 @@ export const post20 = oc.output(zPostAppsByAppIdChatMessagesByTaskIdStopResponse)export const stop = {- post: post20,+ post: post19,}export const byTaskId = {@@ -1594,7 +1567,7 @@ export const completionConversations = {/*** Stop a running completion message generation*/-export const post21 = oc+export const post20 = oc.route({description: 'Stop a running completion message generation',inputStructure: 'detailed',@@ -1607,7 +1580,7 @@ export const post21 = oc.output(zPostAppsByAppIdCompletionMessagesByTaskIdStopResponse)export const stop2 = {- post: post21,+ post: post20,}export const byTaskId2 = {@@ -1617,7 +1590,7 @@ export const byTaskId2 = {/*** Generate completion message for debugging*/-export const post22 = oc+export const post21 = oc.route({description: 'Generate completion message for debugging',inputStructure: 'detailed',@@ -1635,7 +1608,7 @@ export const post22 = oc.output(zPostAppsByAppIdCompletionMessagesResponse)export const completionMessages = {- post: post22,+ post: post21,byTaskId: byTaskId2,}@@ -1670,7 +1643,7 @@ export const conversationVariables = {* Convert expert mode of chatbot app to workflow mode* Convert Completion App to Workflow App*/-export const post23 = oc+export const post22 = oc.route({description:'Convert application to workflow mode\nConvert expert mode of chatbot app to workflow mode\nConvert Completion App to Workflow App',@@ -1690,7 +1663,7 @@ export const post23 = oc.output(zPostAppsByAppIdConvertToWorkflowResponse)export const convertToWorkflow = {- post: post23,+ post: post22,}/**@@ -1698,7 +1671,7 @@ export const convertToWorkflow = {** Create a copy of an existing application*/-export const post24 = oc+export const post23 = oc.route({description: 'Create a copy of an existing application',inputStructure: 'detailed',@@ -1713,7 +1686,7 @@ export const post24 = oc.output(zPostAppsByAppIdCopyResponse)export const copy = {- post: post24,+ post: post23,}/**@@ -1767,7 +1740,7 @@ export const export3 = {/*** Create or update message feedback (like/dislike)*/-export const post25 = oc+export const post24 = oc.route({description: 'Create or update message feedback (like/dislike)',inputStructure: 'detailed',@@ -1780,14 +1753,14 @@ export const post25 = oc.output(zPostAppsByAppIdFeedbacksResponse)export const feedbacks = {- post: post25,+ post: post24,export: export3,}/*** Update application icon*/-export const post26 = oc+export const post25 = oc.route({description: 'Update application icon',inputStructure: 'detailed',@@ -1800,7 +1773,7 @@ export const post26 = oc.output(zPostAppsByAppIdIconResponse)export const icon = {- post: post26,+ post: post25,}/**@@ -1831,7 +1804,7 @@ export const messages = {** Update application model configuration*/-export const post27 = oc+export const post26 = oc.route({description: 'Update application model configuration',inputStructure: 'detailed',@@ -1847,13 +1820,13 @@ export const post27 = oc.output(zPostAppsByAppIdModelConfigResponse)export const modelConfig = {- post: post27,+ post: post26,}/*** Check if app name is available*/-export const post28 = oc+export const post27 = oc.route({description: 'Check if app name is available',inputStructure: 'detailed',@@ -1866,13 +1839,13 @@ export const post28 = oc.output(zPostAppsByAppIdNameResponse)export const name = {- post: post28,+ post: post27,}/*** Publish app to Creators Platform*/-export const post29 = oc+export const post28 = oc.route({inputStructure: 'detailed',method: 'POST',@@ -1885,7 +1858,7 @@ export const post29 = oc.output(zPostAppsByAppIdPublishToCreatorsPlatformResponse)export const publishToCreatorsPlatform = {- post: post29,+ post: post28,}/**@@ -1906,7 +1879,7 @@ export const get26 = oc/*** Create MCP server configuration for an application*/-export const post30 = oc+export const post29 = oc.route({description: 'Create MCP server configuration for an application',inputStructure: 'detailed',@@ -1936,14 +1909,14 @@ export const put = ocexport const server = {get: get26,- post: post30,+ post: post29,put,}/*** Reset access token for application site*/-export const post31 = oc+export const post30 = oc.route({description: 'Reset access token for application site',inputStructure: 'detailed',@@ -1956,13 +1929,13 @@ export const post31 = oc.output(zPostAppsByAppIdSiteAccessTokenResetResponse)export const accessTokenReset = {- post: post31,+ post: post30,}/*** Update application site configuration*/-export const post32 = oc+export const post31 = oc.route({description: 'Update application site configuration',inputStructure: 'detailed',@@ -1975,14 +1948,14 @@ export const post32 = oc.output(zPostAppsByAppIdSiteResponse)export const site = {- post: post32,+ post: post31,accessTokenReset,}/*** Enable or disable app site*/-export const post33 = oc+export const post32 = oc.route({description: 'Enable or disable app site',inputStructure: 'detailed',@@ -1995,7 +1968,7 @@ export const post33 = oc.output(zPostAppsByAppIdSiteEnableResponse)export const siteEnable = {- post: post33,+ post: post32,}/**@@ -2016,7 +1989,7 @@ export const delete7 = oc/*** Star an application for the current account*/-export const post34 = oc+export const post33 = oc.route({description: 'Star an application for the current account',inputStructure: 'detailed',@@ -2030,7 +2003,7 @@ export const post34 = ocexport const star = {delete: delete7,- post: post34,+ post: post33,}/**@@ -2263,7 +2236,7 @@ export const voices = {/*** Convert text to speech for chat messages*/-export const post35 = oc+export const post34 = oc.route({description: 'Convert text to speech for chat messages',inputStructure: 'detailed',@@ -2278,7 +2251,7 @@ export const post35 = oc.output(zPostAppsByAppIdTextToAudioResponse)export const textToAudio = {- post: post35,+ post: post34,voices,}@@ -2303,7 +2276,7 @@ export const get36 = oc/*** Update app tracing configuration*/-export const post36 = oc+export const post35 = oc.route({description: 'Update app tracing configuration',inputStructure: 'detailed',@@ -2317,7 +2290,7 @@ export const post36 = ocexport const trace = {get: get36,- post: post36,+ post: post35,}/**@@ -2386,7 +2359,7 @@ export const patch = oc** Create a new tracing configuration for an application*/-export const post37 = oc+export const post36 = oc.route({description: 'Create a new tracing configuration for an application',inputStructure: 'detailed',@@ -2406,13 +2379,13 @@ export const traceConfig = {delete: delete8,get: get37,patch,- post: post37,+ post: post36,}/*** Update app trigger (enable/disable)*/-export const post38 = oc+export const post37 = oc.route({inputStructure: 'detailed',method: 'POST',@@ -2430,7 +2403,7 @@ export const post38 = oc.output(zPostAppsByAppIdTriggerEnableResponse)export const triggerEnable = {- post: post38,+ post: post37,}/**@@ -2538,7 +2511,7 @@ export const count3 = {** Stop running workflow task*/-export const post39 = oc+export const post38 = oc.route({description: 'Stop running workflow task',inputStructure: 'detailed',@@ -2552,7 +2525,7 @@ export const post39 = oc.output(zPostAppsByAppIdWorkflowRunsTasksByTaskIdStopResponse)export const stop3 = {- post: post39,+ post: post38,}export const byTaskId3 = {@@ -2655,7 +2628,7 @@ export const read = {/*** Upload one workflow Agent sandbox file as a Dify ToolFile mapping*/-export const post40 = oc+export const post39 = oc.route({description: 'Upload one workflow Agent sandbox file as a Dify ToolFile mapping',inputStructure: 'detailed',@@ -2673,7 +2646,7 @@ export const post40 = oc.output(zPostAppsByAppIdWorkflowRunsByWorkflowRunIdAgentNodesByNodeIdSandboxFilesUploadResponse)export const upload2 = {- post: post40,+ post: post39,}/**@@ -2824,7 +2797,7 @@ export const byReplyId = {** Add a reply to a workflow comment*/-export const post41 = oc+export const post40 = oc.route({description: 'Add a reply to a workflow comment',inputStructure: 'detailed',@@ -2844,7 +2817,7 @@ export const post41 = oc.output(zPostAppsByAppIdWorkflowCommentsByCommentIdRepliesResponse)export const replies = {- post: post41,+ post: post40,byReplyId,}@@ -2853,7 +2826,7 @@ export const replies = {** Resolve a workflow comment*/-export const post42 = oc+export const post41 = oc.route({description: 'Resolve a workflow comment',inputStructure: 'detailed',@@ -2867,7 +2840,7 @@ export const post42 = oc.output(zPostAppsByAppIdWorkflowCommentsByCommentIdResolveResponse)export const resolve = {- post: post42,+ post: post41,}/**@@ -2961,7 +2934,7 @@ export const get50 = oc** Create a new workflow comment*/-export const post43 = oc+export const post42 = oc.route({description: 'Create a new workflow comment',inputStructure: 'detailed',@@ -2982,7 +2955,7 @@ export const post43 = ocexport const comments = {get: get50,- post: post43,+ post: post42,mentionUsers,byCommentId,}@@ -3163,7 +3136,7 @@ export const get57 = oc/*** Update conversation variables for workflow draft*/-export const post44 = oc+export const post43 = oc.route({description: 'Update conversation variables for workflow draft',inputStructure: 'detailed',@@ -3182,7 +3155,7 @@ export const post44 = ocexport const conversationVariables2 = {get: get57,- post: post44,+ post: post43,}/**@@ -3206,7 +3179,7 @@ export const get58 = oc/*** Update environment variables for workflow draft*/-export const post45 = oc+export const post44 = oc.route({description: 'Update environment variables for workflow draft',inputStructure: 'detailed',@@ -3225,13 +3198,13 @@ export const post45 = ocexport const environmentVariables = {get: get58,- post: post45,+ post: post44,}/*** Update draft workflow features*/-export const post46 = oc+export const post45 = oc.route({description: 'Update draft workflow features',inputStructure: 'detailed',@@ -3249,7 +3222,7 @@ export const post46 = oc.output(zPostAppsByAppIdWorkflowsDraftFeaturesResponse)export const features = {- post: post46,+ post: post45,}/**@@ -3257,7 +3230,7 @@ export const features = {** Test human input delivery for workflow*/-export const post47 = oc+export const post46 = oc.route({description: 'Test human input delivery for workflow',inputStructure: 'detailed',@@ -3276,7 +3249,7 @@ export const post47 = oc.output(zPostAppsByAppIdWorkflowsDraftHumanInputNodesByNodeIdDeliveryTestResponse)export const deliveryTest = {- post: post47,+ post: post46,}/**@@ -3284,7 +3257,7 @@ export const deliveryTest = {** Get human input form preview for workflow*/-export const post48 = oc+export const post47 = oc.route({description: 'Get human input form preview for workflow',inputStructure: 'detailed',@@ -3303,7 +3276,7 @@ export const post48 = oc.output(zPostAppsByAppIdWorkflowsDraftHumanInputNodesByNodeIdFormPreviewResponse)export const preview3 = {- post: post48,+ post: post47,}/**@@ -3311,7 +3284,7 @@ export const preview3 = {** Submit human input form preview for workflow*/-export const post49 = oc+export const post48 = oc.route({description: 'Submit human input form preview for workflow',inputStructure: 'detailed',@@ -3330,7 +3303,7 @@ export const post49 = oc.output(zPostAppsByAppIdWorkflowsDraftHumanInputNodesByNodeIdFormRunResponse)export const run5 = {- post: post49,+ post: post48,}export const form2 = {@@ -3356,7 +3329,7 @@ export const humanInput2 = {** Run draft workflow iteration node*/-export const post50 = oc+export const post49 = oc.route({description: 'Run draft workflow iteration node',inputStructure: 'detailed',@@ -3375,7 +3348,7 @@ export const post50 = oc.output(zPostAppsByAppIdWorkflowsDraftIterationNodesByNodeIdRunResponse)export const run6 = {- post: post50,+ post: post49,}export const byNodeId6 = {@@ -3395,7 +3368,7 @@ export const iteration2 = {** Run draft workflow loop node*/-export const post51 = oc+export const post50 = oc.route({description: 'Run draft workflow loop node',inputStructure: 'detailed',@@ -3414,7 +3387,7 @@ export const post51 = oc.output(zPostAppsByAppIdWorkflowsDraftLoopNodesByNodeIdRunResponse)export const run7 = {- post: post51,+ post: post50,}export const byNodeId7 = {@@ -3446,7 +3419,7 @@ export const candidates = {get: get59,}-export const post52 = oc+export const post51 = oc.route({inputStructure: 'detailed',method: 'POST',@@ -3463,10 +3436,10 @@ export const post52 = oc.output(zPostAppsByAppIdWorkflowsDraftNodesByNodeIdAgentComposerImpactResponse)export const impact = {- post: post52,+ post: post51,}-export const post53 = oc+export const post52 = oc.route({inputStructure: 'detailed',method: 'POST',@@ -3483,10 +3456,10 @@ export const post53 = oc.output(zPostAppsByAppIdWorkflowsDraftNodesByNodeIdAgentComposerSaveToRosterResponse)export const saveToRoster = {- post: post53,+ post: post52,}-export const post54 = oc+export const post53 = oc.route({inputStructure: 'detailed',method: 'POST',@@ -3503,7 +3476,7 @@ export const post54 = oc.output(zPostAppsByAppIdWorkflowsDraftNodesByNodeIdAgentComposerValidateResponse)export const validate = {- post: post54,+ post: post53,}export const get60 = oc@@ -3566,7 +3539,7 @@ export const lastRun = {** Run draft workflow node*/-export const post55 = oc+export const post54 = oc.route({description: 'Run draft workflow node',inputStructure: 'detailed',@@ -3585,7 +3558,7 @@ export const post55 = oc.output(zPostAppsByAppIdWorkflowsDraftNodesByNodeIdRunResponse)export const run8 = {- post: post55,+ post: post54,}/**@@ -3593,7 +3566,7 @@ export const run8 = {** Poll for trigger events and execute single node when event arrives*/-export const post56 = oc+export const post55 = oc.route({description: 'Poll for trigger events and execute single node when event arrives',inputStructure: 'detailed',@@ -3607,7 +3580,7 @@ export const post56 = oc.output(zPostAppsByAppIdWorkflowsDraftNodesByNodeIdTriggerRunResponse)export const run9 = {- post: post56,+ post: post55,}export const trigger = {@@ -3667,7 +3640,7 @@ export const nodes7 = {** Run draft workflow*/-export const post57 = oc+export const post56 = oc.route({description: 'Run draft workflow',inputStructure: 'detailed',@@ -3686,7 +3659,7 @@ export const post57 = oc.output(zPostAppsByAppIdWorkflowsDraftRunResponse)export const run10 = {- post: post57,+ post: post56,}/**@@ -3808,7 +3781,7 @@ export const systemVariables = {** Poll for trigger events and execute full workflow when event arrives*/-export const post58 = oc+export const post57 = oc.route({description: 'Poll for trigger events and execute full workflow when event arrives',inputStructure: 'detailed',@@ -3827,7 +3800,7 @@ export const post58 = oc.output(zPostAppsByAppIdWorkflowsDraftTriggerRunResponse)export const run11 = {- post: post58,+ post: post57,}/**@@ -3835,7 +3808,7 @@ export const run11 = {** Full workflow debug when the start node is a trigger*/-export const post59 = oc+export const post58 = oc.route({description: 'Full workflow debug when the start node is a trigger',inputStructure: 'detailed',@@ -3854,7 +3827,7 @@ export const post59 = oc.output(zPostAppsByAppIdWorkflowsDraftTriggerRunAllResponse)export const runAll = {- post: post59,+ post: post58,}export const trigger2 = {@@ -4007,7 +3980,7 @@ export const get70 = oc** Sync draft workflow configuration*/-export const post60 = oc+export const post59 = oc.route({description: 'Sync draft workflow configuration',inputStructure: 'detailed',@@ -4027,7 +4000,7 @@ export const post60 = ocexport const draft2 = {get: get70,- post: post60,+ post: post59,conversationVariables: conversationVariables2,environmentVariables,features,@@ -4063,7 +4036,7 @@ export const get71 = oc/*** Publish workflow*/-export const post61 = oc+export const post60 = oc.route({inputStructure: 'detailed',method: 'POST',@@ -4082,7 +4055,7 @@ export const post61 = ocexport const publish = {get: get71,- post: post61,+ post: post60,}/**@@ -4219,7 +4192,7 @@ export const triggers2 = {/*** Restore a published workflow version into the draft workflow*/-export const post62 = oc+export const post61 = oc.route({description: 'Restore a published workflow version into the draft workflow',inputStructure: 'detailed',@@ -4232,7 +4205,7 @@ export const post62 = oc.output(zPostAppsByAppIdWorkflowsByWorkflowIdRestoreResponse)export const restore = {- post: post62,+ post: post61,}/**@@ -4457,7 +4430,7 @@ export const get79 = oc** Create a new API key for an app*/-export const post63 = oc+export const post62 = oc.route({description: 'Create a new API key for an app',inputStructure: 'detailed',@@ -4473,7 +4446,7 @@ export const post63 = ocexport const apiKeys = {get: get79,- post: post63,+ post: post62,byApiKeyId,}@@ -4531,7 +4504,7 @@ export const get81 = oc** Create a new application*/-export const post64 = oc+export const post63 = oc.route({description: 'Create a new application',inputStructure: 'detailed',@@ -4547,7 +4520,7 @@ export const post64 = ocexport const apps = {get: get81,- post: post64,+ post: post63,imports,starred,workflows,diff --git a/packages/contracts/generated/api/console/apps/types.gen.ts b/packages/contracts/generated/api/console/apps/types.gen.tsindex 8ccf899b451..debd7ff1991 100644--- a/packages/contracts/generated/api/console/apps/types.gen.ts+++ b/packages/contracts/generated/api/console/apps/types.gen.ts@@ -5,10 +5,10 @@ export type ClientOptions = {}export type AppPagination = {- has_next: boolean- items: Array<AppPartial>+ data: Array<AppPartial>+ has_more: boolean+ limit: numberpage: number- per_page: numbertotal: number}@@ -23,7 +23,6 @@ export type CreateAppPayload = {export type AppDetailWithSite = {access_mode?: string | null- active_config_is_published?: booleanapi_base_url?: string | nullapp_id?: string | nullbound_agent_id?: string | null@@ -42,7 +41,6 @@ export type AppDetailWithSite = {mode: stringmodel_config?: ModelConfig | nullname: string- role?: string | nullsite?: Site | nulltags?: Array<Tag>tracing?: JsonValue | null@@ -213,11 +211,6 @@ export type AgentLogResponse = {meta: AgentLogMetaResponse}-export type AgentSkillStandardizeResponse = {- manifest: SkillManifest- skill: AgentSkillRefConfig-}-export type AgentSkillUploadResponse = {manifest: SkillManifestskill: AgentSkillRefConfig@@ -1156,25 +1149,24 @@ export type ApiKeyItem = {export type AppPartial = {access_mode?: string | null- active_config_is_published?: booleanapp_id?: string | null- app_model_config?: ModelConfigPartial | nullauthor_name?: string | nullbound_agent_id?: string | nullcreate_user_name?: string | nullcreated_at?: number | nullcreated_by?: string | null- desc_or_prompt?: string | null+ description?: string | nullhas_draft_trigger?: boolean | nullicon?: string | nullicon_background?: string | nullicon_type?: string | null+ readonly icon_url: string | nullid: stringis_starred?: booleanmax_active_requests?: number | null- mode_compatible_with_agent: string+ mode: string+ model_config?: ModelConfigPartial | nullname: string- role?: string | nulltags?: Array<Tag>updated_at?: number | nullupdated_by?: string | null@@ -2575,9 +2567,16 @@ export type AgentModerationIoConfig = {export type ValueSourceType = 'constant' | 'variable'+export type AppPaginationWritable = {+ data: Array<AppPartialWritable>+ has_more: boolean+ limit: number+ page: number+ total: number+}+export type AppDetailWithSiteWritable = {access_mode?: string | null- active_config_is_published?: booleanapi_base_url?: string | nullapp_id?: string | nullbound_agent_id?: string | null@@ -2595,7 +2594,6 @@ export type AppDetailWithSiteWritable = {mode: stringmodel_config?: ModelConfig | nullname: string- role?: string | nullsite?: SiteWritable | nulltags?: Array<Tag>tracing?: JsonValue | null@@ -2628,6 +2626,32 @@ export type WorkflowCommentDetailWritable = {updated_at?: number | null}+export type AppPartialWritable = {+ access_mode?: string | null+ app_id?: string | null+ author_name?: string | null+ bound_agent_id?: string | null+ create_user_name?: string | null+ created_at?: number | null+ created_by?: string | null+ description?: string | null+ has_draft_trigger?: boolean | null+ icon?: string | null+ icon_background?: string | null+ icon_type?: string | null+ id: string+ is_starred?: boolean+ max_active_requests?: number | null+ mode: string+ model_config?: ModelConfigPartial | null+ name: string+ tags?: Array<Tag>+ updated_at?: number | null+ updated_by?: string | null+ use_icon_as_answer_icon?: boolean | null+ workflow?: WorkflowPartial | null+}+export type SiteWritable = {chat_color_theme?: string | nullchat_color_theme_inverted: boolean@@ -3144,34 +3168,16 @@ export type GetAppsByAppIdAgentLogsResponses = {export type GetAppsByAppIdAgentLogsResponse= GetAppsByAppIdAgentLogsResponses[keyof GetAppsByAppIdAgentLogsResponses]-export type PostAppsByAppIdAgentSkillsStandardizeData = {- body?: never+export type PostAppsByAppIdAgentSkillsUploadData = {+ body: {+ file: Blob | File+ }path: {app_id: string}query?: {node_id?: string}- url: '/apps/{app_id}/agent/skills/standardize'-}--export type PostAppsByAppIdAgentSkillsStandardizeErrors = {- 400: unknown-}--export type PostAppsByAppIdAgentSkillsStandardizeResponses = {- 201: AgentSkillStandardizeResponse-}--export type PostAppsByAppIdAgentSkillsStandardizeResponse- = PostAppsByAppIdAgentSkillsStandardizeResponses[keyof PostAppsByAppIdAgentSkillsStandardizeResponses]--export type PostAppsByAppIdAgentSkillsUploadData = {- body?: never- path: {- app_id: string- }- query?: neverurl: '/apps/{app_id}/agent/skills/upload'}diff --git a/packages/contracts/generated/api/console/apps/zod.gen.ts b/packages/contracts/generated/api/console/apps/zod.gen.tsindex df275e5fb9c..83a0b79c624 100644--- a/packages/contracts/generated/api/console/apps/zod.gen.ts+++ b/packages/contracts/generated/api/console/apps/zod.gen.ts@@ -990,14 +990,6 @@ export const zAgentSkillRefConfig = z.object({skill_md_key: z.string().max(512).nullish(),})-/**- * AgentSkillStandardizeResponse- */-export const zAgentSkillStandardizeResponse = z.object({- manifest: zSkillManifest,- skill: zAgentSkillRefConfig,-})-/*** AgentSkillUploadResponse*/@@ -1946,25 +1938,24 @@ export const zModelConfigPartial = z.object({*/export const zAppPartial = z.object({access_mode: z.string().nullish(),- active_config_is_published: z.boolean().optional().default(false),app_id: z.string().nullish(),- app_model_config: zModelConfigPartial.nullish(),author_name: z.string().nullish(),bound_agent_id: z.string().nullish(),create_user_name: z.string().nullish(),created_at: z.int().nullish(),created_by: z.string().nullish(),- desc_or_prompt: z.string().nullish(),+ description: z.string().nullish(),has_draft_trigger: z.boolean().nullish(),icon: z.string().nullish(),icon_background: z.string().nullish(),icon_type: z.string().nullish(),+ icon_url: z.string().nullable(),id: z.string(),is_starred: z.boolean().optional().default(false),max_active_requests: z.int().nullish(),- mode_compatible_with_agent: z.string(),+ mode: z.string(),+ model_config: zModelConfigPartial.nullish(),name: z.string(),- role: z.string().nullish(),tags: z.array(zTag).optional(),updated_at: z.int().nullish(),updated_by: z.string().nullish(),@@ -1976,10 +1967,10 @@ export const zAppPartial = z.object({* AppPagination*/export const zAppPagination = z.object({- has_next: z.boolean(),- items: z.array(zAppPartial),+ data: z.array(zAppPartial),+ has_more: z.boolean(),+ limit: z.int(),page: z.int(),- per_page: z.int(),total: z.int(),})@@ -2005,7 +1996,6 @@ export const zModelConfig = z.object({*/export const zAppDetailWithSite = z.object({access_mode: z.string().nullish(),- active_config_is_published: z.boolean().optional().default(false),api_base_url: z.string().nullish(),app_id: z.string().nullish(),bound_agent_id: z.string().nullish(),@@ -2024,7 +2014,6 @@ export const zAppDetailWithSite = z.object({mode: z.string(),model_config: zModelConfig.nullish(),name: z.string(),- role: z.string().nullish(),site: zSite.nullish(),tags: z.array(zTag).optional(),tracing: zJsonValue.nullish(),@@ -3472,6 +3461,46 @@ export const zMessageInfiniteScrollPaginationResponse = z.object({*/export const zGeneratedAppResponseWritable = zJsonValue+/**+ * AppPartial+ */+export const zAppPartialWritable = z.object({+ access_mode: z.string().nullish(),+ app_id: z.string().nullish(),+ author_name: z.string().nullish(),+ bound_agent_id: z.string().nullish(),+ create_user_name: z.string().nullish(),+ created_at: z.int().nullish(),+ created_by: z.string().nullish(),+ description: z.string().nullish(),+ has_draft_trigger: z.boolean().nullish(),+ icon: z.string().nullish(),+ icon_background: z.string().nullish(),+ icon_type: z.string().nullish(),+ id: z.string(),+ is_starred: z.boolean().optional().default(false),+ max_active_requests: z.int().nullish(),+ mode: z.string(),+ model_config: zModelConfigPartial.nullish(),+ name: z.string(),+ tags: z.array(zTag).optional(),+ updated_at: z.int().nullish(),+ updated_by: z.string().nullish(),+ use_icon_as_answer_icon: z.boolean().nullish(),+ workflow: zWorkflowPartial.nullish(),+})++/**+ * AppPagination+ */+export const zAppPaginationWritable = z.object({+ data: z.array(zAppPartialWritable),+ has_more: z.boolean(),+ limit: z.int(),+ page: z.int(),+ total: z.int(),+})+/*** Site*/@@ -3496,7 +3525,6 @@ export const zSiteWritable = z.object({*/export const zAppDetailWithSiteWritable = z.object({access_mode: z.string().nullish(),- active_config_is_published: z.boolean().optional().default(false),api_base_url: z.string().nullish(),app_id: z.string().nullish(),bound_agent_id: z.string().nullish(),@@ -3514,7 +3542,6 @@ export const zAppDetailWithSiteWritable = z.object({mode: z.string(),model_config: zModelConfig.nullish(),name: z.string(),- role: z.string().nullish(),site: zSiteWritable.nullish(),tags: z.array(zTag).optional(),tracing: zJsonValue.nullish(),@@ -3917,25 +3944,20 @@ export const zGetAppsByAppIdAgentLogsQuery = z.object({*/export const zGetAppsByAppIdAgentLogsResponse = zAgentLogResponse-export const zPostAppsByAppIdAgentSkillsStandardizePath = z.object({- app_id: z.uuid(),+export const zPostAppsByAppIdAgentSkillsUploadBody = z.object({+ file: z.custom<Blob | File>(),})-export const zPostAppsByAppIdAgentSkillsStandardizeQuery = z.object({- node_id: z.string().optional(),-})--/**- * Skill standardized into drive- */-export const zPostAppsByAppIdAgentSkillsStandardizeResponse = zAgentSkillStandardizeResponse-export const zPostAppsByAppIdAgentSkillsUploadPath = z.object({app_id: z.uuid(),})+export const zPostAppsByAppIdAgentSkillsUploadQuery = z.object({+ node_id: z.string().optional(),+})+/**- * Skill validated+ * Skill uploaded into drive*/export const zPostAppsByAppIdAgentSkillsUploadResponse = zAgentSkillUploadResponsediff --git a/packages/iconify-collections/assets/public/agent/building-blocks.svg b/packages/iconify-collections/assets/public/agent/building-blocks.svgnew file mode 100644index 00000000000..8037f6f0865--- /dev/null+++ b/packages/iconify-collections/assets/public/agent/building-blocks.svg@@ -0,0 +1,3 @@+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">+<path fill-rule="evenodd" clip-rule="evenodd" d="M8.30314 1.54615C8.48087 1.50085 8.66708 1.49473 8.84742 1.52858C9.07685 1.57176 9.27914 1.6956 9.41968 1.77467L13.1768 3.88795C13.2961 3.955 13.4666 4.04398 13.6098 4.17701L13.6697 4.23691C13.7899 4.36839 13.8809 4.52463 13.9366 4.69394C14.0074 4.90941 13.9998 5.13856 13.9998 5.29485V9.55917C13.9998 9.70492 14.0069 9.91888 13.9444 10.1223C13.9076 10.2422 13.8527 10.3559 13.7823 10.4596L13.7068 10.5598C13.5702 10.7233 13.3869 10.8339 13.2647 10.9133L8.25171 14.1718C8.11671 14.2596 7.92272 14.396 7.69637 14.4537C7.51868 14.499 7.33292 14.5051 7.15275 14.4713C6.92315 14.4281 6.72034 14.3049 6.57984 14.2258L2.82268 12.1119C2.68658 12.0353 2.48283 11.9301 2.32984 11.7629C2.20953 11.6314 2.11852 11.475 2.06291 11.3059C1.99209 11.0903 1.99976 10.8606 1.99976 10.7044V6.44069C1.99976 6.29486 1.99262 6.08092 2.0551 5.87753L2.09807 5.7597C2.14656 5.64426 2.21216 5.53647 2.29273 5.44003L2.34611 5.38144C2.47424 5.24974 2.62775 5.15609 2.73479 5.08652L7.85979 1.75514C7.98194 1.67712 8.13342 1.58951 8.30314 1.54615ZM3.33309 10.7044C3.33309 10.7559 3.33334 10.7962 3.33374 10.8307C3.33392 10.8452 3.33411 10.8578 3.33439 10.8684C3.34356 10.8739 3.3543 10.8806 3.36695 10.8879C3.39682 10.9052 3.43208 10.9245 3.47697 10.9498L6.74064 12.7857V11.649L3.33309 9.73235V10.7044ZM8.07398 11.621V12.6972L12.5382 9.7955C12.5784 9.76933 12.6098 9.74883 12.6365 9.73105C12.6475 9.72368 12.6564 9.71639 12.6645 9.71087C12.6647 9.70125 12.6656 9.69004 12.6658 9.67701C12.6661 9.64494 12.6664 9.60721 12.6664 9.55917V8.636L8.07398 11.621ZM3.33309 8.2024L6.74064 10.1191V8.98235L3.33309 7.06568V8.2024ZM8.07398 8.95436V10.0299L12.6664 7.04485V5.96933L8.07398 8.95436ZM8.58374 2.87493L3.95288 5.8847L7.38192 7.81373L12.046 4.78183L8.76604 2.93613C8.71971 2.91007 8.68338 2.89008 8.6521 2.87298C8.63863 2.86561 8.62684 2.85931 8.61695 2.8541C8.60751 2.85987 8.59651 2.86685 8.58374 2.87493Z" fill="#155AEF"/>+</svg>diff --git a/packages/iconify-collections/assets/vender/agent-v2/access-point.svg b/packages/iconify-collections/assets/vender/agent-v2/access-point.svgnew file mode 100644index 00000000000..6f2c2f1926f--- /dev/null+++ b/packages/iconify-collections/assets/vender/agent-v2/access-point.svg@@ -0,0 +1,8 @@+<svg width="15" height="15" viewBox="0 0 15 15" fill="none" xmlns="http://www.w3.org/2000/svg">+ <path d="M7.5 11.25C7.91421 11.25 8.25 11.5858 8.25 12V14.25C8.25 14.6642 7.91421 15 7.5 15C7.08579 15 6.75 14.6642 6.75 14.25V12C6.75 11.5858 7.08579 11.25 7.5 11.25Z" fill="currentColor" />+ <path d="M2.19653 2.19653C2.48937 1.90372 2.96418 1.90382 3.25708 2.19653L8.03027 6.96973C8.09162 7.03108 8.13966 7.10082 8.17529 7.1748C8.19164 7.20869 8.20587 7.24378 8.21704 7.28027C8.24638 7.37633 8.25641 7.477 8.24634 7.57617C8.23743 7.66451 8.21216 7.74788 8.17529 7.82446C8.13963 7.89868 8.09176 7.96874 8.03027 8.03027L3.25708 12.8035C2.96419 13.096 2.48932 13.0962 2.19653 12.8035C1.90394 12.5107 1.90405 12.0358 2.19653 11.7429L5.68945 8.25H0.75C0.335786 8.25 0 7.91421 0 7.5C0 7.08579 0.335786 6.75 0.75 6.75H5.68945L2.19653 3.25708C1.90389 2.96423 1.90388 2.48937 2.19653 2.19653Z" fill="currentColor" />+ <path d="M10.1521 10.1521C10.445 9.85921 10.9198 9.85921 11.2126 10.1521L12.8035 11.7429C13.096 12.0358 13.0962 12.5107 12.8035 12.8035C12.5107 13.0962 12.0358 13.096 11.7429 12.8035L10.1521 11.2126C9.85921 10.9198 9.85922 10.445 10.1521 10.1521Z" fill="currentColor" />+ <path d="M14.25 6.75C14.6642 6.75 15 7.08579 15 7.5C15 7.91421 14.6642 8.25 14.25 8.25H12C11.5858 8.25 11.25 7.91421 11.25 7.5C11.25 7.08579 11.5858 6.75 12 6.75H14.25Z" fill="currentColor" />+ <path d="M11.7422 2.19653C12.035 1.90387 12.5098 1.90406 12.8027 2.19653C13.0956 2.4894 13.0955 2.96419 12.8027 3.25708L11.2119 4.8479C10.919 5.14079 10.4443 5.1408 10.1514 4.8479C9.85883 4.55497 9.85858 4.08013 10.1514 3.78735L11.7422 2.19653Z" fill="currentColor" />+ <path d="M7.5 0C7.91421 0 8.25 0.335786 8.25 0.75V3C8.25 3.41421 7.91421 3.75 7.5 3.75C7.08579 3.75 6.75 3.41421 6.75 3V0.75C6.75 0.335786 7.08579 0 7.5 0Z" fill="currentColor" />+</svg>diff --git a/packages/iconify-collections/assets/vender/agent-v2/end-user-auth.svg b/packages/iconify-collections/assets/vender/agent-v2/end-user-auth.svgnew file mode 100644index 00000000000..1632376e944--- /dev/null+++ b/packages/iconify-collections/assets/vender/agent-v2/end-user-auth.svg@@ -0,0 +1,5 @@+<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">+<path fill-rule="evenodd" clip-rule="evenodd" d="M12 7.33325C13.1046 7.33325 14 8.22865 14 9.33325C14 10.1403 13.5218 10.8356 12.8333 11.1516V11.9999L12.3333 12.4999L12.8333 12.9511V13.6666L12 14.3333L11.1667 13.6666V11.1516C10.4782 10.8356 10 10.1403 10 9.33325C10 8.22865 10.8954 7.33325 12 7.33325ZM12 8.66659C11.6318 8.66659 11.3333 8.96505 11.3333 9.33325C11.3333 9.70145 11.6318 9.99992 12 9.99992C12.3682 9.99992 12.6667 9.70145 12.6667 9.33325C12.6667 8.96505 12.3682 8.66659 12 8.66659Z" fill="currentColor"/>+<path d="M8 7.99992C8.2545 7.99992 8.50382 8.01506 8.7474 8.04484L8.58594 9.36841C8.39687 9.34527 8.20127 9.33325 8 9.33325C5.8465 9.33325 4.25915 10.7274 3.78646 12.6666H10V13.9999H2.26758L2.33594 13.2708C2.61081 10.3473 4.82817 7.99992 8 7.99992Z" fill="currentColor"/>+<path fill-rule="evenodd" clip-rule="evenodd" d="M8 1.33325C9.65687 1.33325 11 2.6764 11 4.33325C11 5.99011 9.65687 7.33325 8 7.33325C6.34315 7.33325 5 5.99011 5 4.33325C5 2.6764 6.34315 1.33325 8 1.33325ZM8 2.66659C7.07953 2.66659 6.33333 3.41278 6.33333 4.33325C6.33333 5.25373 7.07953 5.99992 8 5.99992C8.92047 5.99992 9.66667 5.25373 9.66667 4.33325C9.66667 3.41278 8.92047 2.66659 8 2.66659Z" fill="currentColor"/>+</svg>diff --git a/packages/iconify-collections/assets/vender/agent-v2/plan.svg b/packages/iconify-collections/assets/vender/agent-v2/plan.svgnew file mode 100644index 00000000000..a9456e4806b--- /dev/null+++ b/packages/iconify-collections/assets/vender/agent-v2/plan.svg@@ -0,0 +1,3 @@+<svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">+ <path fill-rule="evenodd" clip-rule="evenodd" d="M17 0C17.5523 0 18 0.447715 18 1V6C18 6.55228 17.5523 7 17 7H12C11.4477 7 11 6.55228 11 6V4.5H6.94629C5.92438 4.50039 5.56101 5.85276 6.44531 6.36523L12.5576 9.90332C15.2116 11.4402 14.1206 15.4996 11.0537 15.5H7V17C7 17.5523 6.55228 18 6 18H1C0.447715 18 0 17.5523 0 17V12C0 11.4477 0.447715 11 1 11H6C6.55228 11 7 11.4477 7 12V13.5H11.0537C12.0756 13.4996 12.4394 12.1472 11.5557 11.6348L5.44336 8.09668C2.789 6.55983 3.87917 2.50039 6.94629 2.5H11V1C11 0.447715 11.4477 0 12 0H17ZM2 16H5V13H2V16ZM13 5H16V2H13V5Z" fill="currentColor"/>+</svg>diff --git a/packages/iconify-collections/assets/vender/agent-v2/prompt-insert.svg b/packages/iconify-collections/assets/vender/agent-v2/prompt-insert.svgnew file mode 100644index 00000000000..f0be50ee5fe--- /dev/null+++ b/packages/iconify-collections/assets/vender/agent-v2/prompt-insert.svg@@ -0,0 +1,3 @@+<svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">+ <path d="M2.91669 1.16669C1.95019 1.16669 1.16669 1.95019 1.16669 2.91669V11.0834C1.16669 12.0499 1.95019 12.8334 2.91669 12.8334H11.0834C12.0499 12.8334 12.8334 12.0499 12.8334 11.0834V2.91669C12.8334 1.95019 12.0499 1.16669 11.0834 1.16669H2.91669ZM2.33335 2.91669C2.33335 2.59452 2.59452 2.33335 2.91669 2.33335H11.0834C11.4055 2.33335 11.6667 2.59452 11.6667 2.91669V11.0834C11.6667 11.4055 11.4055 11.6667 11.0834 11.6667H2.91669C2.59452 11.6667 2.33335 11.4055 2.33335 11.0834V2.91669ZM5.67188 10.5L9.67186 3.50002H8.32815L4.32817 10.5H5.67188Z" fill="#676F83" />+</svg>diff --git a/packages/iconify-collections/assets/vender/agent-v2/robot-3.svg b/packages/iconify-collections/assets/vender/agent-v2/robot-3.svgnew file mode 100644index 00000000000..0f8617ef3a0--- /dev/null+++ b/packages/iconify-collections/assets/vender/agent-v2/robot-3.svg@@ -0,0 +1,5 @@+<svg xmlns="http://www.w3.org/2000/svg" width="17" height="16" viewBox="0 0 17 16" fill="none">+ <path d="M6.25 6.875C6.82523 6.875 7.29167 7.34128 7.29167 7.91667V9.16667C7.29167 9.74205 6.82523 10.2083 6.25 10.2083C5.67477 10.2083 5.20833 9.74205 5.20833 9.16667V7.91667C5.20833 7.34128 5.67477 6.875 6.25 6.875Z" fill="#676F83"/>+ <path d="M10.4167 6.875C10.992 6.875 11.4583 7.34135 11.4583 7.91667V9.16667C11.4583 9.74199 10.992 10.2083 10.4167 10.2083C9.84135 10.2083 9.375 9.74199 9.375 9.16667V7.91667C9.375 7.34135 9.84135 6.875 10.4167 6.875Z" fill="#676F83"/>+ <path fill-rule="evenodd" clip-rule="evenodd" d="M8.33333 0C9.13875 0 9.79167 0.652918 9.79167 1.45833C9.79167 2.02329 9.46964 2.51173 8.99984 2.75391V3.33822C9.38912 3.34279 9.77995 3.35006 10.175 3.36263C11.6983 3.41112 12.7377 3.42425 13.6401 3.90951C14.375 4.30477 15.0255 4.97655 15.3971 5.72347C15.5468 6.02442 15.6427 6.33532 15.7056 6.66667H15.8333C16.2936 6.66667 16.6667 7.03976 16.6667 7.5V10C16.6667 10.4602 16.2936 10.8333 15.8333 10.8333H15.8285C15.8235 11.2254 15.813 11.5735 15.7869 11.8831C15.7386 12.4571 15.6361 12.9628 15.3971 13.4432C15.0254 14.1901 14.3749 14.8619 13.6401 15.2572C12.7377 15.7424 11.6982 15.7556 10.175 15.804C8.93336 15.8436 7.73328 15.8436 6.4917 15.804C4.96843 15.7556 3.92896 15.7424 3.02653 15.2572C2.29178 14.8619 1.64121 14.1902 1.26953 13.4432C1.03058 12.9628 0.928072 12.4571 0.87972 11.8831C0.853642 11.5735 0.843216 11.2254 0.838216 10.8333H0.833333C0.373096 10.8333 0 10.4602 0 10V7.5C0 7.03976 0.373096 6.66667 0.833333 6.66667H0.9611C1.02392 6.33532 1.11984 6.02442 1.26953 5.72347C1.64119 4.97649 2.29177 4.30475 3.02653 3.90951C3.92895 3.42425 4.96837 3.41112 6.4917 3.36263C6.88671 3.35006 7.27754 3.34279 7.66683 3.33822V2.75391C7.19703 2.51173 6.875 2.02329 6.875 1.45833C6.875 0.652918 7.52792 0 8.33333 0ZM10.1213 5.02848C8.91522 4.9901 7.75142 4.9901 6.54541 5.02848C4.85908 5.08217 4.29323 5.12091 3.81592 5.3776C3.38476 5.60954 2.98015 6.02734 2.76204 6.46566C2.65217 6.68652 2.57959 6.96168 2.54069 7.4235C2.50069 7.89854 2.5 8.50363 2.5 9.37825V9.78841C2.5 10.663 2.50069 11.2681 2.54069 11.7432C2.57959 12.205 2.65215 12.4801 2.76204 12.701C2.98015 13.1393 3.38475 13.5571 3.81592 13.7891C4.29321 14.0458 4.85904 14.0845 6.54541 14.1382C7.75141 14.1766 8.91523 14.1766 10.1213 14.1382C11.8075 14.0845 12.3734 14.0458 12.8507 13.7891C13.2819 13.5572 13.6865 13.1394 13.9046 12.701C14.0145 12.4801 14.0871 12.205 14.126 11.7432C14.166 11.2681 14.1667 10.663 14.1667 9.78841V9.37825C14.1667 8.50363 14.166 7.89854 14.126 7.4235C14.0871 6.96168 14.0145 6.68652 13.9046 6.46566C13.6865 6.02729 13.2819 5.60951 12.8507 5.3776C12.3734 5.12091 11.8075 5.08217 10.1213 5.02848Z" fill="#676F83"/>+</svg>diff --git a/packages/iconify-collections/assets/vender/main-nav/roster-active.svg b/packages/iconify-collections/assets/vender/main-nav/roster-active.svgnew file mode 100644index 00000000000..0d0fbb95fe9--- /dev/null+++ b/packages/iconify-collections/assets/vender/main-nav/roster-active.svg@@ -0,0 +1,6 @@+<svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">+<path d="M11.9362 1.5C12.4177 1.50006 12.8411 1.81975 12.9727 2.28296L15.4651 11.061C15.5117 11.2251 15.6125 11.3687 15.7515 11.4675L16.1235 11.7319C16.3544 11.8963 16.4728 12.1769 16.4297 12.4571L15.9206 15.7669C15.8394 16.2948 15.2475 16.5708 14.7905 16.2942L12.8006 15.0893C12.6837 15.0186 12.5618 14.9546 12.4307 14.9165C12.2411 14.8615 12.0443 14.833 11.8462 14.833C10.6885 14.833 9.75 13.8945 9.75 12.7368V9.14722C9.75 8.23747 10.4875 7.5 11.3972 7.5C11.5688 7.5 11.7164 7.62113 11.7503 7.78928L12.3824 10.9483L12.4043 11.0215C12.4721 11.182 12.6457 11.2781 12.8233 11.2427C13.0009 11.2072 13.1242 11.0515 13.125 10.8772L13.1177 10.8017L12.4856 7.6428C12.3818 7.12384 11.9265 6.75002 11.3972 6.75C11.08 6.75 10.7771 6.81165 10.5 6.92359V2.93628C10.5 2.14312 11.1431 1.5 11.9362 1.5Z" fill="currentColor"/>+<path d="M2.28761 11.1211C2.263 11.2855 2.25026 11.4538 2.25026 11.625C2.25026 13.3862 3.59948 14.8313 5.32057 14.9854L3.0757 16.3674C2.65801 16.6245 2.10961 16.418 1.96534 15.9492L0.926773 12.5742C0.823558 12.2388 0.967018 11.876 1.27174 11.7019L2.28761 11.1211Z" fill="currentColor"/>+<path d="M6.42041 1.5C7.01664 1.5 7.49997 1.98337 7.49997 2.57959V8.81835C6.96373 8.4594 6.31878 8.25 5.62501 8.25C4.91854 8.25 4.26271 8.46705 3.7207 8.83815L5.01124 2.6455C5.15039 1.97822 5.73876 1.50007 6.42041 1.5Z" fill="currentColor"/>+<path fill-rule="evenodd" clip-rule="evenodd" d="M5.625 9C7.07475 9 8.25 10.1753 8.25 11.625C8.25 13.0747 7.07475 14.25 5.625 14.25C4.17525 14.25 3 13.0747 3 11.625C3 10.1753 4.17525 9 5.625 9ZM5.625 10.875C5.21078 10.875 4.875 11.2108 4.875 11.625C4.875 12.0392 5.21078 12.375 5.625 12.375C6.03921 12.375 6.375 12.0392 6.375 11.625C6.375 11.2108 6.03921 10.875 5.625 10.875Z" fill="currentColor"/>+</svg>diff --git a/packages/iconify-collections/assets/vender/main-nav/roster.svg b/packages/iconify-collections/assets/vender/main-nav/roster.svgnew file mode 100644index 00000000000..5169111425e--- /dev/null+++ b/packages/iconify-collections/assets/vender/main-nav/roster.svg@@ -0,0 +1,9 @@+<svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">+<path d="M7.875 11.8125C7.875 13.1587 6.7837 14.25 5.4375 14.25C4.0913 14.25 3 13.1587 3 11.8125C3 10.4663 4.0913 9.375 5.4375 9.375C6.7837 9.375 7.875 10.4663 7.875 11.8125Z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>+<path d="M2.25 15.75L5.625 14.25" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>+<path d="M1.5 11.25L3 10.875" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>+<path d="M5.41699 12.5625C5.83121 12.5625 6.16699 12.2267 6.16699 11.8125C6.16699 11.3983 5.83121 11.0625 5.41699 11.0625C5.00278 11.0625 4.66699 11.3983 4.66699 11.8125C4.66699 12.2267 5.00278 12.5625 5.41699 12.5625Z" fill="currentColor"/>+<path d="M13.125 11.25L12.4956 8.10292C12.4255 7.75237 12.1177 7.5 11.7601 7.5H11.625C10.7966 7.5 10.125 8.17155 10.125 9V12.3939C10.125 13.419 10.956 14.25 11.9811 14.25C12.2408 14.25 12.4976 14.3045 12.7349 14.41L15.75 15.75" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>+<path d="M10.875 7.5V3.75C10.875 2.92157 11.5466 2.25 12.375 2.25H12.5394C12.8836 2.25 13.1836 2.48422 13.267 2.81811L15.3332 11.0833L16.5 11.625" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>+<path d="M7.125 9.75V3C7.125 2.58579 6.78921 2.25 6.375 2.25H5.52089C5.14964 2.25 4.83426 2.5216 4.77919 2.88875L3.75 9.75" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>+</svg>diff --git a/packages/iconify-collections/assets/vender/workflow/agent.svg b/packages/iconify-collections/assets/vender/workflow/agent.svgindex f30c0b455fc..09bf8c0683c 100644--- a/packages/iconify-collections/assets/vender/workflow/agent.svg+++ b/packages/iconify-collections/assets/vender/workflow/agent.svg@@ -1,8 +1,6 @@-<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">-<g id="agent">-<g id="Vector">-<path d="M14.7401 5.80454C14.5765 4.77996 14.1638 3.79808 13.5306 2.97273C12.8973 2.14738 12.0648 1.48568 11.1185 1.06589C10.1722 0.646098 9.12632 0.461106 8.08751 0.546487C7.05582 0.624753 6.04548 0.966277 5.17744 1.53548C4.3094 2.09758 3.58366 2.88024 3.09272 3.79808C2.59466 4.70881 2.33852 5.7405 2.33852 6.7793V7.22756L1.25703 9.3692C1.04357 9.80322 1.22145 10.3368 1.65547 10.5574L2.3314 10.8989V12.3006C2.3314 12.82 2.53063 13.3038 2.90061 13.6738C3.2706 14.0367 3.75442 14.243 4.27382 14.243H6.01702V14.7624C6.01702 15.1538 6.3372 15.4739 6.72853 15.4739C7.11986 15.4739 7.44004 15.1538 7.44004 14.7624V13.7094C7.44004 13.2185 7.04159 12.82 6.55065 12.82H4.27382C4.13864 12.82 4.00345 12.7631 3.91095 12.6706C3.81846 12.5781 3.76154 12.4429 3.76154 12.3077V10.5716C3.76154 10.2301 3.56943 9.92417 3.2706 9.77476L2.77254 9.52573L3.66904 7.73984C3.72596 7.61889 3.76154 7.4837 3.76154 7.34851V6.77219C3.76154 5.96818 3.96076 5.17129 4.34498 4.4669C4.72919 3.76251 5.28417 3.15772 5.9601 2.7237C6.63603 2.28968 7.41158 2.02643 8.20847 1.96239C9.00536 1.89835 9.81648 2.04066 10.5493 2.36795C11.2822 2.69524 11.9225 3.20042 12.4135 3.84077C12.8973 4.47402 13.2246 5.23533 13.3456 6.02511C13.4665 6.81488 13.3954 7.63312 13.125 8.38731C12.8617 9.12017 12.4206 9.78187 11.8585 10.3084C11.6735 10.4792 11.5668 10.7139 11.5668 10.9701V14.7624C11.5668 15.1538 11.887 15.4739 12.2783 15.4739C12.6696 15.4739 12.9898 15.1538 12.9898 14.7624V11.1978C13.6515 10.5432 14.1567 9.73918 14.4697 8.87114C14.8184 7.89637 14.918 6.83623 14.7615 5.81165L14.7401 5.80454Z" fill="white"/>-<path d="M10.8055 7.99599C10.8909 7.83234 10.962 7.66158 11.0189 7.4837H11.6522C12.0435 7.4837 12.3637 7.16352 12.3637 6.77219C12.3637 6.38086 12.0435 6.06068 11.6522 6.06068H11.0189C10.9691 5.8828 10.898 5.71204 10.8055 5.54839L11.2537 5.10014C11.5312 4.82266 11.5312 4.3744 11.2537 4.09692C10.9762 3.81943 10.528 3.81943 10.2505 4.09692L9.80225 4.54517C9.6386 4.45267 9.46784 4.38863 9.28996 4.33171V3.69847C9.28996 3.30714 8.96978 2.98696 8.57845 2.98696C8.18712 2.98696 7.86694 3.30714 7.86694 3.69847V4.33171C7.68907 4.38152 7.5183 4.45267 7.35466 4.54517L6.90641 4.09692C6.62892 3.81943 6.18067 3.81943 5.90318 4.09692C5.62569 4.3744 5.62569 4.82266 5.90318 5.10014L6.35143 5.54839C6.26605 5.71204 6.1949 5.8828 6.13798 6.06068H5.50473C5.1134 6.06068 4.79323 6.38086 4.79323 6.77219C4.79323 7.16352 5.1134 7.4837 5.50473 7.4837H6.13798C6.18778 7.66158 6.25893 7.83234 6.35143 7.99599L5.90318 8.44424C5.62569 8.72172 5.62569 9.16997 5.90318 9.44746C6.04548 9.58976 6.22336 9.6538 6.40835 9.6538C6.59334 9.6538 6.77122 9.58265 6.91352 9.44746L7.36177 8.99921C7.52542 9.08459 7.69618 9.15574 7.87406 9.21267V9.84591C7.87406 10.2372 8.19424 10.5574 8.58557 10.5574C8.9769 10.5574 9.29708 10.2372 9.29708 9.84591V9.21267C9.47496 9.16286 9.64572 9.09171 9.80936 8.99921L10.2576 9.44746C10.3999 9.58976 10.5778 9.6538 10.7628 9.6538C10.9478 9.6538 11.1257 9.58265 11.268 9.44746C11.5454 9.16997 11.5454 8.72172 11.268 8.44424L10.8197 7.99599H10.8055ZM7.44004 6.77219C7.44004 6.14606 7.94521 5.64089 8.57134 5.64089C9.19747 5.64089 9.70264 6.14606 9.70264 6.77219C9.70264 7.39832 9.19747 7.90349 8.57134 7.90349C7.94521 7.90349 7.44004 7.39832 7.44004 6.77219Z" fill="white"/>-</g>+<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">+<g id="agent" transform="translate(2.5 1)">+<path d="M3.3178 20.9524V15.7184C3.31774 15.7136 3.31456 15.6845 3.28404 15.6468L3.24312 15.6069C1.26589 13.9971 0 11.5398 0 8.78813C0.000122972 3.93464 3.93464 0.000122969 8.78813 0C13.5146 0 17.3698 3.73066 17.5691 8.40858C17.5712 8.45846 17.5841 8.48161 17.5865 8.48531L19.3226 11.089C19.7937 11.7956 19.6309 12.7481 18.9513 13.2579L17.5998 14.2707C17.5851 14.2819 17.5763 14.2996 17.5763 14.3178V15.4237C17.576 17.2235 16.1176 18.682 14.3178 18.6822H13.2119C13.1798 18.6822 13.1537 18.7085 13.1536 18.7405V20.9524C13.1536 21.5309 12.6845 21.9999 12.1059 22C11.5274 22 11.0583 21.531 11.0583 20.9524V18.7405C11.0584 17.5513 12.0226 16.587 13.2119 16.587H14.3178C14.9604 16.5868 15.4808 16.0663 15.481 15.4237V14.3178C15.481 13.64 15.8006 13.0016 16.3424 12.595L17.3195 11.8614L15.8432 9.64853C15.603 9.28835 15.4913 8.88291 15.4749 8.49758C15.323 4.93639 12.3872 2.09524 8.78813 2.09524C5.09181 2.09536 2.09536 5.09181 2.09524 8.78813C2.09524 10.883 3.05647 12.7533 4.56594 13.9822C5.0571 14.3822 5.41299 15.0012 5.41304 15.7184V20.9524C5.41304 21.5309 4.94385 21.9998 4.36542 22C3.78684 22 3.3178 21.531 3.3178 20.9524Z" fill="currentColor"/>+<path d="M9.79012 6.5163L9.31429 5.27923C9.23058 5.06159 9.02158 4.91799 8.78836 4.91799C8.55514 4.91799 8.34614 5.06159 8.26243 5.27923L7.7866 6.5163C7.56194 7.10037 7.10038 7.56194 6.5163 7.78659L5.27923 8.26239C5.06159 8.34609 4.91799 8.55519 4.91799 8.78836C4.91799 9.02158 5.06159 9.23058 5.27923 9.31429L6.5163 9.79012C7.10037 10.0148 7.56194 10.4764 7.7866 11.0604L8.26243 12.2975C8.34614 12.5151 8.55514 12.6587 8.78836 12.6587C9.02158 12.6587 9.23058 12.5151 9.31429 12.2975L9.79012 11.0604C10.0148 10.4764 10.4764 10.0148 11.0604 9.79012L12.2975 9.31429C12.5151 9.23058 12.6587 9.02158 12.6587 8.78836C12.6587 8.55519 12.5151 8.34609 12.2975 8.26239L11.0604 7.78659C10.4764 7.56194 10.0148 7.10038 9.79012 6.5163Z" fill="currentColor"/></g></svg>diff --git a/packages/iconify-collections/custom-public/icons.json b/packages/iconify-collections/custom-public/icons.jsonindex 7a4ea8bdaf1..0f83cf3b3e8 100644--- a/packages/iconify-collections/custom-public/icons.json+++ b/packages/iconify-collections/custom-public/icons.json@@ -1,7 +1,10 @@{"prefix": "custom-public",- "lastModified": 1781246368,+ "lastModified": 1781515983,"icons": {+ "agent-building-blocks": {+ "body": "<path fill=\"#155AEF\" fill-rule=\"evenodd\" d=\"M8.303 1.546c.178-.045.364-.051.544-.017c.23.043.432.167.573.246l3.757 2.113c.12.067.29.156.433.289l.06.06c.12.131.21.288.267.457c.07.215.063.445.063.6V9.56c0 .146.007.36-.056.563q-.055.181-.162.338l-.075.1c-.137.163-.32.274-.442.353l-5.013 3.259c-.135.088-.33.224-.556.282a1.3 1.3 0 0 1-.543.017c-.23-.043-.433-.166-.573-.245l-3.757-2.114c-.136-.077-.34-.182-.493-.35a1.3 1.3 0 0 1-.267-.456C1.993 11.09 2 10.86 2 10.704V6.441c0-.146-.007-.36.055-.563l.043-.118a1.3 1.3 0 0 1 .195-.32l.053-.059c.128-.131.282-.225.389-.294L7.86 1.755c.122-.078.273-.165.443-.209m-4.97 9.158l.001.164l.033.02l.11.062l3.264 1.836v-1.137L3.333 9.732zm4.741.917v1.076l4.464-2.901l.098-.065l.029-.02v-.034l.001-.118v-.923zm-4.74-3.419L6.74 10.12V8.982L3.333 7.066zm4.74.752v1.076l4.592-2.985V5.969zm.51-6.08l-4.631 3.01l3.429 1.93l4.664-3.032l-3.28-1.846l-.15-.082z\" clip-rule=\"evenodd\"/>"+ },"avatar-user": {"body": "<g fill=\"none\"><g clip-path=\"url(#svgID0)\"><rect width=\"512\" height=\"512\" fill=\"#B2DDFF\" rx=\"256\"/><circle cx=\"256\" cy=\"196\" r=\"84\" fill=\"#fff\" opacity=\".68\"/><ellipse cx=\"256\" cy=\"583.5\" fill=\"#fff\" opacity=\".68\" rx=\"266\" ry=\"274.5\"/></g><defs><clipPath id=\"svgID0\"><rect width=\"512\" height=\"512\" fill=\"#fff\" rx=\"256\"/></clipPath></defs></g>","width": 512,diff --git a/packages/iconify-collections/custom-public/info.json b/packages/iconify-collections/custom-public/info.jsonindex 115e9e25f90..1b439b73724 100644--- a/packages/iconify-collections/custom-public/info.json+++ b/packages/iconify-collections/custom-public/info.json@@ -1,7 +1,7 @@{"prefix": "custom-public","name": "Dify Custom Public",- "total": 144,+ "total": 145,"version": "0.0.0-private","author": {"name": "LangGenius, Inc.",@@ -13,12 +13,12 @@"url": "https://github.com/langgenius/dify/blob/main/LICENSE"},"samples": [+ "agent-building-blocks","avatar-user","billing-ar-cube-1","billing-asterisk","billing-aws-marketplace-dark",- "billing-aws-marketplace-light",- "billing-azure"+ "billing-aws-marketplace-light"],"palette": false}diff --git a/packages/iconify-collections/custom-vender/icons.json b/packages/iconify-collections/custom-vender/icons.jsonindex bf08a795057..048c5af7553 100644--- a/packages/iconify-collections/custom-vender/icons.json+++ b/packages/iconify-collections/custom-vender/icons.json@@ -1,7 +1,29 @@{"prefix": "custom-vender",- "lastModified": 1781246368,+ "lastModified": 1781515983,"icons": {+ "agent-v2-access-point": {+ "body": "<g fill=\"none\"><path d=\"M7.5 11.25C7.91421 11.25 8.25 11.5858 8.25 12V14.25C8.25 14.6642 7.91421 15 7.5 15C7.08579 15 6.75 14.6642 6.75 14.25V12C6.75 11.5858 7.08579 11.25 7.5 11.25Z\" fill=\"currentColor\"/><path d=\"M2.19653 2.19653C2.48937 1.90372 2.96418 1.90382 3.25708 2.19653L8.03027 6.96973C8.09162 7.03108 8.13966 7.10082 8.17529 7.1748C8.19164 7.20869 8.20587 7.24378 8.21704 7.28027C8.24638 7.37633 8.25641 7.477 8.24634 7.57617C8.23743 7.66451 8.21216 7.74788 8.17529 7.82446C8.13963 7.89868 8.09176 7.96874 8.03027 8.03027L3.25708 12.8035C2.96419 13.096 2.48932 13.0962 2.19653 12.8035C1.90394 12.5107 1.90405 12.0358 2.19653 11.7429L5.68945 8.25H0.75C0.335786 8.25 0 7.91421 0 7.5C0 7.08579 0.335786 6.75 0.75 6.75H5.68945L2.19653 3.25708C1.90389 2.96423 1.90388 2.48937 2.19653 2.19653Z\" fill=\"currentColor\"/><path d=\"M10.1521 10.1521C10.445 9.85921 10.9198 9.85921 11.2126 10.1521L12.8035 11.7429C13.096 12.0358 13.0962 12.5107 12.8035 12.8035C12.5107 13.0962 12.0358 13.096 11.7429 12.8035L10.1521 11.2126C9.85921 10.9198 9.85922 10.445 10.1521 10.1521Z\" fill=\"currentColor\"/><path d=\"M14.25 6.75C14.6642 6.75 15 7.08579 15 7.5C15 7.91421 14.6642 8.25 14.25 8.25H12C11.5858 8.25 11.25 7.91421 11.25 7.5C11.25 7.08579 11.5858 6.75 12 6.75H14.25Z\" fill=\"currentColor\"/><path d=\"M11.7422 2.19653C12.035 1.90387 12.5098 1.90406 12.8027 2.19653C13.0956 2.4894 13.0955 2.96419 12.8027 3.25708L11.2119 4.8479C10.919 5.14079 10.4443 5.1408 10.1514 4.8479C9.85883 4.55497 9.85858 4.08013 10.1514 3.78735L11.7422 2.19653Z\" fill=\"currentColor\"/><path d=\"M7.5 0C7.91421 0 8.25 0.335786 8.25 0.75V3C8.25 3.41421 7.91421 3.75 7.5 3.75C7.08579 3.75 6.75 3.41421 6.75 3V0.75C6.75 0.335786 7.08579 0 7.5 0Z\" fill=\"currentColor\"/></g>",+ "width": 15,+ "height": 15+ },+ "agent-v2-end-user-auth": {+ "body": "<g fill=\"none\"><path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M12 7.33325C13.1046 7.33325 14 8.22865 14 9.33325C14 10.1403 13.5218 10.8356 12.8333 11.1516V11.9999L12.3333 12.4999L12.8333 12.9511V13.6666L12 14.3333L11.1667 13.6666V11.1516C10.4782 10.8356 10 10.1403 10 9.33325C10 8.22865 10.8954 7.33325 12 7.33325ZM12 8.66659C11.6318 8.66659 11.3333 8.96505 11.3333 9.33325C11.3333 9.70145 11.6318 9.99992 12 9.99992C12.3682 9.99992 12.6667 9.70145 12.6667 9.33325C12.6667 8.96505 12.3682 8.66659 12 8.66659Z\" fill=\"currentColor\"/><path d=\"M8 7.99992C8.2545 7.99992 8.50382 8.01506 8.7474 8.04484L8.58594 9.36841C8.39687 9.34527 8.20127 9.33325 8 9.33325C5.8465 9.33325 4.25915 10.7274 3.78646 12.6666H10V13.9999H2.26758L2.33594 13.2708C2.61081 10.3473 4.82817 7.99992 8 7.99992Z\" fill=\"currentColor\"/><path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M8 1.33325C9.65687 1.33325 11 2.6764 11 4.33325C11 5.99011 9.65687 7.33325 8 7.33325C6.34315 7.33325 5 5.99011 5 4.33325C5 2.6764 6.34315 1.33325 8 1.33325ZM8 2.66659C7.07953 2.66659 6.33333 3.41278 6.33333 4.33325C6.33333 5.25373 7.07953 5.99992 8 5.99992C8.92047 5.99992 9.66667 5.25373 9.66667 4.33325C9.66667 3.41278 8.92047 2.66659 8 2.66659Z\" fill=\"currentColor\"/></g>"+ },+ "agent-v2-plan": {+ "body": "<g fill=\"none\"><path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M17 0C17.5523 0 18 0.447715 18 1V6C18 6.55228 17.5523 7 17 7H12C11.4477 7 11 6.55228 11 6V4.5H6.94629C5.92438 4.50039 5.56101 5.85276 6.44531 6.36523L12.5576 9.90332C15.2116 11.4402 14.1206 15.4996 11.0537 15.5H7V17C7 17.5523 6.55228 18 6 18H1C0.447715 18 0 17.5523 0 17V12C0 11.4477 0.447715 11 1 11H6C6.55228 11 7 11.4477 7 12V13.5H11.0537C12.0756 13.4996 12.4394 12.1472 11.5557 11.6348L5.44336 8.09668C2.789 6.55983 3.87917 2.50039 6.94629 2.5H11V1C11 0.447715 11.4477 0 12 0H17ZM2 16H5V13H2V16ZM13 5H16V2H13V5Z\" fill=\"currentColor\"/></g>",+ "width": 18,+ "height": 18+ },+ "agent-v2-prompt-insert": {+ "body": "<g fill=\"none\"><path d=\"M2.91669 1.16669C1.95019 1.16669 1.16669 1.95019 1.16669 2.91669V11.0834C1.16669 12.0499 1.95019 12.8334 2.91669 12.8334H11.0834C12.0499 12.8334 12.8334 12.0499 12.8334 11.0834V2.91669C12.8334 1.95019 12.0499 1.16669 11.0834 1.16669H2.91669ZM2.33335 2.91669C2.33335 2.59452 2.59452 2.33335 2.91669 2.33335H11.0834C11.4055 2.33335 11.6667 2.59452 11.6667 2.91669V11.0834C11.6667 11.4055 11.4055 11.6667 11.0834 11.6667H2.91669C2.59452 11.6667 2.33335 11.4055 2.33335 11.0834V2.91669ZM5.67188 10.5L9.67186 3.50002H8.32815L4.32817 10.5H5.67188Z\" fill=\"currentColor\"/></g>",+ "width": 14,+ "height": 14+ },+ "agent-v2-robot-3": {+ "body": "<g fill=\"none\"><path d=\"M6.25 6.875C6.82523 6.875 7.29167 7.34128 7.29167 7.91667V9.16667C7.29167 9.74205 6.82523 10.2083 6.25 10.2083C5.67477 10.2083 5.20833 9.74205 5.20833 9.16667V7.91667C5.20833 7.34128 5.67477 6.875 6.25 6.875Z\" fill=\"currentColor\"/><path d=\"M10.4167 6.875C10.992 6.875 11.4583 7.34135 11.4583 7.91667V9.16667C11.4583 9.74199 10.992 10.2083 10.4167 10.2083C9.84135 10.2083 9.375 9.74199 9.375 9.16667V7.91667C9.375 7.34135 9.84135 6.875 10.4167 6.875Z\" fill=\"currentColor\"/><path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M8.33333 0C9.13875 0 9.79167 0.652918 9.79167 1.45833C9.79167 2.02329 9.46964 2.51173 8.99984 2.75391V3.33822C9.38912 3.34279 9.77995 3.35006 10.175 3.36263C11.6983 3.41112 12.7377 3.42425 13.6401 3.90951C14.375 4.30477 15.0255 4.97655 15.3971 5.72347C15.5468 6.02442 15.6427 6.33532 15.7056 6.66667H15.8333C16.2936 6.66667 16.6667 7.03976 16.6667 7.5V10C16.6667 10.4602 16.2936 10.8333 15.8333 10.8333H15.8285C15.8235 11.2254 15.813 11.5735 15.7869 11.8831C15.7386 12.4571 15.6361 12.9628 15.3971 13.4432C15.0254 14.1901 14.3749 14.8619 13.6401 15.2572C12.7377 15.7424 11.6982 15.7556 10.175 15.804C8.93336 15.8436 7.73328 15.8436 6.4917 15.804C4.96843 15.7556 3.92896 15.7424 3.02653 15.2572C2.29178 14.8619 1.64121 14.1902 1.26953 13.4432C1.03058 12.9628 0.928072 12.4571 0.87972 11.8831C0.853642 11.5735 0.843216 11.2254 0.838216 10.8333H0.833333C0.373096 10.8333 0 10.4602 0 10V7.5C0 7.03976 0.373096 6.66667 0.833333 6.66667H0.9611C1.02392 6.33532 1.11984 6.02442 1.26953 5.72347C1.64119 4.97649 2.29177 4.30475 3.02653 3.90951C3.92895 3.42425 4.96837 3.41112 6.4917 3.36263C6.88671 3.35006 7.27754 3.34279 7.66683 3.33822V2.75391C7.19703 2.51173 6.875 2.02329 6.875 1.45833C6.875 0.652918 7.52792 0 8.33333 0ZM10.1213 5.02848C8.91522 4.9901 7.75142 4.9901 6.54541 5.02848C4.85908 5.08217 4.29323 5.12091 3.81592 5.3776C3.38476 5.60954 2.98015 6.02734 2.76204 6.46566C2.65217 6.68652 2.57959 6.96168 2.54069 7.4235C2.50069 7.89854 2.5 8.50363 2.5 9.37825V9.78841C2.5 10.663 2.50069 11.2681 2.54069 11.7432C2.57959 12.205 2.65215 12.4801 2.76204 12.701C2.98015 13.1393 3.38475 13.5571 3.81592 13.7891C4.29321 14.0458 4.85904 14.0845 6.54541 14.1382C7.75141 14.1766 8.91523 14.1766 10.1213 14.1382C11.8075 14.0845 12.3734 14.0458 12.8507 13.7891C13.2819 13.5572 13.6865 13.1394 13.9046 12.701C14.0145 12.4801 14.0871 12.205 14.126 11.7432C14.166 11.2681 14.1667 10.663 14.1667 9.78841V9.37825C14.1667 8.50363 14.166 7.89854 14.126 7.4235C14.0871 6.96168 14.0145 6.68652 13.9046 6.46566C13.6865 6.02729 13.2819 5.60951 12.8507 5.3776C12.3734 5.12091 11.8075 5.08217 10.1213 5.02848Z\" fill=\"currentColor\"/></g>",+ "width": 17+ },"features-citations": {"body": "<g fill=\"none\"><path d=\"M1 12C1 5.92487 5.92487 1 12 1C18.0751 1 23 5.92487 23 12C23 18.0751 18.0751 23 12 23C5.92487 23 1 18.0751 1 12ZM7 11.9702V14.958H11.0356V11.2339H8.8125C8.78418 10.8185 8.85498 10.4173 9.0249 10.0303C9.35531 9.29395 10.002 8.77474 10.9648 8.47266V7C9.67155 7.25488 8.68506 7.79297 8.00537 8.61426C7.33512 9.43555 7 10.5542 7 11.9702ZM15.0391 10.0586C15.3695 9.29395 16.0114 8.7653 16.9648 8.47266V7C15.7093 7.25488 14.7323 7.78825 14.0337 8.6001C13.3446 9.41195 13 10.5353 13 11.9702V14.958H17.0356V11.2339H14.8125C14.7747 10.8563 14.8503 10.4645 15.0391 10.0586Z\" fill=\"currentColor\"/></g>","width": 24,@@ -811,6 +833,16 @@"width": 24,"height": 24},+ "main-nav-roster": {+ "body": "<g fill=\"none\"><path d=\"M7.875 11.8125C7.875 13.1587 6.7837 14.25 5.4375 14.25C4.0913 14.25 3 13.1587 3 11.8125C3 10.4663 4.0913 9.375 5.4375 9.375C6.7837 9.375 7.875 10.4663 7.875 11.8125Z\" stroke=\"currentColor\" stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/><path d=\"M2.25 15.75L5.625 14.25\" stroke=\"currentColor\" stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/><path d=\"M1.5 11.25L3 10.875\" stroke=\"currentColor\" stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/><path d=\"M5.41699 12.5625C5.83121 12.5625 6.16699 12.2267 6.16699 11.8125C6.16699 11.3983 5.83121 11.0625 5.41699 11.0625C5.00278 11.0625 4.66699 11.3983 4.66699 11.8125C4.66699 12.2267 5.00278 12.5625 5.41699 12.5625Z\" fill=\"currentColor\"/><path d=\"M13.125 11.25L12.4956 8.10292C12.4255 7.75237 12.1177 7.5 11.7601 7.5H11.625C10.7966 7.5 10.125 8.17155 10.125 9V12.3939C10.125 13.419 10.956 14.25 11.9811 14.25C12.2408 14.25 12.4976 14.3045 12.7349 14.41L15.75 15.75\" stroke=\"currentColor\" stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/><path d=\"M10.875 7.5V3.75C10.875 2.92157 11.5466 2.25 12.375 2.25H12.5394C12.8836 2.25 13.1836 2.48422 13.267 2.81811L15.3332 11.0833L16.5 11.625\" stroke=\"currentColor\" stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/><path d=\"M7.125 9.75V3C7.125 2.58579 6.78921 2.25 6.375 2.25H5.52089C5.14964 2.25 4.83426 2.5216 4.77919 2.88875L3.75 9.75\" stroke=\"currentColor\" stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></g>",+ "width": 18,+ "height": 18+ },+ "main-nav-roster-active": {+ "body": "<g fill=\"none\"><path d=\"M11.9362 1.5C12.4177 1.50006 12.8411 1.81975 12.9727 2.28296L15.4651 11.061C15.5117 11.2251 15.6125 11.3687 15.7515 11.4675L16.1235 11.7319C16.3544 11.8963 16.4728 12.1769 16.4297 12.4571L15.9206 15.7669C15.8394 16.2948 15.2475 16.5708 14.7905 16.2942L12.8006 15.0893C12.6837 15.0186 12.5618 14.9546 12.4307 14.9165C12.2411 14.8615 12.0443 14.833 11.8462 14.833C10.6885 14.833 9.75 13.8945 9.75 12.7368V9.14722C9.75 8.23747 10.4875 7.5 11.3972 7.5C11.5688 7.5 11.7164 7.62113 11.7503 7.78928L12.3824 10.9483L12.4043 11.0215C12.4721 11.182 12.6457 11.2781 12.8233 11.2427C13.0009 11.2072 13.1242 11.0515 13.125 10.8772L13.1177 10.8017L12.4856 7.6428C12.3818 7.12384 11.9265 6.75002 11.3972 6.75C11.08 6.75 10.7771 6.81165 10.5 6.92359V2.93628C10.5 2.14312 11.1431 1.5 11.9362 1.5Z\" fill=\"currentColor\"/><path d=\"M2.28761 11.1211C2.263 11.2855 2.25026 11.4538 2.25026 11.625C2.25026 13.3862 3.59948 14.8313 5.32057 14.9854L3.0757 16.3674C2.65801 16.6245 2.10961 16.418 1.96534 15.9492L0.926773 12.5742C0.823558 12.2388 0.967018 11.876 1.27174 11.7019L2.28761 11.1211Z\" fill=\"currentColor\"/><path d=\"M6.42041 1.5C7.01664 1.5 7.49997 1.98337 7.49997 2.57959V8.81835C6.96373 8.4594 6.31878 8.25 5.62501 8.25C4.91854 8.25 4.26271 8.46705 3.7207 8.83815L5.01124 2.6455C5.15039 1.97822 5.73876 1.50007 6.42041 1.5Z\" fill=\"currentColor\"/><path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M5.625 9C7.07475 9 8.25 10.1753 8.25 11.625C8.25 13.0747 7.07475 14.25 5.625 14.25C4.17525 14.25 3 13.0747 3 11.625C3 10.1753 4.17525 9 5.625 9ZM5.625 10.875C5.21078 10.875 4.875 11.2108 4.875 11.625C4.875 12.0392 5.21078 12.375 5.625 12.375C6.03921 12.375 6.375 12.0392 6.375 11.625C6.375 11.2108 6.03921 10.875 5.625 10.875Z\" fill=\"currentColor\"/></g>",+ "width": 18,+ "height": 18+ },"main-nav-studio": {"body": "<g fill=\"none\"><path d=\"M15.8206 2.0275C15.7973 1.82217 15.6238 1.66696 15.4171 1.66675C15.2104 1.66654 15.0365 1.82139 15.0128 2.02667C14.865 3.30836 14.1416 4.03176 12.8599 4.17959C12.6547 4.20326 12.4998 4.37719 12.5 4.58383C12.5003 4.79047 12.6554 4.96408 12.8608 4.98733C14.1243 5.13046 14.8978 5.84689 15.0117 7.12955C15.0304 7.33946 15.2064 7.50032 15.4171 7.50008C15.6278 7.49984 15.8035 7.33859 15.8217 7.12863C15.9311 5.86411 16.6973 5.09787 17.9619 4.98841C18.1718 4.97023 18.3331 4.79461 18.3333 4.58387C18.3336 4.37313 18.1728 4.19715 17.9628 4.17851C16.6802 4.06457 15.9637 3.29101 15.8206 2.0275Z\" fill=\"currentColor\"/><path d=\"M7.29167 9.16659C8.9025 9.16659 10.2083 7.86075 10.2083 6.24992C10.2083 4.63909 8.9025 3.33325 7.29167 3.33325C5.68084 3.33325 4.375 4.63909 4.375 6.24992C4.375 7.86075 5.68084 9.16659 7.29167 9.16659Z\" stroke=\"currentColor\" stroke-width=\"1.5\"/><path d=\"M1.66699 16.6667C1.66699 13.9053 3.90557 11.6667 6.66699 11.6667H7.08366\" stroke=\"currentColor\" stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/><path d=\"M9.16634 16.6666L10.833 10.8333H18.333L16.6663 16.6666H9.16634ZM9.16634 16.6666H5.83301\" stroke=\"currentColor\" stroke-width=\"1.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></g>","width": 20,@@ -1295,9 +1327,9 @@"height": 24},"workflow-agent": {- "body": "<g fill=\"none\"><g id=\"agent\"><g id=\"Vector\"><path d=\"M14.7401 5.80454C14.5765 4.77996 14.1638 3.79808 13.5306 2.97273C12.8973 2.14738 12.0648 1.48568 11.1185 1.06589C10.1722 0.646098 9.12632 0.461106 8.08751 0.546487C7.05582 0.624753 6.04548 0.966277 5.17744 1.53548C4.3094 2.09758 3.58366 2.88024 3.09272 3.79808C2.59466 4.70881 2.33852 5.7405 2.33852 6.7793V7.22756L1.25703 9.3692C1.04357 9.80322 1.22145 10.3368 1.65547 10.5574L2.3314 10.8989V12.3006C2.3314 12.82 2.53063 13.3038 2.90061 13.6738C3.2706 14.0367 3.75442 14.243 4.27382 14.243H6.01702V14.7624C6.01702 15.1538 6.3372 15.4739 6.72853 15.4739C7.11986 15.4739 7.44004 15.1538 7.44004 14.7624V13.7094C7.44004 13.2185 7.04159 12.82 6.55065 12.82H4.27382C4.13864 12.82 4.00345 12.7631 3.91095 12.6706C3.81846 12.5781 3.76154 12.4429 3.76154 12.3077V10.5716C3.76154 10.2301 3.56943 9.92417 3.2706 9.77476L2.77254 9.52573L3.66904 7.73984C3.72596 7.61889 3.76154 7.4837 3.76154 7.34851V6.77219C3.76154 5.96818 3.96076 5.17129 4.34498 4.4669C4.72919 3.76251 5.28417 3.15772 5.9601 2.7237C6.63603 2.28968 7.41158 2.02643 8.20847 1.96239C9.00536 1.89835 9.81648 2.04066 10.5493 2.36795C11.2822 2.69524 11.9225 3.20042 12.4135 3.84077C12.8973 4.47402 13.2246 5.23533 13.3456 6.02511C13.4665 6.81488 13.3954 7.63312 13.125 8.38731C12.8617 9.12017 12.4206 9.78187 11.8585 10.3084C11.6735 10.4792 11.5668 10.7139 11.5668 10.9701V14.7624C11.5668 15.1538 11.887 15.4739 12.2783 15.4739C12.6696 15.4739 12.9898 15.1538 12.9898 14.7624V11.1978C13.6515 10.5432 14.1567 9.73918 14.4697 8.87114C14.8184 7.89637 14.918 6.83623 14.7615 5.81165L14.7401 5.80454Z\" fill=\"currentColor\"/><path d=\"M10.8055 7.99599C10.8909 7.83234 10.962 7.66158 11.0189 7.4837H11.6522C12.0435 7.4837 12.3637 7.16352 12.3637 6.77219C12.3637 6.38086 12.0435 6.06068 11.6522 6.06068H11.0189C10.9691 5.8828 10.898 5.71204 10.8055 5.54839L11.2537 5.10014C11.5312 4.82266 11.5312 4.3744 11.2537 4.09692C10.9762 3.81943 10.528 3.81943 10.2505 4.09692L9.80225 4.54517C9.6386 4.45267 9.46784 4.38863 9.28996 4.33171V3.69847C9.28996 3.30714 8.96978 2.98696 8.57845 2.98696C8.18712 2.98696 7.86694 3.30714 7.86694 3.69847V4.33171C7.68907 4.38152 7.5183 4.45267 7.35466 4.54517L6.90641 4.09692C6.62892 3.81943 6.18067 3.81943 5.90318 4.09692C5.62569 4.3744 5.62569 4.82266 5.90318 5.10014L6.35143 5.54839C6.26605 5.71204 6.1949 5.8828 6.13798 6.06068H5.50473C5.1134 6.06068 4.79323 6.38086 4.79323 6.77219C4.79323 7.16352 5.1134 7.4837 5.50473 7.4837H6.13798C6.18778 7.66158 6.25893 7.83234 6.35143 7.99599L5.90318 8.44424C5.62569 8.72172 5.62569 9.16997 5.90318 9.44746C6.04548 9.58976 6.22336 9.6538 6.40835 9.6538C6.59334 9.6538 6.77122 9.58265 6.91352 9.44746L7.36177 8.99921C7.52542 9.08459 7.69618 9.15574 7.87406 9.21267V9.84591C7.87406 10.2372 8.19424 10.5574 8.58557 10.5574C8.9769 10.5574 9.29708 10.2372 9.29708 9.84591V9.21267C9.47496 9.16286 9.64572 9.09171 9.80936 8.99921L10.2576 9.44746C10.3999 9.58976 10.5778 9.6538 10.7628 9.6538C10.9478 9.6538 11.1257 9.58265 11.268 9.44746C11.5454 9.16997 11.5454 8.72172 11.268 8.44424L10.8197 7.99599H10.8055ZM7.44004 6.77219C7.44004 6.14606 7.94521 5.64089 8.57134 5.64089C9.19747 5.64089 9.70264 6.14606 9.70264 6.77219C9.70264 7.39832 9.19747 7.90349 8.57134 7.90349C7.94521 7.90349 7.44004 7.39832 7.44004 6.77219Z\" fill=\"currentColor\"/></g></g></g>",- "width": 16,- "height": 16+ "body": "<g fill=\"none\"><g id=\"agent\" transform=\"translate(2.5 1)\"><path d=\"M3.3178 20.9524V15.7184C3.31774 15.7136 3.31456 15.6845 3.28404 15.6468L3.24312 15.6069C1.26589 13.9971 0 11.5398 0 8.78813C0.000122972 3.93464 3.93464 0.000122969 8.78813 0C13.5146 0 17.3698 3.73066 17.5691 8.40858C17.5712 8.45846 17.5841 8.48161 17.5865 8.48531L19.3226 11.089C19.7937 11.7956 19.6309 12.7481 18.9513 13.2579L17.5998 14.2707C17.5851 14.2819 17.5763 14.2996 17.5763 14.3178V15.4237C17.576 17.2235 16.1176 18.682 14.3178 18.6822H13.2119C13.1798 18.6822 13.1537 18.7085 13.1536 18.7405V20.9524C13.1536 21.5309 12.6845 21.9999 12.1059 22C11.5274 22 11.0583 21.531 11.0583 20.9524V18.7405C11.0584 17.5513 12.0226 16.587 13.2119 16.587H14.3178C14.9604 16.5868 15.4808 16.0663 15.481 15.4237V14.3178C15.481 13.64 15.8006 13.0016 16.3424 12.595L17.3195 11.8614L15.8432 9.64853C15.603 9.28835 15.4913 8.88291 15.4749 8.49758C15.323 4.93639 12.3872 2.09524 8.78813 2.09524C5.09181 2.09536 2.09536 5.09181 2.09524 8.78813C2.09524 10.883 3.05647 12.7533 4.56594 13.9822C5.0571 14.3822 5.41299 15.0012 5.41304 15.7184V20.9524C5.41304 21.5309 4.94385 21.9998 4.36542 22C3.78684 22 3.3178 21.531 3.3178 20.9524Z\" fill=\"currentColor\"/><path d=\"M9.79012 6.5163L9.31429 5.27923C9.23058 5.06159 9.02158 4.91799 8.78836 4.91799C8.55514 4.91799 8.34614 5.06159 8.26243 5.27923L7.7866 6.5163C7.56194 7.10037 7.10038 7.56194 6.5163 7.78659L5.27923 8.26239C5.06159 8.34609 4.91799 8.55519 4.91799 8.78836C4.91799 9.02158 5.06159 9.23058 5.27923 9.31429L6.5163 9.79012C7.10037 10.0148 7.56194 10.4764 7.7866 11.0604L8.26243 12.2975C8.34614 12.5151 8.55514 12.6587 8.78836 12.6587C9.02158 12.6587 9.23058 12.5151 9.31429 12.2975L9.79012 11.0604C10.0148 10.4764 10.4764 10.0148 11.0604 9.79012L12.2975 9.31429C12.5151 9.23058 12.6587 9.02158 12.6587 8.78836C12.6587 8.55519 12.5151 8.34609 12.2975 8.26239L11.0604 7.78659C10.4764 7.56194 10.0148 7.10038 9.79012 6.5163Z\" fill=\"currentColor\"/></g></g>",+ "width": 24,+ "height": 24},"workflow-answer": {"body": "<g fill=\"none\"><g id=\"icons/answer\"><path id=\"Vector (Stroke)\" fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M3.50114 1.67701L10.5011 1.677C11.5079 1.677 12.3241 2.49311 12.3241 3.49992V9.35414C12.3241 10.3609 11.5079 11.177 10.5012 11.1771H8.9954L7.41734 12.4845C7.17339 12.6866 6.81987 12.6856 6.57708 12.4821L5.02026 11.1771H3.50114C2.49436 11.1771 1.67822 10.3608 1.67822 9.35414V3.49993C1.67822 2.49316 2.49437 1.67701 3.50114 1.67701ZM10.5011 2.9895L3.50114 2.98951C3.21924 2.98951 2.99072 3.21803 2.99072 3.49993V9.35414C2.99072 9.63601 3.21926 9.86455 3.50114 9.86455H5.04675C5.33794 9.86455 5.61984 9.96705 5.84302 10.1541L7.00112 11.1249L8.17831 10.1496C8.40069 9.96537 8.68041 9.86455 8.96916 9.86455H10.5011C10.5011 9.86455 10.5011 9.86455 10.5011 9.86455C10.783 9.8645 11.0116 9.63592 11.0116 9.35414V3.49992C11.0116 3.21806 10.7831 2.9895 10.5011 2.9895ZM9.06809 4.93171C9.32437 5.18799 9.32437 5.60351 9.06809 5.85979L7.02642 7.90146C6.77014 8.15774 6.35464 8.15774 6.09835 7.90146L5.22333 7.02646C4.96704 6.77019 4.96704 6.35467 5.22332 6.09839C5.4796 5.8421 5.89511 5.8421 6.15139 6.09837L6.56238 6.50935L8.14001 4.93171C8.3963 4.67543 8.81181 4.67543 9.06809 4.93171Z\" fill=\"currentColor\"/></g></g>",diff --git a/packages/iconify-collections/custom-vender/info.json b/packages/iconify-collections/custom-vender/info.jsonindex cef352ac549..608b5020f04 100644--- a/packages/iconify-collections/custom-vender/info.json+++ b/packages/iconify-collections/custom-vender/info.json@@ -1,7 +1,7 @@{"prefix": "custom-vender","name": "Dify Custom Vender",- "total": 319,+ "total": 326,"version": "0.0.0-private","author": {"name": "LangGenius, Inc.",@@ -13,12 +13,12 @@"url": "https://github.com/langgenius/dify/blob/main/LICENSE"},"samples": [- "features-citations",- "features-content-moderation",- "features-document",- "features-folder-upload",- "features-love-message",- "features-message-fast"+ "agent-v2-access-point",+ "agent-v2-end-user-auth",+ "agent-v2-plan",+ "agent-v2-prompt-insert",+ "agent-v2-robot-3",+ "features-citations"],"palette": false}diff --git a/web/.env.example b/web/.env.exampleindex 762db54dafa..112232e529c 100644--- a/web/.env.example+++ b/web/.env.example@@ -90,6 +90,9 @@ NEXT_PUBLIC_ENABLE_SINGLE_DOLLAR_LATEX=false# /refine slash commands in the "Go to Anything" command palette)NEXT_PUBLIC_ENABLE_FEATURE_PREVIEW=false+# Enable Agent v2 frontend entry points.+NEXT_PUBLIC_ENABLE_AGENT_V2=false+# The maximum number of tree node depth for workflowNEXT_PUBLIC_MAX_TREE_DEPTH=50diff --git a/web/AGENTS.md b/web/AGENTS.mdindex 21def787b9e..6221b2376ae 100644--- a/web/AGENTS.md+++ b/web/AGENTS.md@@ -38,6 +38,15 @@- Do not access `localStorage`, `window.localStorage`, or `globalThis.localStorage` directly in app code; use the storage hook boundary and preserve existing raw/custom storage formats.- Do not add ad hoc global event listeners for shared state. Prefer atoms, existing stores, or a shared subscription hook so listeners are centralized and deduplicated.+## Agent V2 Frontend++- Keep Agent V2 separate from legacy workflow Agent. Use `web/features/agent-v2`, `web/app/components/workflow/nodes/agent-v2`, the `agent_node_kind: 'dify_agent'` and `version: '2'` payload discriminator, and `BlockEnum.AgentV2` where the graph type is already migrated. Do not bridge Agent V2 to legacy `agent_strategy_*` behavior or data shapes.+- Use generated contracts and `consoleQuery` / `consoleClient` from `@/service/client` for Agent V2 backend calls. Do not add handwritten REST helpers, handwritten API types, mock-backed app state, or direct edits to generated contract files.+- Treat TanStack Query as the server source of truth. Scope editable drafts with an instance-level `AgentComposerProvider`, hydrate Jotai `originalDraft`, `publishedDraft`, and `draft` from contract data, and compute dirty or unpublished state from those draft snapshots.+- Keep transitional defaults and mock data at the owning surface, such as the configure page or workflow node, not in shared composer defaults.+- Use `@langgenius/dify-ui/*` primitives and primitive data/CSS selectors first. Add call-site Tailwind only for real design deltas, avoid arbitrary values when token utilities exist, and keep focus rings visible without making inert layout regions focusable.+- Keep Agent V2 copy in the `agentV2` i18n namespace, currently backed by `agent-v-2.json` in the maintained locale set.+## Automated Test Generation- Use `./docs/test.md` as the canonical instruction set for generating frontend automated tests.diff --git a/web/__tests__/env.spec.ts b/web/__tests__/env.spec.tsnew file mode 100644index 00000000000..89781d32685--- /dev/null+++ b/web/__tests__/env.spec.ts@@ -0,0 +1,42 @@+describe('env runtime transport', () => {+ const originalAgentV2Env = process.env.NEXT_PUBLIC_ENABLE_AGENT_V2++ beforeEach(() => {+ vi.clearAllMocks()+ vi.resetModules()+ vi.doUnmock('../utils/client')+ document.body.removeAttribute('data-enable-agent-v2')+ document.body.removeAttribute('data-enable-agent-v-2')+ delete process.env.NEXT_PUBLIC_ENABLE_AGENT_V2+ })++ afterAll(() => {+ if (originalAgentV2Env === undefined)+ delete process.env.NEXT_PUBLIC_ENABLE_AGENT_V2+ else+ process.env.NEXT_PUBLIC_ENABLE_AGENT_V2 = originalAgentV2Env+ })++ it('should read NEXT_PUBLIC_ENABLE_AGENT_V2 from the browser runtime dataset key', async () => {+ document.body.setAttribute('data-enable-agent-v2', 'true')++ const { env } = await import('../env')++ expect(env.NEXT_PUBLIC_ENABLE_AGENT_V2).toBe(true)+ })++ it('should emit the Agent v2 runtime dataset attribute from getDatasetMap on the server', async () => {+ process.env.NEXT_PUBLIC_ENABLE_AGENT_V2 = 'true'++ vi.doMock('../utils/client', () => ({+ isClient: false,+ isServer: true,+ }))++ const { getDatasetMap } = await import('../env')+ const datasetMap = getDatasetMap()++ expect(datasetMap['data-enable-agent-v2']).toBe(true)+ expect(datasetMap['data-enable-agent-v-2']).toBeUndefined()+ })+})diff --git a/web/app/(commonLayout)/role-route-guard.tsx b/web/app/(commonLayout)/role-route-guard.tsxindex 05cf59aee42..0fee1d72f08 100644--- a/web/app/(commonLayout)/role-route-guard.tsx+++ b/web/app/(commonLayout)/role-route-guard.tsx@@ -7,7 +7,7 @@ import { systemFeaturesQueryOptions } from '@/features/system-features/client'import { redirect, usePathname } from '@/next/navigation'import { consoleQuery } from '@/service/client'-const datasetOperatorRedirectRoutes = ['/', '/apps', '/app', '/deployments', '/snippets', '/explore', '/tools', '/integrations'] as const+const datasetOperatorRedirectRoutes = ['/', '/apps', '/app', '/deployments', '/snippets', '/roster', '/explore', '/tools', '/integrations'] as constfunction isPathUnderRoute(pathname: string, route: string) {return pathname === route || pathname.startsWith(`${route}/`)diff --git a/web/app/(commonLayout)/roster/__tests__/feature-guard.spec.ts b/web/app/(commonLayout)/roster/__tests__/feature-guard.spec.tsnew file mode 100644index 00000000000..343e0797776--- /dev/null+++ b/web/app/(commonLayout)/roster/__tests__/feature-guard.spec.ts@@ -0,0 +1,41 @@+const mocks = vi.hoisted(() => ({+ agentV2Enabled: true,+ notFound: vi.fn(() => {+ throw new Error('NEXT_NOT_FOUND')+ }),+}))++vi.mock('@/env', () => ({+ env: {+ get NEXT_PUBLIC_ENABLE_AGENT_V2() {+ return mocks.agentV2Enabled+ },+ },+}))++vi.mock('@/next/navigation', () => ({+ notFound: () => mocks.notFound(),+}))++describe('guardAgentV2Route', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mocks.agentV2Enabled = true+ })++ it('should allow roster routes when Agent v2 is enabled', async () => {+ const { guardAgentV2Route } = await import('../feature-guard')++ expect(() => guardAgentV2Route()).not.toThrow()+ expect(mocks.notFound).not.toHaveBeenCalled()+ })++ it('should throw notFound when Agent v2 is disabled', async () => {+ mocks.agentV2Enabled = false++ const { guardAgentV2Route } = await import('../feature-guard')++ expect(() => guardAgentV2Route()).toThrow('NEXT_NOT_FOUND')+ expect(mocks.notFound).toHaveBeenCalledTimes(1)+ })+})diff --git a/web/app/(commonLayout)/roster/__tests__/layout.spec.tsx b/web/app/(commonLayout)/roster/__tests__/layout.spec.tsxnew file mode 100644index 00000000000..0d4dbc66dc2--- /dev/null+++ b/web/app/(commonLayout)/roster/__tests__/layout.spec.tsx@@ -0,0 +1,43 @@+import { render, screen } from '@testing-library/react'++const mocks = vi.hoisted(() => ({+ guardAgentV2Route: vi.fn(),+}))++vi.mock('../feature-guard', () => ({+ guardAgentV2Route: () => mocks.guardAgentV2Route(),+}))++describe('RosterLayout', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ it('should render children when Agent v2 is enabled', async () => {+ const { default: RosterLayout } = await import('../layout')++ render(+ <RosterLayout>+ <div>Roster content</div>+ </RosterLayout>,+ )++ expect(mocks.guardAgentV2Route).toHaveBeenCalledTimes(1)+ expect(screen.getByText('Roster content')).toBeInTheDocument()+ })++ it('should block rendering when the roster guard throws notFound', async () => {+ mocks.guardAgentV2Route.mockImplementation(() => {+ throw new Error('NEXT_NOT_FOUND')+ })++ const { default: RosterLayout } = await import('../layout')++ expect(() => render(+ <RosterLayout>+ <div>Roster content</div>+ </RosterLayout>,+ )).toThrow('NEXT_NOT_FOUND')+ expect(mocks.guardAgentV2Route).toHaveBeenCalled()+ })+})diff --git a/web/app/(commonLayout)/roster/agent/[agentId]/access/page.tsx b/web/app/(commonLayout)/roster/agent/[agentId]/access/page.tsxnew file mode 100644index 00000000000..31d2fac8652--- /dev/null+++ b/web/app/(commonLayout)/roster/agent/[agentId]/access/page.tsx@@ -0,0 +1,13 @@+import { AgentDetailPage } from '@/features/agent-v2/agent-detail/page'++type PageProps = {+ params: Promise<{ agentId: string }>+}++export default async function Page({+ params,+}: PageProps) {+ const { agentId } = await params++ return <AgentDetailPage agentId={agentId} section="access" />+}diff --git a/web/app/(commonLayout)/roster/agent/[agentId]/configure/page.tsx b/web/app/(commonLayout)/roster/agent/[agentId]/configure/page.tsxnew file mode 100644index 00000000000..a8a25ba6c3f--- /dev/null+++ b/web/app/(commonLayout)/roster/agent/[agentId]/configure/page.tsx@@ -0,0 +1,13 @@+import { AgentDetailPage } from '@/features/agent-v2/agent-detail/page'++type PageProps = {+ params: Promise<{ agentId: string }>+}++export default async function Page({+ params,+}: PageProps) {+ const { agentId } = await params++ return <AgentDetailPage agentId={agentId} section="configure" />+}diff --git a/web/app/(commonLayout)/roster/agent/[agentId]/layout.tsx b/web/app/(commonLayout)/roster/agent/[agentId]/layout.tsxnew file mode 100644index 00000000000..384443d58bc--- /dev/null+++ b/web/app/(commonLayout)/roster/agent/[agentId]/layout.tsx@@ -0,0 +1,20 @@+import type { ReactNode } from 'react'+import { AgentDetailLayout } from '@/features/agent-v2/agent-detail/layout'++type LayoutProps = {+ children: ReactNode+ params: Promise<{ agentId: string }>+}++export default async function Layout({+ children,+ params,+}: LayoutProps) {+ const { agentId } = await params++ return (+ <AgentDetailLayout agentId={agentId}>+ {children}+ </AgentDetailLayout>+ )+}diff --git a/web/app/(commonLayout)/roster/agent/[agentId]/logs/page.tsx b/web/app/(commonLayout)/roster/agent/[agentId]/logs/page.tsxnew file mode 100644index 00000000000..1cbcd7bbd90--- /dev/null+++ b/web/app/(commonLayout)/roster/agent/[agentId]/logs/page.tsx@@ -0,0 +1,13 @@+import { AgentDetailPage } from '@/features/agent-v2/agent-detail/page'++type PageProps = {+ params: Promise<{ agentId: string }>+}++export default async function Page({+ params,+}: PageProps) {+ const { agentId } = await params++ return <AgentDetailPage agentId={agentId} section="logs" />+}diff --git a/web/app/(commonLayout)/roster/agent/[agentId]/monitoring/page.tsx b/web/app/(commonLayout)/roster/agent/[agentId]/monitoring/page.tsxnew file mode 100644index 00000000000..ad61db5f8b8--- /dev/null+++ b/web/app/(commonLayout)/roster/agent/[agentId]/monitoring/page.tsx@@ -0,0 +1,13 @@+import { AgentDetailPage } from '@/features/agent-v2/agent-detail/page'++type PageProps = {+ params: Promise<{ agentId: string }>+}++export default async function Page({+ params,+}: PageProps) {+ const { agentId } = await params++ return <AgentDetailPage agentId={agentId} section="monitoring" />+}diff --git a/web/app/(commonLayout)/roster/agent/[agentId]/page.tsx b/web/app/(commonLayout)/roster/agent/[agentId]/page.tsxnew file mode 100644index 00000000000..470fa13f12c--- /dev/null+++ b/web/app/(commonLayout)/roster/agent/[agentId]/page.tsx@@ -0,0 +1,13 @@+import { redirect } from '@/next/navigation'++type PageProps = {+ params: Promise<{ agentId: string }>+}++export default async function Page({+ params,+}: PageProps) {+ const { agentId } = await params++ redirect(`/roster/agent/${agentId}/configure`)+}diff --git a/web/app/(commonLayout)/roster/feature-guard.ts b/web/app/(commonLayout)/roster/feature-guard.tsnew file mode 100644index 00000000000..41f74b6696e--- /dev/null+++ b/web/app/(commonLayout)/roster/feature-guard.ts@@ -0,0 +1,7 @@+import { env } from '@/env'+import { notFound } from '@/next/navigation'++export const guardAgentV2Route = () => {+ if (!env.NEXT_PUBLIC_ENABLE_AGENT_V2)+ notFound()+}diff --git a/web/app/(commonLayout)/roster/layout.tsx b/web/app/(commonLayout)/roster/layout.tsxnew file mode 100644index 00000000000..be88ab89e2c--- /dev/null+++ b/web/app/(commonLayout)/roster/layout.tsx@@ -0,0 +1,12 @@+import type { ReactNode } from 'react'+import { guardAgentV2Route } from './feature-guard'++export default function Layout({+ children,+}: {+ children: ReactNode+}) {+ guardAgentV2Route()++ return children+}diff --git a/web/app/(commonLayout)/roster/page.tsx b/web/app/(commonLayout)/roster/page.tsxnew file mode 100644index 00000000000..fff610b6448--- /dev/null+++ b/web/app/(commonLayout)/roster/page.tsx@@ -0,0 +1,5 @@+import RosterPage from '@/features/agent-v2/roster/page'++export default function Page() {+ return <RosterPage />+}diff --git a/web/app/(shareLayout)/agent/[token]/page.tsx b/web/app/(shareLayout)/agent/[token]/page.tsxnew file mode 100644index 00000000000..5dc2777c9c4--- /dev/null+++ b/web/app/(shareLayout)/agent/[token]/page.tsx@@ -0,0 +1,15 @@+'use client'++import * as React from 'react'+import ChatWithHistoryWrap from '@/app/components/base/chat/chat-with-history'+import AuthenticatedLayout from '../../components/authenticated-layout'++function Agent() {+ return (+ <AuthenticatedLayout>+ <ChatWithHistoryWrap />+ </AuthenticatedLayout>+ )+}++export default React.memo(Agent)diff --git a/web/app/components/app/configuration/config/agent/agent-tools/__tests__/setting-built-in-tool.spec.tsx b/web/app/components/app/configuration/config/agent/agent-tools/__tests__/setting-built-in-tool.spec.tsxindex 083e93b086d..cd72279fe38 100644--- a/web/app/components/app/configuration/config/agent/agent-tools/__tests__/setting-built-in-tool.spec.tsx+++ b/web/app/components/app/configuration/config/agent/agent-tools/__tests__/setting-built-in-tool.spec.tsx@@ -186,6 +186,20 @@ describe('SettingBuiltInTool', () => {expect(screen.getByTestId('mock-form')).toBeInTheDocument()})+ it('should render a masked drawer with balanced vertical offsets', async () => {+ const { baseElement } = renderComponent()+ await waitFor(() => {+ expect(screen.getByTestId('mock-form')).toBeInTheDocument()+ })++ expect(baseElement.querySelector('.bg-background-overlay')).toBeInTheDocument()+ const drawerPopup = baseElement.querySelector('[role="dialog"]')+ expect(drawerPopup).toHaveClass(+ 'data-[swipe-direction=right]:top-6',+ 'data-[swipe-direction=right]:bottom-6',+ )+ })+it('should call onSave with updated values when save button clicked', async () => {const { onSave } = renderComponent()await waitFor(() => expect(screen.getByTestId('mock-form')).toBeInTheDocument())diff --git a/web/app/components/app/configuration/config/agent/agent-tools/setting-built-in-tool.tsx b/web/app/components/app/configuration/config/agent/agent-tools/setting-built-in-tool.tsxindex ccfbd3be14b..113ef2a1c40 100644--- a/web/app/components/app/configuration/config/agent/agent-tools/setting-built-in-tool.tsx+++ b/web/app/components/app/configuration/config/agent/agent-tools/setting-built-in-tool.tsx@@ -181,9 +181,9 @@ const SettingBuiltInTool: FC<Props> = ({}}><DrawerPortal>- <DrawerBackdrop className="bg-transparent" />+ <DrawerBackdrop className="bg-background-overlay" /><DrawerViewport>- <DrawerPopup className={cn('justify-start bg-components-panel-bg! p-0! shadow-xl data-[swipe-direction=right]:top-16 data-[swipe-direction=right]:right-2 data-[swipe-direction=right]:bottom-2 data-[swipe-direction=right]:h-auto data-[swipe-direction=right]:w-[420px] data-[swipe-direction=right]:max-w-[420px] data-[swipe-direction=right]:rounded-2xl data-[swipe-direction=right]:border-[0.5px] data-[swipe-direction=right]:border-components-panel-border')}>+ <DrawerPopup className={cn('justify-start bg-components-panel-bg! p-0! shadow-xl data-[swipe-direction=right]:top-6 data-[swipe-direction=right]:right-2 data-[swipe-direction=right]:bottom-6 data-[swipe-direction=right]:h-auto data-[swipe-direction=right]:w-[420px] data-[swipe-direction=right]:max-w-[420px] data-[swipe-direction=right]:rounded-2xl data-[swipe-direction=right]:border-[0.5px] data-[swipe-direction=right]:border-components-panel-border')}><DrawerContent className="flex min-h-0 flex-1 flex-col p-0 pb-0">{isLoading && <Loading type="app" />}{!isLoading && (diff --git a/web/app/components/app/configuration/dataset-config/select-dataset/index.tsx b/web/app/components/app/configuration/dataset-config/select-dataset/index.tsxindex 45647160a01..8b1d7b106f8 100644--- a/web/app/components/app/configuration/dataset-config/select-dataset/index.tsx+++ b/web/app/components/app/configuration/dataset-config/select-dataset/index.tsx@@ -19,6 +19,7 @@ import { useInfiniteDatasets } from '@/service/knowledge/use-dataset'type ISelectDataSetProps = {isShow: boolean+ modal?: booleanonClose: () => voidselectedIds: string[]onSelect: (dataSet: DataSet[]) => void@@ -26,6 +27,7 @@ type ISelectDataSetProps = {const SelectDataSet: FC<ISelectDataSetProps> = ({isShow,+ modal,onClose,selectedIds,onSelect,@@ -90,8 +92,8 @@ const SelectDataSet: FC<ISelectDataSetProps> = ({}, [handleClose])return (- <Dialog open={isShow} onOpenChange={handleOpenChange}>- <DialogContent className="w-100 overflow-hidden">+ <Dialog modal={modal} open={isShow} onOpenChange={handleOpenChange}>+ <DialogContent backdropProps={{ forceRender: true }} className="w-100 overflow-hidden"><DialogTitle className="title-2xl-semi-bold text-text-primary">{t('feature.dataSet.selectTitle', { ns: 'appDebug' })}</DialogTitle>diff --git a/web/app/components/app/configuration/dataset-config/settings-modal/index.tsx b/web/app/components/app/configuration/dataset-config/settings-modal/index.tsxindex ba11de128db..5350bb04474 100644--- a/web/app/components/app/configuration/dataset-config/settings-modal/index.tsx+++ b/web/app/components/app/configuration/dataset-config/settings-modal/index.tsx@@ -30,6 +30,7 @@ import { RetrievalChangeTip, RetrievalSection } from './retrieval-section'type SettingsModalProps = {currentDataset: DataSet+ height?: stringonCancel: () => voidonSave: (newDataset: DataSet) => void}@@ -44,6 +45,7 @@ const labelClass = `const SettingsModal: FC<SettingsModalProps> = ({currentDataset,+ height = 'calc(100vh - 72px)',onCancel,onSave,}) => {@@ -186,9 +188,9 @@ const SettingsModal: FC<SettingsModalProps> = ({return (<div- className="flex w-full flex-col overflow-hidden rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg shadow-xl"+ className="flex min-h-0 w-full flex-col overflow-hidden rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg shadow-xl"style={{- height: 'calc(100vh - 72px)',+ height,}}ref={ref}>diff --git a/web/app/components/base/app-icon/index.tsx b/web/app/components/base/app-icon/index.tsxindex 1010720e838..fa83560c0ce 100644--- a/web/app/components/base/app-icon/index.tsx+++ b/web/app/components/base/app-icon/index.tsx@@ -8,10 +8,18 @@ import { useHover } from 'ahooks'import { cva } from 'class-variance-authority'import { init } from 'emoji-mart'import * as React from 'react'-import { useRef } from 'react'+import { useRef, useSyncExternalStore } from 'react'init({ data })+const subscribeHydrationState = () => () => {}++const useIsHydrated = () => useSyncExternalStore(+ subscribeHydrationState,+ () => true,+ () => false,+)+type AppIconProps = {size?: 'xs' | 'tiny' | 'small' | 'medium' | 'large' | 'xl' | 'xxl'rounded?: boolean@@ -105,9 +113,20 @@ const AppIcon: FC<AppIconProps> = ({}) => {const isValidImageIcon = iconType === 'image' && imageUrlconst emojiIcon = (icon && icon !== '') ? icon : '🤖'- const Icon = <em-emoji key={emojiIcon} id={emojiIcon} />+ const isHydrated = useIsHydrated()+ const Icon = isHydrated ? <em-emoji key={emojiIcon} id={emojiIcon} /> : emojiIconconst wrapperRef = useRef<HTMLSpanElement>(null)const isHovering = useHover(wrapperRef)+ const handleKeyDown = (event: React.KeyboardEvent<HTMLSpanElement>) => {+ if (!onClick)+ return++ if (event.key !== 'Enter' && event.key !== ' ')+ return++ event.preventDefault()+ onClick()+ }return (<span@@ -115,6 +134,9 @@ const AppIcon: FC<AppIconProps> = ({className={cn(appIconVariants({ size, rounded }), className)}style={{ background: isValidImageIcon ? undefined : (background || '#FFEAD5') }}onClick={onClick}+ onKeyDown={onClick ? handleKeyDown : undefined}+ role={onClick ? 'button' : undefined}+ tabIndex={onClick ? 0 : undefined}>{isValidImageIcondiff --git a/web/app/components/base/features/new-feature-panel/__tests__/index.spec.tsx b/web/app/components/base/features/new-feature-panel/__tests__/index.spec.tsxindex 4947d2c7c01..7946523c7ba 100644--- a/web/app/components/base/features/new-feature-panel/__tests__/index.spec.tsx+++ b/web/app/components/base/features/new-feature-panel/__tests__/index.spec.tsx@@ -57,6 +57,7 @@ const renderPanel = (props: Partial<{onClose: () => voidinWorkflow: booleanshowFileUpload: boolean+ showAnnotationReply: boolean}> = {}) => {return render(<FeaturesProvider features={defaultFeatures}>@@ -68,6 +69,7 @@ const renderPanel = (props: Partial<{onClose={props.onClose ?? vi.fn()}inWorkflow={props.inWorkflow}showFileUpload={props.showFileUpload}+ showAnnotationReply={props.showAnnotationReply}/></FeaturesProvider>,)@@ -191,5 +193,11 @@ describe('NewFeaturePanel', () => {expect(screen.queryByText(/feature\.annotation\.title/)).not.toBeInTheDocument()})++ it('should not render AnnotationReply when showAnnotationReply is false', () => {+ renderPanel({ isChatMode: true, inWorkflow: false, showAnnotationReply: false })++ expect(screen.queryByText(/feature\.annotation\.title/)).not.toBeInTheDocument()+ })})})diff --git a/web/app/components/base/features/new-feature-panel/index.tsx b/web/app/components/base/features/new-feature-panel/index.tsxindex 3c8f441521a..2cb21d9382c 100644--- a/web/app/components/base/features/new-feature-panel/index.tsx+++ b/web/app/components/base/features/new-feature-panel/index.tsx@@ -1,3 +1,4 @@+import type { ReactNode } from 'react'import type { OnFeaturesChange } from '@/app/components/base/features/types'import type { InputVar } from '@/app/components/workflow/types'import type { PromptVariable } from '@/models/debug'@@ -26,9 +27,14 @@ type Props = Readonly<{onClose: () => voidinWorkflow?: booleanshowFileUpload?: boolean+ showModeration?: boolean+ showAnnotationReply?: booleanpromptVariables?: PromptVariable[]workflowVariables?: InputVar[]onAutoAddPromptVariable?: (variable: PromptVariable[]) => void+ title?: ReactNode+ description?: ReactNode+ drawerClassName?: string}>const NewFeaturePanel = ({@@ -39,9 +45,14 @@ const NewFeaturePanel = ({onClose,inWorkflow = true,showFileUpload = true,+ showModeration = true,+ showAnnotationReply = true,promptVariables,workflowVariables,onAutoAddPromptVariable,+ title,+ description,+ drawerClassName,}: Props) => {const { t } = useTranslation()const { data: speech2textDefaultModel } = useDefaultModel(ModelTypeEnum.speech2text)@@ -52,13 +63,14 @@ const NewFeaturePanel = ({show={show}onClose={onClose}inWorkflow={inWorkflow}+ className={drawerClassName}><div className="flex h-full grow flex-col">{/* header */}<div className="flex shrink-0 justify-between p-4 pb-3"><div>- <div className="system-xl-semibold text-text-primary">{t('common.features', { ns: 'workflow' })}</div>- <div className="body-xs-regular text-text-tertiary">{t('common.featuresDescription', { ns: 'workflow' })}</div>+ <div className="system-xl-semibold text-text-primary">{title ?? t('common.features', { ns: 'workflow' })}</div>+ <div className="body-xs-regular text-text-tertiary">{description ?? t('common.featuresDescription', { ns: 'workflow' })}</div></div><DrawerCloseButtonaria-label={t('operation.close', { ns: 'common' })}@@ -93,8 +105,8 @@ const NewFeaturePanel = ({{isChatMode && (<Citation disabled={disabled} onChange={onChange} />)}- {(isChatMode || !inWorkflow) && <Moderation disabled={disabled} onChange={onChange} />}- {!inWorkflow && isChatMode && (+ {showModeration && (isChatMode || !inWorkflow) && <Moderation disabled={disabled} onChange={onChange} />}+ {showAnnotationReply && !inWorkflow && isChatMode && (<AnnotationReply disabled={disabled} onChange={onChange} />)}</div>diff --git a/web/app/components/base/features/new-feature-panel/moderation/__tests__/moderation-setting-modal.spec.tsx b/web/app/components/base/features/new-feature-panel/moderation/__tests__/moderation-setting-modal.spec.tsxindex 4f55e6eb7b2..c6359f3713b 100644--- a/web/app/components/base/features/new-feature-panel/moderation/__tests__/moderation-setting-modal.spec.tsx+++ b/web/app/components/base/features/new-feature-panel/moderation/__tests__/moderation-setting-modal.spec.tsx@@ -302,6 +302,37 @@ describe('ModerationSettingModal', () => {}))})+ it('should save the latest preset response when content textarea changes', async () => {+ const data: ModerationConfig = {+ ...defaultData,+ config: {+ keywords: 'bad',+ inputs_config: { enabled: true, preset_response: 'blocked' },+ outputs_config: { enabled: false, preset_response: '' },+ },+ }+ await renderModal(+ <ModerationSettingModal+ data={data}+ onCancel={vi.fn()}+ onSave={onSave}+ />,+ )++ fireEvent.change(screen.getByRole('textbox', { name: /feature\.moderation\.modal\.content\.preset/ }), {+ target: { value: 'updated blocked response' },+ })+ fireEvent.click(screen.getByText(/operation\.save/))++ expect(onSave).toHaveBeenCalledWith(expect.objectContaining({+ config: expect.objectContaining({+ inputs_config: expect.objectContaining({+ preset_response: 'updated blocked response',+ }),+ }),+ }))+ })+it('should show api selector when api type is selected', async () => {await renderModal(<ModerationSettingModal@@ -702,7 +733,10 @@ describe('ModerationSettingModal', () => {expect(mockSetShowAccountSettingModal).toHaveBeenCalled()- expect(mockSetShowAccountSettingModal).toHaveBeenCalledWith({ payload: 'provider' })+ expect(mockSetShowAccountSettingModal).toHaveBeenCalledWith({+ payload: 'provider',+ onCancelCallback: expect.any(Function),+ })})it('should not save when OpenAI type is selected but not configured', async () => {diff --git a/web/app/components/base/features/new-feature-panel/moderation/moderation-content.tsx b/web/app/components/base/features/new-feature-panel/moderation/moderation-content.tsxindex 9df107bf848..b008490ae6f 100644--- a/web/app/components/base/features/new-feature-panel/moderation/moderation-content.tsx+++ b/web/app/components/base/features/new-feature-panel/moderation/moderation-content.tsx@@ -2,6 +2,7 @@ import type { FC } from 'react'import type { ModerationContentConfig } from '@/models/debug'import { Switch } from '@langgenius/dify-ui/switch'import { Textarea } from '@langgenius/dify-ui/textarea'+import { useState } from 'react'import { useTranslation } from 'react-i18next'type ModerationContentProps = {@@ -19,57 +20,71 @@ const ModerationContent: FC<ModerationContentProps> = ({onConfigChange,}) => {const { t } = useTranslation()+ const [presetResponse, setPresetResponse] = useState(config.preset_response || '')const handleConfigChange = (field: string, value: boolean | string) => {if (field === 'preset_response' && typeof value === 'string')value = value.slice(0, 100)- onConfigChange({ ...config, [field]: value })++ onConfigChange({+ ...config,+ preset_response: field === 'preset_response' ? value as string : presetResponse,+ [field]: value,+ })+ }++ const handlePresetResponseChange = (value: string) => {+ const nextValue = value.slice(0, 100)+ setPresetResponse(nextValue)+ handleConfigChange('preset_response', nextValue)}return (- <div className="py-2">- <div className="rounded-lg border border-components-panel-border bg-components-panel-bg">- <div className="flex h-10 items-center justify-between rounded-lg px-3">- <div className="shrink-0 text-sm font-medium text-text-primary">{title}</div>- <div className="flex grow items-center justify-end">- {- info && (- <div className="mr-2 truncate text-xs text-text-tertiary" title={info}>{info}</div>- )- }- <Switch- size="lg"- checked={config.enabled}- onCheckedChange={v => handleConfigChange('enabled', v)}- />- </div>+ <div className="rounded-xl border-[0.5px] border-components-panel-border-subtle bg-components-panel-on-panel-item-bg shadow-xs">+ <div className="flex min-h-10 items-center gap-2 px-3 py-2">+ <div className="min-w-0 flex-1 system-sm-medium text-text-secondary">{title}</div>+ <div className="flex min-w-0 shrink-0 items-center justify-end">+ {+ info && (+ <div className="mr-2 truncate system-xs-regular text-text-tertiary" title={info}>{info}</div>+ )+ }+ <Switch+ checked={config.enabled}+ onCheckedChange={v => handleConfigChange('enabled', v)}+ /></div>- {- config.enabled && showPreset && (- <div className="rounded-lg bg-components-panel-bg px-3 pt-1 pb-3">- <div className="flex h-8 items-center justify-between text-[13px] font-medium text-text-secondary">+ </div>+ {+ config.enabled && showPreset && (+ <div className="px-3 pt-0.5 pb-3">+ <div className="flex h-8 items-center justify-between gap-2">+ <span className="system-2xs-medium-uppercase text-text-secondary">{t('feature.moderation.modal.content.preset', { ns: 'appDebug' })}- <span className="text-xs font-normal text-text-tertiary">{t('feature.moderation.modal.content.supportMarkdown', { ns: 'appDebug' })}</span>- </div>- {/* Keep this counter composed locally; extract only if more textarea counter cases repeat. */}- <div className="relative h-20">- <Textarea- aria-label={t('feature.moderation.modal.content.preset', { ns: 'appDebug' }) as string}- value={config.preset_response || ''}- className="size-full resize-none pb-8"- placeholder={t('feature.moderation.modal.content.placeholder', { ns: 'appDebug' }) || ''}- onValueChange={value => handleConfigChange('preset_response', value)}- />- <div className="absolute right-2 bottom-2 flex h-5 items-center rounded-md bg-background-section px-1 text-xs font-medium text-text-quaternary">- <span>{(config.preset_response || '').length}</span>- /- <span className="text-text-tertiary">100</span>- </div>+ </span>+ <span className="flex shrink-0 items-center gap-0.5 rounded bg-background-section px-1 py-0.5 system-2xs-medium-uppercase text-text-tertiary">+ <span className="i-ri-markdown-line size-3" aria-hidden />+ {t('feature.moderation.modal.content.supportMarkdown', { ns: 'appDebug' })}+ </span>+ </div>+ {/* Keep this counter composed locally; extract only if more textarea counter cases repeat. */}+ <div className="relative h-20">+ <Textarea+ aria-label={t('feature.moderation.modal.content.preset', { ns: 'appDebug' }) as string}+ value={presetResponse}+ className="size-full resize-none pb-8"+ placeholder={t('feature.moderation.modal.content.placeholder', { ns: 'appDebug' }) || ''}+ onValueChange={handlePresetResponseChange}+ />+ <div className="absolute right-2 bottom-2 flex h-5 items-center rounded-md bg-background-section px-1 system-2xs-medium-uppercase text-text-quaternary">+ <span>{presetResponse.length}</span>+ /+ <span className="text-text-tertiary">100</span></div></div>- )- }- </div>+ </div>+ )+ }</div>)}diff --git a/web/app/components/base/features/new-feature-panel/moderation/moderation-setting-modal.tsx b/web/app/components/base/features/new-feature-panel/moderation/moderation-setting-modal.tsxindex 163f13819a7..313e399e2e5 100644--- a/web/app/components/base/features/new-feature-panel/moderation/moderation-setting-modal.tsx+++ b/web/app/components/base/features/new-feature-panel/moderation/moderation-setting-modal.tsx@@ -1,4 +1,4 @@-import type { FC } from 'react'+import type { FC, ReactNode } from 'react'import type { CodeBasedExtensionItem } from '@/models/common'import type { ModerationConfig, ModerationContentConfig } from '@/models/debug'import { Button } from '@langgenius/dify-ui/button'@@ -6,7 +6,7 @@ import { cn } from '@langgenius/dify-ui/cn'import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'import { Textarea } from '@langgenius/dify-ui/textarea'import { toast } from '@langgenius/dify-ui/toast'-import { useState } from 'react'+import { useCallback, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import Divider from '@/app/components/base/divider'import { ApiBasedExtensionSelector } from '@/app/components/header/account-setting/api-based-extension-page/selector'@@ -27,6 +27,27 @@ type Provider = {form_schema?: CodeBasedExtensionItem['form_schema']}+function ProviderIcon({ type }: { type: string }) {+ if (type === 'openai_moderation')+ return <span className="i-ri-openai-fill size-4 text-text-secondary" aria-hidden />++ if (type === 'keywords')+ return <span className="i-ri-search-line size-4 text-util-colors-green-green-600" aria-hidden />++ return <span className="i-ri-image-line size-4 text-util-colors-violet-violet-600" aria-hidden />+}++function LabeledDivider({ children }: { children: ReactNode }) {+ return (+ <div className="flex w-full items-center gap-2">+ <span className="shrink-0 system-xs-medium-uppercase text-text-tertiary">+ {children}+ </span>+ <Divider bgStyle="gradient" className="my-0 h-px flex-1" />+ </div>+ )+}+type ModerationSettingModalProps = {data: ModerationConfigonCancel: () => void@@ -41,12 +62,27 @@ const ModerationSettingModal: FC<ModerationSettingModalProps> = ({const { t } = useTranslation()const docLink = useDocLink()const locale = useLocale()- const { data: modelProviders, isPending: isLoading } = useModelProviders()+ const { data: modelProviders, isPending: isLoading, refetch: refetchModelProviders } = useModelProviders()+ const localeDataRef = useRef<ModerationConfig>(data)const [localeData, setLocaleData] = useState<ModerationConfig>(data)const openIntegrationsSetting = useIntegrationsSetting()+ const updateLocaleData = useCallback((+ update: ModerationConfig | ((current: ModerationConfig) => ModerationConfig),+ options: { render?: boolean } = {},+ ) => {+ const nextLocaleData = typeof update === 'function'+ ? update(localeDataRef.current)+ : update++ localeDataRef.current = nextLocaleData++ if (options.render !== false)+ setLocaleData(nextLocaleData)+ }, [])const handleOpenSettingsModal = () => {openIntegrationsSetting({payload: ACCOUNT_SETTING_TAB.PROVIDER,+ onCancelCallback: refetchModelProviders,})}const { data: codeBasedExtensionList } = useCodeBasedExtensions('moderation')@@ -85,20 +121,20 @@ const ModerationSettingModal: FC<ModerationSettingModalProps> = ({const currentProvider = providers.find(provider => provider.key === localeData.type)const handleDataTypeChange = (type: string) => {- let config: undefined | Record<string, any>+ let config: undefined | Record<string, string>const currProvider = providers.find(provider => provider.key === type)if (systemTypes.findIndex(t => t === type) < 0 && currProvider?.form_schema) {config = currProvider?.form_schema.reduce((prev, next) => {prev[next.variable] = next.defaultreturn prev- }, {} as Record<string, any>)+ }, {} as Record<string, string>)}- setLocaleData({- ...localeData,+ updateLocaleData(current => ({+ ...current,type,config,- })+ }))}const handleDataKeywordsChange = (value: string) => {@@ -111,43 +147,46 @@ const ModerationSettingModal: FC<ModerationSettingModalProps> = ({return prev}, [])- setLocaleData({- ...localeData,+ updateLocaleData(current => ({+ ...current,config: {- ...localeData.config,+ ...current.config,keywords: arr.slice(0, 100).join('\n'),},- })+ }))}const handleDataContentChange = (contentType: string, contentConfig: ModerationContentConfig) => {- setLocaleData({- ...localeData,+ const previousContentConfig = localeDataRef.current.config?.[contentType] as ModerationContentConfig | undefined+ const shouldRender = previousContentConfig?.enabled !== contentConfig.enabled++ updateLocaleData(current => ({+ ...current,config: {- ...localeData.config,+ ...current.config,[contentType]: contentConfig,},- })+ }), { render: shouldRender })}const handleDataApiBasedChange = (apiBasedExtensionId: string) => {- setLocaleData({- ...localeData,+ updateLocaleData(current => ({+ ...current,config: {- ...localeData.config,+ ...current.config,api_based_extension_id: apiBasedExtensionId,},- })+ }))}const handleDataExtraChange = (extraValue: Record<string, string>) => {- setLocaleData({- ...localeData,+ updateLocaleData(current => ({+ ...current,config: {- ...localeData.config,+ ...current.config,...extraValue,},- })+ }))}const formatData = (originData: ModerationConfig) => {@@ -179,115 +218,116 @@ const ModerationSettingModal: FC<ModerationSettingModalProps> = ({}const handleSave = () => {+ const currentLocaleData = localeDataRef.current+ const providerForSave = providers.find(provider => provider.key === currentLocaleData.type)+/* v8 ignore next -- UI-invariant guard: same condition is used in Save button disabled logic, so when true handleSave has no user-triggerable invocation path. @preserve */- if (localeData.type === 'openai_moderation' && !isOpenAIProviderConfigured)+ if (currentLocaleData.type === 'openai_moderation' && !isOpenAIProviderConfigured)return- if (!localeData.config?.inputs_config?.enabled && !localeData.config?.outputs_config?.enabled) {+ if (!currentLocaleData.config?.inputs_config?.enabled && !currentLocaleData.config?.outputs_config?.enabled) {toast.error(t('feature.moderation.modal.content.condition', { ns: 'appDebug' }))return}- if (localeData.type === 'keywords' && !localeData.config.keywords) {+ if (currentLocaleData.type === 'keywords' && !currentLocaleData.config.keywords) {toast.error(t('errorMessage.valueOfVarRequired', { ns: 'appDebug', key: locale !== LanguagesSupported[1] ? 'keywords' : '关键词' }))return}- if (localeData.type === 'api' && !localeData.config.api_based_extension_id) {+ if (currentLocaleData.type === 'api' && !currentLocaleData.config.api_based_extension_id) {toast.error(t('errorMessage.valueOfVarRequired', { ns: 'appDebug', key: locale !== LanguagesSupported[1] ? 'API Extension' : 'API 扩展' }))return}- if (systemTypes.findIndex(t => t === localeData.type) < 0 && currentProvider?.form_schema) {- for (let i = 0; i < currentProvider.form_schema.length; i++) {- if (!localeData.config?.[currentProvider.form_schema[i]!.variable] && currentProvider.form_schema[i]!.required) {- toast.error(t('errorMessage.valueOfVarRequired', { ns: 'appDebug', key: locale !== LanguagesSupported[1] ? currentProvider.form_schema[i]!.label['en-US'] : currentProvider.form_schema[i]!.label['zh-Hans'] }))+ if (systemTypes.findIndex(t => t === currentLocaleData.type) < 0 && providerForSave?.form_schema) {+ for (let i = 0; i < providerForSave.form_schema.length; i++) {+ if (!currentLocaleData.config?.[providerForSave.form_schema[i]!.variable] && providerForSave.form_schema[i]!.required) {+ toast.error(t('errorMessage.valueOfVarRequired', { ns: 'appDebug', key: locale !== LanguagesSupported[1] ? providerForSave.form_schema[i]!.label['en-US'] : providerForSave.form_schema[i]!.label['zh-Hans'] }))return}}}- if (localeData.config.inputs_config?.enabled && !localeData.config.inputs_config.preset_response && localeData.type !== 'api') {+ if (currentLocaleData.config.inputs_config?.enabled && !currentLocaleData.config.inputs_config.preset_response && currentLocaleData.type !== 'api') {toast.error(t('feature.moderation.modal.content.errorMessage', { ns: 'appDebug' }))return}- if (localeData.config.outputs_config?.enabled && !localeData.config.outputs_config.preset_response && localeData.type !== 'api') {+ if (currentLocaleData.config.outputs_config?.enabled && !currentLocaleData.config.outputs_config.preset_response && currentLocaleData.type !== 'api') {toast.error(t('feature.moderation.modal.content.errorMessage', { ns: 'appDebug' }))return}- onSave(formatData(localeData))+ onSave(formatData(currentLocaleData))}return (<Dialog open>- <DialogContent className="mt-14! w-[600px]! max-w-none! border-none p-6! text-left align-middle">-- <div className="flex items-center justify-between">- <div className="title-2xl-semi-bold text-text-primary">{t('feature.moderation.modal.title', { ns: 'appDebug' })}</div>+ <DialogContent className="mt-14! w-[600px]! max-w-none! overflow-hidden border-[0.5px]! border-components-panel-border! p-0! text-left align-middle">+ <div className="flex items-start gap-2 px-6 pt-6 pr-14 pb-3">+ <div className="title-2xl-semi-bold text-text-primary">+ {t('feature.moderation.modal.title', { ns: 'appDebug' })}+ </div><buttontype="button"aria-label={t('operation.close', { ns: 'common' })}- className="cursor-pointer border-none bg-transparent p-1 focus-visible:ring-1 focus-visible:ring-components-input-border-active focus-visible:outline-hidden"+ className="absolute top-5 right-5 flex size-8 cursor-pointer items-center justify-center rounded-lg border-none bg-transparent text-text-tertiary hover:bg-state-base-hover hover:text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"onClick={onCancel}>- <span className="i-ri-close-line size-4 text-text-tertiary" aria-hidden="true" />+ <span className="i-ri-close-line size-[18px]" aria-hidden="true" /></button></div>- <div className="py-2">- <div className="text-sm/9 font-medium text-text-primary">- {t('feature.moderation.modal.provider.title', { ns: 'appDebug' })}- </div>- <div className="grid grid-cols-3 gap-2.5">- {- providers.map(provider => (- <div+ <div className="flex flex-col gap-4 px-6 py-3">+ <div className="flex flex-col gap-1">+ <div className="system-sm-medium text-text-secondary">+ {t('feature.moderation.modal.provider.title', { ns: 'appDebug' })}+ </div>+ <div className="grid grid-cols-3 gap-2">+ {providers.map(provider => (+ <button+ type="button"key={provider.key}className={cn(- 'flex h-8 cursor-default items-center rounded-md border border-components-option-card-option-border bg-components-option-card-option-bg px-2 system-sm-regular text-text-secondary',- localeData.type !== provider.key && 'cursor-pointer hover:border-components-option-card-option-border-hover hover:bg-components-option-card-option-bg-hover hover:shadow-xs',- localeData.type === provider.key && 'border-[1.5px] border-components-option-card-option-selected-border bg-components-option-card-option-selected-bg system-sm-medium shadow-xs',+ 'flex min-h-[68px] flex-col items-start justify-center gap-1.5 rounded-xl border border-components-option-card-option-border bg-components-option-card-option-bg px-3 py-2 text-left text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden',+ localeData.type !== provider.key && 'hover:border-components-option-card-option-border-hover hover:bg-components-option-card-option-bg-hover hover:shadow-xs',+ localeData.type === provider.key && 'border-[1.5px] border-components-option-card-option-selected-border bg-components-option-card-option-selected-bg shadow-xs',localeData.type === 'openai_moderation' && provider.key === 'openai_moderation' && !isOpenAIProviderConfigured && 'text-text-disabled',)}onClick={() => handleDataTypeChange(provider.key)}>- <div className={cn(- 'mr-2 size-4 rounded-full border border-components-radio-border bg-components-radio-bg shadow-xs',- localeData.type === provider.key && 'border-[5px] border-components-radio-border-checked',- )}- >+ <div className="flex size-8 items-center justify-center rounded-lg border-[0.5px] border-divider-regular bg-background-default-dodge">+ <ProviderIcon type={provider.key} /></div>- {provider.name}- </div>- ))- }- </div>- {- !isLoading && !isOpenAIProviderConfigured && localeData.type === 'openai_moderation' && (+ <span className="w-full truncate system-xs-regular">+ {provider.name}+ </span>+ </button>+ ))}+ </div>+ {!isLoading && !isOpenAIProviderConfigured && localeData.type === 'openai_moderation' && (<div className="mt-2 flex items-center rounded-lg border border-[#FEF0C7] bg-[#FFFAEB] px-3 py-2"><span className="mr-1 i-custom-vender-line-general-info-circle h-4 w-4 text-[#F79009]" /><div className="flex items-center text-xs font-medium text-gray-700">{t('feature.moderation.modal.openaiNotConfig.before', { ns: 'appDebug' })}- <span+ <button+ type="button"className="cursor-pointer text-primary-600"onClick={handleOpenSettingsModal}>- + {t('settings.provider', { ns: 'common' })}- - </span>+ + </button>{t('feature.moderation.modal.openaiNotConfig.after', { ns: 'appDebug' })}</div></div>- )- }- </div>- {- localeData.type === 'keywords' && (- <div className="py-2">- <div className="mb-1 text-sm font-medium text-text-primary">{t('feature.moderation.modal.provider.keywords', { ns: 'appDebug' })}</div>- <div className="mb-2 text-xs text-text-tertiary">{t('feature.moderation.modal.keywords.tip', { ns: 'appDebug' })}</div>+ )}+ </div>+ {localeData.type === 'keywords' && (+ <div className="flex flex-col gap-1">+ <div className="system-sm-medium text-text-secondary">{t('feature.moderation.modal.provider.keywords', { ns: 'appDebug' })}</div>+ <div className="system-xs-regular text-text-tertiary">{t('feature.moderation.modal.keywords.tip', { ns: 'appDebug' })}</div>{/* Keep this counter composed locally; extract only if more textarea counter cases repeat. */}<div className="relative h-[88px]"><Textarea@@ -297,7 +337,7 @@ const ModerationSettingModal: FC<ModerationSettingModalProps> = ({className="size-full resize-none pb-8"placeholder={t('feature.moderation.modal.keywords.placeholder', { ns: 'appDebug' }) || ''}/>- <div className="absolute right-2 bottom-2 flex h-5 items-center rounded-md bg-background-section px-1 text-xs font-medium text-text-quaternary">+ <div className="absolute right-2 bottom-2 flex h-5 items-center rounded-md bg-background-section px-1 system-2xs-medium-uppercase text-text-quaternary"><span>{(localeData.config?.keywords || '').split('\n').filter(Boolean).length}</span>/<span className="text-text-tertiary">@@ -307,18 +347,16 @@ const ModerationSettingModal: FC<ModerationSettingModalProps> = ({</div></div></div>- )- }- {- localeData.type === 'api' && (- <div className="py-2">- <div className="flex h-9 items-center justify-between">- <div className="text-sm font-medium text-text-primary">{t('apiBasedExtension.selector.title', { ns: 'common' })}</div>+ )}+ {localeData.type === 'api' && (+ <div className="flex flex-col gap-1">+ <div className="flex h-6 items-center justify-between">+ <div className="system-sm-medium text-text-secondary">{t('apiBasedExtension.selector.title', { ns: 'common' })}</div><ahref={docLink('/use-dify/workspace/api-extension/api-extension')}target="_blank"rel="noopener noreferrer"- className="group flex items-center text-xs text-text-tertiary hover:text-primary-600"+ className="group flex items-center system-xs-regular text-text-tertiary hover:text-primary-600"><span className="mr-1 i-custom-vender-line-education-book-open-01 size-3 text-text-tertiary group-hover:text-primary-600" />{t('apiBasedExtension.link', { ns: 'common' })}@@ -329,46 +367,51 @@ const ModerationSettingModal: FC<ModerationSettingModalProps> = ({onChange={handleDataApiBasedChange}/></div>- )- }- {- systemTypes.findIndex(t => t === localeData.type) < 0- && currentProvider?.form_schema- && (- <FormGeneration- forms={currentProvider?.form_schema}- value={localeData.config}- onChange={handleDataExtraChange}+ )}+ {systemTypes.findIndex(t => t === localeData.type) < 0+ && currentProvider?.form_schema+ && (+ <FormGeneration+ forms={currentProvider?.form_schema}+ value={localeData.config}+ onChange={handleDataExtraChange}+ />+ )}+ <div className="flex flex-col gap-2">+ <LabeledDivider>{t('feature.moderation.title', { ns: 'appDebug' })}</LabeledDivider>+ <ModerationContent+ key={`inputs-${localeData.type}-${localeData.config?.inputs_config?.preset_response ?? ''}`}+ title={t('feature.moderation.modal.content.input', { ns: 'appDebug' }) || ''}+ config={localeData.config?.inputs_config || { enabled: false, preset_response: '' }}+ onConfigChange={config => handleDataContentChange('inputs_config', config)}+ info={(localeData.type === 'api' && t('feature.moderation.modal.content.fromApi', { ns: 'appDebug' })) || ''}+ showPreset={localeData.type !== 'api'}/>- )- }- <Divider bgStyle="gradient" className="my-3 h-px" />- <ModerationContent- title={t('feature.moderation.modal.content.input', { ns: 'appDebug' }) || ''}- config={localeData.config?.inputs_config || { enabled: false, preset_response: '' }}- onConfigChange={config => handleDataContentChange('inputs_config', config)}- info={(localeData.type === 'api' && t('feature.moderation.modal.content.fromApi', { ns: 'appDebug' })) || ''}- showPreset={localeData.type !== 'api'}- />- <ModerationContent- title={t('feature.moderation.modal.content.output', { ns: 'appDebug' }) || ''}- config={localeData.config?.outputs_config || { enabled: false, preset_response: '' }}- onConfigChange={config => handleDataContentChange('outputs_config', config)}- info={(localeData.type === 'api' && t('feature.moderation.modal.content.fromApi', { ns: 'appDebug' })) || ''}- showPreset={localeData.type !== 'api'}- />- <div className="mt-1 mb-8 text-xs font-medium text-text-tertiary">{t('feature.moderation.modal.content.condition', { ns: 'appDebug' })}</div>- <div className="flex items-center justify-end">+ <ModerationContent+ key={`outputs-${localeData.type}-${localeData.config?.outputs_config?.preset_response ?? ''}`}+ title={t('feature.moderation.modal.content.output', { ns: 'appDebug' }) || ''}+ config={localeData.config?.outputs_config || { enabled: false, preset_response: '' }}+ onConfigChange={config => handleDataContentChange('outputs_config', config)}+ info={(localeData.type === 'api' && t('feature.moderation.modal.content.fromApi', { ns: 'appDebug' })) || ''}+ showPreset={localeData.type !== 'api'}+ />+ <div className="py-0.5 system-xs-regular text-text-tertiary">{t('feature.moderation.modal.content.condition', { ns: 'appDebug' })}</div>+ </div>+ </div>+ <div className="flex h-[76px] items-center justify-end gap-2 px-6 pt-5 pb-6"><ButtononClick={onCancel}- className="mr-2"+ size="medium"+ className="min-w-[72px]">{t('operation.cancel', { ns: 'common' })}</Button><Buttonvariant="primary"+ size="medium"onClick={handleSave}disabled={localeData.type === 'openai_moderation' && !isOpenAIProviderConfigured}+ className="min-w-[72px]">{t('operation.save', { ns: 'common' })}</Button>diff --git a/web/app/components/base/icons/src/vender/workflow/Agent.json b/web/app/components/base/icons/src/vender/workflow/Agent.jsonindex 996040ee091..a195e8d6f27 100644--- a/web/app/components/base/icons/src/vender/workflow/Agent.json+++ b/web/app/components/base/icons/src/vender/workflow/Agent.json@@ -4,9 +4,9 @@"isRootNode": true,"name": "svg","attributes": {- "width": "16",- "height": "16",- "viewBox": "0 0 16 16",+ "width": "24",+ "height": "24",+ "viewBox": "0 0 24 24","fill": "none","xmlns": "http://www.w3.org/2000/svg"},@@ -15,35 +15,27 @@"type": "element","name": "g","attributes": {- "id": "agent"+ "id": "agent",+ "transform": "translate(2.5 1)"},"children": [{"type": "element",- "name": "g",+ "name": "path","attributes": {- "id": "Vector"+ "d": "M3.3178 20.9524V15.7184C3.31774 15.7136 3.31456 15.6845 3.28404 15.6468L3.24312 15.6069C1.26589 13.9971 0 11.5398 0 8.78813C0.000122972 3.93464 3.93464 0.000122969 8.78813 0C13.5146 0 17.3698 3.73066 17.5691 8.40858C17.5712 8.45846 17.5841 8.48161 17.5865 8.48531L19.3226 11.089C19.7937 11.7956 19.6309 12.7481 18.9513 13.2579L17.5998 14.2707C17.5851 14.2819 17.5763 14.2996 17.5763 14.3178V15.4237C17.576 17.2235 16.1176 18.682 14.3178 18.6822H13.2119C13.1798 18.6822 13.1537 18.7085 13.1536 18.7405V20.9524C13.1536 21.5309 12.6845 21.9999 12.1059 22C11.5274 22 11.0583 21.531 11.0583 20.9524V18.7405C11.0584 17.5513 12.0226 16.587 13.2119 16.587H14.3178C14.9604 16.5868 15.4808 16.0663 15.481 15.4237V14.3178C15.481 13.64 15.8006 13.0016 16.3424 12.595L17.3195 11.8614L15.8432 9.64853C15.603 9.28835 15.4913 8.88291 15.4749 8.49758C15.323 4.93639 12.3872 2.09524 8.78813 2.09524C5.09181 2.09536 2.09536 5.09181 2.09524 8.78813C2.09524 10.883 3.05647 12.7533 4.56594 13.9822C5.0571 14.3822 5.41299 15.0012 5.41304 15.7184V20.9524C5.41304 21.5309 4.94385 21.9998 4.36542 22C3.78684 22 3.3178 21.531 3.3178 20.9524Z",+ "fill": "currentColor"},- "children": [- {- "type": "element",- "name": "path",- "attributes": {- "d": "M14.7401 5.80454C14.5765 4.77996 14.1638 3.79808 13.5306 2.97273C12.8973 2.14738 12.0648 1.48568 11.1185 1.06589C10.1722 0.646098 9.12632 0.461106 8.08751 0.546487C7.05582 0.624753 6.04548 0.966277 5.17744 1.53548C4.3094 2.09758 3.58366 2.88024 3.09272 3.79808C2.59466 4.70881 2.33852 5.7405 2.33852 6.7793V7.22756L1.25703 9.3692C1.04357 9.80322 1.22145 10.3368 1.65547 10.5574L2.3314 10.8989V12.3006C2.3314 12.82 2.53063 13.3038 2.90061 13.6738C3.2706 14.0367 3.75442 14.243 4.27382 14.243H6.01702V14.7624C6.01702 15.1538 6.3372 15.4739 6.72853 15.4739C7.11986 15.4739 7.44004 15.1538 7.44004 14.7624V13.7094C7.44004 13.2185 7.04159 12.82 6.55065 12.82H4.27382C4.13864 12.82 4.00345 12.7631 3.91095 12.6706C3.81846 12.5781 3.76154 12.4429 3.76154 12.3077V10.5716C3.76154 10.2301 3.56943 9.92417 3.2706 9.77476L2.77254 9.52573L3.66904 7.73984C3.72596 7.61889 3.76154 7.4837 3.76154 7.34851V6.77219C3.76154 5.96818 3.96076 5.17129 4.34498 4.4669C4.72919 3.76251 5.28417 3.15772 5.9601 2.7237C6.63603 2.28968 7.41158 2.02643 8.20847 1.96239C9.00536 1.89835 9.81648 2.04066 10.5493 2.36795C11.2822 2.69524 11.9225 3.20042 12.4135 3.84077C12.8973 4.47402 13.2246 5.23533 13.3456 6.02511C13.4665 6.81488 13.3954 7.63312 13.125 8.38731C12.8617 9.12017 12.4206 9.78187 11.8585 10.3084C11.6735 10.4792 11.5668 10.7139 11.5668 10.9701V14.7624C11.5668 15.1538 11.887 15.4739 12.2783 15.4739C12.6696 15.4739 12.9898 15.1538 12.9898 14.7624V11.1978C13.6515 10.5432 14.1567 9.73918 14.4697 8.87114C14.8184 7.89637 14.918 6.83623 14.7615 5.81165L14.7401 5.80454Z",- "fill": "currentColor"- },- "children": []- },- {- "type": "element",- "name": "path",- "attributes": {- "d": "M10.8055 7.99599C10.8909 7.83234 10.962 7.66158 11.0189 7.4837H11.6522C12.0435 7.4837 12.3637 7.16352 12.3637 6.77219C12.3637 6.38086 12.0435 6.06068 11.6522 6.06068H11.0189C10.9691 5.8828 10.898 5.71204 10.8055 5.54839L11.2537 5.10014C11.5312 4.82266 11.5312 4.3744 11.2537 4.09692C10.9762 3.81943 10.528 3.81943 10.2505 4.09692L9.80225 4.54517C9.6386 4.45267 9.46784 4.38863 9.28996 4.33171V3.69847C9.28996 3.30714 8.96978 2.98696 8.57845 2.98696C8.18712 2.98696 7.86694 3.30714 7.86694 3.69847V4.33171C7.68907 4.38152 7.5183 4.45267 7.35466 4.54517L6.90641 4.09692C6.62892 3.81943 6.18067 3.81943 5.90318 4.09692C5.62569 4.3744 5.62569 4.82266 5.90318 5.10014L6.35143 5.54839C6.26605 5.71204 6.1949 5.8828 6.13798 6.06068H5.50473C5.1134 6.06068 4.79323 6.38086 4.79323 6.77219C4.79323 7.16352 5.1134 7.4837 5.50473 7.4837H6.13798C6.18778 7.66158 6.25893 7.83234 6.35143 7.99599L5.90318 8.44424C5.62569 8.72172 5.62569 9.16997 5.90318 9.44746C6.04548 9.58976 6.22336 9.6538 6.40835 9.6538C6.59334 9.6538 6.77122 9.58265 6.91352 9.44746L7.36177 8.99921C7.52542 9.08459 7.69618 9.15574 7.87406 9.21267V9.84591C7.87406 10.2372 8.19424 10.5574 8.58557 10.5574C8.9769 10.5574 9.29708 10.2372 9.29708 9.84591V9.21267C9.47496 9.16286 9.64572 9.09171 9.80936 8.99921L10.2576 9.44746C10.3999 9.58976 10.5778 9.6538 10.7628 9.6538C10.9478 9.6538 11.1257 9.58265 11.268 9.44746C11.5454 9.16997 11.5454 8.72172 11.268 8.44424L10.8197 7.99599H10.8055ZM7.44004 6.77219C7.44004 6.14606 7.94521 5.64089 8.57134 5.64089C9.19747 5.64089 9.70264 6.14606 9.70264 6.77219C9.70264 7.39832 9.19747 7.90349 8.57134 7.90349C7.94521 7.90349 7.44004 7.39832 7.44004 6.77219Z",- "fill": "currentColor"- },- "children": []- }- ]+ "children": []+ },+ {+ "type": "element",+ "name": "path",+ "attributes": {+ "d": "M9.79012 6.5163L9.31429 5.27923C9.23058 5.06159 9.02158 4.91799 8.78836 4.91799C8.55514 4.91799 8.34614 5.06159 8.26243 5.27923L7.7866 6.5163C7.56194 7.10037 7.10038 7.56194 6.5163 7.78659L5.27923 8.26239C5.06159 8.34609 4.91799 8.55519 4.91799 8.78836C4.91799 9.02158 5.06159 9.23058 5.27923 9.31429L6.5163 9.79012C7.10037 10.0148 7.56194 10.4764 7.7866 11.0604L8.26243 12.2975C8.34614 12.5151 8.55514 12.6587 8.78836 12.6587C9.02158 12.6587 9.23058 12.5151 9.31429 12.2975L9.79012 11.0604C10.0148 10.4764 10.4764 10.0148 11.0604 9.79012L12.2975 9.31429C12.5151 9.23058 12.6587 9.02158 12.6587 8.78836C12.6587 8.55519 12.5151 8.34609 12.2975 8.26239L11.0604 7.78659C10.4764 7.56194 10.0148 7.10038 9.79012 6.5163Z",+ "fill": "currentColor"+ },+ "children": []}]}diff --git a/web/app/components/base/prompt-editor/__tests__/index.spec.tsx b/web/app/components/base/prompt-editor/__tests__/index.spec.tsxindex 9c0b3cec39f..df89f1cb1dd 100644--- a/web/app/components/base/prompt-editor/__tests__/index.spec.tsx+++ b/web/app/components/base/prompt-editor/__tests__/index.spec.tsx@@ -9,6 +9,13 @@ import {UPDATE_HISTORY_EVENT_EMITTER,} from '../constants'import PromptEditor from '../index'+import { CustomTextNode } from '../plugins/custom-text/node'++type MockNodeReplacementConfig = {+ replace?: unknown+ with?: (arg: { __text: string }) => void+ withKlass?: unknown+}const mocks = vi.hoisted(() => {const commandHandlers = new Map<unknown, (payload: unknown) => boolean>()@@ -18,6 +25,7 @@ const mocks = vi.hoisted(() => {return {emit: vi.fn(),rootLines: ['first line', 'second line'],+ nodeReplacementConfig: undefined as MockNodeReplacementConfig | undefined,commandHandlers,subscriptions,rootElement,@@ -86,7 +94,7 @@ vi.mock('@lexical/react/LexicalComposer', () => ({LexicalComposer: ({ initialConfig, children }: {initialConfig: {onError?: (error: Error) => void- nodes?: Array<{ replace?: unknown, with: (arg: { __text: string }) => void }>+ nodes?: unknown[]}children: ReactNode}) => {@@ -99,9 +107,11 @@ vi.mock('@lexical/react/LexicalComposer', () => ({}}if (initialConfig?.nodes) {- const textNodeConf = initialConfig.nodes.find((n: { replace?: unknown, with: (arg: { __text: string }) => void }) => n?.replace)- if (textNodeConf)- textNodeConf.with({ __text: 'test' })+ const textNodeConf = initialConfig.nodes.find((node): node is MockNodeReplacementConfig => {+ return typeof node === 'object' && node !== null && 'replace' in node+ })+ mocks.nodeReplacementConfig = textNodeConf+ textNodeConf?.with?.({ __text: 'test' })}return <div data-testid="lexical-composer">{children}</div>},@@ -173,10 +183,17 @@ describe('PromptEditor', () => {mocks.commandHandlers.clear()mocks.subscriptions.length = 0mocks.rootLines = ['first line', 'second line']+ mocks.nodeReplacementConfig = undefined})// Rendering shell and text output from lexical state.describe('Rendering', () => {+ it('should register CustomTextNode as the TextNode replacement class', () => {+ render(<PromptEditor />)++ expect(mocks.nodeReplacementConfig?.withKlass).toBe(CustomTextNode)+ })+it('should render placeholder and call onChange with joined lexical text', async () => {const onChange = vi.fn()diff --git a/web/app/components/base/prompt-editor/__tests__/prompt-editor-content.spec.tsx b/web/app/components/base/prompt-editor/__tests__/prompt-editor-content.spec.tsxindex 02de482073b..3d6766b0024 100644--- a/web/app/components/base/prompt-editor/__tests__/prompt-editor-content.spec.tsx+++ b/web/app/components/base/prompt-editor/__tests__/prompt-editor-content.spec.tsx@@ -7,6 +7,7 @@ import { LexicalComposer } from '@lexical/react/LexicalComposer'import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'import {+ $getRoot,BLUR_COMMAND,COMMAND_PRIORITY_EDITOR,createCommand,@@ -17,6 +18,7 @@ import { useEffect } from 'react'import { GeneratorType } from '@/app/components/app/configuration/config/automatic/types'import { useEventEmitterContextContext } from '@/context/event-emitter'import { EventEmitterContextProvider } from '@/context/event-emitter-provider'+import { AgentOutputBlockNode } from '../plugins/agent-output-block/node'import { ContextBlockNode } from '../plugins/context-block'import { CurrentBlockNode } from '../plugins/current-block'import { CustomTextNode } from '../plugins/custom-text/node'@@ -26,6 +28,7 @@ import { HITLInputNode } from '../plugins/hitl-input-block'import { LastRunBlockNode } from '../plugins/last-run-block'import { QueryBlockNode } from '../plugins/query-block'import { RequestURLBlockNode } from '../plugins/request-url-block'+import { RosterReferenceBlockNode } from '../plugins/roster-reference-block/node'import { PROMPT_EDITOR_UPDATE_VALUE_BY_EVENT_EMITTER } from '../plugins/update-block'import { VariableValueBlockNode } from '../plugins/variable-value-block/node'import { WorkflowVariableBlockNode } from '../plugins/workflow-variable-block'@@ -108,10 +111,12 @@ const PromptEditorContentHarness = ({RequestURLBlockNode,WorkflowVariableBlockNode,VariableValueBlockNode,+ RosterReferenceBlockNode,HITLInputNode,CurrentBlockNode,ErrorMessageBlockNode,LastRunBlockNode,+ AgentOutputBlockNode,],editorState: textToEditorState(initialText),onError: (error: Error) => {@@ -201,6 +206,117 @@ describe('PromptEditorContent', () => {expect(screen.getByRole('textbox')).toBeInTheDocument()})+ it('should render adjacent agent output tokens as inline output blocks', async () => {+ const captures: Captures = { editor: null, eventEmitter: null }+ const initialText = '[§output:ccc:ccc§][§output:output_3ggg:output_3ggg§][§output:ggg:ggg§][§output:output_3fdfdf:output_3fdfdf§]'++ const { container } = render(+ <PromptEditorContentHarness+ captures={captures}+ initialText={initialText}+ shortcutPopups={[]}+ floatingAnchorElem={document.createElement('div')}+ onEditorChange={vi.fn()}+ agentOutputBlock={{+ show: true,+ outputs: [+ { name: 'ccc', type: 'string' },+ { name: 'output_3ggg', type: 'string' },+ { name: 'ggg', type: 'string' },+ { name: 'output_3fdfdf', type: 'string' },+ ],+ }}+ />,+ )++ await waitFor(() => {+ expect(screen.getByText('ccc')).toBeInTheDocument()+ expect(screen.getByText('output_3ggg')).toBeInTheDocument()+ expect(screen.getByText('ggg')).toBeInTheDocument()+ expect(screen.getByText('output_3fdfdf')).toBeInTheDocument()+ })+ expect(container).not.toHaveTextContent('[§output:ccc:ccc§]')++ await waitFor(() => {+ expect(captures.editor).not.toBeNull()+ })+ captures.editor!.getEditorState().read(() => {+ expect($getRoot().getTextContent()).toBe(initialText)+ })+ })++ it('should infer file type when rendering a file-name output token', async () => {+ const captures: Captures = { editor: null, eventEmitter: null }++ render(+ <PromptEditorContentHarness+ captures={captures}+ initialText="[§output:qna_report.pdf:qna_report.pdf§]"+ shortcutPopups={[]}+ floatingAnchorElem={document.createElement('div')}+ onEditorChange={vi.fn()}+ agentOutputBlock={{+ show: true,+ outputs: [+ { name: 'qna_report.pdf', type: 'string' },+ ],+ }}+ />,+ )++ await waitFor(() => {+ expect(screen.getByText('qna_report.pdf')).toBeInTheDocument()+ expect(screen.getByText('file')).toBeInTheDocument()+ })+ })++ it('should update rendered output block type when declared output config changes', async () => {+ const captures: Captures = { editor: null, eventEmitter: null }+ const outputBlock = {+ show: true,+ outputs: [+ { name: 'summary', type: 'string' as const },+ ],+ }++ const { rerender } = render(+ <PromptEditorContentHarness+ captures={captures}+ initialText="[§output:summary:summary§]"+ shortcutPopups={[]}+ floatingAnchorElem={document.createElement('div')}+ onEditorChange={vi.fn()}+ agentOutputBlock={outputBlock}+ />,+ )++ await waitFor(() => {+ expect(screen.getByText('summary')).toBeInTheDocument()+ expect(screen.getByText('string')).toBeInTheDocument()+ })++ rerender(+ <PromptEditorContentHarness+ captures={captures}+ initialText="[§output:summary:summary§]"+ shortcutPopups={[]}+ floatingAnchorElem={document.createElement('div')}+ onEditorChange={vi.fn()}+ agentOutputBlock={{+ show: true,+ outputs: [+ { name: 'summary', type: 'file' },+ ],+ }}+ />,+ )++ await waitFor(() => {+ expect(screen.getByText('file')).toBeInTheDocument()+ })+ expect(screen.queryByText('string')).not.toBeInTheDocument()+ })+it('should render optional blocks and open shortcut popups with the real editor runtime', async () => {const captures: Captures = { editor: null, eventEmitter: null }const onEditorChange = vi.fn()@@ -291,5 +407,29 @@ describe('PromptEditorContent', () => {expect(screen.queryByTestId('draggable-target-line')).not.toBeInTheDocument()expect(screen.getByText('common.promptEditor.placeholder')).toBeInTheDocument()})++ it('should render roster references as inline token pills when enabled', async () => {+ const captures: Captures = { editor: null, eventEmitter: null }++ const { container } = render(+ <PromptEditorContentHarness+ captures={captures}+ shortcutPopups={[]}+ initialText="Use [§file:file-1:qna_report.pdf§]"+ floatingAnchorElem={null}+ onEditorChange={vi.fn()}+ rosterReferenceBlock={{ show: true }}+ />,+ )++ await waitFor(() => {+ expect(captures.editor).not.toBeNull()+ })++ const token = container.querySelector('[data-roster-reference-kind="file"]') as HTMLElement+ expect(token).toBeInTheDocument()+ expect(token).toHaveTextContent('qna_report.pdf')+ expect(token.querySelector('.i-ri-file-pdf-2-fill')).toBeInTheDocument()+ })})})diff --git a/web/app/components/base/prompt-editor/index.tsx b/web/app/components/base/prompt-editor/index.tsxindex da2de727702..c663f9deb0c 100644--- a/web/app/components/base/prompt-editor/index.tsx+++ b/web/app/components/base/prompt-editor/index.tsx@@ -7,6 +7,7 @@ import type {import type { FC } from 'react'import type { Hotkey, ShortcutPopupDisplayMode, ShortcutPopupInsertHandler } from './plugins/shortcuts-popup-plugin'import type {+ AgentOutputBlockType,ContextBlockType,CurrentBlockType,ErrorMessageBlockType,@@ -16,6 +17,7 @@ import type {LastRunBlockType,QueryBlockType,RequestURLBlockType,+ RosterReferenceBlockType,VariableBlockType,WorkflowVariableBlockType,} from './types'@@ -34,6 +36,7 @@ import {UPDATE_DATASETS_EVENT_EMITTER,UPDATE_HISTORY_EVENT_EMITTER,} from './constants'+import { AgentOutputBlockNode } from './plugins/agent-output-block/node'import {ContextBlockNode,} from './plugins/context-block'@@ -44,10 +47,10 @@ import { CustomTextNode } from './plugins/custom-text/node'import {ErrorMessageBlockNode,} from './plugins/error-message-block'+import {HistoryBlockNode,} from './plugins/history-block'-import {HITLInputNode,} from './plugins/hitl-input-block'@@ -60,6 +63,7 @@ import {import {RequestURLBlockNode,} from './plugins/request-url-block'+import { RosterReferenceBlockNode } from './plugins/roster-reference-block/node'import { VariableValueBlockNode } from './plugins/variable-value-block/node'import {WorkflowVariableBlockNode,@@ -108,6 +112,7 @@ const EditableSyncPlugin: FC<{ editable: boolean }> = ({ editable }) => {export type PromptEditorProps = {instanceId?: string+ children?: React.ReactNodecompact?: booleanwrapperClassName?: stringclassName?: string@@ -124,13 +129,17 @@ export type PromptEditorProps = {requestURLBlock?: RequestURLBlockTypehistoryBlock?: HistoryBlockTypevariableBlock?: VariableBlockType+ rosterReferenceBlock?: RosterReferenceBlockTypeexternalToolBlock?: ExternalToolBlockTypeworkflowVariableBlock?: WorkflowVariableBlockType+ agentOutputBlock?: AgentOutputBlockTypehitlInputBlock?: HITLInputBlockTypecurrentBlock?: CurrentBlockTypeerrorMessageBlock?: ErrorMessageBlockTypelastRunBlock?: LastRunBlockTypeisSupportFileVar?: boolean+ disableSlashPicker?: boolean+ disableBracePicker?: booleanshortcutPopups?: Array<{hotkey: HotkeydisplayMode?: ShortcutPopupDisplayMode@@ -140,6 +149,7 @@ export type PromptEditorProps = {const PromptEditor: FC<PromptEditorProps> = ({instanceId,+ children,compact,wrapperClassName,className,@@ -156,13 +166,17 @@ const PromptEditor: FC<PromptEditorProps> = ({requestURLBlock,historyBlock,variableBlock,+ rosterReferenceBlock,externalToolBlock,workflowVariableBlock,+ agentOutputBlock,hitlInputBlock,currentBlock,errorMessageBlock,lastRunBlock,isSupportFileVar,+ disableSlashPicker = false,+ disableBracePicker = false,shortcutPopups = [],}) => {const { eventEmitter } = useEventEmitterContextContext()@@ -177,6 +191,7 @@ const PromptEditor: FC<PromptEditorProps> = ({{replace: TextNode,with: (node: TextNode) => new CustomTextNode(node.__text),+ withKlass: CustomTextNode,},ContextBlockNode,HistoryBlockNode,@@ -184,10 +199,12 @@ const PromptEditor: FC<PromptEditorProps> = ({RequestURLBlockNode,WorkflowVariableBlockNode,VariableValueBlockNode,+ RosterReferenceBlockNode,HITLInputNode,CurrentBlockNode,ErrorMessageBlockNode,LastRunBlockNode, // LastRunBlockNode is used for error message block replacement+ AgentOutputBlockNode,],editorState: textToEditorState(value || ''),onError: (error: Error) => {@@ -242,13 +259,17 @@ const PromptEditor: FC<PromptEditorProps> = ({requestURLBlock={requestURLBlock}historyBlock={historyBlock}variableBlock={variableBlock}+ rosterReferenceBlock={rosterReferenceBlock}externalToolBlock={externalToolBlock}workflowVariableBlock={workflowVariableBlock}+ agentOutputBlock={agentOutputBlock}hitlInputBlock={hitlInputBlock}currentBlock={currentBlock}errorMessageBlock={errorMessageBlock}lastRunBlock={lastRunBlock}isSupportFileVar={isSupportFileVar}+ disableSlashPicker={disableSlashPicker}+ disableBracePicker={disableBracePicker}onBlur={onBlur}onFocus={onFocus}instanceId={instanceId}@@ -257,6 +278,7 @@ const PromptEditor: FC<PromptEditorProps> = ({/><ValueSyncPlugin value={value} /><EditableSyncPlugin editable={editable} />+ {children}</div></LexicalComposer>)diff --git a/web/app/components/base/prompt-editor/plugins/agent-output-block/__tests__/component.spec.tsx b/web/app/components/base/prompt-editor/plugins/agent-output-block/__tests__/component.spec.tsxnew file mode 100644index 00000000000..a40a5f3d4ca--- /dev/null+++ b/web/app/components/base/prompt-editor/plugins/agent-output-block/__tests__/component.spec.tsx@@ -0,0 +1,369 @@+import type { DeclaredOutputConfig } from '@dify/contracts/api/console/apps/types.gen'+import type { ButtonHTMLAttributes, ReactNode } from 'react'+import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'+import { fireEvent, render, screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { $getNodeByKey } from 'lexical'+import AgentOutputBlockComponent from '../component'+import { $createAgentOutputBlockNode } from '../node'++const { mockEditorFocus, mockEditorUpdate, mockGetRootText, mockNodeReplace, mockSelectNext } = vi.hoisted(() => ({+ mockEditorFocus: vi.fn(),+ mockEditorUpdate: vi.fn((callback: () => void) => callback()),+ mockGetRootText: {+ value: '[§output:summary:summary§]',+ },+ mockNodeReplace: vi.fn(),+ mockSelectNext: vi.fn(),+}))++vi.mock('@lexical/react/LexicalComposerContext')+vi.mock('@langgenius/dify-ui/select', () => ({+ Select: ({+ children,+ onValueChange,+ }: {+ children: ReactNode+ onValueChange: (value: string) => void+ }) => (+ <div>+ {children}+ <button type="button" onClick={() => onValueChange('file')}>Select file</button>+ </div>+ ),+ SelectContent: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ SelectItem: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ SelectItemIndicator: () => <span />,+ SelectItemText: ({ children }: { children: ReactNode }) => <span>{children}</span>,+ SelectLabel: ({ children }: { children: ReactNode }) => <span>{children}</span>,+ SelectTrigger: ({+ children,+ onClick,+ onMouseDown,+ ...props+ }: ButtonHTMLAttributes<HTMLButtonElement>) => (+ <button type="button" onClick={onClick} onMouseDown={onMouseDown} {...props}>+ {children}+ </button>+ ),+}))+vi.mock('lexical', async (importOriginal) => {+ const actual = await importOriginal<typeof import('lexical')>()++ return {+ ...actual,+ $getNodeByKey: vi.fn(),+ $getRoot: vi.fn(() => ({+ getChildren: () => [{+ getTextContent: () => mockGetRootText.value,+ }],+ })),+ }+})++vi.mock('../node', () => ({+ $createAgentOutputBlockNode: vi.fn((name: string, outputType: string, isEditing: boolean) => ({+ isEditing,+ name,+ outputType,+ })),+ $isAgentOutputBlockNode: () => true,+}))++const outputs: DeclaredOutputConfig[] = [+ {+ name: 'output',+ type: 'string',+ required: false,+ },+]++describe('AgentOutputBlockComponent', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockGetRootText.value = '[§output:summary:summary§]'+ vi.mocked(useLexicalComposerContext).mockReturnValue([+ {+ focus: mockEditorFocus,+ update: mockEditorUpdate,+ },+ {},+ ] as unknown as ReturnType<typeof useLexicalComposerContext>)+ vi.mocked($getNodeByKey).mockReturnValue({+ replace: mockNodeReplace.mockReturnValue({+ selectNext: mockSelectNext,+ }),+ } as never)+ })++ it('does not replace the Lexical node while typing an output name and commits on blur', async () => {+ const user = userEvent.setup()+ const onChange = vi.fn()++ render(+ <AgentOutputBlockComponent+ nodeKey="output-node"+ name="output"+ outputType="string"+ isEditing+ outputs={outputs}+ onChange={onChange}+ />,+ )++ const input = screen.getByRole('textbox', { name: 'workflow.nodes.agent.outputVars.nameLabel' })++ await user.clear(input)+ await user.type(input, 'summary')++ expect(input).toHaveValue('summary')+ expect(mockNodeReplace).not.toHaveBeenCalled()+ expect(onChange).not.toHaveBeenCalled()++ await user.tab()++ expect($createAgentOutputBlockNode).toHaveBeenCalledWith(+ 'summary',+ 'string',+ false,+ expect.arrayContaining([+ expect.objectContaining({+ name: 'summary',+ type: 'string',+ required: false,+ }),+ ]),+ onChange,+ )+ expect(mockNodeReplace).toHaveBeenCalledTimes(1)+ expect(mockSelectNext).not.toHaveBeenCalled()+ expect(mockEditorFocus).not.toHaveBeenCalled()+ expect(onChange).toHaveBeenCalledWith(expect.arrayContaining([+ expect.objectContaining({+ name: 'summary',+ type: 'string',+ required: false,+ }),+ ]), '[§output:summary:summary§]')+ })++ it('moves the editor selection after the output block when committing with Enter', async () => {+ const user = userEvent.setup()++ render(+ <AgentOutputBlockComponent+ nodeKey="output-node"+ name="output"+ outputType="string"+ isEditing+ outputs={outputs}+ />,+ )++ const input = screen.getByRole('textbox', { name: 'workflow.nodes.agent.outputVars.nameLabel' })++ await user.clear(input)+ await user.type(input, 'summary')+ await user.keyboard('{Enter}')++ expect(mockNodeReplace).toHaveBeenCalledTimes(1)+ expect(mockSelectNext).toHaveBeenCalledTimes(1)+ await waitFor(() => {+ expect(mockEditorFocus).toHaveBeenCalledTimes(1)+ })+ })++ it('commits the input DOM value on Enter even before React state rerenders', () => {+ const onChange = vi.fn()++ render(+ <AgentOutputBlockComponent+ nodeKey="output-node"+ name="output"+ outputType="string"+ isEditing+ outputs={outputs}+ onChange={onChange}+ />,+ )++ const input = screen.getByRole('textbox', { name: 'workflow.nodes.agent.outputVars.nameLabel' })++ fireEvent.change(input, { target: { value: 'summary' } })+ fireEvent.keyDown(input, { key: 'Enter' })++ expect($createAgentOutputBlockNode).toHaveBeenCalledWith(+ 'summary',+ 'string',+ false,+ expect.arrayContaining([+ expect.objectContaining({+ name: 'summary',+ }),+ ]),+ onChange,+ )+ })++ it('automatically commits file-name outputs as file type', () => {+ const onChange = vi.fn()+ mockGetRootText.value = '[§output:qna_report.pdf:qna_report.pdf§]'++ render(+ <AgentOutputBlockComponent+ nodeKey="output-node"+ name="output"+ outputType="string"+ isEditing+ outputs={outputs}+ onChange={onChange}+ />,+ )++ const input = screen.getByRole('textbox', { name: 'workflow.nodes.agent.outputVars.nameLabel' })++ fireEvent.change(input, { target: { value: 'qna_report.pdf' } })+ fireEvent.keyDown(input, { key: 'Enter' })++ expect($createAgentOutputBlockNode).toHaveBeenCalledWith(+ 'qna_report.pdf',+ 'file',+ false,+ expect.arrayContaining([+ expect.objectContaining({+ name: 'qna_report.pdf',+ type: 'file',+ file: {+ extensions: [],+ mime_types: [],+ },+ }),+ ]),+ onChange,+ )+ expect(onChange).toHaveBeenCalledWith(expect.arrayContaining([+ expect.objectContaining({+ name: 'qna_report.pdf',+ type: 'file',+ }),+ ]), '[§output:qna_report.pdf:qna_report.pdf§]')+ })++ it('keeps dotted output names as the selected type when the extension is not whitelisted', () => {+ const onChange = vi.fn()+ mockGetRootText.value = '[§output:report.customext:report.customext§]'++ render(+ <AgentOutputBlockComponent+ nodeKey="output-node"+ name="output"+ outputType="string"+ isEditing+ outputs={outputs}+ onChange={onChange}+ />,+ )++ const input = screen.getByRole('textbox', { name: 'workflow.nodes.agent.outputVars.nameLabel' })++ fireEvent.change(input, { target: { value: 'report.customext' } })+ fireEvent.keyDown(input, { key: 'Enter' })++ expect($createAgentOutputBlockNode).toHaveBeenCalledWith(+ 'report.customext',+ 'string',+ false,+ expect.arrayContaining([+ expect.objectContaining({+ name: 'report.customext',+ type: 'string',+ }),+ ]),+ onChange,+ )+ })++ it('does not commit the name blur before selecting an output type', () => {+ const onChange = vi.fn()+ mockGetRootText.value = '[§output:summary:summary§]'++ render(+ <AgentOutputBlockComponent+ nodeKey="output-node"+ name="output"+ outputType="string"+ isEditing+ outputs={outputs}+ onChange={onChange}+ />,+ )++ const input = screen.getByRole('textbox', { name: 'workflow.nodes.agent.outputVars.nameLabel' })+ const typeTrigger = screen.getByRole('button', { name: 'workflow.nodes.agent.outputVars.typeLabel' })++ fireEvent.change(input, { target: { value: 'summary' } })+ fireEvent.mouseDown(typeTrigger)+ fireEvent.blur(input)++ expect(onChange).not.toHaveBeenCalled()++ fireEvent.click(screen.getByRole('button', { name: 'Select file' }))++ expect($createAgentOutputBlockNode).toHaveBeenCalledWith(+ 'summary',+ 'file',+ false,+ expect.arrayContaining([+ expect.objectContaining({+ name: 'summary',+ type: 'file',+ }),+ ]),+ onChange,+ )+ })++ it('does not save stale output data when the Lexical node has already been replaced', async () => {+ const user = userEvent.setup()+ const onChange = vi.fn()+ vi.mocked($getNodeByKey).mockReturnValue(null)++ render(+ <AgentOutputBlockComponent+ nodeKey="output-node"+ name="output"+ outputType="string"+ isEditing+ outputs={outputs}+ onChange={onChange}+ />,+ )++ const input = screen.getByRole('textbox', { name: 'workflow.nodes.agent.outputVars.nameLabel' })++ await user.clear(input)+ await user.type(input, 'summary')+ await user.keyboard('{Enter}')++ expect(mockNodeReplace).not.toHaveBeenCalled()+ expect(onChange).not.toHaveBeenCalled()+ expect(mockEditorFocus).not.toHaveBeenCalled()+ })++ it('renders the committed output block as non-editable adaptive text', () => {+ render(+ <AgentOutputBlockComponent+ nodeKey="output-node"+ name="qna_report_pdf"+ outputType="file"+ isEditing={false}+ outputs={outputs}+ />,+ )++ expect(screen.queryByRole('textbox', { name: 'workflow.nodes.agent.outputVars.nameLabel' })).not.toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'workflow.nodes.agent.outputVars.typeLabel' })).not.toBeInTheDocument()+ expect(screen.getByText('qna_report_pdf')).toBeInTheDocument()+ expect(screen.getByText('file')).toBeInTheDocument()+ })+})diff --git a/web/app/components/base/prompt-editor/plugins/agent-output-block/__tests__/node.spec.tsx b/web/app/components/base/prompt-editor/plugins/agent-output-block/__tests__/node.spec.tsxnew file mode 100644index 00000000000..95f71afc67a--- /dev/null+++ b/web/app/components/base/prompt-editor/plugins/agent-output-block/__tests__/node.spec.tsx@@ -0,0 +1,106 @@+import type {+ Klass,+ LexicalEditor,+ LexicalNode,+} from 'lexical'+import { createEditor } from 'lexical'+import {+ $createAgentOutputBlockNode,+ $isAgentOutputBlockNode,+ AgentOutputBlockNode,+} from '../node'+import {+ extractAgentOutputNames,+ getAgentOutputToken,+ inferAgentOutputType,+ parseAgentOutputToken,+ replaceAgentOutputName,+} from '../utils'++describe('AgentOutputBlockNode', () => {+ let editor: LexicalEditor++ beforeEach(() => {+ vi.clearAllMocks()+ editor = createEditor({+ nodes: [AgentOutputBlockNode as unknown as Klass<LexicalNode>],+ })+ })++ const runInEditor = (callback: () => void) => {+ editor.update(callback, { discrete: true })+ }++ it('should persist output tokens with bracket wrappers', () => {+ runInEditor(() => {+ const node = $createAgentOutputBlockNode('summary', 'string')++ expect(node.getTextContent()).toBe('[§output:summary:summary§]')+ expect(getAgentOutputToken('summary')).toBe('[§output:summary:summary§]')+ })+ })++ it('should persist and parse file-name output tokens', () => {+ runInEditor(() => {+ const node = $createAgentOutputBlockNode('qna_report.pdf', 'file')++ expect(node.getTextContent()).toBe('[§output:qna_report.pdf:qna_report.pdf§]')+ expect(getAgentOutputToken('qna_report.pdf')).toBe('[§output:qna_report.pdf:qna_report.pdf§]')+ })++ expect(parseAgentOutputToken('Use [§output:qna_report.pdf:qna_report.pdf§]')).toEqual({+ name: 'qna_report.pdf',+ start: 4,+ end: 44,+ })+ })++ it('should infer file type only for whitelisted file extensions', () => {+ expect(inferAgentOutputType('qna_report.pdf', 'string')).toBe('file')+ expect(inferAgentOutputType('QNA_REPORT.PDF', 'string')).toBe('file')+ expect(inferAgentOutputType('report.customext', 'string')).toBe('string')+ expect(inferAgentOutputType('report.customext', 'object')).toBe('object')+ })++ it('should parse bracketed output tokens and legacy bare tokens', () => {+ expect(parseAgentOutputToken('before [§output:summary:summary§] after')).toEqual({+ name: 'summary',+ start: 7,+ end: 33,+ })+ expect(parseAgentOutputToken('before §output:summary:summary§ after')).toEqual({+ name: 'summary',+ start: 7,+ end: 31,+ })+ expect(parseAgentOutputToken('[§skill:summary:summary§]')).toBeNull()+ })++ it('should extract output names from bracketed and legacy tokens', () => {+ expect([...extractAgentOutputNames('A [§output:summary:summary§] B §output:qna_report.pdf:qna_report.pdf§')]).toEqual([+ 'summary',+ 'qna_report.pdf',+ ])+ })++ it('should replace only matching output token names', () => {+ expect(replaceAgentOutputName(+ 'Use [§output:summary:summary§] and §output:other:other§',+ 'summary',+ 'final_summary',+ )).toBe('Use [§output:final_summary:final_summary§] and §output:other:other§')+ })++ it('should create node with helper and support type guard checks', () => {+ runInEditor(() => {+ const node = $createAgentOutputBlockNode('result', 'object')++ expect(node).toBeInstanceOf(AgentOutputBlockNode)+ expect(node.getTextContent()).toBe('[§output:result:result§]')+ expect($isAgentOutputBlockNode(node)).toBe(true)+ expect($isAgentOutputBlockNode(null)).toBe(false)+ expect($isAgentOutputBlockNode(undefined)).toBe(false)+ expect($isAgentOutputBlockNode({} as LexicalNode)).toBe(false)+ })+ })+})diff --git a/web/app/components/base/prompt-editor/plugins/agent-output-block/commands.ts b/web/app/components/base/prompt-editor/plugins/agent-output-block/commands.tsnew file mode 100644index 00000000000..c4f8745426e--- /dev/null+++ b/web/app/components/base/prompt-editor/plugins/agent-output-block/commands.ts@@ -0,0 +1,3 @@+import { createCommand } from 'lexical'++export const INSERT_AGENT_OUTPUT_BLOCK_COMMAND = createCommand('INSERT_AGENT_OUTPUT_BLOCK_COMMAND')diff --git a/web/app/components/base/prompt-editor/plugins/agent-output-block/component.tsx b/web/app/components/base/prompt-editor/plugins/agent-output-block/component.tsxnew file mode 100644index 00000000000..68d128f956c--- /dev/null+++ b/web/app/components/base/prompt-editor/plugins/agent-output-block/component.tsx@@ -0,0 +1,211 @@+import type { DeclaredOutputConfig } from '@dify/contracts/api/console/apps/types.gen'+import type { AgentOutputTypeOptionValue } from './utils'+import {+ Select,+ SelectContent,+ SelectItem,+ SelectItemIndicator,+ SelectItemText,+ SelectLabel,+ SelectTrigger,+} from '@langgenius/dify-ui/select'+import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'+import { $getNodeByKey, $getRoot } from 'lexical'+import { memo, useRef, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { $createAgentOutputBlockNode, $isAgentOutputBlockNode } from './node'+import {+ AGENT_OUTPUT_NAME_PATTERN,+ AGENT_OUTPUT_TYPE_OPTIONS,+ createAgentOutputConfig,+ getAgentOutputTypeOption,+ inferAgentOutputType,+} from './utils'++type AgentOutputBlockComponentProps = {+ nodeKey: string+ name: string+ outputType: AgentOutputTypeOptionValue+ isEditing: boolean+ outputs: DeclaredOutputConfig[]+ onChange?: (outputs: DeclaredOutputConfig[], prompt?: string) => void+}++function upsertOutput(+ outputs: DeclaredOutputConfig[],+ oldName: string,+ nextName: string,+ outputType: AgentOutputTypeOptionValue,+) {+ const trimmedName = nextName.trim()+ if (!AGENT_OUTPUT_NAME_PATTERN.test(trimmedName))+ return null++ const nextOutputType = inferAgentOutputType(trimmedName, outputType)+ const existingIndex = outputs.findIndex(output => output.name === oldName)+ const duplicateIndex = outputs.findIndex(output => output.name === trimmedName && output.name !== oldName)+ if (duplicateIndex >= 0)+ return null++ const nextOutput = createAgentOutputConfig(trimmedName, nextOutputType)+ if (existingIndex >= 0)+ return outputs.map((output, index) => index === existingIndex ? nextOutput : output)++ return [...outputs, nextOutput]+}++const AgentOutputBlockComponent = ({+ nodeKey,+ name,+ outputType,+ isEditing,+ outputs,+ onChange,+}: AgentOutputBlockComponentProps) => {+ const { t } = useTranslation()+ const [editor] = useLexicalComposerContext()+ const selected = getAgentOutputTypeOption(outputType)+ const [draftName, setDraftName] = useState(name)+ const [lastNodeName, setLastNodeName] = useState(name)+ const skipNextBlurCommitRef = useRef(false)+ const latestDraftNameRef = useRef(name)++ if (name !== lastNodeName) {+ setLastNodeName(name)+ setDraftName(name)+ latestDraftNameRef.current = name+ }++ const commitOutput = (nextName: string, nextType: AgentOutputTypeOptionValue, selectAfterCommit = false) => {+ const trimmedName = nextName.trim()+ const nextOutputs = upsertOutput(outputs, name, trimmedName, nextType)+ if (!nextOutputs) {+ setDraftName(name)+ return false+ }++ let didCommit = false+ let nextPrompt: string | undefined+ editor.update(() => {+ const node = $getNodeByKey(nodeKey)+ if (!$isAgentOutputBlockNode(node))+ return++ const nextOutputType = inferAgentOutputType(trimmedName, nextType)+ const nextNode = node.replace($createAgentOutputBlockNode(trimmedName, nextOutputType, false, nextOutputs, onChange))+ if (selectAfterCommit)+ nextNode.selectNext()+ nextPrompt = $getRoot().getChildren().map(node => node.getTextContent()).join('\n')+ didCommit = true+ })++ if (!didCommit)+ return false++ onChange?.(nextOutputs, nextPrompt)++ return true+ }++ if (!isEditing) {+ return (+ <span+ contentEditable={false}+ className="inline-flex min-w-[18px] items-center gap-1 rounded-[5px] border border-util-colors-violet-violet-100 bg-util-colors-violet-violet-50 px-1 py-0.5 align-middle shadow-xs"+ >+ <span aria-hidden="true" className="i-custom-vender-workflow-variable-x size-3.5 shrink-0 text-util-colors-violet-violet-700" />+ <span className="system-xs-medium whitespace-nowrap text-util-colors-violet-violet-700">+ {name}+ </span>+ <span className="rounded-[3px] px-0.5 system-2xs-medium-uppercase whitespace-nowrap text-text-tertiary">+ {selected.label}+ </span>+ </span>+ )+ }++ return (+ <span+ contentEditable={false}+ className="inline-flex items-center gap-[3px] rounded-[5px] border border-util-colors-violet-violet-700 bg-util-colors-violet-violet-50 p-px align-middle shadow-xs"+ >+ <span className="flex min-w-0 items-center gap-0.5 pl-0.5">+ <span aria-hidden="true" className="i-custom-vender-workflow-variable-x size-3.5 shrink-0 text-util-colors-violet-violet-700" />+ <input+ aria-label={t('nodes.agent.outputVars.nameLabel', { ns: 'workflow' })}+ value={draftName}+ className="h-4 max-w-28 min-w-5 border-0 bg-transparent p-0 text-center system-xs-regular text-util-colors-violet-violet-700 outline-hidden placeholder:text-util-colors-violet-violet-700/50 focus:w-24"+ placeholder={t('nodes.agent.outputVars.namePlaceholder', { ns: 'workflow' })}+ onMouseDown={event => event.stopPropagation()}+ onClick={event => event.stopPropagation()}+ onKeyDown={(event) => {+ event.stopPropagation()+ event.nativeEvent.stopImmediatePropagation?.()+ if (event.key === 'Enter') {+ event.preventDefault()+ skipNextBlurCommitRef.current = true+ const didCommit = commitOutput(event.currentTarget.value, outputType, true)+ if (!didCommit) {+ skipNextBlurCommitRef.current = false+ return+ }++ queueMicrotask(() => {+ editor.focus()+ })+ }+ if (event.key === 'Escape') {+ event.preventDefault()+ setDraftName(name)+ event.currentTarget.blur()+ }+ }}+ onChange={(event) => {+ latestDraftNameRef.current = event.currentTarget.value+ setDraftName(event.currentTarget.value)+ }}+ onBlur={(event) => {+ if (skipNextBlurCommitRef.current) {+ skipNextBlurCommitRef.current = false+ return+ }++ commitOutput(event.currentTarget.value, outputType)+ }}+ />+ </span>+ <Select<AgentOutputTypeOptionValue>+ value={outputType}+ onValueChange={(nextType) => {+ skipNextBlurCommitRef.current = false+ if (nextType)+ commitOutput(latestDraftNameRef.current, nextType)+ }}+ >+ <SelectLabel className="sr-only">+ {t('nodes.agent.outputVars.typeLabel', { ns: 'workflow' })}+ </SelectLabel>+ <SelectTrigger+ aria-label={t('nodes.agent.outputVars.typeLabel', { ns: 'workflow' })}+ className="h-4 min-w-4 rounded bg-util-colors-violet-violet-200 py-0 pr-0.5 pl-1 system-2xs-semibold-uppercase text-util-colors-violet-violet-700 hover:bg-util-colors-violet-violet-200"+ onMouseDown={() => {+ skipNextBlurCommitRef.current = true+ }}+ onClick={event => event.stopPropagation()}+ >+ {selected.label}+ </SelectTrigger>+ <SelectContent popupClassName="w-40">+ {AGENT_OUTPUT_TYPE_OPTIONS.map(option => (+ <SelectItem key={option.value} value={option.value}>+ <SelectItemText>{option.label}</SelectItemText>+ <SelectItemIndicator />+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </span>+ )+}++export default memo(AgentOutputBlockComponent)diff --git a/web/app/components/base/prompt-editor/plugins/agent-output-block/index.tsx b/web/app/components/base/prompt-editor/plugins/agent-output-block/index.tsxnew file mode 100644index 00000000000..aeafc69c5f4--- /dev/null+++ b/web/app/components/base/prompt-editor/plugins/agent-output-block/index.tsx@@ -0,0 +1,138 @@+import type { ElementNode, TextNode } from 'lexical'+import type { AgentOutputBlockType } from '../../types'+import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'+import { mergeRegister } from '@lexical/utils'+import {+ $applyNodeReplacement,+ $getRoot,+ $insertNodes,+ $isElementNode,+ COMMAND_PRIORITY_EDITOR,+} from 'lexical'+import { memo, useCallback, useEffect } from 'react'+import { decoratorTransform } from '../../utils'+import { CustomTextNode } from '../custom-text/node'+import { INSERT_AGENT_OUTPUT_BLOCK_COMMAND } from './commands'+import { $createAgentOutputBlockNode, AgentOutputBlockNode } from './node'+import {+ createAgentOutputConfig,+ getAgentOutputTypeOptionValue,+ getUniqueAgentOutputName,+ inferAgentOutputType,+ parseAgentOutputToken,+} from './utils'++function getAgentOutputBlockNodeType(name: string, outputs: NonNullable<AgentOutputBlockType['outputs']>) {+ const output = outputs.find(item => item.name === name)++ return inferAgentOutputType(name, output ? getAgentOutputTypeOptionValue(output) : 'string')+}++const AgentOutputBlock = memo(({+ outputs = [],+ onChange,+}: AgentOutputBlockType) => {+ const [editor] = useLexicalComposerContext()++ useEffect(() => {+ if (!editor.hasNodes([AgentOutputBlockNode]))+ throw new Error('AgentOutputBlockPlugin: AgentOutputBlock not registered on editor')++ return mergeRegister(+ editor.registerCommand(+ INSERT_AGENT_OUTPUT_BLOCK_COMMAND,+ () => {+ const name = getUniqueAgentOutputName(outputs)+ const outputType = 'string'+ const nextOutputs = [...outputs, createAgentOutputConfig(name, outputType)]+ const agentOutputBlockNode = $createAgentOutputBlockNode(name, outputType, true, nextOutputs, onChange)++ $insertNodes([agentOutputBlockNode])+ const nextPrompt = $getRoot().getChildren().map(node => node.getTextContent()).join('\n')+ onChange?.(nextOutputs, nextPrompt)++ return true+ },+ COMMAND_PRIORITY_EDITOR,+ ),+ )+ }, [editor, onChange, outputs])++ return null+})+AgentOutputBlock.displayName = 'AgentOutputBlock'++const AgentOutputBlockReplacementBlock = memo(({+ outputs = [],+ onChange,+}: AgentOutputBlockType) => {+ const [editor] = useLexicalComposerContext()++ useEffect(() => {+ if (!editor.hasNodes([AgentOutputBlockNode]))+ throw new Error('AgentOutputBlockNodePlugin: AgentOutputBlockNode not registered on editor')+ }, [editor])++ const createAgentOutputBlockNode = useCallback((textNode: TextNode): AgentOutputBlockNode => {+ const match = parseAgentOutputToken(textNode.getTextContent())+ const name = match?.name || ''+ const outputType = getAgentOutputBlockNodeType(name, outputs)++ return $applyNodeReplacement($createAgentOutputBlockNode(name, outputType, false, outputs, onChange))+ }, [onChange, outputs])++ const getMatch = useCallback((text: string) => {+ const match = parseAgentOutputToken(text)++ if (!match)+ return null++ return {+ end: match.end,+ start: match.start,+ }+ }, [])++ const transformListener = useCallback((textNode: CustomTextNode) => {+ return decoratorTransform(textNode, getMatch, createAgentOutputBlockNode, {+ allowAdjacentMatches: true,+ })+ }, [createAgentOutputBlockNode, getMatch])++ useEffect(() => {+ return mergeRegister(+ editor.registerNodeTransform(CustomTextNode, transformListener),+ )+ }, [editor, transformListener])++ useEffect(() => {+ editor.update(() => {+ const visitNode = (node: ElementNode) => {+ node.getChildren().forEach((child) => {+ if (child instanceof AgentOutputBlockNode) {+ const name = child.getName()+ const outputType = getAgentOutputBlockNodeType(name, outputs)+ if (+ child.getOutputType() !== outputType+ || child.getOutputs() !== outputs+ || child.getOnChange() !== onChange+ ) {+ child.replace($createAgentOutputBlockNode(name, outputType, child.isEditing(), outputs, onChange))+ }+ return+ }++ if ($isElementNode(child))+ visitNode(child)+ })+ }++ visitNode($getRoot())+ })+ }, [editor, onChange, outputs])++ return null+})+AgentOutputBlockReplacementBlock.displayName = 'AgentOutputBlockReplacementBlock'++export { AgentOutputBlock, AgentOutputBlockReplacementBlock }diff --git a/web/app/components/base/prompt-editor/plugins/agent-output-block/node.tsx b/web/app/components/base/prompt-editor/plugins/agent-output-block/node.tsxnew file mode 100644index 00000000000..11e14f7c245--- /dev/null+++ b/web/app/components/base/prompt-editor/plugins/agent-output-block/node.tsx@@ -0,0 +1,131 @@+import type { DeclaredOutputConfig } from '@dify/contracts/api/console/apps/types.gen'+import type { LexicalNode, NodeKey, SerializedLexicalNode } from 'lexical'+import type { AgentOutputTypeOptionValue } from './utils'+import { DecoratorNode } from 'lexical'+import AgentOutputBlockComponent from './component'+import { getAgentOutputToken } from './utils'++type SerializedNode = SerializedLexicalNode & {+ name: string+ outputType: AgentOutputTypeOptionValue+}++export class AgentOutputBlockNode extends DecoratorNode<React.JSX.Element> {+ __name: string+ __outputType: AgentOutputTypeOptionValue+ __isEditing: boolean+ __outputs: DeclaredOutputConfig[]+ __onChange?: (outputs: DeclaredOutputConfig[], prompt?: string) => void++ static override getType(): string {+ return 'agent-output-block'+ }++ static override clone(node: AgentOutputBlockNode): AgentOutputBlockNode {+ return new AgentOutputBlockNode(+ node.__name,+ node.__outputType,+ node.__isEditing,+ node.__outputs,+ node.__onChange,+ node.__key,+ )+ }++ override isInline(): boolean {+ return true+ }++ constructor(+ name: string,+ outputType: AgentOutputTypeOptionValue,+ isEditing = false,+ outputs: DeclaredOutputConfig[] = [],+ onChange?: (outputs: DeclaredOutputConfig[], prompt?: string) => void,+ key?: NodeKey,+ ) {+ super(key)++ this.__name = name+ this.__outputType = outputType+ this.__isEditing = isEditing+ this.__outputs = outputs+ this.__onChange = onChange+ }++ override createDOM(): HTMLElement {+ const div = document.createElement('div')+ div.classList.add('inline-flex', 'items-center', 'align-middle')+ return div+ }++ override updateDOM(): false {+ return false+ }++ override decorate(): React.JSX.Element {+ return (+ <AgentOutputBlockComponent+ nodeKey={this.getKey()}+ name={this.getName()}+ outputType={this.getOutputType()}+ isEditing={this.isEditing()}+ outputs={this.getOutputs()}+ onChange={this.getOnChange()}+ />+ )+ }++ static override importJSON(serializedNode: SerializedNode): AgentOutputBlockNode {+ return $createAgentOutputBlockNode(serializedNode.name, serializedNode.outputType)+ }++ override exportJSON(): SerializedNode {+ return {+ type: 'agent-output-block',+ version: 1,+ name: this.getName(),+ outputType: this.getOutputType(),+ }+ }++ getName(): string {+ return this.getLatest().__name+ }++ getOutputType(): AgentOutputTypeOptionValue {+ return this.getLatest().__outputType+ }++ isEditing(): boolean {+ return this.getLatest().__isEditing+ }++ getOutputs(): DeclaredOutputConfig[] {+ return this.getLatest().__outputs+ }++ getOnChange(): ((outputs: DeclaredOutputConfig[], prompt?: string) => void) | undefined {+ return this.getLatest().__onChange+ }++ override getTextContent(): string {+ return getAgentOutputToken(this.getName())+ }+}++export function $createAgentOutputBlockNode(+ name: string,+ outputType: AgentOutputTypeOptionValue = 'string',+ isEditing = false,+ outputs: DeclaredOutputConfig[] = [],+ onChange?: (outputs: DeclaredOutputConfig[], prompt?: string) => void,+): AgentOutputBlockNode {+ return new AgentOutputBlockNode(name, outputType, isEditing, outputs, onChange)+}++export function $isAgentOutputBlockNode(+ node: AgentOutputBlockNode | LexicalNode | null | undefined,+): node is AgentOutputBlockNode {+ return node instanceof AgentOutputBlockNode+}diff --git a/web/app/components/base/prompt-editor/plugins/agent-output-block/utils.ts b/web/app/components/base/prompt-editor/plugins/agent-output-block/utils.tsnew file mode 100644index 00000000000..a45152d4f2b--- /dev/null+++ b/web/app/components/base/prompt-editor/plugins/agent-output-block/utils.ts@@ -0,0 +1,174 @@+import type { DeclaredOutputConfig, DeclaredOutputType } from '@dify/contracts/api/console/apps/types.gen'++export type AgentOutputTypeOptionValue+ = DeclaredOutputType+ | 'array[boolean]'+ | 'array[file]'+ | 'array[number]'+ | 'array[object]'+ | 'array[string]'++export type AgentOutputTypeOption = {+ label: string+ type: DeclaredOutputType+ value: AgentOutputTypeOptionValue+ arrayItemType?: DeclaredOutputType+}++const AGENT_OUTPUT_TOKEN_REGEX = /\[§output:([^:§\]]+):([^:§\]]+)§\]/+const LEGACY_AGENT_OUTPUT_TOKEN_REGEX = /§output:([^:§\]]+):([^:§\]]+)§/+export const AGENT_OUTPUT_NAME_PATTERN = /^[a-z_][\w.-]*$/i+const AGENT_OUTPUT_FILE_NAME_PATTERN = /^[^.][^/\\:*?"<>|\n\r]*\.([a-z0-9]{1,16})$/i+const AGENT_OUTPUT_FILE_EXTENSION_WHITELIST = new Set([+ 'amr',+ 'csv',+ 'doc',+ 'docx',+ 'eml',+ 'epub',+ 'gif',+ 'html',+ 'jpeg',+ 'jpg',+ 'm4a',+ 'markdown',+ 'md',+ 'mdx',+ 'mov',+ 'mp3',+ 'mp4',+ 'mpeg',+ 'mpga',+ 'msg',+ 'pdf',+ 'png',+ 'ppt',+ 'pptx',+ 'svg',+ 'txt',+ 'wav',+ 'webm',+ 'webp',+ 'xls',+ 'xlsx',+ 'xml',+])++export function getAgentOutputToken(name: string) {+ return `[§output:${name}:${name}§]`+}++export function parseAgentOutputToken(text: string) {+ const match = AGENT_OUTPUT_TOKEN_REGEX.exec(text) ?? LEGACY_AGENT_OUTPUT_TOKEN_REGEX.exec(text)+ if (!match)+ return null++ return {+ name: match[1]!,+ start: match.index,+ end: match.index + match[0].length,+ }+}++export function extractAgentOutputNames(text: string) {+ const names = new Set<string>()+ const bracketedRegex = new RegExp(AGENT_OUTPUT_TOKEN_REGEX.source, 'g')+ const legacyRegex = new RegExp(LEGACY_AGENT_OUTPUT_TOKEN_REGEX.source, 'g')++ for (const match of text.matchAll(bracketedRegex))+ names.add(match[1]!)++ for (const match of text.matchAll(legacyRegex))+ names.add(match[1]!)++ return names+}++export function replaceAgentOutputName(text: string, oldName: string, nextName: string) {+ const replaceTokenName = (match: string, name: string, mirrorName: string) => {+ if (name !== oldName)+ return match++ return match.replace(`${name}:${mirrorName}`, `${nextName}:${nextName}`)+ }++ return text+ .replace(new RegExp(AGENT_OUTPUT_TOKEN_REGEX.source, 'g'), replaceTokenName)+ .replace(new RegExp(LEGACY_AGENT_OUTPUT_TOKEN_REGEX.source, 'g'), replaceTokenName)+}++export const AGENT_OUTPUT_TYPE_OPTIONS: AgentOutputTypeOption[] = [+ { value: 'string', label: 'string', type: 'string' },+ { value: 'number', label: 'number', type: 'number' },+ { value: 'boolean', label: 'boolean', type: 'boolean' },+ { value: 'object', label: 'object', type: 'object' },+ { value: 'file', label: 'file', type: 'file' },+ { value: 'array[string]', label: 'array[string]', type: 'array', arrayItemType: 'string' },+ { value: 'array[number]', label: 'array[number]', type: 'array', arrayItemType: 'number' },+ { value: 'array[boolean]', label: 'array[boolean]', type: 'array', arrayItemType: 'boolean' },+ { value: 'array[object]', label: 'array[object]', type: 'array', arrayItemType: 'object' },+ { value: 'array[file]', label: 'array[file]', type: 'array', arrayItemType: 'file' },+]++export function getAgentOutputTypeOption(value: AgentOutputTypeOptionValue) {+ return AGENT_OUTPUT_TYPE_OPTIONS.find(option => option.value === value) || AGENT_OUTPUT_TYPE_OPTIONS[0]!+}++function isSupportedAgentOutputFileName(name: string) {+ const match = AGENT_OUTPUT_FILE_NAME_PATTERN.exec(name.trim())+ if (!match)+ return false++ return AGENT_OUTPUT_FILE_EXTENSION_WHITELIST.has(match[1]!.toLowerCase())+}++export function inferAgentOutputType(name: string, fallbackType: AgentOutputTypeOptionValue): AgentOutputTypeOptionValue {+ if (isSupportedAgentOutputFileName(name))+ return 'file'++ return fallbackType+}++export function getAgentOutputTypeOptionValue(output: DeclaredOutputConfig): AgentOutputTypeOptionValue {+ if (output.type !== 'array')+ return output.type++ return `array[${output.array_item?.type || 'object'}]` as AgentOutputTypeOptionValue+}++export function createAgentOutputConfig(name: string, type: AgentOutputTypeOptionValue): DeclaredOutputConfig {+ const option = getAgentOutputTypeOption(type)+ const output: DeclaredOutputConfig = {+ name: name.trim(),+ type: option.type,+ required: false,+ }++ if (option.type === 'array') {+ output.array_item = {+ type: option.arrayItemType || 'object',+ }+ }++ if (option.type === 'file') {+ output.file = {+ extensions: [],+ mime_types: [],+ }+ }++ return output+}++export function getUniqueAgentOutputName(outputs: DeclaredOutputConfig[]) {+ const outputNames = new Set(outputs.map(output => output.name))+ const baseName = 'output'+ if (!outputNames.has(baseName))+ return baseName++ let index = 1+ while (outputNames.has(`${baseName}_${index}`))+ index += 1++ return `${baseName}_${index}`+}diff --git a/web/app/components/base/prompt-editor/plugins/component-picker-block/__tests__/index.spec.tsx b/web/app/components/base/prompt-editor/plugins/component-picker-block/__tests__/index.spec.tsxindex 886b23f18b2..9465c2027fe 100644--- a/web/app/components/base/prompt-editor/plugins/component-picker-block/__tests__/index.spec.tsx+++ b/web/app/components/base/prompt-editor/plugins/component-picker-block/__tests__/index.spec.tsx@@ -1,6 +1,7 @@import type { EventEmitter } from 'ahooks/lib/useEventEmitter'import type { LexicalEditor } from 'lexical'import type {+ AgentOutputBlockType,ContextBlockType,CurrentBlockType,ErrorMessageBlockType,@@ -33,6 +34,7 @@ import { VAR_REFERENCE_CHILD_POPUP_CLASS_NAME } from '@/app/components/workflow/import { VarType } from '@/app/components/workflow/types'import { useEventEmitterContextContext } from '@/context/event-emitter'import { EventEmitterContextProvider } from '@/context/event-emitter-provider'+import { INSERT_AGENT_OUTPUT_BLOCK_COMMAND } from '../../agent-output-block/commands'import { INSERT_CONTEXT_BLOCK_COMMAND } from '../../context-block'import { INSERT_CURRENT_BLOCK_COMMAND } from '../../current-block'import { INSERT_ERROR_MESSAGE_BLOCK_COMMAND } from '../../error-message-block'@@ -148,6 +150,7 @@ const MinimalEditor: React.FC<{queryBlock?: QueryBlockTypevariableBlock?: VariableBlockTypeworkflowVariableBlock?: WorkflowVariableBlockType+ agentOutputBlock?: AgentOutputBlockTypecurrentBlock?: CurrentBlockTypeerrorMessageBlock?: ErrorMessageBlockTypelastRunBlock?: LastRunBlockType@@ -158,6 +161,7 @@ const MinimalEditor: React.FC<{queryBlock,variableBlock,workflowVariableBlock,+ agentOutputBlock,currentBlock,errorMessageBlock,lastRunBlock,@@ -187,6 +191,7 @@ const MinimalEditor: React.FC<{queryBlock={queryBlock}variableBlock={variableBlock}workflowVariableBlock={workflowVariableBlock}+ agentOutputBlock={agentOutputBlock}currentBlock={currentBlock}errorMessageBlock={errorMessageBlock}lastRunBlock={lastRunBlock}@@ -600,6 +605,48 @@ describe('ComponentPicker (component-picker-block/index.tsx)', () => {})})+ it('clears slash trigger state after creating an agent output from the footer action', async () => {+ const captures: Captures = { editor: null, eventEmitter: null }++ render((+ <MinimalEditor+ triggerString="/"+ workflowVariableBlock={makeWorkflowVariableBlock({}, [+ makeWorkflowVarNode('node-1', 'Node 1', [+ makeWorkflowNodeVar('output', VarType.string),+ ]),+ ])}+ agentOutputBlock={{+ show: true,+ outputs: [],+ onChange: vi.fn(),+ }}+ captures={captures}+ />+ ))++ const editor = await waitForEditor(captures)+ const dispatchSpy = vi.spyOn(editor, 'dispatchCommand')++ await setEditorText(editor, '/', true)+ await flushNextTick()++ const newOutputAction = await screen.findByText('workflow.nodes.agent.outputVars.newOutput')+ fireEvent.click(newOutputAction)++ expect(dispatchSpy).toHaveBeenCalledWith(INSERT_AGENT_OUTPUT_BLOCK_COMMAND, undefined)+ await waitFor(() => {+ expect(readEditorText(editor)).not.toContain('/')+ expect(screen.queryByText('workflow.nodes.agent.outputVars.newOutput')).not.toBeInTheDocument()+ })++ const editable = screen.getByTestId(CONTENT_EDITABLE_TEST_ID)+ fireEvent.focus(editable)++ await flushNextTick()+ expect(screen.queryByText('workflow.nodes.agent.outputVars.newOutput')).not.toBeInTheDocument()+ })+it('defaults to the first workflow variable and removes the full slash query when selecting by keyboard', async () => {const captures: Captures = { editor: null, eventEmitter: null }diff --git a/web/app/components/base/prompt-editor/plugins/component-picker-block/index.tsx b/web/app/components/base/prompt-editor/plugins/component-picker-block/index.tsxindex 5aa207e2d39..afe43d2c379 100644--- a/web/app/components/base/prompt-editor/plugins/component-picker-block/index.tsx+++ b/web/app/components/base/prompt-editor/plugins/component-picker-block/index.tsx@@ -1,6 +1,7 @@import type { MenuRenderFn } from '@lexical/react/LexicalTypeaheadMenuPlugin'import type { LexicalEditor, TextNode } from 'lexical'import type {+ AgentOutputBlockType,ContextBlockType,CurrentBlockType,ErrorMessageBlockType,@@ -39,11 +40,13 @@ import {useState,} from 'react'import ReactDOM from 'react-dom'+import { useTranslation } from 'react-i18next'import { GeneratorType } from '@/app/components/app/configuration/config/automatic/types'import VarReferenceVars, { VAR_REFERENCE_CHILD_POPUP_CLASS_NAME } from '@/app/components/workflow/nodes/_base/components/variable/var-reference-vars'import { useEventEmitterContextContext } from '@/context/event-emitter'import { useBasicTypeaheadTriggerMatch } from '../../hooks'import { $splitNodeContainingQuery } from '../../utils'+import { INSERT_AGENT_OUTPUT_BLOCK_COMMAND } from '../agent-output-block/commands'import { INSERT_CURRENT_BLOCK_COMMAND } from '../current-block'import { INSERT_ERROR_MESSAGE_BLOCK_COMMAND } from '../error-message-block'import { INSERT_LAST_RUN_BLOCK_COMMAND } from '../last-run-block'@@ -60,6 +63,7 @@ type ComponentPickerProps = {variableBlock?: VariableBlockTypeexternalToolBlock?: ExternalToolBlockTypeworkflowVariableBlock?: WorkflowVariableBlockType+ agentOutputBlock?: AgentOutputBlockTypecurrentBlock?: CurrentBlockTypeerrorMessageBlock?: ErrorMessageBlockTypelastRunBlock?: LastRunBlockType@@ -74,11 +78,13 @@ const ComponentPicker = ({variableBlock,externalToolBlock,workflowVariableBlock,+ agentOutputBlock,currentBlock,errorMessageBlock,lastRunBlock,isSupportFileVar,}: ComponentPickerProps) => {+ const { t } = useTranslation()const { eventEmitter } = useEventEmitterContextContext()const { refs, floatingStyles, isPositioned } = useFloating({placement: 'bottom-start',@@ -105,6 +111,7 @@ const ComponentPicker = ({const [queryString, setQueryString] = useState<string | null>(null)const [blurHidden, setBlurHidden] = useState(false)const blurTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)+ const showAgentOutputAction = triggerString === '/' && agentOutputBlock?.showconst clearBlurTimer = useCallback(() => {if (blurTimerRef.current) {@@ -210,6 +217,12 @@ const ComponentPicker = ({}}, [editor, currentBlock?.generatorType, checkForTriggerMatch, triggerString])+ const resetTypeaheadState = useCallback(() => {+ triggerMatchRef.current = null+ setQueryString(null)+ setBlurHidden(true)+ }, [])+const handleClose = useCallback(() => {const escapeEvent = new KeyboardEvent('keydown', { key: 'Escape' })editor.dispatchCommand(KEY_ESCAPE_COMMAND, escapeEvent)@@ -223,7 +236,7 @@ const ComponentPicker = ({if (blurHidden)return null- if (!(anchorElementRef.current && (allFlattenOptions.length || workflowVariableBlock?.show)))+ if (!(anchorElementRef.current && (allFlattenOptions.length || workflowVariableBlock?.show || showAgentOutputAction)))return nullsetTimeout(() => {@@ -299,6 +312,29 @@ const ComponentPicker = ({))}</div>+ {showAgentOutputAction && (+ <div className="mt-1 border-t border-divider-subtle p-1">+ <button+ type="button"+ className="flex h-6 w-full items-center gap-1 rounded-md py-1 pr-1 pl-3 text-left system-sm-regular text-text-secondary hover:bg-state-base-hover focus-visible:bg-state-base-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"+ onMouseDown={event => event.preventDefault()}+ onClick={() => {+ editor.update(() => {+ const currentTriggerMatch = triggerMatchRef.current ?? checkForTriggerMatch(triggerString, editor)+ const needRemove = currentTriggerMatch ? $splitNodeContainingQuery(currentTriggerMatch) : null+ if (needRemove)+ needRemove.remove()+ })+ editor.dispatchCommand(INSERT_AGENT_OUTPUT_BLOCK_COMMAND, undefined)+ resetTypeaheadState()+ }}+ >+ <span aria-hidden="true" className="i-ri-add-line size-4 shrink-0" />+ <span className="min-w-0 flex-1 truncate">{t('nodes.agent.outputVars.newOutput', { ns: 'workflow' })}</span>+ <span aria-hidden="true" className="i-ri-question-line size-3.5 shrink-0 text-text-quaternary" />+ </button>+ </div>+ )}</div></div>,anchorElementRef.current,@@ -306,7 +342,7 @@ const ComponentPicker = ({}</>)- }, [blurHidden, allFlattenOptions.length, workflowVariableBlock?.show, floatingStyles, isPositioned, refs, workflowVariableOptions, isSupportFileVar, handleClose, currentBlock?.generatorType, handleSelectWorkflowVariable, queryString, triggerString, workflowVariableBlock?.showManageInputField, workflowVariableBlock?.onManageInputField])+ }, [blurHidden, allFlattenOptions.length, workflowVariableBlock?.show, showAgentOutputAction, floatingStyles, isPositioned, refs, workflowVariableOptions, isSupportFileVar, handleClose, currentBlock?.generatorType, handleSelectWorkflowVariable, queryString, triggerString, workflowVariableBlock?.showManageInputField, workflowVariableBlock?.onManageInputField, editor, checkForTriggerMatch, t, resetTypeaheadState])return (<LexicalTypeaheadMenuPlugindiff --git a/web/app/components/base/prompt-editor/plugins/roster-reference-block/__tests__/node.spec.tsx b/web/app/components/base/prompt-editor/plugins/roster-reference-block/__tests__/node.spec.tsxnew file mode 100644index 00000000000..178a20f71d6--- /dev/null+++ b/web/app/components/base/prompt-editor/plugins/roster-reference-block/__tests__/node.spec.tsx@@ -0,0 +1,119 @@+import type {+ Klass,+ LexicalEditor,+ LexicalNode,+} from 'lexical'+import { render, screen } from '@testing-library/react'+import { createEditor } from 'lexical'+import RosterReferenceBlockComponent from '../component'+import {+ $createRosterReferenceBlockNode,+ $isRosterReferenceBlockNode,+ RosterReferenceBlockNode,+} from '../node'+import {+ getRosterReferenceFileIconType,+ parseRosterReferenceToken,+} from '../utils'++describe('RosterReferenceBlockNode', () => {+ let editor: LexicalEditor++ beforeEach(() => {+ vi.clearAllMocks()+ editor = createEditor({+ nodes: [RosterReferenceBlockNode as unknown as Klass<LexicalNode>],+ })+ })++ const runInEditor = (callback: () => void) => {+ editor.update(callback, { discrete: true })+ }++ it('should parse roster reference tokens and infer icon classes', () => {+ expect(parseRosterReferenceToken('[§skill:2c3176de8a01:tender-analyzer§]')).toEqual({+ kind: 'skill',+ id: '2c3176de8a01',+ label: 'tender-analyzer',+ })+ expect(parseRosterReferenceToken('[§file:1f0ad3e2:qna_report:final.pdf§]')).toEqual({+ kind: 'file',+ id: '1f0ad3e2',+ label: 'qna_report:final.pdf',+ })+ expect(parseRosterReferenceToken('[§unknown:1:item§]')).toBeNull()+ expect(getRosterReferenceFileIconType('qna_report.pdf')).toBe('pdf')+ })++ it('should render a non-editable token pill component', () => {+ const { container } = render(+ <RosterReferenceBlockComponent text="[§tool-all:tavily/tavily:tavily§]" />,+ )++ const token = screen.getByTitle('tavily')+ expect(token).toHaveAttribute('contenteditable', 'false')+ expect(token).toHaveAttribute('data-roster-reference-kind', 'tool-all')+ expect(token).toHaveAttribute('data-roster-reference-id', 'tavily/tavily')+ expect(token).toHaveClass('border-state-accent-hover-alt')+ expect(token).toHaveClass('bg-state-accent-hover')+ expect(token).toHaveTextContent('tavily')+ expect(container.querySelector('.i-custom-public-other-default-tool-icon')).toBeInTheDocument()+ })++ it('should render knowledge icon with the configured retrieval row style', () => {+ const { container } = render(+ <RosterReferenceBlockComponent text="[§knowledge:manual-1:产品手册§]" />,+ )++ const iconShell = container.querySelector('.bg-util-colors-green-green-500')+ expect(iconShell).toBeInTheDocument()+ expect(iconShell).toHaveClass('text-text-primary-on-surface')+ expect(iconShell?.querySelector('.i-ri-book-open-line')).toBeInTheDocument()+ })++ it('should expose DecoratorNode behavior and preserve raw text content', () => {+ runInEditor(() => {+ const node = new RosterReferenceBlockNode('[§tool-all:tavily/tavily:tavily§]', 'node-key')+ const cloned = RosterReferenceBlockNode.clone(node)+ const dom = node.createDOM()++ expect(RosterReferenceBlockNode.getType()).toBe('roster-reference-block')+ expect(cloned).toBeInstanceOf(RosterReferenceBlockNode)+ expect(cloned.getKey()).toBe('node-key')+ expect(node.isInline()).toBe(true)+ expect(dom).toHaveClass('inline-flex')+ expect(dom).toHaveClass('align-middle')+ expect(node.getTextContent()).toBe('[§tool-all:tavily/tavily:tavily§]')+ })+ })++ it('should import and export serialized node text', () => {+ runInEditor(() => {+ const imported = RosterReferenceBlockNode.importJSON({+ text: '[§knowledge:manual-1:产品手册§]',+ type: 'roster-reference-block',+ version: 1,+ })+ const exported = imported.exportJSON()++ expect(exported).toEqual({+ text: '[§knowledge:manual-1:产品手册§]',+ type: 'roster-reference-block',+ version: 1,+ })+ })+ })++ it('should create node with helper and support type guard checks', () => {+ runInEditor(() => {+ const node = $createRosterReferenceBlockNode('[§skill:playwright:Playwright§]')++ expect(node).toBeInstanceOf(RosterReferenceBlockNode)+ expect(node.getTextContent()).toBe('[§skill:playwright:Playwright§]')+ expect($isRosterReferenceBlockNode(node)).toBe(true)+ expect($isRosterReferenceBlockNode(null)).toBe(false)+ expect($isRosterReferenceBlockNode(undefined)).toBe(false)+ expect($isRosterReferenceBlockNode({} as LexicalNode)).toBe(false)+ })+ })+})diff --git a/web/app/components/base/prompt-editor/plugins/roster-reference-block/component.tsx b/web/app/components/base/prompt-editor/plugins/roster-reference-block/component.tsxnew file mode 100644index 00000000000..bfe83cd322b--- /dev/null+++ b/web/app/components/base/prompt-editor/plugins/roster-reference-block/component.tsx@@ -0,0 +1,55 @@+import { cn } from '@langgenius/dify-ui/cn'+import { FileTreeIcon } from '@langgenius/dify-ui/file-tree'+import { use } from 'react'+import { RosterReferenceBlockContext } from './context'+import {+ getRosterReferenceFileIconType,+ getRosterReferenceIconClassName,+ parseRosterReferenceToken,+} from './utils'++type RosterReferenceBlockComponentProps = {+ text: string+}++const RosterReferenceBlockComponent = ({+ text,+}: RosterReferenceBlockComponentProps) => {+ const rosterReferenceBlock = use(RosterReferenceBlockContext)+ const token = parseRosterReferenceToken(text)++ if (!token)+ return null++ const isKnowledge = token.kind === 'knowledge'+ const customIcon = rosterReferenceBlock?.renderIcon?.(token)+ const defaultIcon = token.kind === 'file'+ ? <FileTreeIcon type={getRosterReferenceFileIconType(token.label)} className="size-4" />+ : <span className={cn(isKnowledge ? 'size-3.5' : 'size-3.5 shrink-0', getRosterReferenceIconClassName(token))} />++ return (+ <span+ contentEditable={false}+ data-roster-reference-kind={token.kind}+ data-roster-reference-id={token.id}+ title={token.label}+ className="inline-flex min-w-[18px] items-center gap-0.5 overflow-hidden rounded-[5px] border border-state-accent-hover-alt bg-state-accent-hover py-px pr-1 pl-px align-middle shadow-xs shadow-shadow-shadow-3"+ >+ <span+ aria-hidden+ className={cn(+ 'inline-flex size-4 shrink-0 items-center justify-center rounded-[5px] border-[0.5px] border-divider-subtle bg-background-default-dodge',+ token.kind === 'cli_tool' && 'border-divider-regular bg-text-tertiary',+ isKnowledge && 'border-divider-subtle bg-util-colors-green-green-500 p-[3px] text-text-primary-on-surface shadow-xs shadow-shadow-shadow-3',+ )}+ >+ {customIcon || defaultIcon}+ </span>+ <span className="max-w-48 truncate system-xs-medium text-text-accent">+ {token.label}+ </span>+ </span>+ )+}++export default RosterReferenceBlockComponentdiff --git a/web/app/components/base/prompt-editor/plugins/roster-reference-block/context.ts b/web/app/components/base/prompt-editor/plugins/roster-reference-block/context.tsnew file mode 100644index 00000000000..2669dc27178--- /dev/null+++ b/web/app/components/base/prompt-editor/plugins/roster-reference-block/context.ts@@ -0,0 +1,4 @@+import type { RosterReferenceBlockType } from '../../types'+import { createContext } from 'react'++export const RosterReferenceBlockContext = createContext<RosterReferenceBlockType | undefined>(undefined)diff --git a/web/app/components/base/prompt-editor/plugins/roster-reference-block/index.tsx b/web/app/components/base/prompt-editor/plugins/roster-reference-block/index.tsxnew file mode 100644index 00000000000..64354617017--- /dev/null+++ b/web/app/components/base/prompt-editor/plugins/roster-reference-block/index.tsx@@ -0,0 +1,63 @@+import type { EntityMatch } from '@lexical/text'+import type { LexicalEditor, TextNode } from 'lexical'+import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'+import { mergeRegister } from '@lexical/utils'+import { $applyNodeReplacement } from 'lexical'+import {+ useCallback,+ useEffect,+} from 'react'+import { decoratorTransform } from '../../utils'+import { CustomTextNode } from '../custom-text/node'+import { RosterReferenceBlockNode } from './node'+import { ROSTER_REFERENCE_REGEX } from './utils'++type RosterReferenceNodeRegistry = {+ _nodes: Map<string, { klass: typeof RosterReferenceBlockNode }>+}++function createRegisteredRosterReferenceBlockNode(editor: LexicalEditor, textNode: TextNode): RosterReferenceBlockNode {+ const RegisteredRosterReferenceBlockNode = (editor as unknown as RosterReferenceNodeRegistry)+ ._nodes+ .get(RosterReferenceBlockNode.getType())+ ?.klass ?? RosterReferenceBlockNode++ return $applyNodeReplacement(new RegisteredRosterReferenceBlockNode(textNode.getTextContent()))+}++const RosterReferenceBlock = () => {+ const [editor] = useLexicalComposerContext()++ useEffect(() => {+ if (!editor.hasNodes([RosterReferenceBlockNode]))+ throw new Error('RosterReferenceBlockPlugin: RosterReferenceBlockNode not registered on editor')+ }, [editor])++ const createRosterReferenceBlockNode = useCallback((textNode: CustomTextNode): RosterReferenceBlockNode => (+ createRegisteredRosterReferenceBlockNode(editor, textNode)+ ), [editor])++ const getRosterReferenceMatch = useCallback((text: string): EntityMatch | null => {+ const matchArr = ROSTER_REFERENCE_REGEX.exec(text)++ if (matchArr === null)+ return null++ const startOffset = matchArr.index+ const endOffset = startOffset + matchArr[0].length+ return {+ end: endOffset,+ start: startOffset,+ }+ }, [])++ useEffect(() => {+ return mergeRegister(+ editor.registerNodeTransform(CustomTextNode, textNode => decoratorTransform(textNode, getRosterReferenceMatch, createRosterReferenceBlockNode)),+ )+ }, [createRosterReferenceBlockNode, editor, getRosterReferenceMatch])++ return null+}++export default RosterReferenceBlockdiff --git a/web/app/components/base/prompt-editor/plugins/roster-reference-block/node.tsx b/web/app/components/base/prompt-editor/plugins/roster-reference-block/node.tsxnew file mode 100644index 00000000000..19c33f44918--- /dev/null+++ b/web/app/components/base/prompt-editor/plugins/roster-reference-block/node.tsx@@ -0,0 +1,76 @@+import type {+ LexicalNode,+ NodeKey,+ SerializedLexicalNode,+} from 'lexical'+import type { JSX } from 'react'+import {+ $applyNodeReplacement,+ DecoratorNode,+} from 'lexical'+import RosterReferenceBlockComponent from './component'++type SerializedRosterReferenceBlockNode = SerializedLexicalNode & {+ text: string+}++export class RosterReferenceBlockNode extends DecoratorNode<JSX.Element> {+ __text: string++ static override getType(): string {+ return 'roster-reference-block'+ }++ static override clone(node: RosterReferenceBlockNode): RosterReferenceBlockNode {+ return new RosterReferenceBlockNode(node.__text, node.__key)+ }++ constructor(text: string, key?: NodeKey) {+ super(key)+ this.__text = text+ }++ override isInline(): boolean {+ return true+ }++ override createDOM(): HTMLElement {+ const span = document.createElement('span')+ span.classList.add('inline-flex', 'items-center', 'align-middle')+ return span+ }++ override updateDOM(): false {+ return false+ }++ override decorate(): JSX.Element {+ return <RosterReferenceBlockComponent text={this.getTextContent()} />+ }++ static override importJSON(serializedNode: SerializedRosterReferenceBlockNode): RosterReferenceBlockNode {+ return $createRosterReferenceBlockNode(serializedNode.text)+ }++ override exportJSON(): SerializedRosterReferenceBlockNode {+ return {+ text: this.getTextContent(),+ type: 'roster-reference-block',+ version: 1,+ }+ }++ override getTextContent(): string {+ return this.getLatest().__text+ }+}++export function $createRosterReferenceBlockNode(text = ''): RosterReferenceBlockNode {+ return $applyNodeReplacement(new RosterReferenceBlockNode(text))+}++export function $isRosterReferenceBlockNode(+ node: LexicalNode | null | undefined,+): node is RosterReferenceBlockNode {+ return node instanceof RosterReferenceBlockNode+}diff --git a/web/app/components/base/prompt-editor/plugins/roster-reference-block/utils.ts b/web/app/components/base/prompt-editor/plugins/roster-reference-block/utils.tsnew file mode 100644index 00000000000..82af42492da--- /dev/null+++ b/web/app/components/base/prompt-editor/plugins/roster-reference-block/utils.ts@@ -0,0 +1,111 @@+import type { FileTreeIconType } from '@langgenius/dify-ui/file-tree'++type RosterReferenceKind = 'skill' | 'file' | 'tool-all' | 'tool' | 'cli_tool' | 'knowledge'++export type RosterReferenceToken = {+ kind: RosterReferenceKind+ id: string+ label: string+}++export const ROSTER_REFERENCE_REGEX = /\[§(?:skill|file|tool-all|tool|cli_tool|knowledge):[^\]§\n\r]+§\]/++const KNOWN_KINDS = new Set<RosterReferenceKind>([+ 'skill',+ 'file',+ 'tool-all',+ 'tool',+ 'cli_tool',+ 'knowledge',+])++export function parseRosterReferenceToken(text: string): RosterReferenceToken | null {+ if (!text.startsWith('[§') || !text.endsWith('§]'))+ return null++ const body = text.slice(2, -2)+ const firstColonIndex = body.indexOf(':')+ if (firstColonIndex === -1)+ return null++ const kind = body.slice(0, firstColonIndex) as RosterReferenceKind+ if (!KNOWN_KINDS.has(kind))+ return null++ const rest = body.slice(firstColonIndex + 1)+ const secondColonIndex = rest.indexOf(':')+ const id = secondColonIndex === -1 ? rest : rest.slice(0, secondColonIndex)+ const label = secondColonIndex === -1 ? id : rest.slice(secondColonIndex + 1)++ if (!id || !label)+ return null++ return {+ kind,+ id,+ label,+ }+}++const codeFileExtensions = new Set([+ 'css',+ 'go',+ 'html',+ 'htm',+ 'js',+ 'jsx',+ 'py',+ 'rb',+ 'rs',+ 'scss',+ 'sh',+ 'ts',+ 'tsx',+ 'vue',+ 'yaml',+ 'yml',+])+const imageFileExtensions = new Set(['apng', 'avif', 'bmp', 'gif', 'ico', 'jpeg', 'jpg', 'png', 'svg', 'webp'])+const tableFileExtensions = new Set(['csv', 'xls', 'xlsx'])+const archiveFileExtensions = new Set(['7z', 'gz', 'rar', 'tar', 'zip'])++export function getRosterReferenceFileIconType(label: string): FileTreeIconType {+ const extension = label.includes('.') ? label.split('.').pop()?.toLowerCase() : undefined++ if (!extension)+ return 'folder'+ if (imageFileExtensions.has(extension))+ return 'image'+ if (extension === 'pdf')+ return 'pdf'+ if (extension === 'md' || extension === 'markdown' || extension === 'mdx')+ return 'markdown'+ if (extension === 'json')+ return 'json'+ if (tableFileExtensions.has(extension))+ return 'table'+ if (archiveFileExtensions.has(extension))+ return 'archive'+ if (codeFileExtensions.has(extension))+ return 'code'+ if (extension === 'txt')+ return 'text'++ return 'file'+}++export function getRosterReferenceIconClassName(token: RosterReferenceToken) {+ switch (token.kind) {+ case 'skill':+ return 'i-custom-public-agent-building-blocks text-text-tertiary'+ case 'file':+ return ''+ case 'tool-all':+ case 'tool':+ return 'i-custom-public-other-default-tool-icon text-[#ef5b39]'+ case 'cli_tool':+ return 'i-ri-terminal-box-line text-text-primary-on-surface'+ case 'knowledge':+ return 'i-ri-book-open-line'+ }+}diff --git a/web/app/components/base/prompt-editor/prompt-editor-content.tsx b/web/app/components/base/prompt-editor/prompt-editor-content.tsxindex ac2385fa341..db0a8361c29 100644--- a/web/app/components/base/prompt-editor/prompt-editor-content.tsx+++ b/web/app/components/base/prompt-editor/prompt-editor-content.tsx@@ -2,6 +2,7 @@ import type { EditorState } from 'lexical'import type { FC } from 'react'import type { Hotkey, ShortcutPopupDisplayMode, ShortcutPopupInsertHandler } from './plugins/shortcuts-popup-plugin'import type {+ AgentOutputBlockType,ContextBlockType,CurrentBlockType,ErrorMessageBlockType,@@ -11,6 +12,7 @@ import type {LastRunBlockType,QueryBlockType,RequestURLBlockType,+ RosterReferenceBlockType,VariableBlockType,WorkflowVariableBlockType,} from './types'@@ -21,6 +23,10 @@ import { HistoryPlugin } from '@lexical/react/LexicalHistoryPlugin'import { OnChangePlugin } from '@lexical/react/LexicalOnChangePlugin'import { RichTextPlugin } from '@lexical/react/LexicalRichTextPlugin'import * as React from 'react'+import {+ AgentOutputBlock,+ AgentOutputBlockReplacementBlock,+} from './plugins/agent-output-block'import ComponentPickerBlock from './plugins/component-picker-block'import {ContextBlock,@@ -57,6 +63,8 @@ import {RequestURLBlock,RequestURLBlockReplacementBlock,} from './plugins/request-url-block'+import RosterReferenceBlock from './plugins/roster-reference-block'+import { RosterReferenceBlockContext } from './plugins/roster-reference-block/context'import ShortcutsPopupPlugin from './plugins/shortcuts-popup-plugin'import UpdateBlock from './plugins/update-block'import VariableBlock from './plugins/variable-block'@@ -84,13 +92,17 @@ type PromptEditorContentProps = {requestURLBlock?: RequestURLBlockTypehistoryBlock?: HistoryBlockTypevariableBlock?: VariableBlockType+ rosterReferenceBlock?: RosterReferenceBlockTypeexternalToolBlock?: ExternalToolBlockTypeworkflowVariableBlock?: WorkflowVariableBlockType+ agentOutputBlock?: AgentOutputBlockTypehitlInputBlock?: HITLInputBlockTypecurrentBlock?: CurrentBlockTypeerrorMessageBlock?: ErrorMessageBlockTypelastRunBlock?: LastRunBlockTypeisSupportFileVar?: boolean+ disableSlashPicker?: boolean+ disableBracePicker?: booleanonBlur?: () => voidonFocus?: () => voidinstanceId?: string@@ -110,13 +122,17 @@ const PromptEditorContent: FC<PromptEditorContentProps> = ({requestURLBlock,historyBlock,variableBlock,+ rosterReferenceBlock,externalToolBlock,workflowVariableBlock,+ agentOutputBlock,hitlInputBlock,currentBlock,errorMessageBlock,lastRunBlock,isSupportFileVar,+ disableSlashPicker,+ disableBracePicker,onBlur,onFocus,instanceId,@@ -124,7 +140,7 @@ const PromptEditorContent: FC<PromptEditorContentProps> = ({onEditorChange,}) => {return (- <>+ <RosterReferenceBlockContext value={rosterReferenceBlock}><RichTextPlugincontentEditable={(<ContentEditable@@ -150,34 +166,40 @@ const PromptEditorContent: FC<PromptEditorContentProps> = ({{(closePortal, onInsert) => <Popup onClose={closePortal} onInsert={onInsert} />}</ShortcutsPopupPlugin>))}- <ComponentPickerBlock- triggerString="/"- contextBlock={contextBlock}- historyBlock={historyBlock}- queryBlock={queryBlock}- requestURLBlock={requestURLBlock}- variableBlock={variableBlock}- externalToolBlock={externalToolBlock}- workflowVariableBlock={workflowVariableBlock}- currentBlock={currentBlock}- errorMessageBlock={errorMessageBlock}- lastRunBlock={lastRunBlock}- isSupportFileVar={isSupportFileVar}- />- <ComponentPickerBlock- triggerString="{"- contextBlock={contextBlock}- historyBlock={historyBlock}- queryBlock={queryBlock}- requestURLBlock={requestURLBlock}- variableBlock={variableBlock}- externalToolBlock={externalToolBlock}- workflowVariableBlock={workflowVariableBlock}- currentBlock={currentBlock}- errorMessageBlock={errorMessageBlock}- lastRunBlock={lastRunBlock}- isSupportFileVar={isSupportFileVar}- />+ {!disableSlashPicker && (+ <ComponentPickerBlock+ triggerString="/"+ contextBlock={contextBlock}+ historyBlock={historyBlock}+ queryBlock={queryBlock}+ requestURLBlock={requestURLBlock}+ variableBlock={variableBlock}+ externalToolBlock={externalToolBlock}+ workflowVariableBlock={workflowVariableBlock}+ agentOutputBlock={agentOutputBlock}+ currentBlock={currentBlock}+ errorMessageBlock={errorMessageBlock}+ lastRunBlock={lastRunBlock}+ isSupportFileVar={isSupportFileVar}+ />+ )}+ {!disableBracePicker && (+ <ComponentPickerBlock+ triggerString="{"+ contextBlock={contextBlock}+ historyBlock={historyBlock}+ queryBlock={queryBlock}+ requestURLBlock={requestURLBlock}+ variableBlock={variableBlock}+ externalToolBlock={externalToolBlock}+ workflowVariableBlock={workflowVariableBlock}+ agentOutputBlock={agentOutputBlock}+ currentBlock={currentBlock}+ errorMessageBlock={errorMessageBlock}+ lastRunBlock={lastRunBlock}+ isSupportFileVar={isSupportFileVar}+ />+ )}{contextBlock?.show && (<><ContextBlock {...contextBlock} />@@ -202,12 +224,21 @@ const PromptEditorContent: FC<PromptEditorContentProps> = ({<VariableValueBlock /></>)}+ {rosterReferenceBlock?.show && (+ <RosterReferenceBlock />+ )}{workflowVariableBlock?.show && (<><WorkflowVariableBlock {...workflowVariableBlock} /><WorkflowVariableBlockReplacementBlock {...workflowVariableBlock} /></>)}+ {agentOutputBlock?.show && (+ <>+ <AgentOutputBlock {...agentOutputBlock} />+ <AgentOutputBlockReplacementBlock {...agentOutputBlock} />+ </>+ )}{hitlInputBlock?.show && (<><HITLInputBlock {...hitlInputBlock} />@@ -248,7 +279,7 @@ const PromptEditorContent: FC<PromptEditorContentProps> = ({{floatingAnchorElem && (<DraggableBlockPlugin anchorElem={floatingAnchorElem} />)}- </>+ </RosterReferenceBlockContext>)}diff --git a/web/app/components/base/prompt-editor/types.ts b/web/app/components/base/prompt-editor/types.tsindex 93bbb2f8b7c..5846ca51229 100644--- a/web/app/components/base/prompt-editor/types.ts+++ b/web/app/components/base/prompt-editor/types.ts@@ -1,8 +1,10 @@+import type { DeclaredOutputConfig } from '@dify/contracts/api/console/apps/types.gen'import type { GeneratorType } from '../../app/configuration/config/automatic/types'import type { FormInputItem } from '../../workflow/nodes/human-input/types'import type { Type } from '../../workflow/nodes/llm/types'import type { Dataset } from './plugins/context-block'import type { RoleName } from './plugins/history-block'+import type { RosterReferenceToken } from './plugins/roster-reference-block/utils'import type {Node,NodeOutPutVar,@@ -59,6 +61,11 @@ export type VariableBlockType = {variables?: Option[]}+export type RosterReferenceBlockType = {+ show?: boolean+ renderIcon?: (token: RosterReferenceToken) => React.ReactNode+}+export type ExternalToolBlockType = {show?: booleanexternalTools?: ExternalToolOption[]@@ -81,6 +88,12 @@ export type WorkflowVariableBlockType = {onManageInputField?: () => void}+export type AgentOutputBlockType = {+ show?: boolean+ outputs?: DeclaredOutputConfig[]+ onChange?: (outputs: DeclaredOutputConfig[], prompt?: string) => void+}+export type WorkflowNodesMap = Record<string, Pick<Node['data'], 'title' | 'type' | 'height' | 'width' | 'position'> & { modelProvider?: string }>export type HITLInputBlockType = {diff --git a/web/app/components/base/prompt-editor/utils.ts b/web/app/components/base/prompt-editor/utils.tsindex af1d0524009..2f94ba7d087 100644--- a/web/app/components/base/prompt-editor/utils.ts+++ b/web/app/components/base/prompt-editor/utils.ts@@ -140,9 +140,9 @@ export function registerLexicalTextEntity<T extends TextNode>(let nodeToReplaceif (match.start === 0)- [nodeToReplace, currentNode] = (currentNode.splitText(match.end)) as [any, TextNode]+ [nodeToReplace, currentNode] = currentNode.splitText(match.end) as [TextNode, TextNode]else- [, nodeToReplace, currentNode] = (currentNode.splitText(match.start, match.end)) as [unknown, any, TextNode]+ [, nodeToReplace, currentNode] = currentNode.splitText(match.start, match.end) as [TextNode, TextNode, TextNode]const replacementNode = createNode(nodeToReplace!)replacementNode.setFormat(nodeToReplace!.getFormat())@@ -194,6 +194,9 @@ export const decoratorTransform = (node: CustomTextNode,getMatch: (text: string) => null | EntityMatch,createNode: (textNode: TextNode) => LexicalNode,+ options?: {+ allowAdjacentMatches?: boolean+ },) => {if (!node.isSimpleText())return@@ -227,7 +230,7 @@ export const decoratorTransform = (else {const nextMatch = getMatch(nextText)- if (nextMatch !== null && nextMatch.start === 0)+ if (!options?.allowAdjacentMatches && nextMatch !== null && nextMatch.start === 0)return}@@ -240,9 +243,9 @@ export const decoratorTransform = (let nodeToReplaceif (match.start === 0)- [nodeToReplace, currentNode] = (currentNode.splitText(match.end)) as [any, CustomTextNode]+ [nodeToReplace, currentNode] = currentNode.splitText(match.end) as [CustomTextNode, CustomTextNode]else- [, nodeToReplace, currentNode] = (currentNode.splitText(match.start, match.end)) as [unknown, any, CustomTextNode]+ [, nodeToReplace, currentNode] = currentNode.splitText(match.start, match.end) as [CustomTextNode, CustomTextNode, CustomTextNode]const replacementNode = createNode(nodeToReplace!)nodeToReplace!.replace(replacementNode)diff --git a/web/app/components/header/account-setting/__tests__/use-integrations-setting.spec.ts b/web/app/components/header/account-setting/__tests__/use-integrations-setting.spec.tsindex f850c60d8b7..e8b5536b40e 100644--- a/web/app/components/header/account-setting/__tests__/use-integrations-setting.spec.ts+++ b/web/app/components/header/account-setting/__tests__/use-integrations-setting.spec.ts@@ -40,4 +40,25 @@ describe('useIntegrationsSetting', () => {expect(mockSetShowAccountSettingModal).toHaveBeenCalledWith({ payload: 'mcp' })})++ it('should preserve the agent source for agent-scoped settings', () => {+ const { result } = renderHook(() => useIntegrationsSetting())++ act(() => {+ result.current({ payload: ACCOUNT_SETTING_TAB.PROVIDER, source: 'agent' })+ })++ expect(mockSetShowAccountSettingModal).toHaveBeenCalledWith({ payload: 'provider', source: 'agent' })+ })++ it('should preserve the cancel callback for migrated integrations settings', () => {+ const onCancelCallback = vi.fn()+ const { result } = renderHook(() => useIntegrationsSetting())++ act(() => {+ result.current({ payload: ACCOUNT_SETTING_TAB.PROVIDER, onCancelCallback })+ })++ expect(mockSetShowAccountSettingModal).toHaveBeenCalledWith({ payload: 'provider', onCancelCallback })+ })})diff --git a/web/app/components/header/account-setting/menu-dialog.tsx b/web/app/components/header/account-setting/menu-dialog.tsxindex ab2812bd1cc..9c9ec81db19 100644--- a/web/app/components/header/account-setting/menu-dialog.tsx+++ b/web/app/components/header/account-setting/menu-dialog.tsx@@ -4,6 +4,7 @@ import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'import { useCallback } from 'react'type DialogProps = {+ backdropClassName?: stringclassName?: stringchildren: ReactNodeshow: boolean@@ -11,6 +12,7 @@ type DialogProps = {}const MenuDialog = ({+ backdropClassName,className,children,show,@@ -27,7 +29,7 @@ const MenuDialog = ({}}><DialogContent- backdropClassName="z-40 bg-transparent"+ backdropClassName={cn('z-40 bg-transparent', backdropClassName)}className={cn('top-0 left-0 z-40 h-full max-h-none w-full max-w-none translate-x-0 translate-y-0 scale-100 overflow-hidden rounded-none border-none bg-background-sidenav-bg p-0 shadow-none backdrop-blur-md transition-opacity data-ending-style:scale-100 data-starting-style:scale-100',className,diff --git a/web/app/components/header/account-setting/model-provider-page/declarations.ts b/web/app/components/header/account-setting/model-provider-page/declarations.tsindex fc18f019a01..e497cb7614c 100644--- a/web/app/components/header/account-setting/model-provider-page/declarations.ts+++ b/web/app/components/header/account-setting/model-provider-page/declarations.ts@@ -247,6 +247,7 @@ export type DefaultModelResponse = {export type DefaultModel = {provider: stringmodel: string+ plugin_id?: string}export type CustomConfigurationModelFixedFields = {diff --git a/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/index.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/index.spec.tsxindex fd6b2298e74..41721774e68 100644--- a/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/index.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/index.spec.tsx@@ -108,7 +108,11 @@ describe('ModelSelector', () => {fireEvent.click(screen.getByRole('combobox'))fireEvent.click(screen.getByText('select'))- expect(onSelect).toHaveBeenCalledWith({ provider: 'openai', model: 'gpt-4' })+ expect(onSelect).toHaveBeenCalledWith({+ provider: 'openai',+ model: 'gpt-4',+ plugin_id: 'langgenius/openai',+ })})it('should close popup when popup requests hide', () => {diff --git a/web/app/components/header/account-setting/model-provider-page/model-selector/index.tsx b/web/app/components/header/account-setting/model-provider-page/model-selector/index.tsxindex 93e0ac8fae8..0b4f43d9072 100644--- a/web/app/components/header/account-setting/model-provider-page/model-selector/index.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-selector/index.tsx@@ -11,6 +11,15 @@ import ModelSelectorTrigger from './model-selector-trigger'import Popup from './popup'import { getModelSelectorValueLabel, isSameModelSelectorValue } from './types'+const getModelProviderPluginId = (provider: string) => {+ const [organization, pluginName] = provider.split('/').filter(Boolean)++ if (organization && pluginName)+ return `${organization}/${pluginName}`++ return provider ? `langgenius/${provider}` : ''+}+type ModelSelectorProps = {defaultModel?: DefaultModelmodelList: Model[]@@ -24,6 +33,7 @@ type ModelSelectorProps = {showDeprecatedWarnIcon?: booleanhideProviderSettingsFooter?: booleanonConfigureEmptyState?: () => void+ providerSettingsSource?: 'agent'showModelMeta?: boolean}function ModelSelector({@@ -39,6 +49,7 @@ function ModelSelector({showDeprecatedWarnIcon = true,hideProviderSettingsFooter,onConfigureEmptyState,+ providerSettingsSource,showModelMeta,}: ModelSelectorProps) {const { t } = useTranslation()@@ -74,8 +85,13 @@ function ModelSelector({setOpen(false)setInputValue('')- if (onSelect)- onSelect({ provider, model: model.model })+ if (onSelect) {+ onSelect({+ provider,+ model: model.model,+ plugin_id: getModelProviderPluginId(provider),+ })+ }}, [onSelect])const handleValueChange = useCallback((value: ModelSelectorValue | null) => {@@ -150,6 +166,7 @@ function ModelSelector({modelList={modelList}scopeFeatures={scopeFeatures}hideProviderSettingsFooter={hideProviderSettingsFooter}+ providerSettingsSource={providerSettingsSource}onConfigureEmptyState={onConfigureEmptyState ? handleConfigureEmptyState : undefined}onInputValueChange={setInputValue}onHide={handleHide}diff --git a/web/app/components/header/account-setting/model-provider-page/model-selector/popup.tsx b/web/app/components/header/account-setting/model-provider-page/model-selector/popup.tsxindex dd759fe60ad..7cf543a3568 100644--- a/web/app/components/header/account-setting/model-provider-page/model-selector/popup.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-selector/popup.tsx@@ -38,6 +38,7 @@ export type PopupProps = {modelList: Model[]scopeFeatures?: ModelFeatureEnum[]hideProviderSettingsFooter?: boolean+ providerSettingsSource?: 'agent'onConfigureEmptyState?: () => voidonInputValueChange: (value: string) => voidonHide: () => void@@ -48,6 +49,7 @@ function Popup({modelList,scopeFeatures = [],hideProviderSettingsFooter,+ providerSettingsSource,onConfigureEmptyState,onInputValueChange,onHide,@@ -173,8 +175,8 @@ function Popup({const handleOpenSettings = useCallback(() => {onHide()- openIntegrationsSetting({ payload: ACCOUNT_SETTING_TAB.PROVIDER })- }, [onHide, openIntegrationsSetting])+ openIntegrationsSetting({ payload: ACCOUNT_SETTING_TAB.PROVIDER, source: providerSettingsSource })+ }, [onHide, openIntegrationsSetting, providerSettingsSource])const handleClosePreviewCard = useCallback(() => {previewCardHandle.close()}, [previewCardHandle])diff --git a/web/app/components/header/account-setting/use-integrations-setting.ts b/web/app/components/header/account-setting/use-integrations-setting.tsindex 04f2f65a411..06181a5f56f 100644--- a/web/app/components/header/account-setting/use-integrations-setting.ts+++ b/web/app/components/header/account-setting/use-integrations-setting.ts@@ -7,8 +7,8 @@ import { useModalContext } from '@/context/modal-context'import { integrationSectionByMovedAccountSettingTab } from './destinations'type IntegrationsSettingState- = | { payload: MovedAccountSettingTab }- | { section: IntegrationSection }+ = | { payload: MovedAccountSettingTab, source?: 'agent', onCancelCallback?: () => void }+ | { section: IntegrationSection, source?: 'agent', onCancelCallback?: () => void }export const useIntegrationsSetting = () => {const { setShowAccountSettingModal } = useModalContext()@@ -19,7 +19,12 @@ export const useIntegrationsSetting = () => {? state.section: integrationSectionByMovedAccountSettingTab[state.payload]- if (section)- setShowAccountSettingModal({ payload: section })+ if (section) {+ setShowAccountSettingModal({+ payload: section,+ ...(state.source ? { source: state.source } : {}),+ ...(state.onCancelCallback ? { onCancelCallback: state.onCancelCallback } : {}),+ })+ }}, [setShowAccountSettingModal])}diff --git a/web/app/components/main-nav/__tests__/index.spec.tsx b/web/app/components/main-nav/__tests__/index.spec.tsxindex 0d3fee692d4..d86576bcac6 100644--- a/web/app/components/main-nav/__tests__/index.spec.tsx+++ b/web/app/components/main-nav/__tests__/index.spec.tsx@@ -24,15 +24,20 @@ import MainNav from '../index'const activeEdgeClassName = 'before:pointer-events-none'-const { mockSwitchWorkspace, mockToastSuccess, hotkeyRegistrations } = vi.hoisted(() => ({+const { mockIsAgentV2Enabled, mockSwitchWorkspace, mockToastSuccess, hotkeyRegistrations } = vi.hoisted(() => ({mockSwitchWorkspace: vi.fn(),mockToastSuccess: vi.fn(),+ mockIsAgentV2Enabled: vi.fn(() => true),hotkeyRegistrations: new Map<string, {handler: (event: { preventDefault: () => void }) => voidoptions?: { ignoreInputs?: boolean }}>(),}))+vi.mock('@/features/agent-v2/feature-flag', () => ({+ isAgentV2Enabled: () => mockIsAgentV2Enabled(),+}))+vi.mock('@/context/app-context', () => ({useAppContext: vi.fn(),}))@@ -159,6 +164,15 @@ vi.mock('@/app/components/app-sidebar/dataset-detail-top', () => ({),}))+vi.mock('@/features/agent-v2/agent-detail/navigation', () => ({+ AgentDetailSection: ({ expand }: { expand: boolean }) => <div data-testid="agent-detail-section" data-expand={expand} />,+ AgentDetailTop: ({ expand, onToggle }: { expand: boolean, onToggle: () => void }) => (+ <div data-testid="agent-detail-top" data-expand={expand}>+ <button type="button" data-testid="agent-detail-toggle" onClick={onToggle}>Toggle</button>+ </div>+ ),+}))+vi.mock('@/features/deployments/detail/deployment-sidebar', () => ({DeploymentDetailSection: ({ expand }: { expand: boolean }) => <div data-testid="deployment-detail-section" data-expand={expand} />,DeploymentDetailTop: ({ expand, onToggle }: { expand: boolean, onToggle: () => void }) => (@@ -285,6 +299,7 @@ describe('MainNav', () => {{ id: 'workspace-1', name: 'Solar Studio', plan: Plan.team, status: 'normal', created_at: 0, current: true },{ id: 'workspace-2', name: 'Evan Workspace', plan: Plan.sandbox, status: 'normal', created_at: 0, current: false },]+ mockIsAgentV2Enabled.mockReturnValue(true);(usePathname as Mock).mockImplementation(() => mockPathname);(useRouter as Mock).mockReturnValue({@@ -331,11 +346,20 @@ describe('MainNav', () => {expect(screen.getByRole('button', { name: 'common.account.account' })).not.toHaveTextContent(Plan.team)expect(screen.getByRole('link', { name: /common.mainNav.home/ })).toHaveAttribute('href', '/')expect(screen.getByRole('link', { name: /common.menus.apps/ })).toHaveAttribute('href', '/apps')+ expect(screen.getByRole('link', { name: /common.menus.roster/ })).toHaveAttribute('href', '/roster')expect(screen.getByRole('link', { name: /common.menus.datasets/ })).toHaveAttribute('href', '/datasets')expect(screen.getByRole('link', { name: /common.mainNav.integrations/ })).toHaveAttribute('href', '/integrations/model-provider')expect(screen.getByRole('link', { name: /common.mainNav.marketplace/ })).toHaveAttribute('href', '/marketplace')})+ it('hides the roster entry when Agent v2 is disabled', () => {+ mockIsAgentV2Enabled.mockReturnValue(false)++ renderMainNav()++ expect(screen.queryByRole('link', { name: /common.menus.roster/ })).not.toBeInTheDocument()+ })+it('renders deployments in primary navigation when app deploy is enabled', () => {renderMainNav({ branding: { enabled: false }, enable_app_deploy: true })@@ -460,6 +484,7 @@ describe('MainNav', () => {expect(screen.queryByRole('link', { name: /common.mainNav.home/ })).not.toBeInTheDocument()expect(screen.queryByRole('link', { name: /common.menus.apps/ })).not.toBeInTheDocument()+ expect(screen.queryByRole('link', { name: /common.menus.roster/ })).not.toBeInTheDocument()expect(screen.getByRole('link', { name: /common.menus.datasets/ })).toHaveAttribute('href', '/datasets')expect(screen.queryByRole('link', { name: /common.mainNav.integrations/ })).not.toBeInTheDocument()expect(screen.getByRole('link', { name: /common.mainNav.marketplace/ })).toHaveAttribute('href', '/marketplace')@@ -483,6 +508,7 @@ describe('MainNav', () => {expect(screen.getByRole('link', { name: /common.mainNav.home/ })).toBeInTheDocument()expect(screen.getByRole('link', { name: /common.menus.apps/ })).toBeInTheDocument()+ expect(screen.getByRole('link', { name: /common.menus.roster/ })).toBeInTheDocument()expect(screen.queryByRole('link', { name: /common.menus.datasets/ })).not.toBeInTheDocument()expect(screen.getByRole('link', { name: /common.mainNav.integrations/ })).toBeInTheDocument()expect(screen.queryByRole('link', { name: /common.menus.deployments/ })).not.toBeInTheDocument()@@ -652,6 +678,33 @@ describe('MainNav', () => {expect(screen.getByTestId('dataset-detail-section')).toHaveAttribute('data-expand', 'true')})+ it('replaces global navigation with agent detail navigation on roster detail routes', () => {+ mockPathname = '/roster/agent/agent-1/configure'++ renderMainNav()++ expect(screen.getByTestId('agent-detail-top')).toBeInTheDocument()+ expect(screen.getByTestId('agent-detail-section')).toBeInTheDocument()+ expect(screen.getByTestId('agent-detail-top')).toHaveAttribute('data-expand', 'true')+ expect(screen.getByTestId('agent-detail-section')).toHaveAttribute('data-expand', 'true')+ expect(screen.getByRole('complementary')).toHaveClass('w-[248px]')+ expect(screen.getByRole('complementary')).toHaveClass('p-1')+ expect(screen.getByRole('complementary')).toHaveClass('bg-background-body')+ expect(screen.queryByRole('button', { name: 'common.mainNav.workspace.openMenu' })).not.toBeInTheDocument()+ expect(screen.queryByRole('link', { name: /common.menus.roster/ })).not.toBeInTheDocument()+ })++ it('keeps roster detail navigation hidden when Agent v2 is disabled', () => {+ mockIsAgentV2Enabled.mockReturnValue(false)+ mockPathname = '/roster/agent/agent-1/configure'++ renderMainNav()++ expect(screen.queryByTestId('agent-detail-top')).not.toBeInTheDocument()+ expect(screen.queryByTestId('agent-detail-section')).not.toBeInTheDocument()+ expect(screen.queryByRole('link', { name: /common.menus.roster/ })).not.toBeInTheDocument()+ })+it('replaces global navigation with deployment detail navigation on deployment routes', () => {mockPathname = '/deployments/app-instance-1/releases'@@ -669,6 +722,19 @@ describe('MainNav', () => {expect(screen.queryByRole('link', { name: /common.menus.deployments/ })).not.toBeInTheDocument()})+ it('collapses agent detail navigation from the top-right toggle', () => {+ mockPathname = '/roster/agent/agent-1/configure'++ renderMainNav()+ fireEvent.click(screen.getByTestId('agent-detail-toggle'))++ expect(screen.getByRole('complementary')).toHaveClass('w-16')+ expect(screen.getByRole('complementary')).toHaveClass('p-1')+ expect(screen.getByTestId('agent-detail-top')).toHaveAttribute('data-expand', 'false')+ expect(screen.getByTestId('agent-detail-section')).toHaveAttribute('data-expand', 'false')+ expect(localStorage.getItem('app-detail-collapse-or-expand')).toBe('collapse')+ })+it('collapses deployment detail navigation from the top-right toggle', () => {mockPathname = '/deployments/app-instance-1/releases'@@ -705,6 +771,21 @@ describe('MainNav', () => {expect.objectContaining({ ignoreInputs: false }),)})++ it('shows agent detail navigation as a floating preview when hovering the collapsed top toggle', () => {+ mockPathname = '/roster/agent/agent-1/configure'++ renderMainNav()+ fireEvent.click(screen.getByTestId('agent-detail-toggle'))+ fireEvent.mouseEnter(screen.getByTestId('agent-detail-top').parentElement!)++ expect(screen.getByRole('complementary')).toHaveClass('w-16', 'overflow-visible')+ expect(localStorage.getItem('app-detail-collapse-or-expand')).toBe('collapse')+ expect(screen.getAllByTestId('agent-detail-top')).toHaveLength(1)+ expect(screen.getByTestId('agent-detail-top')).toHaveAttribute('data-expand', 'true')+ expect(screen.getByTestId('agent-detail-section')).toHaveAttribute('data-expand', 'true')+ })+it.each(['/datasets/create','/datasets/create-from-pipeline',@@ -731,6 +812,16 @@ describe('MainNav', () => {expect(marketplaceLink).toHaveClass(activeEdgeClassName)})+ it('marks roster active on roster routes', () => {+ mockPathname = '/roster'++ renderMainNav()++ const rosterLink = screen.getByRole('link', { name: /common.menus.roster/ })+ expect(rosterLink).toHaveClass(activeEdgeClassName)+ expect(rosterLink).toHaveAttribute('aria-current', 'page')+ })+it('applies the Figma glass active state to the Home route', () => {mockPathname = '/'diff --git a/web/app/components/main-nav/index.tsx b/web/app/components/main-nav/index.tsxindex 340d40c7596..07d66c3a2d8 100644--- a/web/app/components/main-nav/index.tsx+++ b/web/app/components/main-nav/index.tsx@@ -17,6 +17,8 @@ import DifyLogo from '@/app/components/base/logo/dify-logo'import EnvNav from '@/app/components/header/env-nav'import { buildIntegrationPath } from '@/app/components/integrations/routes'import { useAppContext } from '@/context/app-context'+import { AgentDetailSection, AgentDetailTop } from '@/features/agent-v2/agent-detail/navigation'+import { isAgentV2Enabled } from '@/features/agent-v2/feature-flag'import { DeploymentDetailSection, DeploymentDetailTop } from '@/features/deployments/detail/deployment-sidebar'import { systemFeaturesQueryOptions } from '@/features/system-features/client'import Link from '@/next/link'@@ -62,6 +64,12 @@ const isDatasetDetailPathname = (pathname: string) => {return true}+const isAgentDetailPathname = (pathname: string) => {+ const [section, type, agentId] = pathname.split('/').filter(Boolean)++ return section === 'roster' && type === 'agent' && !!agentId+}+const isDeploymentDetailPathname = (pathname: string) => {const [section, appInstanceId] = pathname.split('/').filter(Boolean)@@ -81,13 +89,15 @@ const MainNav = ({const pathname = usePathname()const { langGeniusVersionInfo, isCurrentWorkspaceDatasetOperator, isCurrentWorkspaceEditor } = useAppContext()const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())+ const agentV2Enabled = isAgentV2Enabled()const showEnvTag = langGeniusVersionInfo.current_env === 'TESTING' || langGeniusVersionInfo.current_env === 'DEVELOPMENT'const canUseAppDeploy = isCurrentWorkspaceEditor && systemFeatures.enable_app_deployconst showAppDetailNavigation = !isCurrentWorkspaceDatasetOperator && pathname.startsWith('/app/')const showDatasetDetailNavigation = isDatasetDetailPathname(pathname)+ const showAgentDetailNavigation = agentV2Enabled && !isCurrentWorkspaceDatasetOperator && isAgentDetailPathname(pathname)const showDeploymentDetailNavigation = canUseAppDeploy && !isCurrentWorkspaceDatasetOperator && isDeploymentDetailPathname(pathname)const showSnippetDetailBottomNavigation = isSnippetDetailPathname(pathname)- const showDetailNavigation = showAppDetailNavigation || showDatasetDetailNavigation || showDeploymentDetailNavigation+ const showDetailNavigation = showAppDetailNavigation || showDatasetDetailNavigation || showAgentDetailNavigation || showDeploymentDetailNavigationconst { hasAppDetail, appSidebarExpand, setAppDetail, setAppSidebarExpand } = useAppStore(useShallow(state => ({hasAppDetail: !!state.appDetail,appSidebarExpand: state.appSidebarExpand,@@ -192,6 +202,15 @@ const MainNav = ({icon: 'i-custom-vender-main-nav-studio',activeIcon: 'i-custom-vender-main-nav-studio-active',},+ ...(agentV2Enabled+ ? [{+ href: '/roster',+ label: t('menus.roster', { ns: 'common' }),+ active: (path: string) => path.startsWith('/roster'),+ icon: 'i-custom-vender-main-nav-roster',+ activeIcon: 'i-custom-vender-main-nav-roster-active',+ }]+ : []),]: []),...((isCurrentWorkspaceEditor || isCurrentWorkspaceDatasetOperator)@@ -232,25 +251,29 @@ const MainNav = ({activeIcon: 'i-ri-rocket-fill',}]: []),- ], [canUseAppDeploy, isCurrentWorkspaceDatasetOperator, isCurrentWorkspaceEditor, t])+ ], [agentV2Enabled, canUseAppDeploy, isCurrentWorkspaceDatasetOperator, isCurrentWorkspaceEditor, t])- const renderLogo = () => (- <Link- href="/"- className="flex h-8 shrink-0 items-center overflow-hidden focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"- aria-label={systemFeatures.branding.enabled && systemFeatures.branding.application_title ? systemFeatures.branding.application_title : 'Dify'}- >- {systemFeatures.branding.enabled && systemFeatures.branding.workspace_logo- ? (- <img- src={systemFeatures.branding.workspace_logo}- className="block h-5.5 w-auto object-contain"- alt=""- />- )- : <DifyLogo alt="" />}- </Link>- )+ const renderLogo = () => {+ const appTitle = systemFeatures.branding.enabled && systemFeatures.branding.application_title ? systemFeatures.branding.application_title : 'Dify'++ return (+ <Link+ href="/"+ className="flex h-8 shrink-0 items-center overflow-hidden focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"+ aria-label={appTitle}+ >+ {systemFeatures.branding.enabled && systemFeatures.branding.workspace_logo+ ? (+ <img+ src={systemFeatures.branding.workspace_logo}+ className="block h-5.5 w-auto object-contain"+ alt=""+ />+ )+ : <DifyLogo alt="" />}+ </Link>+ )+ }return (<aside@@ -298,12 +321,19 @@ const MainNav = ({onToggle={handleToggleDetailNavigation}/>)- : (- <DeploymentDetailTop- expand={detailNavigationVisibleExpanded}- onToggle={handleToggleDetailNavigation}- />- )+ : showAgentDetailNavigation+ ? (+ <AgentDetailTop+ expand={detailNavigationVisibleExpanded}+ onToggle={handleToggleDetailNavigation}+ />+ )+ : (+ <DeploymentDetailTop+ expand={detailNavigationVisibleExpanded}+ onToggle={handleToggleDetailNavigation}+ />+ ): showSnippetDetailBottomNavigation? null: (@@ -322,7 +352,9 @@ const MainNav = ({? <AppDetailSection expand={detailNavigationVisibleExpanded} />: showDatasetDetailNavigation? <DatasetDetailSection expand={detailNavigationVisibleExpanded} />- : <DeploymentDetailSection expand={detailNavigationVisibleExpanded} />+ : showAgentDetailNavigation+ ? <AgentDetailSection expand={detailNavigationVisibleExpanded} />+ : <DeploymentDetailSection expand={detailNavigationVisibleExpanded} />: showSnippetDetailBottomNavigation? null: (diff --git a/web/app/components/plugins/plugin-auth/__tests__/authorized-in-node.spec.tsx b/web/app/components/plugins/plugin-auth/__tests__/authorized-in-node.spec.tsxindex eaf586125c0..ba542bdc9ed 100644--- a/web/app/components/plugins/plugin-auth/__tests__/authorized-in-node.spec.tsx+++ b/web/app/components/plugins/plugin-auth/__tests__/authorized-in-node.spec.tsx@@ -1,7 +1,7 @@import type { ReactNode } from 'react'import type { Credential, PluginPayload } from '../types'import { QueryClient, QueryClientProvider } from '@tanstack/react-query'-import { fireEvent, render, screen } from '@testing-library/react'+import { fireEvent, render, screen, waitFor } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'import { AuthCategory, CredentialTypeEnum } from '../types'@@ -118,6 +118,24 @@ describe('AuthorizedInNode Component', () => {expect(screen.getByText('plugin.auth.workspaceDefault'))!.toBeInTheDocument()})+ it('should expose the workspace default credential id when requested', async () => {+ const AuthorizedInNode = (await import('../authorized-in-node')).default+ const onDefaultCredentialChange = vi.fn()+ const pluginPayload = createPluginPayload()+ render(+ <AuthorizedInNode+ pluginPayload={pluginPayload}+ onAuthorizationItemClick={vi.fn()}+ onDefaultCredentialChange={onDefaultCredentialChange}+ />,+ { wrapper: createWrapper() },+ )++ await waitFor(() => {+ expect(onDefaultCredentialChange).toHaveBeenCalledWith('test-credential-id')+ })+ })+it('should render credential name when credentialId matches', async () => {const AuthorizedInNode = (await import('../authorized-in-node')).defaultconst credential = createCredential({ id: 'selected-id', name: 'My Credential' })diff --git a/web/app/components/plugins/plugin-auth/authorized-in-node.tsx b/web/app/components/plugins/plugin-auth/authorized-in-node.tsxindex 82c4119b7af..de2bcab7c22 100644--- a/web/app/components/plugins/plugin-auth/authorized-in-node.tsx+++ b/web/app/components/plugins/plugin-auth/authorized-in-node.tsx@@ -10,6 +10,7 @@ import { RiArrowDownSLine } from '@remixicon/react'import {memo,useCallback,+ useEffect,useState,} from 'react'import { useTranslation } from 'react-i18next'@@ -22,11 +23,13 @@ type AuthorizedInNodeProps = {pluginPayload: PluginPayloadonAuthorizationItemClick: (id: string) => voidcredentialId?: string+ onDefaultCredentialChange?: (id?: string) => void}const AuthorizedInNode = ({pluginPayload,onAuthorizationItemClick,credentialId,+ onDefaultCredentialChange,}: AuthorizedInNodeProps) => {const { t } = useTranslation()const [isOpen, setIsOpen] = useState(false)@@ -38,6 +41,12 @@ const AuthorizedInNode = ({invalidPluginCredentialInfo,notAllowCustomCredential,} = usePluginAuth(pluginPayload, true, credentialId ? [credentialId] : undefined)+ const defaultCredentialId = credentials.find(c => c.is_default)?.id++ useEffect(() => {+ onDefaultCredentialChange?.(defaultCredentialId)+ }, [defaultCredentialId, onDefaultCredentialChange])+const renderTrigger = useCallback((open?: boolean) => {let label = ''let removed = false@@ -108,9 +117,15 @@ const AuthorizedInNode = ({},]const handleAuthorizationItemClick = useCallback((id: string) => {- onAuthorizationItemClick(id)+ onAuthorizationItemClick(+ id === '__workspace_default__' && onDefaultCredentialChange+ ? defaultCredentialId || id+ : id,+ )setIsOpen(false)}, [+ defaultCredentialId,+ onDefaultCredentialChange,onAuthorizationItemClick,setIsOpen,])diff --git a/web/app/components/plugins/types.ts b/web/app/components/plugins/types.tsindex e1d0513f789..0d4863c5629 100644--- a/web/app/components/plugins/types.ts+++ b/web/app/components/plugins/types.ts@@ -3,7 +3,6 @@ import type { CredentialFormSchemaBase } from '../header/account-setting/model-pimport type { AutoUpdateConfig } from './reference-setting-modal/auto-update-setting/types'import type { TypeWithI18N } from '@/app/components/base/form/types'import type { Collection, ToolCredential } from '@/app/components/tools/types'-import type { AgentFeature } from '@/app/components/workflow/nodes/agent/types'import type { Locale } from '@/i18n-config'export enum PluginCategoryEnum {@@ -567,6 +566,12 @@ export type StrategyDetail = {features: AgentFeature[]}+const AgentFeature = {+ HISTORY_MESSAGES: 'history-messages',+} as const++type AgentFeature = typeof AgentFeature[keyof typeof AgentFeature]+type Identity = {author: stringname: stringdiff --git a/web/app/components/rag-pipeline/hooks/__tests__/use-available-nodes-meta-data.spec.ts b/web/app/components/rag-pipeline/hooks/__tests__/use-available-nodes-meta-data.spec.tsindex f3d04533da3..9ed0dbfd15d 100644--- a/web/app/components/rag-pipeline/hooks/__tests__/use-available-nodes-meta-data.spec.ts+++ b/web/app/components/rag-pipeline/hooks/__tests__/use-available-nodes-meta-data.spec.ts@@ -3,10 +3,16 @@ import { describe, expect, it, vi } from 'vitest'import { BlockEnum } from '@/app/components/workflow/types'import { useAvailableNodesMetaData } from '../use-available-nodes-meta-data'+const mockIsAgentV2Enabled = vi.hoisted(() => vi.fn(() => true))+vi.mock('@/context/i18n', () => ({useDocLink: () => (path?: string) => `https://docs.dify.ai${path || ''}`,}))+vi.mock('@/features/agent-v2/feature-flag', () => ({+ isAgentV2Enabled: () => mockIsAgentV2Enabled(),+}))+vi.mock('@/app/components/workflow/constants/node', () => ({WORKFLOW_COMMON_NODES: [{@@ -21,6 +27,14 @@ vi.mock('@/app/components/workflow/constants/node', () => ({metaData: { type: BlockEnum.HttpRequest },defaultValue: { title: 'HTTP Request' },},+ {+ metaData: { type: BlockEnum.Agent },+ defaultValue: { title: 'Agent' },+ },+ {+ metaData: { type: BlockEnum.AgentV2 },+ defaultValue: { title: 'Agent' },+ },],}))@@ -46,6 +60,11 @@ vi.mock('@/app/components/workflow/nodes/knowledge-base/default', () => ({}))describe('useAvailableNodesMetaData', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockIsAgentV2Enabled.mockReturnValue(true)+ })+it('should return nodes and nodesMap', () => {const { result } = renderHook(() => useAvailableNodesMetaData())@@ -98,7 +117,7 @@ describe('useAvailableNodesMetaData', () => {const { result } = renderHook(() => useAvailableNodesMetaData())result.current.nodes.forEach((node) => {- expect(node.defaultValue.type).toBe(node.metaData.type)+ expect(node.defaultValue.type).toBe(node.metaData.type === BlockEnum.AgentV2 ? BlockEnum.Agent : node.metaData.type)expect(node.defaultValue.title).toBe(node.metaData.title)})})@@ -127,4 +146,26 @@ describe('useAvailableNodesMetaData', () => {expect(nodeTypes).toContain(BlockEnum.HttpRequest)expect(nodeTypes).not.toContain(BlockEnum.HumanInput)})++ it('should expose Agent v2 instead of legacy Agent when Agent v2 is enabled', () => {+ const { result } = renderHook(() => useAvailableNodesMetaData())+ const nodeTypes = result.current.nodes.map(n => n.metaData.type)++ expect(nodeTypes).toContain(BlockEnum.AgentV2)+ expect(nodeTypes).not.toContain(BlockEnum.Agent)+ expect(result.current.nodesMap[BlockEnum.AgentV2]).toBeDefined()+ expect(result.current.nodesMap[BlockEnum.Agent]).toBeUndefined()+ })++ it('should expose legacy Agent instead of Agent v2 when Agent v2 is disabled', () => {+ mockIsAgentV2Enabled.mockReturnValue(false)++ const { result } = renderHook(() => useAvailableNodesMetaData())+ const nodeTypes = result.current.nodes.map(n => n.metaData.type)++ expect(nodeTypes).toContain(BlockEnum.Agent)+ expect(nodeTypes).not.toContain(BlockEnum.AgentV2)+ expect(result.current.nodesMap[BlockEnum.Agent]).toBeDefined()+ expect(result.current.nodesMap[BlockEnum.AgentV2]).toBeUndefined()+ })})diff --git a/web/app/components/rag-pipeline/hooks/use-available-nodes-meta-data.ts b/web/app/components/rag-pipeline/hooks/use-available-nodes-meta-data.tsindex eaadf471062..c5d92844342 100644--- a/web/app/components/rag-pipeline/hooks/use-available-nodes-meta-data.ts+++ b/web/app/components/rag-pipeline/hooks/use-available-nodes-meta-data.ts@@ -1,4 +1,5 @@import type { AvailableNodesMetaData } from '@/app/components/workflow/hooks-store/store'+import type { I18nKeysWithPrefix } from '@/types/i18n'import { useMemo } from 'react'import { useTranslation } from 'react-i18next'import { WORKFLOW_COMMON_NODES } from '@/app/components/workflow/constants/node'@@ -7,14 +8,21 @@ import dataSourceDefault from '@/app/components/workflow/nodes/data-source/defauimport knowledgeBaseDefault from '@/app/components/workflow/nodes/knowledge-base/default'import { BlockEnum } from '@/app/components/workflow/types'import { useDocLink } from '@/context/i18n'+import { isAgentV2Enabled } from '@/features/agent-v2/feature-flag'export const useAvailableNodesMetaData = () => {const { t } = useTranslation()const docLink = useDocLink()+ const agentV2Enabled = isAgentV2Enabled()const mergedNodesMetaData = useMemo(() => [- // RAG pipeline doesn't support human-input node temporarily- ...WORKFLOW_COMMON_NODES.filter(node => node.metaData.type !== BlockEnum.HumanInput),+ ...WORKFLOW_COMMON_NODES.filter(node =>+ node.metaData.type !== BlockEnum.HumanInput+ && (+ agentV2Enabled+ ? node.metaData.type !== BlockEnum.Agent+ : node.metaData.type !== BlockEnum.AgentV2+ )),{...dataSourceDefault,defaultValue: {@@ -24,7 +32,7 @@ export const useAvailableNodesMetaData = () => {},knowledgeBaseDefault,dataSourceEmptyDefault,- ], [])+ ], [agentV2Enabled])const helpLinkUri = useMemo(() => docLink('/use-dify/knowledge/knowledge-pipeline/knowledge-pipeline-orchestration',@@ -33,7 +41,7 @@ export const useAvailableNodesMetaData = () => {const availableNodesMetaData = useMemo(() => mergedNodesMetaData.map((node) => {const { metaData } = nodeconst title = t(`blocks.${metaData.type}`, { ns: 'workflow' })- const description = t(`blocksAbout.${metaData.type}`, { ns: 'workflow' })+ const description = t(`blocksAbout.${metaData.type}` as I18nKeysWithPrefix<'workflow', 'blocksAbout.'>, { ns: 'workflow' })return {...node,metaData: {@@ -44,7 +52,7 @@ export const useAvailableNodesMetaData = () => {},defaultValue: {...node.defaultValue,- type: metaData.type,+ type: metaData.type === BlockEnum.AgentV2 ? BlockEnum.Agent : metaData.type,title,},}diff --git a/web/app/components/tools/integrations-setting-modal.tsx b/web/app/components/tools/integrations-setting-modal.tsxindex 86a29df7870..7bd2cee75e3 100644--- a/web/app/components/tools/integrations-setting-modal.tsx+++ b/web/app/components/tools/integrations-setting-modal.tsx@@ -2,6 +2,7 @@import type { IntegrationSection } from '@/app/components/integrations/routes'import { Button } from '@langgenius/dify-ui/button'+import { cn } from '@langgenius/dify-ui/cn'import { useCallback } from 'react'import { useTranslation } from 'react-i18next'import MenuDialog from '@/app/components/header/account-setting/menu-dialog'@@ -10,23 +11,35 @@ import { getMarketplaceUrl } from '@/utils/var'type IntegrationsSettingModalProps = {section: IntegrationSection+ source?: 'agent'onCancel: () => voidonSectionChange: (section: IntegrationSection) => void}export default function IntegrationsSettingModal({section,+ source,onCancel,onSectionChange,}: IntegrationsSettingModalProps) {const { t } = useTranslation()+ const isAgentSource = source === 'agent'const handleSwitchToMarketplace = useCallback((path: string) => {window.open(getMarketplaceUrl(path), '_blank', 'noopener,noreferrer')}, [])return (- <MenuDialog show onClose={onCancel}>- <div className="mx-auto flex h-dvh w-[min(1440px,calc(100vw-48px))] shrink-0 py-6">+ <MenuDialog+ show+ backdropClassName={isAgentSource ? 'bg-background-overlay' : undefined}+ className={isAgentSource ? 'bg-transparent backdrop-blur-none' : undefined}+ onClose={onCancel}+ >+ <div className={cn(+ 'mx-auto flex h-dvh w-[min(1440px,calc(100vw-48px))] shrink-0 py-6',+ isAgentSource && 'w-full p-6',+ )}+ ><div className="relative flex min-h-0 w-full shrink-0 overflow-hidden rounded-2xl border border-divider-subtle bg-components-panel-bg shadow-2xl"><div className="fixed top-6 right-6 z-9999 flex flex-col items-center"><Buttondiff --git a/web/app/components/workflow-app/components/workflow-children.tsx b/web/app/components/workflow-app/components/workflow-children.tsxindex 2e65b5963dc..a151dcae294 100644--- a/web/app/components/workflow-app/components/workflow-children.tsx+++ b/web/app/components/workflow-app/components/workflow-children.tsx@@ -1,5 +1,5 @@import type {- PluginDefaultValue,+ BlockDefaultValue,TriggerDefaultValue,} from '@/app/components/workflow/block-selector/types'import type { EnvironmentVariable } from '@/app/components/workflow/types'@@ -98,7 +98,7 @@ const WorkflowChildren = () => {handleOnboardingClose()}, [handleOnboardingClose])- const handleSelectStartNode = useCallback((nodeType: BlockEnum, toolConfig?: PluginDefaultValue) => {+ const handleSelectStartNode = useCallback((nodeType: BlockEnum, toolConfig?: BlockDefaultValue) => {const nodeDefault = availableNodesMetaData.nodesMap?.[nodeType]if (!nodeDefault?.defaultValue)returndiff --git a/web/app/components/workflow-app/components/workflow-header/__tests__/features-trigger.spec.tsx b/web/app/components/workflow-app/components/workflow-header/__tests__/features-trigger.spec.tsxindex bd8f54890e3..767927d9922 100644--- a/web/app/components/workflow-app/components/workflow-header/__tests__/features-trigger.spec.tsx+++ b/web/app/components/workflow-app/components/workflow-header/__tests__/features-trigger.spec.tsx@@ -1,11 +1,13 @@import type { ReactElement } from 'react'import type { AppPublisherProps } from '@/app/components/app/app-publisher'import type { App } from '@/types/app'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { useStore as useAppStore } from '@/app/components/app/store'import { Plan } from '@/app/components/billing/type'import { BlockEnum, InputVarType } from '@/app/components/workflow/types'+import { consoleQuery } from '@/service/client'import FeaturesTrigger from '../features-trigger'const mockUseIsChatMode = vi.fn()@@ -167,7 +169,15 @@ const createProviderContext = ({})const renderWithToast = (ui: ReactElement) => {- return render(ui)+ const queryClient = new QueryClient()+ return {+ queryClient,+ ...render(+ <QueryClientProvider client={queryClient}>+ {ui}+ </QueryClientProvider>,+ ),+ }}describe('FeaturesTrigger', () => {@@ -442,6 +452,72 @@ describe('FeaturesTrigger', () => {})})+ it('should invalidate roster list after publishing a workflow with a roster Agent v2 node', async () => {+ // Arrange+ const user = userEvent.setup()+ mockUseNodes.mockReturnValue([+ { id: 'start', data: { type: BlockEnum.Start } },+ {+ id: 'agent-v2',+ data: {+ type: BlockEnum.AgentV2,+ version: '2',+ agent_node_kind: 'dify_agent',+ agent_binding: {+ binding_type: 'roster_agent',+ agent_id: 'agent-1',+ },+ },+ },+ ])+ const { queryClient } = renderWithToast(<FeaturesTrigger />)+ const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')++ // Act+ await user.click(screen.getByRole('button', { name: 'publisher-publish' }))++ // Assert+ await waitFor(() => {+ expect(invalidateQueries).toHaveBeenCalledWith({+ queryKey: consoleQuery.agent.get.key(),+ })+ })+ })++ it('should keep roster list cache stable after publishing a workflow without roster Agent v2 nodes', async () => {+ // Arrange+ const user = userEvent.setup()+ mockUseNodes.mockReturnValue([+ { id: 'start', data: { type: BlockEnum.Start } },+ {+ id: 'inline-agent-v2',+ data: {+ type: BlockEnum.AgentV2,+ version: '2',+ agent_node_kind: 'dify_agent',+ agent_binding: {+ binding_type: 'inline_agent',+ agent_id: 'agent-1',+ current_snapshot_id: 'snapshot-1',+ },+ },+ },+ ])+ const { queryClient } = renderWithToast(<FeaturesTrigger />)+ const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')++ // Act+ await user.click(screen.getByRole('button', { name: 'publisher-publish' }))++ // Assert+ await waitFor(() => {+ expect(mockPublishWorkflow).toHaveBeenCalled()+ })+ expect(invalidateQueries).not.toHaveBeenCalledWith({+ queryKey: consoleQuery.agent.get.key(),+ })+ })+it('should pass publish params to workflow publish mutation', async () => {// Arrangeconst user = userEvent.setup()diff --git a/web/app/components/workflow-app/components/workflow-header/features-trigger.tsx b/web/app/components/workflow-app/components/workflow-header/features-trigger.tsxindex 481f57e8e39..a3b36fc0817 100644--- a/web/app/components/workflow-app/components/workflow-header/features-trigger.tsx+++ b/web/app/components/workflow-app/components/workflow-header/features-trigger.tsx@@ -9,6 +9,7 @@ import { Button } from '@langgenius/dify-ui/button'import { cn } from '@langgenius/dify-ui/cn'import { toast } from '@langgenius/dify-ui/toast'import { RiApps2AddLine } from '@remixicon/react'+import { useQueryClient } from '@tanstack/react-query'import {memo,useCallback,@@ -28,6 +29,7 @@ import {useNodesSyncDraft,// useWorkflowRunValidation,} from '@/app/components/workflow/hooks'+import { hasValidRosterAgentBinding, isAgentV2NodeData } from '@/app/components/workflow/nodes/agent-v2/types'import {useStore,useWorkflowStore,@@ -41,6 +43,7 @@ import {import { useProviderContext } from '@/context/provider-context'import useTheme from '@/hooks/use-theme'import { fetchAppDetail } from '@/service/apps'+import { consoleQuery } from '@/service/client'import { useInvalidateAppTriggers } from '@/service/use-tools'import { useInvalidateAppWorkflow, usePublishWorkflow, useResetWorkflowVersionHistory } from '@/service/use-workflow'@@ -49,6 +52,7 @@ const FeaturesTrigger = () => {const { theme } = useTheme()const isChatMode = useIsChatMode()const workflowStore = useWorkflowStore()+ const queryClient = useQueryClient()const appDetail = useAppStore(s => s.appDetail)const appID = appDetail?.idconst setAppDetail = useAppStore(s => s.setAppDetail)@@ -166,6 +170,11 @@ const FeaturesTrigger = () => {updatePublishedWorkflow(appID!)updateAppDetail()invalidateAppTriggers(appID!)+ if (nodes.some(node => isAgentV2NodeData(node.data) && hasValidRosterAgentBinding(node.data))) {+ void queryClient.invalidateQueries({+ queryKey: consoleQuery.agent.get.key(),+ })+ }workflowStore.getState().setPublishedAt(res.created_at)workflowStore.getState().setLastPublishedHasUserInput(hasUserInputNode)resetWorkflowVersionHistory()@@ -174,7 +183,7 @@ const FeaturesTrigger = () => {else {throw new Error('Checklist failed')}- }, [needWarningNodes, handleCheckBeforePublish, publishWorkflow, appID, t, updatePublishedWorkflow, updateAppDetail, workflowStore, resetWorkflowVersionHistory, invalidateAppTriggers, hasUserInputNode])+ }, [needWarningNodes, handleCheckBeforePublish, publishWorkflow, appID, t, updatePublishedWorkflow, updateAppDetail, invalidateAppTriggers, nodes, queryClient, workflowStore, hasUserInputNode, resetWorkflowVersionHistory])const onPublisherToggle = useCallback((state: boolean) => {if (state)diff --git a/web/app/components/workflow-app/components/workflow-onboarding-modal/index.tsx b/web/app/components/workflow-app/components/workflow-onboarding-modal/index.tsxindex 8f25cd00d03..770295526e7 100644--- a/web/app/components/workflow-app/components/workflow-onboarding-modal/index.tsx+++ b/web/app/components/workflow-app/components/workflow-onboarding-modal/index.tsx@@ -1,6 +1,6 @@'use client'import type { FC } from 'react'-import type { PluginDefaultValue } from '@/app/components/workflow/block-selector/types'+import type { BlockDefaultValue } from '@/app/components/workflow/block-selector/types'import { Dialog, DialogCloseButton, DialogContent, DialogDescription, DialogTitle } from '@langgenius/dify-ui/dialog'import { useTranslation } from 'react-i18next'import { BlockEnum } from '@/app/components/workflow/types'@@ -9,7 +9,7 @@ import StartNodeSelectionPanel from './start-node-selection-panel'type WorkflowOnboardingModalProps = {isShow: booleanonClose: () => void- onSelectStartNode: (nodeType: BlockEnum, toolConfig?: PluginDefaultValue) => void+ onSelectStartNode: (nodeType: BlockEnum, toolConfig?: BlockDefaultValue) => void}const WorkflowOnboardingModal: FC<WorkflowOnboardingModalProps> = ({diff --git a/web/app/components/workflow-app/components/workflow-onboarding-modal/start-node-selection-panel.tsx b/web/app/components/workflow-app/components/workflow-onboarding-modal/start-node-selection-panel.tsxindex 61e53b301e3..3e44d5d7a4c 100644--- a/web/app/components/workflow-app/components/workflow-onboarding-modal/start-node-selection-panel.tsx+++ b/web/app/components/workflow-app/components/workflow-onboarding-modal/start-node-selection-panel.tsx@@ -1,6 +1,6 @@'use client'import type { FC } from 'react'-import type { PluginDefaultValue } from '@/app/components/workflow/block-selector/types'+import type { BlockDefaultValue } from '@/app/components/workflow/block-selector/types'import { useCallback, useState } from 'react'import { useTranslation } from 'react-i18next'import NodeSelector from '@/app/components/workflow/block-selector'@@ -10,7 +10,7 @@ import StartNodeOption from './start-node-option'type StartNodeSelectionPanelProps = {onSelectUserInput: () => void- onSelectTrigger: (nodeType: BlockEnum, toolConfig?: PluginDefaultValue) => void+ onSelectTrigger: (nodeType: BlockEnum, toolConfig?: BlockDefaultValue) => void}const StartNodeSelectionPanel: FC<StartNodeSelectionPanelProps> = ({@@ -20,7 +20,7 @@ const StartNodeSelectionPanel: FC<StartNodeSelectionPanelProps> = ({const { t } = useTranslation()const [showTriggerSelector, setShowTriggerSelector] = useState(false)- const handleTriggerSelect = useCallback((nodeType: BlockEnum, toolConfig?: PluginDefaultValue) => {+ const handleTriggerSelect = useCallback((nodeType: BlockEnum, toolConfig?: BlockDefaultValue) => {setShowTriggerSelector(false)onSelectTrigger(nodeType, toolConfig)}, [onSelectTrigger])diff --git a/web/app/components/workflow-app/hooks/__tests__/use-available-nodes-meta-data.spec.ts b/web/app/components/workflow-app/hooks/__tests__/use-available-nodes-meta-data.spec.tsindex a53f0cac380..17083cc87b9 100644--- a/web/app/components/workflow-app/hooks/__tests__/use-available-nodes-meta-data.spec.ts+++ b/web/app/components/workflow-app/hooks/__tests__/use-available-nodes-meta-data.spec.ts@@ -3,11 +3,16 @@ import { BlockEnum } from '@/app/components/workflow/types'import { useAvailableNodesMetaData } from '../use-available-nodes-meta-data'const mockUseIsChatMode = vi.fn()+const mockIsAgentV2Enabled = vi.hoisted(() => vi.fn(() => true))vi.mock('@/app/components/workflow-app/hooks/use-is-chat-mode', () => ({useIsChatMode: () => mockUseIsChatMode(),}))+vi.mock('@/features/agent-v2/feature-flag', () => ({+ isAgentV2Enabled: () => mockIsAgentV2Enabled(),+}))+vi.mock('@/context/i18n', () => ({useDocLink: () => (path: string) => `/docs${path}`,}))@@ -15,6 +20,7 @@ vi.mock('@/context/i18n', () => ({describe('useAvailableNodesMetaData', () => {beforeEach(() => {vi.clearAllMocks()+ mockIsAgentV2Enabled.mockReturnValue(true)})it('should include chat-specific nodes and make the start node undeletable in chat mode', () => {@@ -47,4 +53,29 @@ describe('useAvailableNodesMetaData', () => {title: 'workflow.blocks.start',})})++ it('should expose Agent v2 instead of legacy Agent when Agent v2 is enabled', () => {+ mockUseIsChatMode.mockReturnValue(false)++ const { result } = renderHook(() => useAvailableNodesMetaData())+ const nodeTypes = result.current.nodes.map(node => node.metaData.type)++ expect(nodeTypes).toContain(BlockEnum.AgentV2)+ expect(nodeTypes).not.toContain(BlockEnum.Agent)+ expect(result.current.nodesMap?.[BlockEnum.AgentV2]).toBeDefined()+ expect(result.current.nodesMap?.[BlockEnum.Agent]).toBeUndefined()+ })++ it('should expose legacy Agent instead of Agent v2 when Agent v2 is disabled', () => {+ mockUseIsChatMode.mockReturnValue(false)+ mockIsAgentV2Enabled.mockReturnValue(false)++ const { result } = renderHook(() => useAvailableNodesMetaData())+ const nodeTypes = result.current.nodes.map(node => node.metaData.type)++ expect(nodeTypes).toContain(BlockEnum.Agent)+ expect(nodeTypes).not.toContain(BlockEnum.AgentV2)+ expect(result.current.nodesMap?.[BlockEnum.Agent]).toBeDefined()+ expect(result.current.nodesMap?.[BlockEnum.AgentV2]).toBeUndefined()+ })})diff --git a/web/app/components/workflow-app/hooks/use-available-nodes-meta-data.ts b/web/app/components/workflow-app/hooks/use-available-nodes-meta-data.tsindex bc468e73e35..b001c381898 100644--- a/web/app/components/workflow-app/hooks/use-available-nodes-meta-data.ts+++ b/web/app/components/workflow-app/hooks/use-available-nodes-meta-data.ts@@ -1,5 +1,6 @@import type { AvailableNodesMetaData } from '@/app/components/workflow/hooks-store/store'import type { DocPathWithoutLang } from '@/types/doc-paths'+import type { I18nKeysWithPrefix } from '@/types/i18n'import { useMemo } from 'react'import { useTranslation } from 'react-i18next'import { WORKFLOW_COMMON_NODES } from '@/app/components/workflow/constants/node'@@ -12,12 +13,14 @@ import TriggerScheduleDefault from '@/app/components/workflow/nodes/trigger-scheimport TriggerWebhookDefault from '@/app/components/workflow/nodes/trigger-webhook/default'import { BlockEnum } from '@/app/components/workflow/types'import { useDocLink } from '@/context/i18n'+import { isAgentV2Enabled } from '@/features/agent-v2/feature-flag'import { useIsChatMode } from './use-is-chat-mode'export const useAvailableNodesMetaData = () => {const { t } = useTranslation()const isChatMode = useIsChatMode()const docLink = useDocLink()+ const agentV2Enabled = isAgentV2Enabled()const startNodeMetaData = useMemo(() => ({...StartDefault,@@ -28,8 +31,13 @@ export const useAvailableNodesMetaData = () => {}), [isChatMode])const mergedNodesMetaData = useMemo(() => {+ const commonNodes = WORKFLOW_COMMON_NODES.filter(node =>+ agentV2Enabled+ ? node.metaData.type !== BlockEnum.Agent+ : node.metaData.type !== BlockEnum.AgentV2)+return [- ...WORKFLOW_COMMON_NODES,+ ...commonNodes,startNodeMetaData,...(isChatMode@@ -43,12 +51,12 @@ export const useAvailableNodesMetaData = () => {]),]- }, [isChatMode, startNodeMetaData])+ }, [agentV2Enabled, isChatMode, startNodeMetaData])const availableNodesMetaData = useMemo(() => mergedNodesMetaData.map((node) => {const { metaData } = nodeconst title = t(`blocks.${metaData.type}`, { ns: 'workflow' })- const description = t(`blocksAbout.${metaData.type}`, { ns: 'workflow' })+ const description = t(`blocksAbout.${metaData.type}` as I18nKeysWithPrefix<'workflow', 'blocksAbout.'>, { ns: 'workflow' })const helpLinkPath = `/use-dify/nodes/${metaData.helpLinkUri}` as DocPathWithoutLangreturn {...node,@@ -60,7 +68,7 @@ export const useAvailableNodesMetaData = () => {},defaultValue: {...node.defaultValue,- type: metaData.type,+ type: metaData.type === BlockEnum.AgentV2 ? BlockEnum.Agent : metaData.type,title,},}diff --git a/web/app/components/workflow/__tests__/candidate-node-main.spec.tsx b/web/app/components/workflow/__tests__/candidate-node-main.spec.tsxindex 2e465c6df2c..3b327d7cc98 100644--- a/web/app/components/workflow/__tests__/candidate-node-main.spec.tsx+++ b/web/app/components/workflow/__tests__/candidate-node-main.spec.tsx@@ -16,6 +16,8 @@ const mockCustomNode = vi.hoisted(() => vi.fn())const mockCustomNoteNode = vi.hoisted(() => vi.fn())const mockGetIterationStartNode = vi.hoisted(() => vi.fn())const mockGetLoopStartNode = vi.hoisted(() => vi.fn())+const mockCreateInlineAgentBinding = vi.hoisted(() => vi.fn())+const mockSetOpenInlineAgentPanelNodeId = vi.hoisted(() => vi.fn())vi.mock('ahooks', () => ({useEventListener: (...args: unknown[]) => mockUseEventListener(...args),@@ -68,6 +70,12 @@ vi.mock('@/app/components/workflow/note-node', () => ({},}))+vi.mock('@/app/components/workflow/nodes/agent-v2/hooks', () => ({+ useCreateInlineAgentBinding: () => ({+ createInlineAgentBinding: mockCreateInlineAgentBinding,+ }),+}))+vi.mock('@/app/components/workflow/utils', () => ({getIterationStartNode: (...args: unknown[]) => mockGetIterationStartNode(...args),getLoopStartNode: (...args: unknown[]) => mockGetLoopStartNode(...args),@@ -102,6 +110,9 @@ describe('CandidateNodeMain', () => {mockUseEventListener.mockImplementation((event: 'click' | 'contextmenu', handler: (event: { preventDefault: () => void }) => void) => {eventHandlers[event] = handler})+ mockSetNodes.mockImplementation((nextNodes) => {+ nodes = nextNodes+ })mockUseStoreApi.mockReturnValue({getState: () => ({getNodes: () => nodes,@@ -126,6 +137,9 @@ describe('CandidateNodeMain', () => {},}))mockUseWorkflowStore.mockReturnValue({+ getState: () => ({+ setOpenInlineAgentPanelNodeId: mockSetOpenInlineAgentPanelNodeId,+ }),setState: mockWorkflowStoreSetState,})mockUseHooks.mockReturnValue({@@ -137,6 +151,17 @@ describe('CandidateNodeMain', () => {mockHandleSyncWorkflowDraft.mockImplementation((_isSync: boolean, _force: boolean, options?: { onSuccess?: () => void }) => {options?.onSuccess?.()})+ mockCreateInlineAgentBinding.mockImplementation((_nodeId: string, options?: { onSuccess?: (binding: {+ binding_type: 'inline_agent'+ agent_id: string+ current_snapshot_id: string+ }) => void }) => {+ options?.onSuccess?.({+ binding_type: 'inline_agent',+ agent_id: 'inline-agent-1',+ current_snapshot_id: 'inline-snapshot-1',+ })+ })mockGetIterationStartNode.mockReturnValue(createNode({ id: 'iteration-start' }))mockGetLoopStartNode.mockReturnValue(createNode({ id: 'loop-start' }))})@@ -201,6 +226,97 @@ describe('CandidateNodeMain', () => {expect(mockHandleNodeSelect).toHaveBeenCalledWith('candidate-note')})+ it('should sync draft immediately when committing an Agent v2 node', () => {+ const candidateNode = createNode({+ id: 'candidate-agent-v2',+ type: CUSTOM_NODE,+ data: {+ type: BlockEnum.Agent,+ title: 'Agent Candidate',+ agent_binding: {+ binding_type: 'roster_agent',+ agent_id: 'agent-1',+ },+ agent_node_kind: 'dify_agent',+ version: '2',+ _isCandidate: true,+ },+ })++ render(<CandidateNodeMain candidateNode={candidateNode} />)++ eventHandlers.click?.({ preventDefault: vi.fn() })++ expect(mockSetNodes).toHaveBeenCalledWith(expect.arrayContaining([+ expect.objectContaining({+ id: 'candidate-agent-v2',+ data: expect.objectContaining({+ agent_binding: {+ binding_type: 'roster_agent',+ agent_id: 'agent-1',+ },+ agent_node_kind: 'dify_agent',+ version: '2',+ _isCandidate: false,+ }),+ }),+ ]))+ expect(mockHandleSyncWorkflowDraft).toHaveBeenCalledWith(true, true)+ })++ it('should create inline binding before syncing a start-from-scratch Agent v2 node', () => {+ const candidateNode = createNode({+ id: 'candidate-inline-agent-v2',+ type: CUSTOM_NODE,+ data: {+ type: BlockEnum.Agent,+ title: 'Agent Candidate',+ agent_binding: {+ binding_type: 'inline_agent',+ },+ agent_node_kind: 'dify_agent',+ version: '2',+ _isCandidate: true,+ },+ })++ render(<CandidateNodeMain candidateNode={candidateNode} />)++ eventHandlers.click?.({ preventDefault: vi.fn() })++ expect(mockCreateInlineAgentBinding).toHaveBeenCalledWith('candidate-inline-agent-v2', expect.objectContaining({+ onSuccess: expect.any(Function),+ }))+ expect(mockSetNodes.mock.calls[0]?.[0]).toEqual(expect.arrayContaining([+ expect.objectContaining({+ id: 'candidate-inline-agent-v2',+ data: expect.objectContaining({+ agent_binding: {+ binding_type: 'inline_agent',+ },+ _isTempNode: true,+ }),+ }),+ ]))+ expect(mockSetNodes).toHaveBeenLastCalledWith(expect.arrayContaining([+ expect.objectContaining({+ id: 'candidate-inline-agent-v2',+ data: expect.objectContaining({+ agent_binding: {+ binding_type: 'inline_agent',+ agent_id: 'inline-agent-1',+ current_snapshot_id: 'inline-snapshot-1',+ },+ }),+ }),+ ]))+ const finalNodes = mockSetNodes.mock.calls.at(-1)?.[0]+ const finalAgentNode = finalNodes.find((node: { id: string }) => node.id === 'candidate-inline-agent-v2')+ expect(finalAgentNode.data._isTempNode).toBeUndefined()+ expect(mockSetOpenInlineAgentPanelNodeId).toHaveBeenCalledWith('candidate-inline-agent-v2')+ expect(mockHandleSyncWorkflowDraft).toHaveBeenCalledWith(true, true)+ })+it('should append iteration and loop start helper nodes for control-flow candidates', () => {const iterationNode = createNode({id: 'candidate-iteration',diff --git a/web/app/components/workflow/block-icon.tsx b/web/app/components/workflow/block-icon.tsxindex 15292a07049..afb2acdaa11 100644--- a/web/app/components/workflow/block-icon.tsx+++ b/web/app/components/workflow/block-icon.tsx@@ -68,6 +68,7 @@ const DEFAULT_ICON_MAP: Record<BlockEnum, React.ComponentType<{ className: strin[BlockEnum.DocExtractor]: DocsExtractor,[BlockEnum.ListFilter]: ListFilter,[BlockEnum.Agent]: Agent,+ [BlockEnum.AgentV2]: Agent,[BlockEnum.KnowledgeBase]: KnowledgeBase,[BlockEnum.DataSource]: Datasource,[BlockEnum.DataSourceEmpty]: () => null,@@ -118,6 +119,7 @@ const ICON_CONTAINER_BG_COLOR_MAP: Record<string, string> = {[BlockEnum.DocExtractor]: 'bg-util-colors-green-green-500',[BlockEnum.ListFilter]: 'bg-util-colors-cyan-cyan-500',[BlockEnum.Agent]: 'bg-util-colors-indigo-indigo-500',+ [BlockEnum.AgentV2]: 'bg-util-colors-indigo-indigo-500',[BlockEnum.HumanInput]: 'bg-util-colors-cyan-cyan-500',[BlockEnum.KnowledgeBase]: 'bg-util-colors-warning-warning-500',[BlockEnum.DataSource]: 'bg-components-icon-bg-midnight-solid',diff --git a/web/app/components/workflow/block-selector/__tests__/blocks.spec.tsx b/web/app/components/workflow/block-selector/__tests__/blocks.spec.tsxindex 70900d64b56..a417f974ba8 100644--- a/web/app/components/workflow/block-selector/__tests__/blocks.spec.tsx+++ b/web/app/components/workflow/block-selector/__tests__/blocks.spec.tsx@@ -1,6 +1,10 @@import type { NodeDefault } from '../../types'-import { render, screen } from '@testing-library/react'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'+import { FlowType } from '@/types/common'+import { HooksStoreContext } from '../../hooks-store/provider'+import { createHooksStore } from '../../hooks-store/store'import { BlockEnum } from '../../types'import Blocks from '../blocks'import { BlockClassificationEnum } from '../types'@@ -10,6 +14,11 @@ const runtimeState = vi.hoisted(() => ({nodes: [] as Array<{ data: { type?: BlockEnum } }>,}))+const queryMocks = vi.hoisted(() => ({+ inviteOptionsQueryFn: vi.fn(),+ toastError: vi.fn(),+}))+vi.mock('reactflow', () => ({useStoreApi: () => ({getState: () => ({@@ -26,10 +35,36 @@ vi.mock('@/app/components/app/store', () => ({}),}))-const createBlock = (type: BlockEnum, title: string, classification = BlockClassificationEnum.Default): NodeDefault => ({+vi.mock('@/service/client', () => ({+ consoleQuery: {+ agent: {+ inviteOptions: {+ get: {+ queryOptions: (options: unknown) => ({+ queryKey: ['agents', 'invite-options', options],+ queryFn: () => queryMocks.inviteOptionsQueryFn(options),+ }),+ },+ },+ },+ },+}))++vi.mock('@langgenius/dify-ui/toast', () => ({+ toast: {+ error: (message: string) => queryMocks.toastError(message),+ },+}))++const createBlock = (+ type: BlockEnum,+ title: string,+ classification = BlockClassificationEnum.Default,+ sort = 0,+): NodeDefault => ({metaData: {classification,- sort: 0,+ sort,type,title,author: 'Dify',@@ -65,12 +100,12 @@ describe('Blocks', () => {/>,)- expect(screen.getByText('LLM')).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'LLM' })).toBeInTheDocument()expect(screen.getByText('Exit Loop')).toBeInTheDocument()expect(screen.getByText('workflow.nodes.loop.loopNode')).toBeInTheDocument()expect(screen.queryByText('Knowledge Retrieval')).not.toBeInTheDocument()- await user.click(screen.getByText('LLM'))+ await user.click(screen.getByRole('button', { name: 'LLM' }))expect(onSelect).toHaveBeenCalledWith(BlockEnum.LLM)})@@ -87,4 +122,297 @@ describe('Blocks', () => {expect(screen.getByText('workflow.tabs.noResult')).toBeInTheDocument()})++ it('opens the agent selector on Agent block hover', async () => {+ const user = userEvent.setup()+ queryMocks.inviteOptionsQueryFn.mockResolvedValue({+ data: [],+ has_more: false,+ limit: 8,+ page: 1,+ total: 0,+ })+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: {+ retry: false,+ },+ },+ })+ const hooksStore = createHooksStore({+ configsMap: {+ flowId: 'app-1',+ flowType: FlowType.appFlow,+ fileSettings: {} as never,+ },+ })++ render(+ <QueryClientProvider client={queryClient}>+ <HooksStoreContext value={hooksStore}>+ <Blocks+ searchText=""+ onSelect={vi.fn()}+ availableBlocksTypes={[BlockEnum.AgentV2]}+ blocks={[createBlock(BlockEnum.AgentV2, 'Agent')]}+ />+ </HooksStoreContext>+ </QueryClientProvider>,+ )++ await user.hover(screen.getByRole('button', { name: 'Agent' }))++ expect(await screen.findByRole('dialog', { name: 'agentV2.roster.nodeSelector.dialogLabel' })).toBeInTheDocument()+ })++ it('opens the agent selector from the Agent block and selects an agent', async () => {+ const user = userEvent.setup()+ const onSelect = vi.fn()+ queryMocks.inviteOptionsQueryFn.mockResolvedValue({+ data: [+ {+ id: 'agent-1',+ name: 'Nadia',+ description: 'Clarification Drafter',+ active_config_snapshot_id: 'version-1',+ role: 'Researcher',+ agent_kind: 'dify_agent',+ icon: 'A',+ icon_background: '#E9D7FE',+ icon_type: 'emoji',+ scope: 'roster',+ source: 'workflow',+ status: 'active',+ },+ ],+ has_more: false,+ limit: 8,+ page: 1,+ total: 1,+ })++ const queryClient = new QueryClient({+ defaultOptions: {+ queries: {+ retry: false,+ },+ },+ })+ const hooksStore = createHooksStore({+ configsMap: {+ flowId: 'app-1',+ flowType: FlowType.appFlow,+ fileSettings: {} as never,+ },+ })++ render(+ <QueryClientProvider client={queryClient}>+ <HooksStoreContext value={hooksStore}>+ <Blocks+ searchText=""+ onSelect={onSelect}+ availableBlocksTypes={[BlockEnum.LLM, BlockEnum.AgentV2]}+ blocks={[+ createBlock(BlockEnum.LLM, 'LLM', BlockClassificationEnum.Default, 0),+ createBlock(BlockEnum.AgentV2, 'Agent', BlockClassificationEnum.Default, 3),+ ]}+ />+ </HooksStoreContext>+ </QueryClientProvider>,+ )++ expect(+ screen.getByText('Agent').compareDocumentPosition(screen.getByText('LLM')) & Node.DOCUMENT_POSITION_FOLLOWING,+ ).toBeTruthy()++ await user.click(screen.getByRole('button', { name: 'Agent' }))++ expect(await screen.findByRole('dialog', { name: 'agentV2.roster.nodeSelector.dialogLabel' })).toBeInTheDocument()+ expect(screen.getByRole('combobox', { name: 'agentV2.roster.searchLabel' })).toBeInTheDocument()+ expect(await screen.findByText('Nadia')).toBeInTheDocument()+ expect(screen.getByText('Researcher')).toBeInTheDocument()++ await user.click(screen.getByRole('option', { name: 'Nadia Researcher' }))++ expect(onSelect).toHaveBeenCalledWith(BlockEnum.AgentV2, {+ agent_binding: {+ binding_type: 'roster_agent',+ agent_id: 'agent-1',+ },+ agent_node_kind: 'dify_agent',+ version: '2',+ })+ expect(queryMocks.inviteOptionsQueryFn).toHaveBeenCalledWith({+ input: {+ query: {+ app_id: 'app-1',+ limit: 8,+ page: 1,+ },+ },+ })+ })++ it('does not select an Agent v2 roster agent without active config snapshot', async () => {+ const user = userEvent.setup()+ const onSelect = vi.fn()+ queryMocks.inviteOptionsQueryFn.mockResolvedValue({+ data: [+ {+ id: 'agent-1',+ name: 'Nadia',+ description: 'Clarification Drafter',+ active_config_snapshot_id: null,+ role: 'Researcher',+ agent_kind: 'dify_agent',+ icon: 'A',+ icon_background: '#E9D7FE',+ icon_type: 'emoji',+ scope: 'roster',+ source: 'workflow',+ status: 'active',+ },+ ],+ has_more: false,+ limit: 8,+ page: 1,+ total: 1,+ })++ const queryClient = new QueryClient({+ defaultOptions: {+ queries: {+ retry: false,+ },+ },+ })+ const hooksStore = createHooksStore({+ configsMap: {+ flowId: 'app-1',+ flowType: FlowType.appFlow,+ fileSettings: {} as never,+ },+ })++ render(+ <QueryClientProvider client={queryClient}>+ <HooksStoreContext value={hooksStore}>+ <Blocks+ searchText=""+ onSelect={onSelect}+ availableBlocksTypes={[BlockEnum.AgentV2]}+ blocks={[createBlock(BlockEnum.AgentV2, 'Agent', BlockClassificationEnum.Default, 3)]}+ />+ </HooksStoreContext>+ </QueryClientProvider>,+ )++ await user.click(screen.getByRole('button', { name: 'Agent' }))+ expect(await screen.findByText('Nadia')).toBeInTheDocument()++ await user.click(screen.getByRole('option', { name: 'Nadia Researcher' }))++ await waitFor(() => expect(queryMocks.toastError).toHaveBeenCalledWith('workflow.nodes.agent.modelNotSelected'))+ expect(onSelect).not.toHaveBeenCalled()+ })++ it('inserts an inline Agent v2 node from the selector start action', async () => {+ const user = userEvent.setup()+ const onSelect = vi.fn()+ queryMocks.inviteOptionsQueryFn.mockResolvedValue({+ data: [],+ has_more: false,+ limit: 8,+ page: 1,+ total: 0,+ })+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: {+ retry: false,+ },+ },+ })+ const hooksStore = createHooksStore({+ configsMap: {+ flowId: 'app-1',+ flowType: FlowType.appFlow,+ fileSettings: {} as never,+ },+ })++ render(+ <QueryClientProvider client={queryClient}>+ <HooksStoreContext value={hooksStore}>+ <Blocks+ searchText=""+ onSelect={onSelect}+ availableBlocksTypes={[BlockEnum.AgentV2]}+ blocks={[createBlock(BlockEnum.AgentV2, 'Agent', BlockClassificationEnum.Default, 3)]}+ />+ </HooksStoreContext>+ </QueryClientProvider>,+ )++ await user.click(screen.getByRole('button', { name: 'Agent' }))+ await user.click(await screen.findByRole('button', { name: 'agentV2.roster.nodeSelector.startFromScratch' }))++ expect(onSelect).toHaveBeenCalledWith(BlockEnum.AgentV2, {+ agent_binding: {+ binding_type: 'inline_agent',+ },+ agent_node_kind: 'dify_agent',+ version: '2',+ })+ })++ it('closes the agent selector when Escape closes the combobox', async () => {+ const user = userEvent.setup()+ queryMocks.inviteOptionsQueryFn.mockResolvedValue({+ data: [],+ has_more: false,+ limit: 8,+ page: 1,+ total: 0,+ })+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: {+ retry: false,+ },+ },+ })+ const hooksStore = createHooksStore({+ configsMap: {+ flowId: 'app-1',+ flowType: FlowType.appFlow,+ fileSettings: {} as never,+ },+ })++ render(+ <QueryClientProvider client={queryClient}>+ <HooksStoreContext value={hooksStore}>+ <Blocks+ searchText=""+ onSelect={vi.fn()}+ availableBlocksTypes={[BlockEnum.AgentV2]}+ blocks={[createBlock(BlockEnum.AgentV2, 'Agent')]}+ />+ </HooksStoreContext>+ </QueryClientProvider>,+ )++ await user.click(screen.getByRole('button', { name: 'Agent' }))++ expect(await screen.findByRole('dialog', { name: 'agentV2.roster.nodeSelector.dialogLabel' })).toBeInTheDocument()++ await user.click(screen.getByRole('combobox', { name: 'agentV2.roster.searchLabel' }))+ await user.keyboard('{Escape}')++ await waitFor(() => {+ expect(screen.queryByRole('dialog', { name: 'agentV2.roster.nodeSelector.dialogLabel' })).not.toBeInTheDocument()+ })+ })})diff --git a/web/app/components/workflow/block-selector/__tests__/index.spec.tsx b/web/app/components/workflow/block-selector/__tests__/index.spec.tsxindex 52928540e2d..7aa8c9b9d28 100644--- a/web/app/components/workflow/block-selector/__tests__/index.spec.tsx+++ b/web/app/components/workflow/block-selector/__tests__/index.spec.tsx@@ -53,6 +53,10 @@ const dataSource: ToolWithProvider = {}describe('NodeSelectorWrapper', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })+it('filters hidden block types from hooks store and forwards data sources', async () => {renderWorkflowComponent(<NodeSelectorWrapperdiff --git a/web/app/components/workflow/block-selector/agent-selector.tsx b/web/app/components/workflow/block-selector/agent-selector.tsxnew file mode 100644index 00000000000..05268025ee5--- /dev/null+++ b/web/app/components/workflow/block-selector/agent-selector.tsx@@ -0,0 +1,311 @@+import type { AgentInviteOptionResponse } from '@dify/contracts/api/console/agent/types.gen'+import type { ComboboxRootChangeEventDetails } from '@langgenius/dify-ui/combobox'+import type { NodeDefault } from '../types'+import type { AgentRosterNodeData } from './types'+import { cn } from '@langgenius/dify-ui/cn'+import {+ Combobox,+ ComboboxEmpty,+ ComboboxInput,+ ComboboxInputGroup,+ ComboboxItem,+ ComboboxItemText,+ ComboboxList,+ ComboboxStatus,+} from '@langgenius/dify-ui/combobox'+import {+ Popover,+ PopoverContent,+ PopoverTitle,+ PopoverTrigger,+} from '@langgenius/dify-ui/popover'+import { toast } from '@langgenius/dify-ui/toast'+import { useQuery } from '@tanstack/react-query'+import { useDebounce } from 'ahooks'+import { useState } from 'react'+import { useTranslation } from 'react-i18next'+import AppIcon from '@/app/components/base/app-icon'+import { useHooksStore } from '@/app/components/workflow/hooks-store'+import Link from '@/next/link'+import { consoleQuery } from '@/service/client'+import BlockIcon from '../block-icon'++const AGENT_SELECTOR_PAGE_SIZE = 8++export function AgentSelectorContent({+ open,+ onOpenChange,+ onSelect,+ onStartFromScratch,+}: {+ open: boolean+ onOpenChange: (open: boolean) => void+ onSelect: (agent: AgentRosterNodeData) => void+ onStartFromScratch?: () => void+}) {+ const { t } = useTranslation(['agentV2', 'common', 'workflow'])+ const appId = useHooksStore(s => s.configsMap?.flowId)+ const [searchText, setSearchText] = useState('')+ const debouncedSearchText = useDebounce(searchText.trim(), { wait: 300 })+ const agentsQuery = useQuery({+ ...consoleQuery.agent.inviteOptions.get.queryOptions({+ input: {+ query: {+ limit: AGENT_SELECTOR_PAGE_SIZE,+ page: 1,+ ...(appId ? { app_id: appId } : {}),+ ...(debouncedSearchText ? { keyword: debouncedSearchText } : {}),+ },+ },+ }),+ })+ const agents = agentsQuery.data?.data ?? []+ const handleInputValueChange = (nextSearchText: string, details: ComboboxRootChangeEventDetails) => {+ if (details.reason !== 'item-press')+ setSearchText(nextSearchText)+ }+ const handleValueChange = (agent: AgentInviteOptionResponse | null) => {+ if (!agent)+ return++ if (!agent.active_config_snapshot_id) {+ toast.error(t('nodes.agent.modelNotSelected', { ns: 'workflow' }))+ return+ }++ onSelect(toAgentRosterNodeData(agent))+ }+ const handleOpenChange = (nextOpen: boolean) => {+ if (!nextOpen)+ onOpenChange(false)+ }+ const isLoading = agentsQuery.isPending++ return (+ <div className="w-60 overflow-hidden rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur shadow-lg backdrop-blur-sm">+ <Combobox<AgentInviteOptionResponse>+ filter={null}+ inputValue={searchText}+ items={agents}+ itemToStringLabel={getAgentLabel}+ itemToStringValue={getAgentValue}+ open={open}+ value={null}+ onInputValueChange={handleInputValueChange}+ onOpenChange={handleOpenChange}+ onValueChange={handleValueChange}+ >+ <div className="bg-components-panel-bg-blur p-2 pb-1">+ <ComboboxInputGroup className="h-8 min-h-8 px-2">+ <span aria-hidden className="mr-0.5 i-ri-search-line size-4 shrink-0 text-components-input-text-placeholder" />+ <ComboboxInput+ aria-label={t('roster.searchLabel', { ns: 'agentV2' })}+ placeholder={t('roster.nodeSelector.searchPlaceholder', { ns: 'agentV2' })}+ className="block h-4.5 grow px-1 py-0 system-sm-regular text-components-input-text-filled"+ />+ </ComboboxInputGroup>+ </div>+ <div className="max-h-54 overflow-y-auto p-1">+ {isLoading && (+ <AgentSelectorLoadingSkeleton label={t('loading', { ns: 'common' })} />+ )}+ {!isLoading && agentsQuery.isError && (+ <ComboboxStatus className="px-3 py-2 system-xs-regular">+ {t('roster.loadingError', { ns: 'agentV2' })}+ </ComboboxStatus>+ )}+ {!isLoading && !agentsQuery.isError && (+ <>+ <ComboboxList className="max-h-none overflow-visible p-0">+ {(agent: AgentInviteOptionResponse) => (+ <AgentSelectorItem key={agent.id} agent={agent} />+ )}+ </ComboboxList>+ <ComboboxEmpty className="px-3 py-2 system-xs-regular">+ {debouncedSearchText+ ? t('roster.emptySearch', { ns: 'agentV2' })+ : t('roster.empty', { ns: 'agentV2' })}+ </ComboboxEmpty>+ </>+ )}+ </div>+ </Combobox>+ <div className="border-t border-divider-subtle p-1">+ {onStartFromScratch && (+ <button+ type="button"+ className="flex min-h-7 w-full cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-left system-sm-regular text-text-secondary hover:bg-state-base-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"+ onClick={onStartFromScratch}+ >+ <span aria-hidden className="i-ri-add-line size-4 shrink-0 text-text-tertiary" />+ <span className="min-w-0 flex-1 truncate">+ {t('roster.nodeSelector.startFromScratch', { ns: 'agentV2' })}+ </span>+ </button>+ )}+ <Link+ href="/roster"+ className="flex min-h-7 w-full items-center gap-2 rounded-md px-2 py-1.5 system-sm-regular text-text-secondary hover:bg-state-base-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"+ >+ <span aria-hidden className="i-ri-arrow-right-up-line size-4 shrink-0 text-text-tertiary" />+ <span className="min-w-0 flex-1 truncate">+ {t('roster.nodeSelector.manageInAgentConsole', { ns: 'agentV2' })}+ </span>+ </Link>+ </div>+ </div>+ )+}++function AgentSelectorLoadingSkeleton({+ label,+}: {+ label: string+}) {+ return (+ <ComboboxStatus className="p-0">+ <span className="sr-only">{label}</span>+ <div className="relative overflow-hidden" aria-hidden>+ <div className="p-1">+ {['skeleton-1', 'skeleton-2', 'skeleton-3', 'skeleton-4'].map((key, index) => (+ <div+ key={key}+ className={cn(+ 'flex items-center gap-2 py-1.5 pr-3 pl-2 opacity-20',+ index === 3 && 'opacity-10',+ )}+ >+ <div className="size-8 shrink-0 rounded-full bg-text-quaternary" />+ <div className="flex min-w-0 flex-1 flex-col gap-1.5">+ <div className="h-2 w-20 rounded-xs bg-text-quaternary" />+ <div className="h-2 w-28 rounded-xs bg-text-quaternary" />+ </div>+ </div>+ ))}+ </div>+ <div className="pointer-events-none absolute inset-0 bg-linear-to-b from-components-panel-bg-transparent to-background-default-subtle" />+ </div>+ </ComboboxStatus>+ )+}++function getAgentLabel(agent: AgentInviteOptionResponse) {+ return agent.name+}++function getAgentValue(agent: AgentInviteOptionResponse) {+ return agent.id+}++function toAgentRosterNodeData(agent: AgentInviteOptionResponse): AgentRosterNodeData {+ return {+ description: agent.description,+ icon: agent.icon,+ icon_background: agent.icon_background,+ icon_type: agent.icon_type,+ id: agent.id,+ name: agent.name,+ role: agent.role,+ }+}++function AgentSelectorAvatar({+ agent,+}: {+ agent: AgentInviteOptionResponse+}) {+ return (+ <AppIcon+ size="small"+ iconType={agent.icon_type}+ icon={agent.icon ?? undefined}+ background={agent.icon_background}+ imageUrl={agent.icon ?? undefined}+ />+ )+}++function AgentSelectorItem({+ agent,+}: {+ agent: AgentInviteOptionResponse+}) {+ return (+ <ComboboxItem+ value={agent}+ className="grid-cols-[1fr] gap-0 py-1.5 pr-3 pl-2"+ >+ <ComboboxItemText className="flex items-center gap-2 px-0">+ <span aria-hidden className="shrink-0">+ <AgentSelectorAvatar agent={agent} />+ </span>+ <span className="flex min-w-0 flex-1 flex-col gap-0.5">+ <span className="truncate system-sm-medium text-text-secondary">+ {agent.name}+ </span>+ <span className="truncate system-xs-regular text-text-tertiary">+ {agent.role || agent.description}+ </span>+ </span>+ </ComboboxItemText>+ </ComboboxItem>+ )+}++export function AgentBlockItem({+ block,+ onSelect,+ onStartFromScratch,+}: {+ block: NodeDefault+ onSelect: (agent: AgentRosterNodeData) => void+ onStartFromScratch: () => void+}) {+ const { t } = useTranslation('agentV2')+ const [open, setOpen] = useState(false)+ const handleSelect = (agent: AgentRosterNodeData) => {+ setOpen(false)+ onSelect(agent)+ }++ return (+ <Popover open={open} onOpenChange={setOpen}>+ <PopoverTrigger+ openOnHover+ render={(+ <button+ type="button"+ className="flex h-8 w-full cursor-pointer items-center rounded-lg px-3 text-left hover:bg-state-base-hover focus-visible:bg-state-base-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden data-popup-open:bg-state-base-hover"+ >+ <BlockIcon+ className="mr-2 shrink-0"+ type={block.metaData.type}+ />+ <span className="min-w-0 grow truncate system-sm-medium text-text-secondary">+ {block.metaData.title}+ </span>+ <span aria-hidden className="i-custom-vender-solid-general-arrow-down-round-fill size-4 shrink-0 -rotate-90 text-text-tertiary" />+ </button>+ )}+ />+ <PopoverContent+ placement="right-start"+ sideOffset={4}+ popupClassName="border-none bg-transparent p-0 shadow-none backdrop-blur-none"+ >+ <PopoverTitle className="sr-only">+ {t('roster.nodeSelector.dialogLabel')}+ </PopoverTitle>+ <AgentSelectorContent+ open={open}+ onOpenChange={setOpen}+ onSelect={handleSelect}+ onStartFromScratch={() => {+ setOpen(false)+ onStartFromScratch()+ }}+ />+ </PopoverContent>+ </Popover>+ )+}diff --git a/web/app/components/workflow/block-selector/blocks.tsx b/web/app/components/workflow/block-selector/blocks.tsxindex d5fe0b8b29a..9cc90246754 100644--- a/web/app/components/workflow/block-selector/blocks.tsx+++ b/web/app/components/workflow/block-selector/blocks.tsx@@ -1,4 +1,4 @@-import type { NodeDefault } from '../types'+import type { NodeDefault, OnSelectBlock } from '../types'import type { BlockClassificationEnum } from './types'import {createPreviewCardHandle,@@ -17,12 +17,13 @@ import { useStoreApi } from 'reactflow'import Badge from '@/app/components/base/badge'import BlockIcon from '../block-icon'import { BlockEnum } from '../types'+import { AgentBlockItem } from './agent-selector'import { BLOCK_CLASSIFICATIONS } from './constants'import { useBlocks } from './hooks'type BlocksProps = {searchText: string- onSelect: (type: BlockEnum) => void+ onSelect: OnSelectBlockavailableBlocksTypes?: BlockEnum[]blocks?: NodeDefault[]}@@ -79,7 +80,13 @@ const Blocks = ({const isEmpty = Object.values(groups).every(list => !list.length)const renderGroup = useCallback((classification: BlockClassificationEnum) => {- const list = groups[classification]!.sort((a, b) => (a.metaData.sort || 0) - (b.metaData.sort || 0))+ const list = [...groups[classification]!].sort((a, b) => {+ if (a.metaData.type === BlockEnum.AgentV2)+ return -1+ if (b.metaData.type === BlockEnum.AgentV2)+ return 1+ return (a.metaData.sort || 0) - (b.metaData.sort || 0)+ })const { getNodes } = store.getState()const nodes = getNodes()const hasKnowledgeBaseNode = nodes.some(node => node.data.type === BlockEnum.KnowledgeBase)@@ -102,39 +109,64 @@ const Blocks = ({)}{- // Preview is supplementary: icon/title/description are all reachable- // from the node that gets added on click (inspector + canvas), so- // hover/focus-only activation is a11y-safe. See- // packages/dify-ui/AGENTS.md → Overlay Primitive Selection.- filteredList.map(block => (- <PreviewCardTrigger- key={block.metaData.type}- delay={150}- closeDelay={150}- handle={previewCardHandle}- payload={{ block }}- render={(- <div- className="flex h-8 w-full cursor-pointer items-center rounded-lg px-3 hover:bg-state-base-hover"- onClick={() => onSelect(block.metaData.type)}- >- <BlockIcon- className="mr-2 shrink-0"- type={block.metaData.type}- />- <div className="grow text-sm text-text-secondary">{block.metaData.title}</div>- {- block.metaData.type === BlockEnum.LoopEnd && (- <Badge- text={t('nodes.loop.loopNode', { ns: 'workflow' })}- className="ml-2 shrink-0"- />- )- }- </div>- )}- />- ))+ filteredList.map((block) => {+ if (block.metaData.type === BlockEnum.AgentV2) {+ return (+ <AgentBlockItem+ key={block.metaData.type}+ block={block}+ onSelect={agent =>+ onSelect(BlockEnum.AgentV2, {+ agent_binding: {+ binding_type: 'roster_agent',+ agent_id: agent.id,+ },+ agent_node_kind: 'dify_agent',+ version: '2',+ })}+ onStartFromScratch={() =>+ onSelect(BlockEnum.AgentV2, {+ agent_binding: {+ binding_type: 'inline_agent',+ },+ agent_node_kind: 'dify_agent',+ version: '2',+ })}+ />+ )+ }++ return (+ <PreviewCardTrigger+ key={block.metaData.type}+ delay={150}+ closeDelay={150}+ handle={previewCardHandle}+ payload={{ block }}+ render={(+ <button+ type="button"+ className="flex h-8 w-full cursor-pointer items-center rounded-lg px-3 text-left hover:bg-state-base-hover focus-visible:bg-state-base-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"+ onClick={() => onSelect(block.metaData.type)}+ >+ <BlockIcon+ className="mr-2 shrink-0"+ type={block.metaData.type}+ />+ <span className="min-w-0 grow truncate text-sm text-text-secondary">{block.metaData.title}</span>+ {+ block.metaData.type === BlockEnum.LoopEnd && (+ <Badge+ text={t('nodes.loop.loopNode', { ns: 'workflow' })}+ className="ml-2 shrink-0"+ />+ )+ }+ </button>+ )}+ />+ )+ })}</div>)diff --git a/web/app/components/workflow/block-selector/constants.tsx b/web/app/components/workflow/block-selector/constants.tsxindex 5ecce2aa49d..a036cc270cb 100644--- a/web/app/components/workflow/block-selector/constants.tsx+++ b/web/app/components/workflow/block-selector/constants.tsx@@ -61,6 +61,16 @@ export const ENTRY_NODE_TYPES = [] as constexport const BLOCKS = [+ {+ classification: BlockClassificationEnum.Default,+ type: BlockEnum.Agent,+ title: 'Agent',+ },+ {+ classification: BlockClassificationEnum.Default,+ type: BlockEnum.AgentV2,+ title: 'Agent',+ },{classification: BlockClassificationEnum.Default,type: BlockEnum.LLM,@@ -147,9 +157,4 @@ export const BLOCKS = [type: BlockEnum.ListFilter,title: 'List Filter',},- {- classification: BlockClassificationEnum.Default,- type: BlockEnum.Agent,- title: 'Agent',- },] as const satisfies readonly Block[]diff --git a/web/app/components/workflow/block-selector/tool-picker.tsx b/web/app/components/workflow/block-selector/tool-picker.tsxindex 571f6770058..948b3cd65d9 100644--- a/web/app/components/workflow/block-selector/tool-picker.tsx+++ b/web/app/components/workflow/block-selector/tool-picker.tsx@@ -1,7 +1,7 @@'use client'import type { OffsetOptions } from '@floating-ui/react'import type { Placement } from '@langgenius/dify-ui/popover'-import type { FC } from 'react'+import type { ReactNode } from 'react'import type { ToolDefaultValue, ToolValue } from './types'import type { CustomCollectionBackend } from '@/app/components/tools/types'import type { BlockEnum, OnSelectBlock } from '@/app/components/workflow/types'@@ -14,7 +14,6 @@ import {import { toast } from '@langgenius/dify-ui/toast'import { useSuspenseQuery } from '@tanstack/react-query'import { useBoolean } from 'ahooks'-import * as React from 'react'import { useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'import SearchBox from '@/app/components/plugins/marketplace/search-box'@@ -37,13 +36,17 @@ import {} from '@/service/use-tools'type Props = Readonly<{- panelClassName?: stringdisabled: boolean- trigger: React.ReactNode+ trigger: ReactNodeplacement?: Placementoffset?: OffsetOptionsisShow: booleanonShowChange: (isShow: boolean) => void+}> & ToolPickerContentProps++export type ToolPickerContentProps = Readonly<{+ focusSearchOnMount?: boolean+ panelClassName?: stringonSelect: (tool: ToolDefaultValue) => voidonSelectMultiple: (tools: ToolDefaultValue[]) => voidsupportAddCustomTool?: boolean@@ -51,25 +54,18 @@ type Props = Readonly<{selectedTools?: ToolValue[]}>-const ToolPicker: FC<Props> = ({- disabled,- trigger,- placement = 'right-start',- offset = 0,- isShow,- onShowChange,+export function ToolPickerContent({+ focusSearchOnMount = false,onSelect,onSelectMultiple,supportAddCustomTool,scope = 'all',selectedTools,panelClassName,-}) => {+}: ToolPickerContentProps) {const { t } = useTranslation()const [searchText, setSearchText] = useState('')const [tags, setTags] = useState<string[]>([])- const sideOffset = typeof offset === 'number' ? offset : (typeof offset === 'function' ? 0 : (offset?.mainAxis ?? 0))- const alignOffset = typeof offset === 'number' ? 0 : (typeof offset === 'function' ? 0 : (offset?.crossAxis ?? 0))const { data: enable_marketplace } = useSuspenseQuery({...systemFeaturesQueryOptions(),@@ -120,12 +116,6 @@ const ToolPicker: FC<Props> = ({const handleAddedCustomTool = invalidateCustomTools- const handleOpenChange = (nextOpen: boolean) => {- if (nextOpen && disabled)- return- onShowChange(nextOpen)- }-const handleSelect = (_type: BlockEnum, tool?: ToolDefaultValue) => {onSelect(tool!)}@@ -157,6 +147,70 @@ const ToolPicker: FC<Props> = ({)}+ return (+ <div className={cn('relative min-h-20 rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur shadow-lg backdrop-blur-xs', panelClassName)}>+ <div className="p-2 pb-1">+ <SearchBox+ search={searchText}+ onSearchChange={setSearchText}+ tags={tags}+ onTagsChange={setTags}+ placeholder={t('searchTools', { ns: 'plugin' })!}+ supportAddCustomTool={supportAddCustomTool}+ onAddedCustomTool={handleAddedCustomTool}+ onShowAddCustomCollectionModal={showEditCustomCollectionModal}+ // The picker replaces the focused menu item inside an already-open popover.+ // Focusing search keeps keyboard users in the same add-tool workflow.+ /* eslint-disable-next-line jsx-a11y/no-autofocus */+ autoFocus={focusSearchOnMount}+ inputClassName="grow"+ />+ </div>+ <AllTools+ className="mt-1"+ toolContentClassName="max-w-full"+ tags={tags}+ searchText={searchText}+ onSelect={handleSelect as OnSelectBlock}+ onSelectMultiple={handleSelectMultiple}+ buildInTools={builtinToolList || []}+ customTools={customToolList || []}+ workflowTools={workflowToolList || []}+ mcpTools={mcpTools || []}+ selectedTools={selectedTools}+ onTagsChange={setTags}+ featuredPlugins={featuredPlugins}+ featuredLoading={isFeaturedLoading}+ showFeatured={scope === 'all' && enable_marketplace}+ onFeaturedInstallSuccess={async () => {+ invalidateBuiltInTools()+ invalidateCustomTools()+ invalidateWorkflowTools()+ invalidateMcpTools()+ }}+ />+ </div>+ )+}++function ToolPicker({+ disabled,+ trigger,+ placement = 'right-start',+ offset = 0,+ isShow,+ onShowChange,+ ...contentProps+}: Props) {+ const sideOffset = typeof offset === 'number' ? offset : (typeof offset === 'function' ? 0 : (offset?.mainAxis ?? 0))+ const alignOffset = typeof offset === 'number' ? 0 : (typeof offset === 'function' ? 0 : (offset?.crossAxis ?? 0))++ const handleOpenChange = (nextOpen: boolean) => {+ if (nextOpen && disabled)+ return+ onShowChange(nextOpen)+ }+return (<Popoveropen={isShow}@@ -175,47 +229,10 @@ const ToolPicker: FC<Props> = ({alignOffset={alignOffset}popupClassName="border-none bg-transparent shadow-none">- <div className={cn('relative min-h-20 rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur shadow-lg backdrop-blur-xs', panelClassName)}>- <div className="p-2 pb-1">- <SearchBox- search={searchText}- onSearchChange={setSearchText}- tags={tags}- onTagsChange={setTags}- placeholder={t('searchTools', { ns: 'plugin' })!}- supportAddCustomTool={supportAddCustomTool}- onAddedCustomTool={handleAddedCustomTool}- onShowAddCustomCollectionModal={showEditCustomCollectionModal}- inputClassName="grow"- />- </div>- <AllTools- className="mt-1"- toolContentClassName="max-w-full"- tags={tags}- searchText={searchText}- onSelect={handleSelect as OnSelectBlock}- onSelectMultiple={handleSelectMultiple}- buildInTools={builtinToolList || []}- customTools={customToolList || []}- workflowTools={workflowToolList || []}- mcpTools={mcpTools || []}- selectedTools={selectedTools}- onTagsChange={setTags}- featuredPlugins={featuredPlugins}- featuredLoading={isFeaturedLoading}- showFeatured={scope === 'all' && enable_marketplace}- onFeaturedInstallSuccess={async () => {- invalidateBuiltInTools()- invalidateCustomTools()- invalidateWorkflowTools()- invalidateMcpTools()- }}- />- </div>+ <ToolPickerContent {...contentProps} /></PopoverContent></Popover>)}-export default React.memo(ToolPicker)+export default ToolPickerdiff --git a/web/app/components/workflow/block-selector/tool/action-item.tsx b/web/app/components/workflow/block-selector/tool/action-item.tsxindex 7265b65b300..153bc75ce56 100644--- a/web/app/components/workflow/block-selector/tool/action-item.tsx+++ b/web/app/components/workflow/block-selector/tool/action-item.tsx@@ -85,6 +85,7 @@ const ToolItem: FC<Props> = ({provider_id: provider.id,provider_type: provider.type,provider_name: provider.name,+ provider_show_name: provider.label[language],plugin_id: provider.plugin_id,plugin_unique_identifier: provider.plugin_unique_identifier,provider_icon: normalizedIcon,diff --git a/web/app/components/workflow/block-selector/tool/tool.tsx b/web/app/components/workflow/block-selector/tool/tool.tsxindex a307b0672f7..3802de6137a 100644--- a/web/app/components/workflow/block-selector/tool/tool.tsx+++ b/web/app/components/workflow/block-selector/tool/tool.tsx@@ -118,6 +118,7 @@ const Tool: FC<Props> = ({provider_id: payload.id,provider_type: payload.type,provider_name: payload.name,+ provider_show_name: payload.label[language],plugin_id: payload.plugin_id!,plugin_unique_identifier: payload.plugin_unique_identifier!,provider_icon: normalizedIcon,@@ -148,7 +149,7 @@ const Tool: FC<Props> = ({: `${selectedToolsNum} / ${totalToolsNum}`}</span>)- }, [actions, getIsDisabled, isAllSelected, isHovering, language, onSelectMultiple, payload.id, payload.is_team_authorization, payload.name, payload.type, selectedToolsNum, t, totalToolsNum])+ }, [actions, getIsDisabled, isAllSelected, isHovering, language, normalizedIcon, normalizedIconDark, onSelectMultiple, payload.id, payload.is_team_authorization, payload.label, payload.name, payload.plugin_id, payload.plugin_unique_identifier, payload.type, selectedToolsNum, t, totalToolsNum])if (isFoldHasSearchText !== hasSearchText) {setIsFoldHasSearchText(hasSearchText)@@ -196,6 +197,7 @@ const Tool: FC<Props> = ({provider_id: payload.id,provider_type: payload.type,provider_name: payload.name,+ provider_show_name: payload.label[language],plugin_id: payload.plugin_id,plugin_unique_identifier: payload.plugin_unique_identifier,provider_icon: normalizedIcon,diff --git a/web/app/components/workflow/block-selector/types.ts b/web/app/components/workflow/block-selector/types.tsindex cb74b9c78b0..a6fea38acbd 100644--- a/web/app/components/workflow/block-selector/types.ts+++ b/web/app/components/workflow/block-selector/types.ts@@ -1,3 +1,4 @@+import type { AgentInviteOptionResponse } from '@dify/contracts/api/console/agent/types.gen'import type { ParametersSchema, PluginMeta, PluginTriggerSubscriptionConstructor, SupportedCreationMethods, TriggerEvent } from '../../plugins/types'import type { Collection, Event } from '../../tools/types'import type { TypeWithI18N } from '@/app/components/header/account-setting/model-provider-page/declarations'@@ -48,6 +49,7 @@ export type TriggerDefaultValue = PluginCommonDefaultValue & {}export type ToolDefaultValue = PluginCommonDefaultValue & {+ provider_show_name?: stringtool_name: stringtool_label: stringtool_description: string@@ -75,8 +77,34 @@ export type DataSourceDefaultValue = Omit<PluginCommonDefaultValue, 'provider_idplugin_unique_identifier?: string}+export type AgentRosterNodeData = Pick<+ AgentInviteOptionResponse,+ 'description' | 'icon' | 'icon_background' | 'icon_type' | 'id' | 'name' | 'role'+>++type AgentRosterBinding = {+ binding_type: 'roster_agent'+ agent_id: string+}++export type AgentInlineBinding = {+ binding_type: 'inline_agent'+ agent_id?: string | null+ current_snapshot_id?: string | null+}++export type AgentBinding = AgentRosterBinding | AgentInlineBinding++type AgentDefaultValue = {+ agent_binding: AgentBinding+ agent_node_kind: 'dify_agent'+ version: '2'+}+export type PluginDefaultValue = ToolDefaultValue | DataSourceDefaultValue | TriggerDefaultValue+export type BlockDefaultValue = PluginDefaultValue | AgentDefaultValue+export type ToolValue = {provider_name: stringprovider_show_name?: stringdiff --git a/web/app/components/workflow/candidate-node-main.tsx b/web/app/components/workflow/candidate-node-main.tsxindex 8161f4aefef..d7473023891 100644--- a/web/app/components/workflow/candidate-node-main.tsx+++ b/web/app/components/workflow/candidate-node-main.tsx@@ -1,4 +1,5 @@import type {+ ComponentProps,FC,} from 'react'import type {@@ -17,6 +18,8 @@ import { useCollaborativeWorkflow } from '@/app/components/workflow/hooks/use-coimport { CUSTOM_NODE } from './constants'import { useAutoGenerateWebhookUrl, useNodesInteractions, useNodesSyncDraft, useWorkflowHistory, WorkflowHistoryEvent } from './hooks'import CustomNode from './nodes'+import { useCreateInlineAgentBinding } from './nodes/agent-v2/hooks'+import { isAgentV2NodeData, needsInlineAgentBindingCreation } from './nodes/agent-v2/types'import CustomNoteNode from './note-node'import { CUSTOM_NOTE_NODE } from './note-node/constants'import {@@ -41,18 +44,21 @@ const CandidateNodeMain: FC<Props> = ({const { handleSyncWorkflowDraft } = useNodesSyncDraft()const autoGenerateWebhookUrl = useAutoGenerateWebhookUrl()const collaborativeWorkflow = useCollaborativeWorkflow()+ const { createInlineAgentBinding } = useCreateInlineAgentBinding()useEventListener('click', (e) => {e.preventDefault()const { screenToFlowPosition } = reactflowconst { nodes, setNodes } = collaborativeWorkflow.getState()const { x, y } = screenToFlowPosition({ x: mousePosition.pageX, y: mousePosition.pageY })+ const shouldCreateInlineAgentBinding = isAgentV2NodeData(candidateNode.data) && needsInlineAgentBindingCreation(candidateNode.data)const newNodes = produce(nodes, (draft) => {draft.push({...candidateNode,data: {...candidateNode.data,_isCandidate: false,+ _isTempNode: shouldCreateInlineAgentBinding ? true : candidateNode.data._isTempNode,},position: {x,@@ -81,6 +87,33 @@ const CandidateNodeMain: FC<Props> = ({onSuccess: () => autoGenerateWebhookUrl(candidateNode.id),})}++ if (shouldCreateInlineAgentBinding) {+ createInlineAgentBinding(candidateNode.id, {+ onError: () => {+ const { nodes, setNodes } = collaborativeWorkflow.getState()+ setNodes(nodes.filter(node => node.id !== candidateNode.id))+ },+ onSuccess: (binding) => {+ const { nodes, setNodes } = collaborativeWorkflow.getState()+ setNodes(produce(nodes, (draft) => {+ const node = draft.find(node => node.id === candidateNode.id)+ if (node) {+ if (isAgentV2NodeData(node.data) && needsInlineAgentBindingCreation(node.data))+ node.data.agent_binding = binding+ node.data._openInlineAgentPanel = true+ delete node.data._isTempNode+ }+ }))+ workflowStore.getState().setOpenInlineAgentPanelNodeId(candidateNode.id)+ handleSyncWorkflowDraft(true, true)+ },+ })+ return+ }++ if (isAgentV2NodeData(candidateNode.data))+ handleSyncWorkflowDraft(true, true)})useEventListener('contextmenu', (e) => {@@ -100,12 +133,12 @@ const CandidateNodeMain: FC<Props> = ({>{candidateNode.type === CUSTOM_NODE && (- <CustomNode {...candidateNode as any} />+ <CustomNode {...candidateNode as unknown as ComponentProps<typeof CustomNode>} />)}{candidateNode.type === CUSTOM_NOTE_NODE && (- <CustomNoteNode {...candidateNode as any} />+ <CustomNoteNode {...candidateNode as unknown as ComponentProps<typeof CustomNoteNode>} />)}</div>diff --git a/web/app/components/workflow/constants.ts b/web/app/components/workflow/constants.tsindex 765f10ed3c4..4dc3109a208 100644--- a/web/app/components/workflow/constants.ts+++ b/web/app/components/workflow/constants.ts@@ -121,13 +121,22 @@ export const SUPPORT_OUTPUT_VARS_NODE = [BlockEnum.DocExtractor,BlockEnum.ListFilter,BlockEnum.Agent,+ BlockEnum.AgentV2,BlockEnum.DataSource,BlockEnum.HumanInput,]export const AGENT_OUTPUT_STRUCT: Var[] = [{- variable: 'usage',+ variable: 'text',+ type: VarType.string,+ },+ {+ variable: 'files',+ type: VarType.arrayFile,+ },+ {+ variable: 'json',type: VarType.object,},]diff --git a/web/app/components/workflow/constants/node.ts b/web/app/components/workflow/constants/node.tsindex 4d67f278c25..41269044245 100644--- a/web/app/components/workflow/constants/node.ts+++ b/web/app/components/workflow/constants/node.ts@@ -1,3 +1,4 @@+import agentV2Default from '@/app/components/workflow/nodes/agent-v2/default'import agentDefault from '@/app/components/workflow/nodes/agent/default'import assignerDefault from '@/app/components/workflow/nodes/assigner/default'import codeDefault from '@/app/components/workflow/nodes/code/default'@@ -26,6 +27,7 @@ export const WORKFLOW_COMMON_NODES = [llmDefault,knowledgeRetrievalDefault,agentDefault,+ agentV2Default,questionClassifierDefault,ifElseDefault,iterationDefault,diff --git a/web/app/components/workflow/hooks/__tests__/use-nodes-interactions.spec.ts b/web/app/components/workflow/hooks/__tests__/use-nodes-interactions.spec.tsindex 220b73ea7ce..f0ce89a7018 100644--- a/web/app/components/workflow/hooks/__tests__/use-nodes-interactions.spec.ts+++ b/web/app/components/workflow/hooks/__tests__/use-nodes-interactions.spec.ts@@ -20,6 +20,7 @@ const mockHandleNodeLoopChildrenCopy = vi.hoisted(() => vi.fn(() => ({copyChildren: [],newIdMapping: {},})))+const mockCreateInlineAgentBinding = vi.hoisted(() => vi.fn())const runtimeNodesMetaDataMap = vi.hoisted(() => ({value: {} as Record<string, unknown>,}))@@ -78,6 +79,12 @@ vi.mock('../use-inspect-vars-crud', () => ({}),}))+vi.mock('../../nodes/agent-v2/hooks', () => ({+ useCreateInlineAgentBinding: () => ({+ createInlineAgentBinding: mockCreateInlineAgentBinding,+ }),+}))+vi.mock('../../nodes/iteration/use-interactions', () => ({useNodeIterationInteractions: () => ({handleNodeIterationChildDrag: () => ({ restrictPosition: {} }),@@ -107,6 +114,17 @@ describe('useNodesInteractions', () => {resetReactFlowMockState()runtimeState.nodesReadOnly = falseruntimeState.workflowReadOnly = false+ mockCreateInlineAgentBinding.mockImplementation((_nodeId: string, options?: { onSuccess?: (binding: {+ binding_type: 'inline_agent'+ agent_id: string+ current_snapshot_id: string+ }) => void }) => {+ options?.onSuccess?.({+ binding_type: 'inline_agent',+ agent_id: 'inline-agent-1',+ current_snapshot_id: 'inline-snapshot-1',+ })+ })currentNodes = [createNode({id: 'node-1',@@ -452,6 +470,84 @@ describe('useNodesInteractions', () => {expect(rfState.setEdges).not.toHaveBeenCalled()})+ it('creates an inline agent binding before syncing an added Agent v2 node', () => {+ currentNodes = [+ createNode({+ id: 'node-1',+ width: 100,+ data: {+ type: BlockEnum.Code,+ title: 'Code',+ desc: '',+ },+ }),+ ]+ rfState.nodes = currentNodes as unknown as typeof rfState.nodes+ rfState.edges = []+ rfState.setNodes.mockImplementation((nextNodes) => {+ rfState.nodes = nextNodes+ })+ rfState.setEdges.mockImplementation((nextEdges) => {+ rfState.edges = nextEdges+ })+ runtimeNodesMetaDataMap.value = {+ [BlockEnum.AgentV2]: {+ defaultValue: {+ type: BlockEnum.AgentV2,+ title: 'Agent',+ desc: '',+ agent_node_kind: 'dify_agent',+ version: '2',+ },+ metaData: {+ isSingleton: false,+ },+ },+ }++ const { result, store } = renderWorkflowHook(() => useNodesInteractions(), {+ historyStore: {+ nodes: currentNodes,+ edges: [],+ },+ })++ act(() => {+ result.current.handleNodeAdd(+ {+ nodeType: BlockEnum.AgentV2,+ pluginDefaultValue: {+ agent_binding: {+ binding_type: 'inline_agent',+ },+ agent_node_kind: 'dify_agent',+ version: '2',+ },+ },+ { prevNodeId: 'node-1' },+ )+ })++ const agentNode = rfState.nodes.find(node => node.data.type === BlockEnum.AgentV2)+ const firstSetNodesPayload = rfState.setNodes.mock.calls[0]?.[0]+ const pendingAgentNode = firstSetNodesPayload.find((node: Node) => node.data.type === BlockEnum.AgentV2)+ const finalSetNodesPayload = rfState.setNodes.mock.calls.at(-1)?.[0]+ const finalAgentNode = finalSetNodesPayload.find((node: Node) => node.data.type === BlockEnum.AgentV2)++ expect(pendingAgentNode?.data._isTempNode).toBe(true)+ expect(agentNode?.data.agent_binding).toEqual({+ binding_type: 'inline_agent',+ agent_id: 'inline-agent-1',+ current_snapshot_id: 'inline-snapshot-1',+ })+ expect(finalAgentNode?.data._isTempNode).toBeUndefined()+ expect(mockCreateInlineAgentBinding).toHaveBeenCalledWith(agentNode?.id, expect.objectContaining({+ onSuccess: expect.any(Function),+ }))+ expect(store.getState().openInlineAgentPanelNodeId).toBe(agentNode?.id)+ expect(mockHandleSyncWorkflowDraft).toHaveBeenCalledWith(true, true)+ })+it('cancels selection state with collaborative nodes snapshot', () => {currentNodes = [createNode({diff --git a/web/app/components/workflow/hooks/use-checklist.ts b/web/app/components/workflow/hooks/use-checklist.tsindex 2eb73ae2a2c..643823aab6a 100644--- a/web/app/components/workflow/hooks/use-checklist.ts+++ b/web/app/components/workflow/hooks/use-checklist.ts@@ -56,6 +56,7 @@ import {} from '../hooks'import { useHooksStore } from '../hooks-store/store'import { getNodeUsedVars, isSpecialVar } from '../nodes/_base/components/variable/utils'+import { isAgentV2NodeData } from '../nodes/agent-v2/types'import { IndexMethodEnum } from '../nodes/knowledge-base/types'import { getLLMModelIssue, isLLMModelProviderInstalled, LLMModelIssueCode } from '../nodes/llm/utils'import {@@ -98,6 +99,10 @@ const withFlowType = (moreDataForCheckValid: CheckValidExtraData, flowType?: Flo}}+const getNodeMetaType = (data: CommonNodeType) => {+ return isAgentV2NodeData(data) ? BlockEnum.AgentV2 : data.type+}+const START_NODE_TYPES: BlockEnum[] = [BlockEnum.Start,BlockEnum.TriggerSchedule,@@ -249,7 +254,7 @@ export const useChecklist = (nodes: Node[], edges: Edge[], options?: { flowType?moreDataForCheckValid = getTriggerCheckParams(node!.data as PluginTriggerNodeType, triggerPlugins, language)const toolIcon = getToolIcon(node!.data)- if (node!.data.type === BlockEnum.Agent) {+ if (node!.data.type === BlockEnum.Agent && !isAgentV2NodeData(node!.data)) {const data = node!.data as AgentNodeTypeconst isReadyForCheckValid = !!strategyProvidersconst provider = strategyProviders?.find(provider => provider.declaration.identity.name === data.agent_strategy_provider_name)@@ -267,7 +272,7 @@ export const useChecklist = (nodes: Node[], edges: Edge[], options?: { flowType?if (node!.type === CUSTOM_NODE) {const checkData = getCheckData(node!.data)- const validator = nodesExtraData?.[node!.data.type as BlockEnum]?.checkValid+ const validator = nodesExtraData?.[getNodeMetaType(node!.data) as BlockEnum]?.checkValidconst isPluginMissing = isNodePluginMissing(node!.data, { builtInTools: buildInTools, customTools, workflowTools, mcpTools, triggerPlugins, dataSourceList })const errorMessages: string[] = []@@ -522,7 +527,7 @@ export const useChecklistBeforePublish = () => {if (node!.data.type === BlockEnum.DataSource)moreDataForCheckValid = getDataSourceCheckParams(node!.data as DataSourceNodeType, dataSourceList || [], language)- if (node!.data.type === BlockEnum.Agent) {+ if (node!.data.type === BlockEnum.Agent && !isAgentV2NodeData(node!.data)) {const data = node!.data as AgentNodeTypeconst isReadyForCheckValid = !!strategyProvidersconst provider = strategyProviders?.find(provider => provider.declaration.identity.name === data.agent_strategy_provider_name)@@ -551,7 +556,7 @@ export const useChecklistBeforePublish = () => {}const checkData = getCheckData(node!.data, datasets, embeddingProviderModelMap)- const { errorMessage } = nodesExtraData![node!.data.type as BlockEnum].checkValid(checkData, t, withFlowType(moreDataForCheckValid, flowType))+ const { errorMessage } = nodesExtraData![getNodeMetaType(node!.data) as BlockEnum].checkValid(checkData, t, withFlowType(moreDataForCheckValid, flowType))if (errorMessage) {toast.error(`[${node!.data.title}] ${errorMessage}`)diff --git a/web/app/components/workflow/hooks/use-nodes-interactions.ts b/web/app/components/workflow/hooks/use-nodes-interactions.tsindex 5b8dc1a14e4..4ef36285824 100644--- a/web/app/components/workflow/hooks/use-nodes-interactions.ts+++ b/web/app/components/workflow/hooks/use-nodes-interactions.ts@@ -7,7 +7,7 @@ import type {OnConnectStart,ResizeParamsWithDirection,} from 'reactflow'-import type { PluginDefaultValue } from '../block-selector/types'+import type { BlockDefaultValue } from '../block-selector/types'import type { IterationNodeType } from '../nodes/iteration/types'import type { LoopNodeType } from '../nodes/loop/types'import type { VariableAssignerNodeType } from '../nodes/variable-assigner/types'@@ -36,6 +36,8 @@ import {Y_OFFSET,} from '../constants'import { getNodeUsedVars } from '../nodes/_base/components/variable/utils'+import { useCreateInlineAgentBinding } from '../nodes/agent-v2/hooks'+import { isAgentV2NodeData, needsInlineAgentBindingCreation } from '../nodes/agent-v2/types'import { CUSTOM_ITERATION_START_NODE } from '../nodes/iteration-start/constants'import { useNodeIterationInteractions } from '../nodes/iteration/use-interactions'import { CUSTOM_LOOP_START_NODE } from '../nodes/loop-start/constants'@@ -50,6 +52,7 @@ import {getNestedNodePosition,getNodeCustomTypeByNodeDataType,getNodesConnectedSourceOrTargetHandleIdsMap,+ getNodesWithSameDefaultDataType,getTopLeftNodePosition,isClipboardEdgeStructurallyValid,isClipboardNodeStructurallyValid,@@ -84,6 +87,16 @@ const ENTRY_NODE_WRAPPER_OFFSET = {y: 21, // Adjusted based on visual testing feedback} as const+function needsPendingInlineAgentBinding(defaultValue?: BlockDefaultValue) {+ if (!defaultValue || !('agent_binding' in defaultValue))+ return false++ const binding = defaultValue.agent_binding++ return binding.binding_type === 'inline_agent'+ && (!binding.agent_id || !binding.current_snapshot_id)+}+const pruneClipboardNodesWithFilteredAncestors = (sourceNodes: Node[],candidateNodes: Node[],@@ -174,6 +187,31 @@ export const useNodesInteractions = () => {redo,} = useWorkflowHistory()const autoGenerateWebhookUrl = useAutoGenerateWebhookUrl()+ const { createInlineAgentBinding } = useCreateInlineAgentBinding()++ const createInlineAgentBindingForNode = useCallback((nodeId: string, options?: {+ onError?: () => void+ }) => {+ createInlineAgentBinding(nodeId, {+ onError: () => {+ options?.onError?.()+ },+ onSuccess: (binding) => {+ const { nodes, setNodes } = collaborativeWorkflow.getState()+ setNodes(produce(nodes, (draft) => {+ const node = draft.find(node => node.id === nodeId)+ if (node) {+ if (isAgentV2NodeData(node.data) && needsInlineAgentBindingCreation(node.data))+ node.data.agent_binding = binding+ node.data._openInlineAgentPanel = true+ delete node.data._isTempNode+ }+ }))+ workflowStore.getState().setOpenInlineAgentPanelNodeId(nodeId)+ handleSyncWorkflowDraft(true, true)+ },+ })+ }, [collaborativeWorkflow, createInlineAgentBinding, handleSyncWorkflowDraft, workflowStore])const handleNodeDragStart = useCallback<NodeDragHandler>((_, node) => {@@ -233,12 +271,12 @@ export const useNodesInteractions = () => {const currentNode = draft.find(n => n.id === node.id)!// Check if current dragging node is an entry node- const isCurrentEntryNode = isTriggerNode(node.data.type as any) || node.data.type === BlockEnum.Start+ const isCurrentEntryNode = isTriggerNode(node.data.type as BlockEnum) || node.data.type === BlockEnum.Start// X-axis alignment with offset considerationif (showVerticalHelpLineNodesLength > 0) {const targetNode = showVerticalHelpLineNodes[0]- const isTargetEntryNode = isTriggerNode(targetNode!.data.type as any) || targetNode!.data.type === BlockEnum.Start+ const isTargetEntryNode = isTriggerNode(targetNode!.data.type as BlockEnum) || targetNode!.data.type === BlockEnum.Start// Calculate the wrapper position needed to align the inner nodes// Target inner position = target.position + target.offset@@ -262,7 +300,7 @@ export const useNodesInteractions = () => {// Y-axis alignment with offset considerationif (showHorizontalHelpLineNodesLength > 0) {const targetNode = showHorizontalHelpLineNodes[0]- const isTargetEntryNode = isTriggerNode(targetNode!.data.type as any) || targetNode!.data.type === BlockEnum.Start+ const isTargetEntryNode = isTriggerNode(targetNode!.data.type as BlockEnum) || targetNode!.data.type === BlockEnum.Startconst targetOffset = isTargetEntryNode ? ENTRY_NODE_WRAPPER_OFFSET.y : 0const currentOffset = isCurrentEntryNode ? ENTRY_NODE_WRAPPER_OFFSET.y : 0@@ -619,7 +657,7 @@ export const useNodesInteractions = () => {)const handleNodeConnectEnd = useCallback<OnConnectEnd>(- (e: any) => {+ (e) => {if (getNodesReadOnly())return@@ -645,7 +683,8 @@ export const useNodesInteractions = () => {if (fromNode.parentId !== toNode.parentId)return- const { x, y } = screenToFlowPosition({ x: e.x, y: e.y })+ const pointer = e as { x: number, y: number }+ const { x, y } = screenToFlowPosition({ x: pointer.x, y: pointer.y })if (fromHandleType === 'source'@@ -880,24 +919,24 @@ export const useNodesInteractions = () => {returnconst { nodes, setNodes, edges, setEdges } = collaborativeWorkflow.getState()- const nodesWithSameType = nodes.filter(- node => node.data.type === nodeType,- )const nodeMetaData = nodesMetaDataMap?.[nodeType]if (!nodeMetaData)returnconst { defaultValue } = nodeMetaData+ const nodesWithSameType = getNodesWithSameDefaultDataType(nodes, nodeType, defaultValue)+ const shouldCreateInlineAgentBinding = nodeType === BlockEnum.AgentV2 && needsPendingInlineAgentBinding(pluginDefaultValue)const { newNode, newIterationStartNode, newLoopStartNode }= generateNewNode({type: getNodeCustomTypeByNodeDataType(nodeType),data: {- ...(defaultValue as any),+ ...(defaultValue as Node['data']),title:nodesWithSameType.length > 0? `${defaultValue.title} ${nodesWithSameType.length + 1}`: defaultValue.title,...pluginDefaultValue,selected: true,+ ...(shouldCreateInlineAgentBinding ? { _isTempNode: true } : {}),_showAddVariablePopup:(nodeType === BlockEnum.VariableAssigner|| nodeType === BlockEnum.VariableAggregator)@@ -1141,7 +1180,7 @@ export const useNodesInteractions = () => {}}- let nodesConnectedSourceOrTargetHandleIdsMap: Record<string, any>+ let nodesConnectedSourceOrTargetHandleIdsMap: ReturnType<typeof getNodesConnectedSourceOrTargetHandleIdsMap>if (newEdge) {nodesConnectedSourceOrTargetHandleIdsMap= getNodesConnectedSourceOrTargetHandleIdsMap(@@ -1420,6 +1459,18 @@ export const useNodesInteractions = () => {})setEdges(newEdges)}+ if (isAgentV2NodeData(newNode.data) && needsInlineAgentBindingCreation(newNode.data)) {+ saveStateToHistory(WorkflowHistoryEvent.NodeAdd, { nodeId: newNode.id })+ createInlineAgentBindingForNode(newNode.id, {+ onError: () => {+ const { nodes, setNodes, edges, setEdges } = collaborativeWorkflow.getState()+ setNodes(nodes.filter(node => node.id !== newNode.id))+ setEdges(edges.filter(edge => edge.source !== newNode.id && edge.target !== newNode.id))+ },+ })+ return+ }+handleSyncWorkflowDraft()saveStateToHistory(WorkflowHistoryEvent.NodeAdd, { nodeId: newNode.id })},@@ -1427,6 +1478,7 @@ export const useNodesInteractions = () => {getNodesReadOnly,collaborativeWorkflow,handleSyncWorkflowDraft,+ createInlineAgentBindingForNode,saveStateToHistory,workflowStore,getAfterNodesInSameBranch,@@ -1439,7 +1491,7 @@ export const useNodesInteractions = () => {currentNodeId: string,nodeType: BlockEnum,sourceHandle: string,- pluginDefaultValue?: PluginDefaultValue,+ pluginDefaultValue?: BlockDefaultValue,) => {if (getNodesReadOnly())return@@ -1447,13 +1499,12 @@ export const useNodesInteractions = () => {const { nodes, setNodes, edges, setEdges } = collaborativeWorkflow.getState()const currentNode = nodes.find(node => node.id === currentNodeId)!const connectedEdges = getConnectedEdges([currentNode], edges)- const nodesWithSameType = nodes.filter(- node => node.data.type === nodeType,- )const nodeMetaData = nodesMetaDataMap?.[nodeType]if (!nodeMetaData)returnconst { defaultValue } = nodeMetaData+ const nodesWithSameType = getNodesWithSameDefaultDataType(nodes, nodeType, defaultValue)+ const shouldCreateInlineAgentBinding = nodeType === BlockEnum.AgentV2 && needsPendingInlineAgentBinding(pluginDefaultValue)const {newNode: newCurrentNode,newIterationStartNode,@@ -1461,12 +1512,13 @@ export const useNodesInteractions = () => {} = generateNewNode({type: getNodeCustomTypeByNodeDataType(nodeType),data: {- ...(defaultValue as any),+ ...(defaultValue as Node['data']),title:nodesWithSameType.length > 0? `${defaultValue.title} ${nodesWithSameType.length + 1}`: defaultValue.title,...pluginDefaultValue,+ ...(shouldCreateInlineAgentBinding ? { _isTempNode: true } : {}),_connectedSourceHandleIds: [],_connectedTargetHandleIds: [],selected: currentNode.data.selected,@@ -1651,6 +1703,15 @@ export const useNodesInteractions = () => {onSuccess: () => autoGenerateWebhookUrl(newCurrentNode.id),})}+ else if (isAgentV2NodeData(newCurrentNode.data) && needsInlineAgentBindingCreation(newCurrentNode.data)) {+ createInlineAgentBindingForNode(newCurrentNode.id, {+ onError: () => {+ const { setNodes, setEdges } = collaborativeWorkflow.getState()+ setNodes(nodes)+ setEdges(edges)+ },+ })+ }else {handleSyncWorkflowDraft()}@@ -1663,6 +1724,7 @@ export const useNodesInteractions = () => {getNodesReadOnly,collaborativeWorkflow,handleSyncWorkflowDraft,+ createInlineAgentBindingForNode,saveStateToHistory,nodesMetaDataMap,autoGenerateWebhookUrl,@@ -1729,7 +1791,7 @@ export const useNodesInteractions = () => {if (node.type === CUSTOM_NOTE_NODE)return true- const nodeMeta = nodesMetaDataMap?.[node.data.type as BlockEnum]+ const nodeMeta = nodesMetaDataMap?.[isAgentV2NodeData(node.data) ? BlockEnum.AgentV2 : node.data.type as BlockEnum]if (!nodeMeta)return false@@ -1741,7 +1803,7 @@ export const useNodesInteractions = () => {if (node.type === CUSTOM_NOTE_NODE)return {}- const nodeMeta = nodesMetaDataMap?.[node.data.type as BlockEnum]+ const nodeMeta = nodesMetaDataMap?.[isAgentV2NodeData(node.data) ? BlockEnum.AgentV2 : node.data.type as BlockEnum]return nodeMeta?.defaultValue}, [nodesMetaDataMap])@@ -2359,7 +2421,7 @@ export const useNodesInteractions = () => {const currentNode = nodes.find(n => n.id === nodeId)!const childrenNodes = nodes.filter(n =>- currentNode.data._children?.find((c: any) => c.nodeId === n.id),+ currentNode.data._children?.find((child: NonNullable<Node['data']['_children']>[number]) => child.nodeId === n.id),)let rightNode: Nodelet bottomNode: Nodediff --git a/web/app/components/workflow/hooks/use-nodes-meta-data.ts b/web/app/components/workflow/hooks/use-nodes-meta-data.tsindex 2ea2fd9e9fc..bad25b87078 100644--- a/web/app/components/workflow/hooks/use-nodes-meta-data.ts+++ b/web/app/components/workflow/hooks/use-nodes-meta-data.ts@@ -3,6 +3,7 @@ import type { Node } from '@/app/components/workflow/types'import { useMemo } from 'react'import { CollectionType } from '@/app/components/tools/types'import { useHooksStore } from '@/app/components/workflow/hooks-store'+import { isAgentV2NodeData } from '@/app/components/workflow/nodes/agent-v2/types'import { useStore } from '@/app/components/workflow/store'import { BlockEnum } from '@/app/components/workflow/types'import { useGetLanguage } from '@/context/i18n'@@ -32,7 +33,7 @@ export const useNodeMetaData = (node: Node) => {const dataSourceList = useStore(s => s.dataSourceList)const availableNodesMetaData = useNodesMetaData()const { data } = node- const nodeMetaData = availableNodesMetaData.nodesMap?.[data.type]+ const nodeMetaData = availableNodesMetaData.nodesMap?.[isAgentV2NodeData(data) ? BlockEnum.AgentV2 : data.type]const author = useMemo(() => {if (data.type === BlockEnum.DataSource)return dataSourceList?.find(dataSource => dataSource.plugin_id === data.plugin_id)?.authordiff --git a/web/app/components/workflow/nodes/_base/components/node-handle.tsx b/web/app/components/workflow/nodes/_base/components/node-handle.tsxindex 1cfb6244837..c0c7e8388d2 100644--- a/web/app/components/workflow/nodes/_base/components/node-handle.tsx+++ b/web/app/components/workflow/nodes/_base/components/node-handle.tsx@@ -1,5 +1,5 @@import type { MouseEvent } from 'react'-import type { PluginDefaultValue } from '../../../block-selector/types'+import type { BlockDefaultValue } from '../../../block-selector/types'import type { Node } from '../../../types'import { cn } from '@langgenius/dify-ui/cn'import {@@ -68,7 +68,7 @@ export const NodeTargetHandle = memo(({if (!connected)setOpen(v => !v)}, [connected])- const handleSelect = useCallback((type: BlockEnum, pluginDefaultValue?: PluginDefaultValue) => {+ const handleSelect = useCallback((type: BlockEnum, pluginDefaultValue?: BlockDefaultValue) => {handleNodeAdd({nodeType: type,@@ -161,7 +161,7 @@ export const NodeSourceHandle = memo(({e.stopPropagation()setOpen(v => !v)}, [])- const handleSelect = useCallback((type: BlockEnum, pluginDefaultValue?: PluginDefaultValue) => {+ const handleSelect = useCallback((type: BlockEnum, pluginDefaultValue?: BlockDefaultValue) => {handleNodeAdd({nodeType: type,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.tsindex ec7c4f17deb..8e72be3f677 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,12 +1,13 @@+import type { AgentV2NodeType } from '@/app/components/workflow/nodes/agent-v2/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'import type { Node, PromptItem } from '@/app/components/workflow/types'import { describe, expect, it } from 'vitest'import { DeliveryMethodType } from '@/app/components/workflow/nodes/human-input/types'-import { BlockEnum, EditionType, InputVarType, PromptRole } from '@/app/components/workflow/types'+import { BlockEnum, EditionType, InputVarType, PromptRole, VarType } from '@/app/components/workflow/types'import { AppModeEnum } from '@/types/app'-import { getNodeUsedVars, updateNodeVars } from '../utils'+import { getNodeUsedVars, toNodeAvailableVars, updateNodeVars } from '../utils'const createNode = <T>(data: Node<T>['data']): Node<T> => ({id: 'node-1',@@ -42,6 +43,89 @@ const createLLMNodeData = (promptTemplate: PromptItem[]): LLMNodeType => ({})describe('variable utils', () => {+ describe('toNodeAvailableVars', () => {+ it('uses Agent v2 default declared outputs for agent nodes', () => {+ const node = createNode<AgentV2NodeType>({+ type: BlockEnum.Agent,+ title: 'Agent',+ desc: '',+ agent_node_kind: 'dify_agent',+ version: '2',+ })++ const availableVars = toNodeAvailableVars({+ beforeNodes: [node],+ isChatMode: false,+ filterVar: () => true,+ allPluginInfoList: {},+ })++ expect(availableVars).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ nodeId: 'node-1',+ vars: [+ { variable: 'text', type: VarType.string },+ { variable: 'files', type: VarType.arrayFile },+ { variable: 'json', type: VarType.object },+ ],+ }),+ ]),+ )+ expect(availableVars.find(item => item.nodeId === 'node-1')?.vars).not.toContainEqual({+ variable: 'usage',+ type: VarType.object,+ })+ })++ it('uses Agent v2 declared outputs from graph data', () => {+ const node = createNode<AgentV2NodeType>({+ type: BlockEnum.AgentV2,+ title: 'Agent',+ desc: '',+ agent_node_kind: 'dify_agent',+ agent_declared_outputs: [+ {+ name: 'summary',+ type: 'string',+ description: 'Short summary',+ },+ {+ name: 'attachments',+ type: 'array',+ array_item: {+ type: 'file',+ },+ },+ ],+ version: '2',+ })++ const availableVars = toNodeAvailableVars({+ beforeNodes: [node],+ isChatMode: false,+ filterVar: () => true,+ allPluginInfoList: {},+ })++ expect(availableVars).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ nodeId: 'node-1',+ vars: [+ { variable: 'summary', type: VarType.string },+ { variable: 'attachments', type: VarType.arrayFile },+ ],+ }),+ ]),+ )+ expect(availableVars.find(item => item.nodeId === 'node-1')?.vars).not.toContainEqual({+ variable: 'text',+ type: VarType.string,+ })+ })+ })+describe('getNodeUsedVars', () => {it('should read variables from llm jinja prompt text', () => {const node = createNode<LLMNodeType>(@@ -108,6 +192,19 @@ describe('variable utils', () => {]),)})++ it('should read variables from agent task', () => {+ const node = createNode<AgentV2NodeType>({+ type: BlockEnum.Agent,+ title: 'Agent',+ desc: '',+ agent_node_kind: 'dify_agent',+ agent_task: 'Clarify {{#start.tender#}}',+ version: '2',+ })++ expect(getNodeUsedVars(node)).toContainEqual(['start', 'tender'])+ })})describe('updateNodeVars', () => {@@ -144,6 +241,21 @@ describe('variable utils', () => {})})+ it('should replace agent task references', () => {+ const node = createNode<AgentV2NodeType>({+ type: BlockEnum.Agent,+ title: 'Agent',+ desc: '',+ agent_node_kind: 'dify_agent',+ agent_task: 'Clarify {{#start.tender#}}',+ version: '2',+ })++ const updatedNode = updateNodeVars(node, ['start', 'tender'], ['start', 'question'])++ expect((updatedNode.data as AgentV2NodeType).agent_task).toBe('Clarify {{#start.question#}}')+ })+it('should replace human input email template references', () => {const node = createNode<HumanInputNodeType>({type: BlockEnum.HumanInput,diff --git a/web/app/components/workflow/nodes/_base/components/variable/utils.ts b/web/app/components/workflow/nodes/_base/components/variable/utils.tsindex 80a33eecc6d..0f265b0e7ef 100644--- a/web/app/components/workflow/nodes/_base/components/variable/utils.ts+++ b/web/app/components/workflow/nodes/_base/components/variable/utils.ts@@ -1,4 +1,3 @@-import type { AgentNodeType } from '../../../agent/types'import type { AnswerNodeType } from '../../../answer/types'import type { CodeNodeType } from '../../../code/types'import type { DocExtractorNodeType } from '../../../document-extractor/types'@@ -14,6 +13,8 @@ import type { ParameterExtractorNodeType } from '../../../parameter-extractor/tyimport type { QuestionClassifierNodeType } from '../../../question-classifier/types'import type { TemplateTransformNodeType } from '../../../template-transform/types'import type { ToolNodeType } from '../../../tool/types'+import type { AgentV2NodeType } from '@/app/components/workflow/nodes/agent-v2/types'+import type { AgentNodeType } from '@/app/components/workflow/nodes/agent/types'import type { DataSourceNodeType } from '@/app/components/workflow/nodes/data-source/types'import type { HumanInputNodeType } from '@/app/components/workflow/nodes/human-input/types'import type { CaseItem, Condition } from '@/app/components/workflow/nodes/if-else/types'@@ -51,6 +52,8 @@ import {TEMPLATE_TRANSFORM_OUTPUT_STRUCT,TOOL_OUTPUT_STRUCT,} from '@/app/components/workflow/constants'+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'@@ -592,6 +595,11 @@ const formatItem = (}case BlockEnum.Agent: {+ if (isAgentV2NodeData(data)) {+ res.vars = getAgentV2OutputVars(data)+ break+ }+const payload = data as AgentNodeTypeconst outputs: Var[] = []Object.keys(payload.output_schema?.properties || {}).forEach(@@ -610,6 +618,11 @@ const formatItem = (break}+ case BlockEnum.AgentV2: {+ res.vars = getAgentV2OutputVars(data as AgentV2NodeType)+ break+ }+case BlockEnum.DataSource: {const payload = data as DataSourceNodeTypeconst dataSourceVars@@ -1448,6 +1461,31 @@ export const getNodeUsedVars = (node: Node): ValueSelector[] => {res = [...(mixVars as ValueSelector[]), ...(vars as any)]break}+ case BlockEnum.Agent: {+ if (isAgentV2NodeData(data)) {+ const payload = data as AgentV2NodeType+ res = matchNotSystemVars([payload.agent_task || ''])+ break+ }++ const payload = data as AgentNodeType+ const valueSelectors: ValueSelector[] = []+ if (!payload.agent_parameters)+ break++ Object.keys(payload.agent_parameters || {}).forEach((key) => {+ const { value } = payload.agent_parameters![key]!+ if (typeof value === 'string')+ valueSelectors.push(...matchNotSystemVars([value]))+ })+ res = valueSelectors+ break+ }+ case BlockEnum.AgentV2: {+ const payload = data as AgentV2NodeType+ res = matchNotSystemVars([payload.agent_task || ''])+ break+ }case BlockEnum.DataSource: {const payload = data as DataSourceNodeTypeconst mixVars = matchNotSystemVars(@@ -1507,21 +1545,6 @@ export const getNodeUsedVars = (node: Node): ValueSelector[] => {break}- case BlockEnum.Agent: {- const payload = data as AgentNodeType- const valueSelectors: ValueSelector[] = []- if (!payload.agent_parameters)- break-- Object.keys(payload.agent_parameters || {}).forEach((key) => {- const { value } = payload.agent_parameters![key]!- if (typeof value === 'string')- valueSelectors.push(...matchNotSystemVars([value]))- })- res = valueSelectors- break- }-case BlockEnum.HumanInput: {const payload = data as HumanInputNodeTypeconst formContent = payload.form_content@@ -1882,33 +1905,39 @@ export const updateNodeVars = (}break}- case BlockEnum.DataSource: {- const payload = data as DataSourceNodeType- const hasShouldRenameVar = Object.keys(- payload.datasource_parameters,- )?.filter(- key =>- payload.datasource_parameters[key]!.type !== ToolVarType.constant,- )- if (hasShouldRenameVar) {- Object.keys(payload.datasource_parameters).forEach((key) => {- const value = payload.datasource_parameters[key]!+ case BlockEnum.Agent: {+ if (isAgentV2NodeData(data)) {+ const payload = data as AgentV2NodeType+ payload.agent_task = replaceOldVarInText(+ payload.agent_task || '',+ oldVarSelector,+ newVarSelector,+ )+ break+ }++ const payload = data as AgentNodeType+ if (payload.agent_parameters) {+ Object.keys(payload.agent_parameters).forEach((key) => {+ const value = payload.agent_parameters![key]!const { type } = value!+if (type === ToolVarType.variable+ && Array.isArray(value!.value)&& value!.value.join('.') === oldVarSelector.join('.')) {- payload.datasource_parameters[key] = {+ payload.agent_parameters![key] = {...value,value: newVarSelector,}}- if (type === ToolVarType.mixed) {- payload.datasource_parameters[key] = {+ if (type === ToolVarType.mixed && typeof value!.value === 'string') {+ payload.agent_parameters![key] = {...value,value: replaceOldVarInText(- payload.datasource_parameters[key]!.value as string,+ value!.value,oldVarSelector,newVarSelector,),@@ -1916,31 +1945,52 @@ export const updateNodeVars = (}})}++ if (payload.memory?.query_prompt_template) {+ payload.memory.query_prompt_template = replaceOldVarInText(+ payload.memory.query_prompt_template,+ oldVarSelector,+ newVarSelector,+ )+ }break}- case BlockEnum.Agent: {- const payload = data as AgentNodeType- if (payload.agent_parameters) {- Object.keys(payload.agent_parameters).forEach((key) => {- const value = payload.agent_parameters![key]!+ case BlockEnum.AgentV2: {+ const payload = data as AgentV2NodeType+ payload.agent_task = replaceOldVarInText(+ payload.agent_task || '',+ oldVarSelector,+ newVarSelector,+ )+ break+ }+ case BlockEnum.DataSource: {+ const payload = data as DataSourceNodeType+ const hasShouldRenameVar = Object.keys(+ payload.datasource_parameters,+ )?.filter(+ key =>+ payload.datasource_parameters[key]!.type !== ToolVarType.constant,+ )+ if (hasShouldRenameVar) {+ Object.keys(payload.datasource_parameters).forEach((key) => {+ const value = payload.datasource_parameters[key]!const { type } = value!-if (type === ToolVarType.variable- && Array.isArray(value!.value)&& value!.value.join('.') === oldVarSelector.join('.')) {- payload.agent_parameters![key] = {+ payload.datasource_parameters[key] = {...value,value: newVarSelector,}}- if (type === ToolVarType.mixed && typeof value!.value === 'string') {- payload.agent_parameters![key] = {+ if (type === ToolVarType.mixed) {+ payload.datasource_parameters[key] = {...value,value: replaceOldVarInText(- value!.value,+ payload.datasource_parameters[key]!.value as string,oldVarSelector,newVarSelector,),@@ -1948,14 +1998,6 @@ export const updateNodeVars = (}})}-- if (payload.memory?.query_prompt_template) {- payload.memory.query_prompt_template = replaceOldVarInText(- payload.memory.query_prompt_template,- oldVarSelector,- newVarSelector,- )- }break}case BlockEnum.VariableAssigner: {diff --git a/web/app/components/workflow/nodes/_base/components/workflow-panel/__tests__/index.spec.tsx b/web/app/components/workflow/nodes/_base/components/workflow-panel/__tests__/index.spec.tsxindex 8137b0ff3a6..be30d075213 100644--- a/web/app/components/workflow/nodes/_base/components/workflow-panel/__tests__/index.spec.tsx+++ b/web/app/components/workflow/nodes/_base/components/workflow-panel/__tests__/index.spec.tsx@@ -28,6 +28,14 @@ const mockLogsState = {showSpecialResultPanel: false,}+const createMockSingleRunParams = () => ({+ forms: [],+ onStop: vi.fn(),+ runningStatus: NodeRunningStatus.Succeeded,+ existVarValuesInForms: [],+ filteredExistVarForms: [],+})+const mockLastRunState = {isShowSingleRun: false,hideSingleRun: vi.fn(),@@ -43,13 +51,7 @@ const mockLastRunState = {setIsRunAfterSingleRun: vi.fn(),setTabType: vi.fn(),handleAfterCustomSingleRun: vi.fn(),- singleRunParams: {- forms: [],- onStop: vi.fn(),- runningStatus: NodeRunningStatus.Succeeded,- existVarValuesInForms: [],- filteredExistVarForms: [],- },+ singleRunParams: createMockSingleRunParams(),nodeInfo: { id: 'node-1' },setRunInputData: vi.fn(),handleStop: () => mockHandleStop(),@@ -306,6 +308,7 @@ describe('workflow-panel index', () => {mockLogsState.showSpecialResultPanel = falsemockLastRunState.isShowSingleRun = falsemockLastRunState.tabType = 'settings'+ mockLastRunState.singleRunParams = createMockSingleRunParams()})it('should render the settings panel and wire title, description, run, and close actions', async () => {@@ -460,6 +463,26 @@ describe('workflow-panel index', () => {expect(screen.getByText('data-source-before-run-form')).toBeInTheDocument()})+ it('should keep the settings panel visible when single-run params have no forms', () => {+ mockLastRunState.isShowSingleRun = true+ mockLastRunState.singleRunParams = {} as ReturnType<typeof createMockSingleRunParams>++ renderWorkflowComponent(+ <BasePanel id="node-agent" data={createData({ type: BlockEnum.Agent }) as never}>+ <div>panel-child</div>+ </BasePanel>,+ {+ initialStoreState: {+ nodePanelWidth: 480,+ otherPanelWidth: 200,+ },+ },+ )++ expect(screen.queryByText('before-run-form')).not.toBeInTheDocument()+ expect(screen.getByText('panel-child')).toBeInTheDocument()+ })+it('should render data source authorization controls and jump to the settings modal', () => {renderWorkflowComponent(<BasePanel id="node-1" data={createData({ type: BlockEnum.DataSource, plugin_id: 'source-1', provider_type: 'remote' }) as never}>diff --git a/web/app/components/workflow/nodes/_base/components/workflow-panel/index.tsx b/web/app/components/workflow/nodes/_base/components/workflow-panel/index.tsxindex 5ac6fa2f8d6..92103974a62 100644--- a/web/app/components/workflow/nodes/_base/components/workflow-panel/index.tsx+++ b/web/app/components/workflow/nodes/_base/components/workflow-panel/index.tsx@@ -1,4 +1,4 @@-import type { FC, ReactNode } from 'react'+import type { CSSProperties, FC, ReactNode } from 'react'import type { SimpleSubscription } from '@/app/components/plugins/plugin-detail-panel/subscription-list'import type { Node } from '@/app/components/workflow/types'import { cn } from '@langgenius/dify-ui/cn'@@ -58,6 +58,7 @@ import { useHooksStore } from '@/app/components/workflow/hooks-store'import useInspectVarsCrud from '@/app/components/workflow/hooks/use-inspect-vars-crud'import { NodeActionsDropdown } from '@/app/components/workflow/node-actions-menu'import Split from '@/app/components/workflow/nodes/_base/components/split'+import { isAgentV2NodeData } from '@/app/components/workflow/nodes/agent-v2/types'import { useLogs } from '@/app/components/workflow/run/hooks'import SpecialResultPanel from '@/app/components/workflow/run/special-result-panel'import { useStore } from '@/app/components/workflow/store'@@ -229,6 +230,7 @@ const BasePanel: FC<BasePanelProps> = ({}, [handleNodeDataUpdateWithSyncDraft, id, saveStateToHistory])const isChildNode = !!(data.isInIteration || data.isInLoop)+ const nodeMetaType = isAgentV2NodeData(data) ? BlockEnum.AgentV2 : data.typeconst isSupportSingleRun = canRunBySingle(data.type, isChildNode)const appDetail = useAppStore(state => state.appDetail)@@ -293,7 +295,7 @@ const BasePanel: FC<BasePanelProps> = ({flowId: configsMap?.flowId || '',flowType: configsMap?.flowType || FlowType.appFlow,data,- defaultRunInputData: nodesMap?.[data.type]?.defaultRunInputData || {},+ defaultRunInputData: nodesMap?.[nodeMetaType]?.defaultRunInputData || {},isPaused,})@@ -405,6 +407,11 @@ const BasePanel: FC<BasePanelProps> = ({id,data,}) as Node, [id, data])+ const singleRunForms = singleRunParams?.forms+ const isCustomRunFormNode = isSupportCustomRunForm(data.type)+ const shouldRenderSingleRunPanel = isShowSingleRun && (isCustomRunFormNode || !!singleRunForms)+ const isSingleRunPanelVisible = showSingleRunPanel && shouldRenderSingleRunPanel+if (logParams.showSpecialResultPanel) {return (<div className={cn(@@ -413,7 +420,7 @@ const BasePanel: FC<BasePanelProps> = ({><divref={containerRef}- className={cn('flex h-full flex-col rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg shadow-lg', showSingleRunPanel ? 'overflow-hidden' : 'overflow-y-auto')}+ className={cn('flex h-full flex-col rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg shadow-lg', isSingleRunPanelVisible ? 'overflow-hidden' : 'overflow-y-auto')}style={{width: `${nodePanelWidth}px`,}}@@ -431,20 +438,39 @@ const BasePanel: FC<BasePanelProps> = ({)}- if (isShowSingleRun) {- const form = getCustomRunForm({- nodeId: id,- flowId: configsMap?.flowId || '',- flowType: configsMap?.flowType || FlowType.appFlow,- payload: data,- setRunResult,- setIsRunAfterSingleRun,- isPaused,- isRunAfterSingleRun,- onSuccess: handleAfterCustomSingleRun,- onCancel: hideSingleRun,- appendNodeInspectVars,- })+ if (shouldRenderSingleRunPanel) {+ const customRunForm = isCustomRunFormNode+ ? getCustomRunForm({+ nodeId: id,+ flowId: configsMap?.flowId || '',+ flowType: configsMap?.flowType || FlowType.appFlow,+ payload: data,+ setRunResult,+ setIsRunAfterSingleRun,+ isPaused,+ isRunAfterSingleRun,+ onSuccess: handleAfterCustomSingleRun,+ onCancel: hideSingleRun,+ appendNodeInspectVars,+ })+ : null+ const singleRunPanelContent = isCustomRunFormNode+ ? customRunForm+ : singleRunForms+ ? (+ <BeforeRunForm+ nodeName={data.title}+ nodeType={data.type}+ onHide={hideSingleRun}+ onRun={handleRunWithParams}+ {...singleRunParams!}+ {...passedLogParams}+ existVarValuesInForms={getExistVarValuesInForms(singleRunForms)}+ filteredExistVarForms={getFilteredExistVarForms(singleRunForms)}+ handleAfterHumanInputStepRun={handleAfterCustomSingleRun}+ />+ )+ : nullreturn (<div className={cn(@@ -453,29 +479,12 @@ const BasePanel: FC<BasePanelProps> = ({><divref={containerRef}- className={cn('flex h-full flex-col rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg shadow-lg', showSingleRunPanel ? 'overflow-hidden' : 'overflow-y-auto')}+ className={cn('flex h-full flex-col rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg shadow-lg', isSingleRunPanelVisible ? 'overflow-hidden' : 'overflow-y-auto')}style={{width: `${nodePanelWidth}px`,}}>- {isSupportCustomRunForm(data.type)- ? (- form- )- : (- <BeforeRunForm- nodeName={data.title}- nodeType={data.type}- onHide={hideSingleRun}- onRun={handleRunWithParams}- {...singleRunParams!}- {...passedLogParams}- existVarValuesInForms={getExistVarValuesInForms(singleRunParams?.forms as any)}- filteredExistVarForms={getFilteredExistVarForms(singleRunParams?.forms as any)}- handleAfterHumanInputStepRun={handleAfterCustomSingleRun}- />- )}-+ {singleRunPanelContent}</div></div>)@@ -485,6 +494,9 @@ const BasePanel: FC<BasePanelProps> = ({const singleRunActionLabel = isSingleRunning? t('debug.variableInspect.trigger.stop', { ns: 'workflow' }): runThisStepLabel+ const nodePanelRightOffset = !showMessageLogModal+ ? '4px'+ : `${otherPanelWidth + 8}px`const isStartPlaceholderPanel = data.type === BlockEnum.StartPlaceholderconst panelChildren = cloneElement(children as any, {id,@@ -517,8 +529,9 @@ const BasePanel: FC<BasePanelProps> = ({showMessageLogModal && 'absolute z-0 mr-2 w-[400px] overflow-hidden rounded-2xl border-[0.5px] border-components-panel-border shadow-lg transition-all',)}style={{- right: !showMessageLogModal ? '0' : `${otherPanelWidth}px`,- }}+ 'right': !showMessageLogModal ? '0' : `${otherPanelWidth}px`,+ '--workflow-node-panel-right': nodePanelRightOffset,+ } as CSSProperties}><divref={triggerRef}@@ -530,10 +543,11 @@ const BasePanel: FC<BasePanelProps> = ({ref={containerRef}value={tabType}onValueChange={selectedValue => setTabType(selectedValue)}- className={cn('flex h-full flex-col rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg shadow-lg transition-[width] ease-linear', showSingleRunPanel ? 'overflow-hidden' : 'overflow-y-auto')}+ className={cn('flex h-full flex-col rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg shadow-lg transition-[width] ease-linear', isSingleRunPanelVisible ? 'overflow-hidden' : 'overflow-y-auto')}style={{- width: `${nodePanelWidth}px`,- }}+ 'width': `${nodePanelWidth}px`,+ '--workflow-node-panel-width': `${nodePanelWidth}px`,+ } as CSSProperties}><div className="sticky top-0 z-10 shrink-0 border-b-[0.5px] border-divider-regular bg-components-panel-bg"><div className="flex items-center px-4 pt-4 pb-1">@@ -595,7 +609,7 @@ const BasePanel: FC<BasePanelProps> = ({</Tooltip>)}- <HelpLink nodeType={data.type} />+ <HelpLink nodeType={nodeMetaType} /><NodeActionsDropdown id={id} data={data} showHelpLink={false} /><div className="mx-3 h-3.5 w-px bg-divider-regular" /><buttondiff --git a/web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/use-last-run.ts b/web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/use-last-run.tsindex a538bcf29e3..fb38aaaf4d5 100644--- a/web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/use-last-run.ts+++ b/web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/use-last-run.ts@@ -10,7 +10,6 @@ import {import { useWorkflowRunValidation } from '@/app/components/workflow/hooks/use-checklist'import useInspectVarsCrud from '@/app/components/workflow/hooks/use-inspect-vars-crud'import useOneStepRun from '@/app/components/workflow/nodes/_base/hooks/use-one-step-run'-import useAgentSingleRunFormParams from '@/app/components/workflow/nodes/agent/use-single-run-form-params'import useVariableAssignerSingleRunFormParams from '@/app/components/workflow/nodes/assigner/use-single-run-form-params'import useCodeSingleRunFormParams from '@/app/components/workflow/nodes/code/use-single-run-form-params'import useDocExtractorSingleRunFormParams from '@/app/components/workflow/nodes/document-extractor/use-single-run-form-params'@@ -50,7 +49,8 @@ const singleRunFormParamsHooks: Record<BlockEnum, any> = {[BlockEnum.Tool]: useToolSingleRunFormParams,[BlockEnum.ParameterExtractor]: useParameterExtractorSingleRunFormParams,[BlockEnum.Iteration]: useIterationSingleRunFormParams,- [BlockEnum.Agent]: useAgentSingleRunFormParams,+ [BlockEnum.Agent]: undefined,+ [BlockEnum.AgentV2]: undefined,[BlockEnum.DocExtractor]: useDocExtractorSingleRunFormParams,[BlockEnum.Loop]: useLoopSingleRunFormParams,[BlockEnum.Start]: useStartSingleRunFormParams,@@ -91,6 +91,7 @@ const getDataForCheckMoreHooks: Record<BlockEnum, any> = {[BlockEnum.ParameterExtractor]: undefined,[BlockEnum.Iteration]: undefined,[BlockEnum.Agent]: undefined,+ [BlockEnum.AgentV2]: undefined,[BlockEnum.DocExtractor]: undefined,[BlockEnum.Loop]: undefined,[BlockEnum.Start]: undefined,diff --git a/web/app/components/workflow/nodes/agent-v2/__tests__/default.spec.ts b/web/app/components/workflow/nodes/agent-v2/__tests__/default.spec.tsnew file mode 100644index 00000000000..ed7d9b23395--- /dev/null+++ b/web/app/components/workflow/nodes/agent-v2/__tests__/default.spec.ts@@ -0,0 +1,110 @@+import type { AgentV2NodeType } from '../types'+import { BlockEnum } from '@/app/components/workflow/types'+import nodeDefault from '../default'+import { isAgentV2NodeData } from '../types'++const t = vi.fn((key: string, options?: Record<string, unknown>) => {+ if (key === 'errorMsg.fieldRequired')+ return `required:${options?.field}`++ if (key === 'nodes.agent.roster.label')+ return 'Agent'++ return key+})++const createPayload = (overrides: Partial<AgentV2NodeType> = {}): AgentV2NodeType => ({+ title: 'Agent',+ desc: '',+ type: BlockEnum.AgentV2,+ agent_binding: {+ binding_type: 'roster_agent',+ agent_id: 'agent-1',+ },+ agent_node_kind: 'dify_agent',+ version: '2',+ ...overrides,+})++describe('agent/default', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ it('requires a roster agent id', () => {+ const result = nodeDefault.checkValid(createPayload({+ agent_binding: {+ binding_type: 'roster_agent',+ agent_id: '',+ },+ }), t)++ expect(result).toEqual({+ isValid: false,+ errorMessage: 'required:Agent',+ })+ })++ it('requires a roster agent binding', () => {+ const result = nodeDefault.checkValid(createPayload({ agent_binding: undefined }), t)++ expect(result).toEqual({+ isValid: false,+ errorMessage: 'required:Agent',+ })+ })++ it('passes validation when a roster agent binding is selected', () => {+ const result = nodeDefault.checkValid(createPayload(), t)++ expect(result).toEqual({+ isValid: true,+ errorMessage: '',+ })+ })++ it('requires complete inline agent binding', () => {+ const result = nodeDefault.checkValid(createPayload({+ agent_binding: {+ binding_type: 'inline_agent',+ },+ }), t)++ expect(result).toEqual({+ isValid: false,+ errorMessage: 'required:Agent',+ })+ })++ it('passes validation for complete inline agent binding', () => {+ const result = nodeDefault.checkValid(createPayload({+ agent_binding: {+ binding_type: 'inline_agent',+ agent_id: 'inline-agent-1',+ current_snapshot_id: 'inline-snapshot-1',+ },+ }), t)++ expect(result).toEqual({+ isValid: true,+ errorMessage: '',+ })+ })++ it('creates Agent v2 graph data by default', () => {+ expect(nodeDefault.defaultValue).toMatchObject({+ agent_node_kind: 'dify_agent',+ version: '2',+ })+ })++ it('identifies version 2 agent data as Agent v2', () => {+ expect(isAgentV2NodeData(createPayload({ type: BlockEnum.Agent }))).toBe(true)+ expect(isAgentV2NodeData({+ title: 'Agent',+ desc: '',+ type: BlockEnum.Agent,+ version: '2',+ } as Parameters<typeof isAgentV2NodeData>[0])).toBe(false)+ })+})diff --git a/web/app/components/workflow/nodes/agent-v2/__tests__/hooks.spec.tsx b/web/app/components/workflow/nodes/agent-v2/__tests__/hooks.spec.tsxnew file mode 100644index 00000000000..16963ba9011--- /dev/null+++ b/web/app/components/workflow/nodes/agent-v2/__tests__/hooks.spec.tsx@@ -0,0 +1,280 @@+import { QueryClient } from '@tanstack/react-query'+import { act, waitFor } from '@testing-library/react'+import { FlowType } from '@/types/common'+import { renderWorkflowHook } from '../../../__tests__/workflow-test-env'+import { useWorkflowInlineAgentConfigureSync } from '../agent-soul-config'+import { useCreateInlineAgentBinding } from '../hooks'++const mockDefaultModel = vi.hoisted(() => ({+ value: {+ model: 'gpt-4o-mini',+ model_type: 'llm',+ provider: {+ provider: 'langgenius/openai/openai',+ icon_small: {+ en_US: 'openai',+ zh_Hans: 'openai',+ },+ },+ },+}))+const mockComposerMutationFn = vi.hoisted(() => vi.fn(async (variables: unknown) => ({+ agent_soul: (variables as {+ body?: {+ agent_soul?: unknown+ }+ }).body?.agent_soul,+ binding: {+ binding_type: 'inline_agent',+ agent_id: 'inline-agent-1',+ current_snapshot_id: 'inline-snapshot-1',+ },+ variables,+})))+const mockComposerMutationOptions = vi.hoisted(() => vi.fn(() => ({+ mutationFn: mockComposerMutationFn,+})))++vi.mock('@langgenius/dify-ui/toast', () => ({+ toast: {+ error: vi.fn(),+ },+}))++vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({+ useDefaultModel: () => ({+ data: mockDefaultModel.value,+ }),+}))++vi.mock('@/service/client', () => ({+ consoleQuery: {+ agent: {+ byAgentId: {+ get: {+ queryOptions: vi.fn(),+ },+ },+ },+ apps: {+ byAppId: {+ workflows: {+ draft: {+ nodes: {+ byNodeId: {+ agentComposer: {+ get: {+ queryKey: ({ input }: { input: { params: { app_id: string, node_id: string } } }) => [+ 'workflow-agent-composer',+ input.params.app_id,+ input.params.node_id,+ ],+ },+ put: {+ mutationOptions: mockComposerMutationOptions,+ },+ },+ },+ },+ },+ },+ },+ },+ },+}))++describe('useCreateInlineAgentBinding', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockDefaultModel.value = {+ model: 'gpt-4o-mini',+ model_type: 'llm',+ provider: {+ provider: 'langgenius/openai/openai',+ icon_small: {+ en_US: 'openai',+ zh_Hans: 'openai',+ },+ },+ }+ })++ it('creates inline agent with the default text generation model', async () => {+ const onSuccess = vi.fn()+ const queryClient = new QueryClient({+ defaultOptions: {+ mutations: {+ retry: false,+ },+ },+ })+ const { result } = renderWorkflowHook(() => useCreateInlineAgentBinding(), {+ queryClient,+ hooksStoreProps: {+ configsMap: {+ flowId: 'app-1',+ flowType: FlowType.appFlow,+ fileSettings: {} as never,+ },+ },+ })++ act(() => {+ result.current.createInlineAgentBinding('node-1', { onSuccess })+ })++ await waitFor(() => expect(mockComposerMutationFn).toHaveBeenCalled())+ expect(mockComposerMutationFn).toHaveBeenCalledWith({+ params: {+ app_id: 'app-1',+ node_id: 'node-1',+ },+ body: {+ variant: 'workflow',+ save_strategy: 'node_job_only',+ soul_lock: {+ locked: false,+ },+ agent_soul: {+ schema_version: 1,+ prompt: {+ system_prompt: '',+ },+ model: {+ model_provider: 'langgenius/openai/openai',+ model: 'gpt-4o-mini',+ plugin_id: 'langgenius/openai',+ },+ },+ },+ }, expect.any(Object))+ await waitFor(() => expect(onSuccess).toHaveBeenCalledWith({+ binding_type: 'inline_agent',+ agent_id: 'inline-agent-1',+ current_snapshot_id: 'inline-snapshot-1',+ }))+ })++ it('creates inline agent with a model-less initial soul before the default model loads', async () => {+ mockDefaultModel.value = undefined as never+ const onSuccess = vi.fn()+ const queryClient = new QueryClient({+ defaultOptions: {+ mutations: {+ retry: false,+ },+ },+ })+ const { result } = renderWorkflowHook(() => useCreateInlineAgentBinding(), {+ queryClient,+ hooksStoreProps: {+ configsMap: {+ flowId: 'app-1',+ flowType: FlowType.appFlow,+ fileSettings: {} as never,+ },+ },+ })++ act(() => {+ result.current.createInlineAgentBinding('node-1', { onSuccess })+ })++ await waitFor(() => expect(mockComposerMutationFn).toHaveBeenCalled())+ expect(mockComposerMutationFn).toHaveBeenCalledWith({+ params: {+ app_id: 'app-1',+ node_id: 'node-1',+ },+ body: {+ variant: 'workflow',+ save_strategy: 'node_job_only',+ soul_lock: {+ locked: false,+ },+ agent_soul: {+ schema_version: 1,+ prompt: {+ system_prompt: '',+ },+ },+ },+ }, expect.any(Object))+ await waitFor(() => expect(onSuccess).toHaveBeenCalledWith({+ binding_type: 'inline_agent',+ agent_id: 'inline-agent-1',+ current_snapshot_id: 'inline-snapshot-1',+ }))+ })+})++describe('useWorkflowInlineAgentConfigureSync', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ it('saves inline agent composer changes through the workflow node composer API', async () => {+ vi.setSystemTime(1710000300000)+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: {+ retry: false,+ },+ mutations: {+ retry: false,+ },+ },+ })+ const { result } = renderWorkflowHook(() => useWorkflowInlineAgentConfigureSync({+ nodeId: 'node-1',+ baseConfig: {+ schema_version: 1,+ },+ currentModel: {+ provider: 'langgenius/openai/openai',+ model: 'gpt-4o-mini',+ },+ enabled: true,+ }), {+ queryClient,+ hooksStoreProps: {+ configsMap: {+ flowId: 'app-1',+ flowType: FlowType.appFlow,+ fileSettings: {} as never,+ },+ },+ })++ await act(async () => {+ await result.current.saveDraft()+ })++ expect(mockComposerMutationFn).toHaveBeenCalledWith({+ params: {+ app_id: 'app-1',+ node_id: 'node-1',+ },+ body: expect.objectContaining({+ variant: 'workflow',+ save_strategy: 'node_job_only',+ agent_soul: expect.objectContaining({+ schema_version: 1,+ prompt: expect.objectContaining({+ system_prompt: '',+ }),+ model: expect.objectContaining({+ model_provider: 'langgenius/openai/openai',+ model: 'gpt-4o-mini',+ }),+ }),+ }),+ }, expect.any(Object))+ await waitFor(() => expect(result.current.draftSavedAt).toBe(1710000300000))+ expect(queryClient.getQueryData(['workflow-agent-composer', 'app-1', 'node-1'])).toEqual(expect.objectContaining({+ agent_soul: expect.objectContaining({+ schema_version: 1,+ }),+ }))+ })+})diff --git a/web/app/components/workflow/nodes/agent-v2/__tests__/node.spec.tsx b/web/app/components/workflow/nodes/agent-v2/__tests__/node.spec.tsxnew file mode 100644index 00000000000..f1799608382--- /dev/null+++ b/web/app/components/workflow/nodes/agent-v2/__tests__/node.spec.tsx@@ -0,0 +1,186 @@+import type { ReactNode } from 'react'+import type { AgentV2NodeType } from '../types'+import { render, screen } from '@testing-library/react'+import { BlockEnum } from '@/app/components/workflow/types'+import { AgentV2Node } from '../node'++const {+ mockUseAgentRosterDetail,+ mockUseWorkflowInlineAgentDetail,+} = vi.hoisted(() => ({+ mockUseAgentRosterDetail: vi.fn(),+ mockUseWorkflowInlineAgentDetail: vi.fn(),+}))++vi.mock('../../_base/components/setting-item', () => ({+ SettingItem: ({+ label,+ status,+ tooltip,+ children,+ }: {+ label: ReactNode+ status?: string+ tooltip?: string+ children?: ReactNode+ }) => (+ <div>+ {`${label}:${status || 'normal'}:${tooltip || ''}`}+ {children}+ </div>+ ),+}))++vi.mock('../hooks', () => ({+ useAgentRosterDetail: (agentId?: string) => mockUseAgentRosterDetail(agentId),+ useWorkflowInlineAgentDetail: (nodeId?: string, agentId?: string | null) => mockUseWorkflowInlineAgentDetail(nodeId, agentId),+}))++const createData = (overrides: Partial<AgentV2NodeType> = {}): AgentV2NodeType => ({+ title: 'Agent',+ desc: '',+ type: BlockEnum.AgentV2,+ agent_binding: {+ binding_type: 'roster_agent',+ agent_id: 'agent-1',+ },+ agent_node_kind: 'dify_agent',+ version: '2',+ ...overrides,+})++describe('agent/node', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockUseAgentRosterDetail.mockImplementation((agentId?: string) => ({+ isPending: false,+ data: agentId+ ? {+ id: agentId,+ name: 'Nadia',+ description: 'Clarification Drafter',+ icon: 'N',+ icon_background: '#E9D7FE',+ icon_type: 'emoji',+ }+ : undefined,+ }))+ mockUseWorkflowInlineAgentDetail.mockImplementation((nodeId?: string, agentId?: string | null) => ({+ isPending: false,+ data: nodeId && agentId+ ? {+ agent: {+ id: agentId,+ name: 'Workflow Agent 1',+ description: '',+ scope: 'workflow_only',+ status: 'active',+ },+ }+ : undefined,+ }))+ })++ it('renders the selected roster agent', () => {+ const { container } = render(+ <AgentV2Node+ id="agent-node"+ data={createData()}+ />,+ )++ expect(screen.getByText('workflow.nodes.agent.roster.label')).toHaveClass('px-2.5', 'py-0.5', 'system-2xs-medium-uppercase')+ expect(screen.getByText('Nadia')).toHaveClass('system-xs-regular', 'text-text-secondary')+ expect(container.querySelector('.bg-workflow-block-parma-bg')).toHaveClass('gap-1', 'rounded-lg', 'p-1')+ expect(container.querySelector('.h-1.px-3')).not.toBeInTheDocument()+ })++ it('renders a stable roster placeholder while agent detail is loading', () => {+ mockUseAgentRosterDetail.mockReturnValue({ data: undefined })++ const { container } = render(+ <AgentV2Node+ id="agent-node"+ data={createData()}+ />,+ )++ expect(container.querySelector('.bg-workflow-block-parma-bg')).toBeInTheDocument()+ expect(container.querySelector('.h-2.w-20')).toBeInTheDocument()+ })++ it('renders the inline setup agent style', () => {+ const { container } = render(+ <AgentV2Node+ id="agent-node"+ data={createData({+ agent_binding: {+ binding_type: 'inline_agent',+ },+ })}+ />,+ )++ expect(screen.getByText('workflow.nodes.agent.roster.inlineSetup.name')).toHaveClass('system-xs-regular', 'text-text-secondary')+ expect(screen.getByText('workflow.nodes.agent.roster.inlineSetup.type')).toHaveClass('system-2xs-regular', 'text-text-tertiary')+ const robotIcon = container.querySelector('.i-custom-vender-agent-v2-robot-3')+ expect(robotIcon).toHaveClass('size-5')+ expect(robotIcon?.parentElement).toHaveClass('size-8', 'rounded-full', 'bg-background-default-burn')+ })++ it('renders inline agent name from workflow composer state', () => {+ render(+ <AgentV2Node+ id="agent-node"+ data={createData({+ agent_binding: {+ binding_type: 'inline_agent',+ agent_id: 'inline-agent-1',+ current_snapshot_id: 'snapshot-1',+ },+ })}+ />,+ )++ expect(mockUseAgentRosterDetail).toHaveBeenCalledWith(undefined)+ expect(mockUseWorkflowInlineAgentDetail).toHaveBeenCalledWith('agent-node', 'inline-agent-1')+ expect(screen.getByText('Workflow Agent 1')).toHaveClass('system-xs-regular', 'text-text-secondary')+ expect(screen.getByText('workflow.nodes.agent.roster.inlineSetup.type')).toHaveClass('system-2xs-regular', 'text-text-tertiary')+ })++ it('renders a stable inline placeholder while agent detail is loading', () => {+ mockUseWorkflowInlineAgentDetail.mockReturnValue({+ isPending: true,+ data: undefined,+ })++ const { container } = render(+ <AgentV2Node+ id="agent-node"+ data={createData({+ agent_binding: {+ binding_type: 'inline_agent',+ agent_id: 'inline-agent-1',+ current_snapshot_id: 'snapshot-1',+ },+ })}+ />,+ )++ expect(screen.queryByText('workflow.nodes.agent.roster.inlineSetup.name')).not.toBeInTheDocument()+ expect(container.querySelector('.bg-workflow-block-parma-bg')).toBeInTheDocument()+ expect(container.querySelector('.size-8.shrink-0.rounded-full.bg-text-quaternary\\/20')).toBeInTheDocument()+ expect(container.querySelector('.h-2.w-20')).toBeInTheDocument()+ })++ it('renders an error state when no roster agent is selected', () => {+ render(+ <AgentV2Node+ id="agent-node"+ data={createData({ agent_binding: undefined })}+ />,+ )++ expect(screen.getByText(/workflow.nodes.agent.roster.label:error:/)).toHaveTextContent('workflow.errorMsg.fieldRequired')+ })+})diff --git a/web/app/components/workflow/nodes/agent-v2/__tests__/panel.spec.tsx b/web/app/components/workflow/nodes/agent-v2/__tests__/panel.spec.tsxnew file mode 100644index 00000000000..6212068fe96--- /dev/null+++ b/web/app/components/workflow/nodes/agent-v2/__tests__/panel.spec.tsx@@ -0,0 +1,978 @@+import type { ReactNode } from 'react'+import type { AgentV2NodeType } from '../types'+import type { PromptEditorProps } from '@/app/components/base/prompt-editor'+import type { NodePanelProps } from '@/app/components/workflow/types'+import { fireEvent, render, screen, within } from '@testing-library/react'+import { BlockEnum } from '@/app/components/workflow/types'+import { AgentV2Panel } from '../panel'++const {+ mockEditorFocus,+ mockEditorUpdate,+ mockHandleNodeDataUpdate,+ mockHandleNodeDataUpdateWithSyncDraft,+ mockInsertNodes,+ mockOrchestrateDrawerPanelProps,+ mockPromptEditorProps,+ mockSetInputs,+ mockStoreState,+ mockUseAgentRosterDetail,+ mockUseWorkflowInlineAgentDetail,+ mockUseNodeCrud,+} = vi.hoisted(() => ({+ mockEditorFocus: vi.fn(),+ mockEditorUpdate: vi.fn((callback: () => void) => callback()),+ mockHandleNodeDataUpdate: vi.fn(),+ mockHandleNodeDataUpdateWithSyncDraft: vi.fn((_payload, options) => options?.callback?.onSuccess?.()),+ mockInsertNodes: vi.fn(),+ mockOrchestrateDrawerPanelProps: [] as Array<{+ agentId: string+ inlineComposerState?: unknown+ isInline: boolean+ nodeId: string+ open: boolean+ }>,+ mockPromptEditorProps: [] as PromptEditorProps[],+ mockSetInputs: vi.fn(),+ mockStoreState: {+ openInlineAgentPanelNodeId: undefined as string | undefined,+ setOpenInlineAgentPanelNodeId: vi.fn(),+ },+ mockUseAgentRosterDetail: vi.fn(),+ mockUseWorkflowInlineAgentDetail: vi.fn(),+ mockUseNodeCrud: vi.fn(),+}))++vi.mock('../../_base/components/output-vars', () => ({+ __esModule: true,+ default: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ VarItem: ({ name, type, description }: { name: string, type: string, description?: string }) => (+ <div>{`${name}:${type}:${description || ''}`}</div>+ ),+}))++vi.mock('@/app/components/base/prompt-editor', () => ({+ default: (props: PromptEditorProps) => {+ mockPromptEditorProps.push(props)++ return (+ <>+ <textarea+ aria-label="workflow.nodes.agent.task.label"+ placeholder={typeof props.placeholder === 'string' ? props.placeholder : undefined}+ value={props.value}+ onChange={event => props.onChange?.(event.currentTarget.value)}+ onBlur={props.onBlur}+ onFocus={props.onFocus}+ />+ {props.children}+ </>+ )+ },+}))++vi.mock('@lexical/react/LexicalComposerContext', () => ({+ useLexicalComposerContext: () => [{+ focus: mockEditorFocus,+ update: mockEditorUpdate,+ }],+}))++vi.mock('lexical', async (importOriginal) => {+ const actual = await importOriginal<typeof import('lexical')>()++ return {+ ...actual,+ $insertNodes: mockInsertNodes,+ }+})++vi.mock('@/app/components/base/prompt-editor/plugins/custom-text/node', () => ({+ $createCustomTextNode: (text: string) => ({+ getTextContent: () => text,+ }),+}))++vi.mock('../../_base/hooks/use-node-crud', () => ({+ default: (id: string, data: AgentV2NodeType) => mockUseNodeCrud(id, data),+}))++vi.mock('@/app/components/workflow/block-selector/agent-selector', () => ({+ AgentSelectorContent: ({+ onSelect,+ }: {+ onSelect: (agent: {+ description: string+ icon: string+ icon_background: string+ icon_type: 'emoji'+ id: string+ name: string+ role: string+ }) => void+ }) => (+ <button+ type="button"+ onClick={() => onSelect({+ id: 'agent-2',+ name: 'Mara',+ description: 'Tender Analyst',+ icon: 'M',+ icon_background: '#D1E9FF',+ icon_type: 'emoji',+ role: 'Analyst',+ })}+ >+ Select Mara+ </button>+ ),+}))++vi.mock('../hooks', () => ({+ useAgentRosterDetail: (agentId?: string) => mockUseAgentRosterDetail(agentId),+ useWorkflowInlineAgentDetail: (nodeId?: string, agentId?: string | null) => mockUseWorkflowInlineAgentDetail(nodeId, agentId),+}))++vi.mock('../components/agent-orchestrate-drawer-panel', () => ({+ AgentOrchestrateDrawerPanel: (props: {+ agentId: string+ inlineComposerState?: unknown+ isInline: boolean+ nodeId: string+ open: boolean+ }) => {+ mockOrchestrateDrawerPanelProps.push(props)++ return (+ <div role="region" aria-label={props.isInline ? 'inline-orchestrate-panel' : 'readonly-roster-orchestrate-panel'} />+ )+ },+}))++vi.mock('../../_base/hooks/use-available-var-list', () => ({+ default: () => ({+ availableVars: [{+ nodeId: 'start',+ title: 'START',+ vars: [{ variable: 'question', type: 'string' }],+ }],+ availableNodesWithParent: [{+ id: 'start',+ data: {+ title: 'START',+ type: BlockEnum.Start,+ },+ position: { x: 0, y: 0 },+ }],+ }),+}))++vi.mock('@/app/components/workflow/hooks', () => ({+ useNodeDataUpdate: () => ({+ handleNodeDataUpdate: mockHandleNodeDataUpdate,+ handleNodeDataUpdateWithSyncDraft: mockHandleNodeDataUpdateWithSyncDraft,+ }),+ useWorkflowVariableType: () => vi.fn(),+}))++vi.mock('@/app/components/workflow/store', () => ({+ useStore: (selector: (state: typeof mockStoreState) => unknown) => selector(mockStoreState),+}))++const createData = (overrides: Partial<AgentV2NodeType> = {}): AgentV2NodeType => ({+ title: 'Agent',+ desc: '',+ type: BlockEnum.AgentV2,+ agent_binding: {+ binding_type: 'roster_agent',+ agent_id: 'agent-1',+ },+ agent_node_kind: 'dify_agent',+ version: '2',+ ...overrides,+})++const panelProps = {} as NodePanelProps<AgentV2NodeType>['panelProps']++describe('agent/panel', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockPromptEditorProps.length = 0+ mockOrchestrateDrawerPanelProps.length = 0+ mockStoreState.openInlineAgentPanelNodeId = undefined+ mockUseNodeCrud.mockImplementation((_id: string, data: AgentV2NodeType) => ({+ inputs: data,+ setInputs: mockSetInputs,+ }))+ mockUseAgentRosterDetail.mockImplementation((agentId?: string) => ({+ data: agentId+ ? {+ id: agentId,+ name: 'Nadia',+ description: 'Clarification Drafter',+ icon: 'N',+ icon_background: '#E9D7FE',+ icon_type: 'emoji',+ role: 'Researcher',+ }+ : undefined,+ }))+ mockUseWorkflowInlineAgentDetail.mockImplementation((nodeId?: string, agentId?: string | null) => ({+ data: nodeId && agentId+ ? {+ agent: {+ id: agentId,+ name: 'Workflow Agent 1',+ description: '',+ scope: 'workflow_only',+ status: 'active',+ },+ }+ : undefined,+ }))+ })++ it('renders selected roster agent trigger and default Agent v2 output vars', () => {+ render(+ <AgentV2Panel+ id="agent-node"+ data={createData()}+ panelProps={panelProps}+ />,+ )++ expect(screen.getByText('workflow.nodes.agent.roster.label')).toBeInTheDocument()+ expect(screen.getByText('Nadia')).toBeInTheDocument()+ expect(screen.getByText('workflow.nodes.agent.task.label')).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'workflow.nodes.agent.task.tooltip' })).toBeInTheDocument()+ expect(screen.getByRole('textbox', { name: 'workflow.nodes.agent.task.label' })).toHaveValue('')+ expect(screen.getByRole('button', { name: 'workflow.nodes.agent.advancedSetting' })).toBeInTheDocument()+ expect(screen.getByText('text')).toBeInTheDocument()+ expect(screen.getByText('workflow.nodes.agent.outputVars.text')).toBeInTheDocument()+ expect(screen.queryByText('usage')).not.toBeInTheDocument()+ expect(screen.getByText('files')).toBeInTheDocument()+ expect(screen.getByText('array[file]')).toBeInTheDocument()+ expect(screen.getByText('workflow.nodes.agent.outputVars.files.title')).toBeInTheDocument()+ expect(screen.getByText('json')).toBeInTheDocument()+ expect(screen.getByText('object')).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'workflow.nodes.agent.outputVars.newOutput' })).toBeInTheDocument()+ })++ it('opens and closes the roster agent layered panel', () => {+ render(+ <AgentV2Panel+ id="agent-node"+ data={createData()}+ panelProps={panelProps}+ />,+ )++ fireEvent.click(screen.getByRole('button', { name: /^workflow\.nodes\.agent\.roster\.openPanel/ }))++ const panel = screen.getByRole('dialog', { name: 'Nadia' })+ expect(panel).toBeInTheDocument()+ expect(within(panel).getByText('Researcher')).toBeInTheDocument()+ expect(within(panel).getByRole('link', { name: 'workflow.nodes.agent.roster.editInConsole' })).toHaveAttribute('href', '/roster/agent/agent-1/configure')+ expect(within(panel).getByRole('button', { name: 'workflow.nodes.agent.roster.makeCopy' })).toBeInTheDocument()+ expect(within(panel).getByRole('region', { name: 'readonly-roster-orchestrate-panel' })).toBeInTheDocument()+ expect(mockOrchestrateDrawerPanelProps.at(-1)).toMatchObject({+ agentId: 'agent-1',+ isInline: false,+ nodeId: 'agent-node',+ open: true,+ })++ fireEvent.keyDown(panel, { key: 'Escape' })++ expect(screen.queryByRole('dialog', { name: 'Nadia' })).not.toBeInTheDocument()+ })++ it('renders a required roster state when no roster agent is selected', () => {+ render(+ <AgentV2Panel+ id="agent-node"+ data={createData({ agent_binding: undefined })}+ panelProps={panelProps}+ />,+ )++ expect(screen.getByText('workflow.nodes.agent.roster.label')).toBeInTheDocument()+ expect(screen.getByText(/^workflow\.errorMsg\.fieldRequired/)).toBeInTheDocument()+ expect(screen.getByText('workflow.nodes.agent.task.label')).toBeInTheDocument()+ expect(screen.getByText('text')).toBeInTheDocument()+ expect(screen.getByText('workflow.nodes.agent.outputVars.text')).toBeInTheDocument()+ })++ it('renders a pending inline agent state while the binding is being created', () => {+ const { container } = render(+ <AgentV2Panel+ id="agent-node"+ data={createData({+ _isTempNode: true,+ agent_binding: {+ binding_type: 'inline_agent',+ },+ })}+ panelProps={panelProps}+ />,+ )++ expect(screen.queryByText(/^workflow\.errorMsg\.fieldRequired/)).not.toBeInTheDocument()+ expect(container.querySelector('[aria-busy="true"]')).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'workflow.nodes.agent.roster.change' })).toBeDisabled()+ expect(screen.getByText('workflow.nodes.agent.task.label')).toBeInTheDocument()+ expect(screen.getByText('workflow.nodes.agent.outputVars.text')).toBeInTheDocument()+ expect(container.querySelector('[inert]')).toBeInTheDocument()+ })++ it('renders inline agent detail from workflow composer state and opens the inline panel', () => {+ mockStoreState.openInlineAgentPanelNodeId = 'agent-node'+ const { container } = render(+ <AgentV2Panel+ id="agent-node"+ data={createData({+ _isTempNode: true,+ agent_binding: {+ binding_type: 'inline_agent',+ agent_id: 'inline-agent-1',+ current_snapshot_id: 'snapshot-1',+ },+ })}+ panelProps={panelProps}+ />,+ )++ expect(mockUseAgentRosterDetail).toHaveBeenCalledWith(undefined)+ expect(mockUseWorkflowInlineAgentDetail).toHaveBeenCalledWith('agent-node', 'inline-agent-1')+ expect(screen.queryByText('Workflow Agent 1')).not.toBeInTheDocument()+ expect(screen.getByText('workflow.nodes.agent.roster.inlineSetup.name')).toBeInTheDocument()+ expect(screen.getByText('workflow.nodes.agent.roster.inlineSetup.type')).toBeInTheDocument()+ expect(container.querySelector('.i-custom-vender-agent-v2-robot-3')).toHaveClass('size-5')+ expect(container.querySelector('.i-custom-vender-agent-v2-robot-3')?.parentElement).toHaveClass('size-8', 'rounded-full', 'bg-background-default-burn')+ expect(screen.getByText('workflow.nodes.agent.roster.inlineSetup.title')).toBeInTheDocument()+ expect(screen.getByText('workflow.nodes.agent.roster.inlineSetup.description')).toBeInTheDocument()+ expect(screen.getByRole('button', { name: /^workflow\.nodes\.agent\.roster\.openPanel/ })).toBeInTheDocument()+ expect(screen.getByRole('dialog', { name: 'workflow.nodes.agent.roster.inlineSetup.title' })).toBeInTheDocument()+ expect(screen.getByRole('region', { name: 'inline-orchestrate-panel' })).toBeInTheDocument()+ expect(mockOrchestrateDrawerPanelProps.at(-1)).toMatchObject({+ agentId: 'inline-agent-1',+ isInline: true,+ nodeId: 'agent-node',+ open: true,+ })+ expect(screen.queryByText('workflow.nodes.agent.roster.editInConsole')).not.toBeInTheDocument()+ expect(screen.queryByText('workflow.nodes.agent.roster.makeCopy')).not.toBeInTheDocument()+ expect(screen.getByText('workflow.nodes.agent.task.label')).toBeInTheDocument()+ })++ it('uses the detail header when opening an existing inline agent from the roster trigger', () => {+ const { rerender } = render(+ <AgentV2Panel+ id="agent-node"+ data={createData({+ agent_binding: {+ binding_type: 'inline_agent',+ agent_id: 'inline-agent-1',+ current_snapshot_id: 'snapshot-1',+ },+ })}+ panelProps={panelProps}+ />,+ )++ fireEvent.click(screen.getByRole('button', { name: /^workflow\.nodes\.agent\.roster\.openPanel/ }))+ expect(mockStoreState.setOpenInlineAgentPanelNodeId).toHaveBeenCalledWith('agent-node')++ mockStoreState.openInlineAgentPanelNodeId = 'agent-node'+ rerender(+ <AgentV2Panel+ id="agent-node"+ data={createData({+ agent_binding: {+ binding_type: 'inline_agent',+ agent_id: 'inline-agent-1',+ current_snapshot_id: 'snapshot-1',+ },+ })}+ panelProps={panelProps}+ />,+ )++ const panel = screen.getByRole('dialog', { name: 'Workflow Agent 1' })+ expect(panel).toBeInTheDocument()+ expect(panel.querySelector('header')).not.toHaveClass('h-[108px]')+ expect(within(panel).getByText('workflow.nodes.agent.roster.inlineSetup.type')).toBeInTheDocument()+ expect(within(panel).queryByText('workflow.nodes.agent.roster.inlineSetup.title')).not.toBeInTheDocument()+ expect(within(panel).queryByText('workflow.nodes.agent.roster.inlineSetup.description')).not.toBeInTheDocument()+ expect(within(panel).queryByRole('link', { name: 'workflow.nodes.agent.roster.editInConsole' })).not.toBeInTheDocument()+ expect(within(panel).queryByRole('button', { name: 'workflow.nodes.agent.roster.makeCopy' })).not.toBeInTheDocument()+ expect(screen.getByRole('region', { name: 'inline-orchestrate-panel' })).toBeInTheDocument()+ })++ it('opens the inline panel while workflow composer state is still loading', () => {+ mockStoreState.openInlineAgentPanelNodeId = 'agent-node'+ mockUseWorkflowInlineAgentDetail.mockReturnValue({ data: undefined })++ const { container } = render(+ <AgentV2Panel+ id="agent-node"+ data={createData({+ agent_binding: {+ binding_type: 'inline_agent',+ agent_id: 'inline-agent-1',+ current_snapshot_id: 'snapshot-1',+ },+ })}+ panelProps={panelProps}+ />,+ )++ expect(mockUseWorkflowInlineAgentDetail).toHaveBeenCalledWith('agent-node', 'inline-agent-1')+ expect(container.querySelector('[aria-busy="true"]')).toBeInTheDocument()+ expect(screen.queryByText('workflow.nodes.agent.roster.inlineSetup.name')).not.toBeInTheDocument()+ expect(screen.getByRole('dialog', { name: 'workflow.nodes.agent.roster.inlineSetup.title' })).toBeInTheDocument()+ expect(screen.getByRole('region', { name: 'inline-orchestrate-panel' })).toBeInTheDocument()+ expect(mockOrchestrateDrawerPanelProps.at(-1)).toMatchObject({+ agentId: 'inline-agent-1',+ inlineComposerState: undefined,+ isInline: true,+ nodeId: 'agent-node',+ open: true,+ })+ })++ it('recovers the inline setup panel open state from the node open marker', () => {+ mockUseWorkflowInlineAgentDetail.mockReturnValue({ data: undefined })++ render(+ <AgentV2Panel+ id="agent-node"+ data={createData({+ _openInlineAgentPanel: true,+ agent_binding: {+ binding_type: 'inline_agent',+ agent_id: 'inline-agent-1',+ current_snapshot_id: 'snapshot-1',+ },+ })}+ panelProps={panelProps}+ />,+ )++ expect(mockStoreState.setOpenInlineAgentPanelNodeId).toHaveBeenCalledWith('agent-node')+ expect(mockHandleNodeDataUpdate).toHaveBeenCalledWith({+ id: 'agent-node',+ data: {+ _openInlineAgentPanel: false,+ },+ })+ })++ it('updates roster agent binding from the selector', () => {+ render(+ <AgentV2Panel+ id="agent-node"+ data={createData()}+ panelProps={panelProps}+ />,+ )++ fireEvent.click(screen.getByRole('button', { name: 'workflow.nodes.agent.roster.change' }))+ fireEvent.click(screen.getByRole('button', { name: 'Select Mara' }))++ expect(mockHandleNodeDataUpdateWithSyncDraft).toHaveBeenCalledWith(+ {+ id: 'agent-node',+ data: expect.objectContaining({+ agent_binding: {+ binding_type: 'roster_agent',+ agent_id: 'agent-2',+ },+ }),+ },+ expect.objectContaining({+ sync: true,+ notRefreshWhenSyncError: true,+ }),+ )+ })++ it('does not fall back to the roster agent description when role is empty', () => {+ mockUseAgentRosterDetail.mockReturnValue({+ data: {+ id: 'agent-1',+ name: 'Nadia',+ description: 'Clarification Drafter',+ icon: 'N',+ icon_background: '#E9D7FE',+ icon_type: 'emoji',+ role: '',+ },+ })+ render(+ <AgentV2Panel+ id="agent-node"+ data={createData()}+ panelProps={panelProps}+ />,+ )++ expect(screen.getByText('Nadia')).toBeInTheDocument()+ expect(screen.queryByText('Clarification Drafter')).not.toBeInTheDocument()+ })++ it('updates agent task and opens prompt insertion shortcuts', () => {+ render(+ <AgentV2Panel+ id="agent-node"+ data={createData({ agent_task: 'Graph task' })}+ panelProps={panelProps}+ />,+ )++ const editor = screen.getByRole('textbox', { name: 'workflow.nodes.agent.task.label' })+ expect(editor).toHaveValue('Graph task')++ fireEvent.change(editor, { target: { value: 'Clarify {{#start.question#}}' } })++ expect(mockSetInputs).toHaveBeenCalledWith(expect.objectContaining({+ agent_task: 'Clarify {{#start.question#}}',+ }))+ expect(mockPromptEditorProps[0]?.workflowVariableBlock).toMatchObject({+ show: true,+ })+ expect(mockPromptEditorProps[0]?.agentOutputBlock).toMatchObject({+ show: true,+ outputs: expect.arrayContaining([+ expect.objectContaining({ name: 'text' }),+ ]),+ })+ expect(mockPromptEditorProps[0]?.contextBlock).toBeUndefined()++ expect(screen.queryByRole('button', { name: 'workflow.nodes.agent.task.insert' })).not.toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'workflow.nodes.agent.task.mention' })).not.toBeInTheDocument()++ fireEvent.focus(editor)++ fireEvent.click(screen.getByRole('button', { name: 'workflow.nodes.agent.task.insert' }))+ expect(mockEditorFocus).toHaveBeenCalled()+ expect(mockInsertNodes.mock.calls[0]?.[0]?.[0]?.getTextContent()).toBe('/')+ expect(screen.queryByRole('button', { name: 'workflow.nodes.agent.task.mention' })).not.toBeInTheDocument()+ })++ it('syncs declared outputs created from the agent task editor', () => {+ render(+ <AgentV2Panel+ id="agent-node"+ data={createData()}+ panelProps={panelProps}+ />,+ )++ mockPromptEditorProps[0]?.agentOutputBlock?.onChange?.([+ ...mockPromptEditorProps[0]!.agentOutputBlock!.outputs!,+ {+ name: 'summary',+ type: 'string',+ required: false,+ },+ ], 'Use [§output:summary:summary§]')++ expect(mockHandleNodeDataUpdateWithSyncDraft).toHaveBeenCalledWith(+ {+ id: 'agent-node',+ data: expect.objectContaining({+ agent_task: 'Use [§output:summary:summary§]',+ agent_declared_outputs: expect.arrayContaining([+ expect.objectContaining({+ name: 'summary',+ type: 'string',+ required: false,+ }),+ ]),+ }),+ },+ expect.objectContaining({+ sync: true,+ notRefreshWhenSyncError: true,+ }),+ )+ })++ it('keeps the latest local task draft when outputs change before rerender', () => {+ render(+ <AgentV2Panel+ id="agent-node"+ data={createData()}+ panelProps={panelProps}+ />,+ )++ fireEvent.change(screen.getByRole('textbox', { name: 'workflow.nodes.agent.task.label' }), {+ target: {+ value: 'Draft before output',+ },+ })+ mockPromptEditorProps[0]?.agentOutputBlock?.onChange?.([+ ...mockPromptEditorProps[0]!.agentOutputBlock!.outputs!,+ {+ name: 'summary',+ type: 'string',+ required: false,+ },+ ])++ expect(mockHandleNodeDataUpdateWithSyncDraft).toHaveBeenCalledWith(+ {+ id: 'agent-node',+ data: expect.objectContaining({+ agent_task: 'Draft before output',+ agent_declared_outputs: expect.arrayContaining([+ expect.objectContaining({+ name: 'summary',+ type: 'string',+ required: false,+ }),+ ]),+ }),+ },+ expect.objectContaining({+ sync: true,+ notRefreshWhenSyncError: true,+ }),+ )+ })++ it('saves agent task to workflow draft node data', () => {+ render(+ <AgentV2Panel+ id="agent-node"+ data={createData()}+ panelProps={panelProps}+ />,+ )++ fireEvent.change(screen.getByRole('textbox', { name: 'workflow.nodes.agent.task.label' }), {+ target: {+ value: 'Use the previous result',+ },+ })++ expect(mockSetInputs).toHaveBeenCalledWith(expect.objectContaining({+ agent_task: 'Use the previous result',+ }))+ })++ it('removes declared outputs when their prompt output token is deleted', () => {+ render(+ <AgentV2Panel+ id="agent-node"+ data={createData({+ agent_task: 'Use [§output:summary:summary§] and [§output:manual:manual§]',+ agent_declared_outputs: [+ {+ name: 'summary',+ type: 'string',+ required: false,+ },+ {+ name: 'manual',+ type: 'string',+ required: false,+ },+ ],+ })}+ panelProps={panelProps}+ />,+ )++ fireEvent.change(screen.getByRole('textbox', { name: 'workflow.nodes.agent.task.label' }), {+ target: {+ value: 'Use [§output:manual:manual§]',+ },+ })++ expect(mockSetInputs).toHaveBeenCalledWith(expect.objectContaining({+ agent_task: 'Use [§output:manual:manual§]',+ agent_declared_outputs: [+ expect.objectContaining({+ name: 'manual',+ }),+ ],+ }))+ })++ it('does not remove prompt output tokens when declared outputs are changed from the output list', () => {+ render(+ <AgentV2Panel+ id="agent-node"+ data={createData({+ agent_task: 'Use [§output:summary:summary§]',+ agent_declared_outputs: [+ {+ name: 'summary',+ type: 'string',+ required: false,+ },+ ],+ })}+ panelProps={panelProps}+ />,+ )++ mockPromptEditorProps[0]?.agentOutputBlock?.onChange?.([])++ expect(mockHandleNodeDataUpdateWithSyncDraft).toHaveBeenCalledWith(+ {+ id: 'agent-node',+ data: expect.objectContaining({+ agent_task: 'Use [§output:summary:summary§]',+ agent_declared_outputs: [],+ }),+ },+ expect.objectContaining({+ sync: true,+ notRefreshWhenSyncError: true,+ }),+ )+ })++ it('renames prompt output tokens when a referenced declared output is renamed from the output list', () => {+ render(+ <AgentV2Panel+ id="agent-node"+ data={createData({+ agent_task: 'Use [§output:summary:summary§] and §output:other:other§',+ agent_declared_outputs: [+ {+ name: 'summary',+ type: 'string',+ required: false,+ },+ {+ name: 'other',+ type: 'string',+ required: false,+ },+ ],+ })}+ panelProps={panelProps}+ />,+ )++ mockPromptEditorProps[0]?.agentOutputBlock?.onChange?.([+ {+ name: 'final_summary',+ type: 'string',+ required: false,+ },+ {+ name: 'other',+ type: 'string',+ required: false,+ },+ ])++ expect(mockHandleNodeDataUpdateWithSyncDraft).toHaveBeenCalledWith(+ {+ id: 'agent-node',+ data: expect.objectContaining({+ agent_task: 'Use [§output:final_summary:final_summary§] and §output:other:other§',+ agent_declared_outputs: [+ expect.objectContaining({+ name: 'final_summary',+ }),+ expect.objectContaining({+ name: 'other',+ }),+ ],+ }),+ },+ expect.objectContaining({+ sync: true,+ notRefreshWhenSyncError: true,+ }),+ )+ })++ it('renders declared outputs from workflow draft graph data', () => {+ render(+ <AgentV2Panel+ id="agent-node"+ data={createData({+ agent_declared_outputs: [+ {+ name: 'summary',+ type: 'string',+ description: 'Short summary',+ },+ {+ name: 'attachments',+ type: 'array',+ description: 'Generated files',+ array_item: {+ type: 'file',+ },+ },+ ],+ })}+ panelProps={panelProps}+ />,+ )++ expect(screen.getByText('summary')).toBeInTheDocument()+ expect(screen.getByText('string')).toBeInTheDocument()+ expect(screen.getByText('Short summary')).toBeInTheDocument()+ expect(screen.getByText('attachments')).toBeInTheDocument()+ expect(screen.getByText('array[file]')).toBeInTheDocument()+ expect(screen.getByText('Generated files')).toBeInTheDocument()+ expect(screen.queryByText('workflow.nodes.agent.outputVars.text')).not.toBeInTheDocument()+ })++ it('adds a declared output to workflow draft node data', () => {+ render(+ <AgentV2Panel+ id="agent-node"+ data={createData()}+ panelProps={panelProps}+ />,+ )++ fireEvent.click(screen.getByRole('button', { name: 'workflow.nodes.agent.outputVars.newOutput' }))+ fireEvent.change(screen.getByRole('textbox', { name: 'workflow.nodes.agent.outputVars.nameLabel' }), {+ target: {+ value: 'summary',+ },+ })+ fireEvent.change(screen.getByRole('textbox', { name: 'workflow.nodes.agent.outputVars.descriptionLabel' }), {+ target: {+ value: 'Short summary',+ },+ })+ fireEvent.click(screen.getByRole('button', { name: 'workflow.nodes.agent.outputVars.confirm' }))++ expect(mockHandleNodeDataUpdateWithSyncDraft).toHaveBeenCalledWith(+ {+ id: 'agent-node',+ data: expect.objectContaining({+ agent_declared_outputs: expect.arrayContaining([+ expect.objectContaining({+ name: 'summary',+ type: 'string',+ required: false,+ description: 'Short summary',+ }),+ ]),+ }),+ },+ expect.objectContaining({+ sync: true,+ notRefreshWhenSyncError: true,+ }),+ )+ })++ it('submits the output editor with a scoped Mod+Enter shortcut', () => {+ render(+ <AgentV2Panel+ id="agent-node"+ data={createData()}+ panelProps={panelProps}+ />,+ )++ fireEvent.click(screen.getByRole('button', { name: 'workflow.nodes.agent.outputVars.newOutput' }))+ const nameInput = screen.getByRole('textbox', { name: 'workflow.nodes.agent.outputVars.nameLabel' })+ fireEvent.change(nameInput, {+ target: {+ value: 'summary',+ },+ })+ fireEvent.keyDown(document, { key: 'Enter', ctrlKey: true })++ expect(mockHandleNodeDataUpdateWithSyncDraft).not.toHaveBeenCalled()++ fireEvent.keyDown(nameInput, { key: 'Enter', ctrlKey: true })++ expect(mockHandleNodeDataUpdateWithSyncDraft).toHaveBeenCalledWith(+ {+ id: 'agent-node',+ data: expect.objectContaining({+ agent_declared_outputs: expect.arrayContaining([+ expect.objectContaining({+ name: 'summary',+ }),+ ]),+ }),+ },+ expect.objectContaining({+ sync: true,+ notRefreshWhenSyncError: true,+ }),+ )+ })++ it('cancels the output editor with a scoped Escape shortcut', () => {+ render(+ <AgentV2Panel+ id="agent-node"+ data={createData()}+ panelProps={panelProps}+ />,+ )++ fireEvent.click(screen.getByRole('button', { name: 'workflow.nodes.agent.outputVars.newOutput' }))+ const nameInput = screen.getByRole('textbox', { name: 'workflow.nodes.agent.outputVars.nameLabel' })+ fireEvent.change(nameInput, {+ target: {+ value: 'summary',+ },+ })+ fireEvent.keyDown(document, { key: 'Escape' })++ expect(screen.getByRole('textbox', { name: 'workflow.nodes.agent.outputVars.nameLabel' })).toBeInTheDocument()++ fireEvent.keyDown(nameInput, { key: 'Escape' })++ expect(screen.queryByRole('textbox', { name: 'workflow.nodes.agent.outputVars.nameLabel' })).not.toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'workflow.nodes.agent.outputVars.newOutput' })).toBeInTheDocument()+ expect(mockHandleNodeDataUpdateWithSyncDraft).not.toHaveBeenCalled()+ })++ it('reveals output editor advanced options with the collapsible trigger', () => {+ render(+ <AgentV2Panel+ id="agent-node"+ data={createData()}+ panelProps={panelProps}+ />,+ )++ fireEvent.click(screen.getByRole('button', { name: 'workflow.nodes.agent.outputVars.newOutput' }))++ expect(screen.queryByRole('textbox', { name: 'workflow.nodes.agent.outputVars.defaultValueLabel' })).not.toBeInTheDocument()++ const advancedTrigger = screen.getByRole('button', { name: 'workflow.nodes.agent.outputVars.showAdvancedOptions' })+ expect(advancedTrigger).toHaveAttribute('aria-expanded', 'false')++ fireEvent.click(advancedTrigger)++ expect(advancedTrigger).toHaveAttribute('aria-expanded', 'true')+ expect(screen.getByRole('textbox', { name: 'workflow.nodes.agent.outputVars.defaultValueLabel' })).toBeInTheDocument()+ })++ it('does not show name validation error before the user enters a name', () => {+ render(+ <AgentV2Panel+ id="agent-node"+ data={createData()}+ panelProps={panelProps}+ />,+ )++ fireEvent.click(screen.getByRole('button', { name: 'workflow.nodes.agent.outputVars.newOutput' }))++ expect(screen.queryByText('workflow.nodes.agent.outputVars.nameInvalid')).not.toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'workflow.nodes.agent.outputVars.confirm' })).toBeDisabled()+ })+})diff --git a/web/app/components/workflow/nodes/agent-v2/agent-soul-config.ts b/web/app/components/workflow/nodes/agent-v2/agent-soul-config.tsnew file mode 100644index 00000000000..be73fc9fa60--- /dev/null+++ b/web/app/components/workflow/nodes/agent-v2/agent-soul-config.ts@@ -0,0 +1,170 @@+import type { AgentSoulConfig } from '@dify/contracts/api/console/apps/types.gen'+import type { DefaultModelResponse } from '@/app/components/header/account-setting/model-provider-page/declarations'+import { useMutation, useQueryClient } from '@tanstack/react-query'+import { debounce } from 'es-toolkit/compat'+import { useStore as useJotaiStore, useSetAtom } from 'jotai'+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'+import { useHooksStore } from '@/app/components/workflow/hooks-store'+import { useSerialAsyncCallback } from '@/app/components/workflow/hooks/use-serial-async-callback'+import { agentSoulConfigToFormState, formStateToAgentSoulConfig } from '@/features/agent-v2/agent-composer/conversions'+import {+ agentComposerDraftAtom,+ agentComposerOriginalConfigAtom,+ agentComposerOriginalDraftAtom,+ isAgentComposerDirtyAtom,+} from '@/features/agent-v2/agent-composer/store'+import { consoleQuery } from '@/service/client'+import { FlowType } from '@/types/common'++const DRAFT_AUTOSAVE_WAIT = 5000++function getModelProviderPluginId(provider: string) {+ const [organization, pluginName] = provider.split('/').filter(Boolean)++ if (organization && pluginName)+ return `${organization}/${pluginName}`++ return provider ? `langgenius/${provider}` : ''+}++export function getDefaultAgentSoul(defaultModel?: DefaultModelResponse): AgentSoulConfig {+ const baseConfig: AgentSoulConfig = {+ schema_version: 1,+ prompt: {+ system_prompt: '',+ },+ }++ if (!defaultModel)+ return baseConfig++ const modelProvider = defaultModel.provider.provider++ return {+ ...baseConfig,+ model: {+ model_provider: modelProvider,+ model: defaultModel.model,+ plugin_id: getModelProviderPluginId(modelProvider),+ },+ }+}++export function useWorkflowInlineAgentConfigureSync({+ nodeId,+ baseConfig,+ currentModel,+ enabled,+}: {+ nodeId: string+ baseConfig?: AgentSoulConfig+ currentModel?: {+ provider: string+ model: string+ plugin_id?: string+ }+ enabled: boolean+}) {+ const queryClient = useQueryClient()+ const configsMap = useHooksStore(state => state.configsMap)+ const store = useJotaiStore()+ const setOriginalConfig = useSetAtom(agentComposerOriginalConfigAtom)+ const setOriginalDraft = useSetAtom(agentComposerOriginalDraftAtom)+ const [draftSavedAt, setDraftSavedAt] = useState<number | undefined>(undefined)+ const baseConfigRef = useRef(baseConfig)+ const currentModelRef = useRef(currentModel)+ const enabledRef = useRef(enabled)+ const lastAutosavedDraftKeyRef = useRef<string | undefined>(undefined)+ const saveComposerMutation = useMutation(+ consoleQuery.apps.byAppId.workflows.draft.nodes.byNodeId.agentComposer.put.mutationOptions(),+ )++ baseConfigRef.current = baseConfig+ currentModelRef.current = currentModel+ enabledRef.current = enabled++ const getAgentSoulDraft = useCallback(() => formStateToAgentSoulConfig({+ baseConfig: baseConfigRef.current,+ formState: store.get(agentComposerDraftAtom),+ currentModel: currentModelRef.current,+ }), [store])++ const saveComposer = useSerialAsyncCallback(async (configSnapshot: AgentSoulConfig) => {+ if (!configsMap?.flowId || configsMap.flowType !== FlowType.appFlow)+ return++ const savedDraftKey = JSON.stringify(configSnapshot)+ const composerState = await saveComposerMutation.mutateAsync({+ params: {+ app_id: configsMap.flowId,+ node_id: nodeId,+ },+ body: {+ variant: 'workflow',+ save_strategy: 'node_job_only',+ agent_soul: configSnapshot,+ },+ })++ queryClient.setQueryData(+ consoleQuery.apps.byAppId.workflows.draft.nodes.byNodeId.agentComposer.get.queryKey({+ input: {+ params: {+ app_id: configsMap.flowId,+ node_id: nodeId,+ },+ },+ }),+ composerState,+ )+ setOriginalConfig(composerState.agent_soul)+ setOriginalDraft(agentSoulConfigToFormState(composerState.agent_soul))+ setDraftSavedAt(Date.now())+ lastAutosavedDraftKeyRef.current = savedDraftKey+ })++ const latestDraftSaveRef = useRef<() => void>(() => undefined)+ latestDraftSaveRef.current = () => {+ void saveComposer(getAgentSoulDraft())+ }++ const debouncedSaveDraft = useMemo(() => debounce(() => {+ latestDraftSaveRef.current()+ }, DRAFT_AUTOSAVE_WAIT), [])++ const saveDraft = useCallback(async () => {+ if (!enabledRef.current)+ return++ debouncedSaveDraft.cancel?.()+ await saveComposer(getAgentSoulDraft())+ }, [debouncedSaveDraft, getAgentSoulDraft, saveComposer])++ useEffect(() => {+ return store.sub(agentComposerDraftAtom, () => {+ const agentSoulDraft = getAgentSoulDraft()+ const agentSoulDraftKey = JSON.stringify(agentSoulDraft)++ if (+ !enabledRef.current+ || !store.get(isAgentComposerDirtyAtom)+ || lastAutosavedDraftKeyRef.current === agentSoulDraftKey+ ) {+ return+ }++ debouncedSaveDraft()+ })+ }, [debouncedSaveDraft, getAgentSoulDraft, store])++ useEffect(() => {+ return () => {+ debouncedSaveDraft.flush?.()+ }+ }, [debouncedSaveDraft])++ return {+ draftSavedAt,+ saveDraft,+ }+}diff --git a/web/app/components/workflow/nodes/agent-v2/components/agent-advanced-settings.tsx b/web/app/components/workflow/nodes/agent-v2/components/agent-advanced-settings.tsxnew file mode 100644index 00000000000..d3c43f1ad00--- /dev/null+++ b/web/app/components/workflow/nodes/agent-v2/components/agent-advanced-settings.tsx@@ -0,0 +1,27 @@+import {+ CollapsiblePanel,+ CollapsibleRoot,+ CollapsibleTrigger,+} from '@langgenius/dify-ui/collapsible'+import { useTranslation } from 'react-i18next'++export function AgentAdvancedSettings() {+ const { t } = useTranslation()++ return (+ <CollapsibleRoot className="border-b border-divider-subtle py-2">+ <CollapsibleTrigger className="group h-8 min-h-0 justify-start gap-0 rounded-none px-4 py-0 hover:not-data-disabled:bg-transparent hover:not-data-disabled:text-text-secondary data-panel-open:text-text-secondary">+ <span className="min-w-0 truncate system-sm-semibold-uppercase text-text-secondary">+ {t('nodes.agent.advancedSetting', { ns: 'workflow' })}+ </span>+ <span+ aria-hidden="true"+ className="i-custom-vender-solid-general-arrow-down-round-fill size-4 rotate-270 text-text-quaternary transition-transform group-data-panel-open:rotate-0 motion-reduce:transition-none"+ />+ </CollapsibleTrigger>+ <CollapsiblePanel>+ <div className="px-4" />+ </CollapsiblePanel>+ </CollapsibleRoot>+ )+}diff --git a/web/app/components/workflow/nodes/agent-v2/components/agent-orchestrate-drawer-panel.tsx b/web/app/components/workflow/nodes/agent-v2/components/agent-orchestrate-drawer-panel.tsxnew file mode 100644index 00000000000..bae800df611--- /dev/null+++ b/web/app/components/workflow/nodes/agent-v2/components/agent-orchestrate-drawer-panel.tsx@@ -0,0 +1,119 @@+'use client'++import type { AgentConfigSnapshotSummaryResponse, AgentSoulConfig } from '@dify/contracts/api/console/agent/types.gen'+import type { WorkflowAgentComposerResponse } from '@dify/contracts/api/console/apps/types.gen'+import { skipToken, useQuery } from '@tanstack/react-query'+import { useAtom } from 'jotai'+import Loading from '@/app/components/base/loading'+import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'+import { useDefaultModel, useTextGenerationCurrentProviderAndModelAndModelList } from '@/app/components/header/account-setting/model-provider-page/hooks'+import { AgentComposerProvider } from '@/features/agent-v2/agent-composer/provider'+import { useHydrateAgentSoulConfigDraft } from '@/features/agent-v2/agent-composer/store'+import { agentComposerModelAtom } from '@/features/agent-v2/agent-composer/store-modules/model'+import { AgentOrchestratePanel } from '@/features/agent-v2/agent-detail/configure/components/orchestrate'+import { consoleQuery } from '@/service/client'+import { useWorkflowInlineAgentConfigureSync } from '../agent-soul-config'++type AgentOrchestrateDrawerPanelProps = {+ agentId: string+ inlineComposerState?: WorkflowAgentComposerResponse+ isInline: boolean+ nodeId: string+ open: boolean+}++export function AgentOrchestrateDrawerPanel(props: AgentOrchestrateDrawerPanelProps) {+ return (+ <AgentComposerProvider>+ <AgentOrchestrateDrawerPanelContent {...props} />+ </AgentComposerProvider>+ )+}++function AgentOrchestrateDrawerPanelContent({+ agentId,+ inlineComposerState,+ isInline,+ nodeId,+ open,+}: AgentOrchestrateDrawerPanelProps) {+ const rosterComposerQuery = useQuery(consoleQuery.agent.byAgentId.composer.get.queryOptions({+ input: open && !isInline+ ? {+ params: {+ agent_id: agentId,+ },+ }+ : skipToken,+ }))+ const composerState = isInline ? inlineComposerState : rosterComposerQuery.data+ const agentSoulConfig = composerState?.agent_soul+ const activeConfigSnapshot = ('active_config_snapshot' in (composerState ?? {}))+ ? composerState?.active_config_snapshot as AgentConfigSnapshotSummaryResponse | null | undefined+ : undefined+ const { currentModel, setConfigureModel, textGenerationModelList } = useAgentOrchestrateModelOptions()+ const { draftSavedAt, saveDraft } = useWorkflowInlineAgentConfigureSync({+ nodeId,+ baseConfig: agentSoulConfig,+ currentModel,+ enabled: open && isInline && !!agentSoulConfig,+ })++ useHydrateAgentSoulConfigDraft({+ agentId: isInline ? `${nodeId}:${agentId}` : agentId,+ activeVersionId: activeConfigSnapshot?.id,+ config: agentSoulConfig as AgentSoulConfig | undefined,+ })++ if (!agentSoulConfig) {+ return (+ <div className="flex h-full min-h-80 items-center justify-center bg-components-panel-bg">+ <Loading type="app" />+ </div>+ )+ }++ return (+ <AgentOrchestratePanel+ agentId={agentId}+ activeConfigSnapshot={activeConfigSnapshot}+ agentSoulConfig={agentSoulConfig as AgentSoulConfig}+ agentName={composerState?.agent?.name}+ currentModel={currentModel}+ textGenerationModelList={textGenerationModelList}+ draftSavedAt={draftSavedAt}+ readOnly={!isInline}+ showHeader={false}+ showPublishBar={false}+ className="h-full max-w-none min-w-0 flex-none rounded-none border-0"+ onSelectModel={setConfigureModel}+ onPublish={() => {+ void saveDraft()+ }}+ onOpenVersions={() => undefined}+ />+ )+}++function useAgentOrchestrateModelOptions() {+ const [model, setModel] = useAtom(agentComposerModelAtom)+ const {+ data: defaultTextGenerationModel,+ } = useDefaultModel(ModelTypeEnum.textGeneration)+ const defaultModel = defaultTextGenerationModel+ ? {+ provider: defaultTextGenerationModel.provider.provider,+ model: defaultTextGenerationModel.model,+ }+ : undefined+ const currentModel = model ?? defaultModel+ const {+ textGenerationModelList,+ } = useTextGenerationCurrentProviderAndModelAndModelList(currentModel)++ return {+ currentModel,+ setConfigureModel: setModel,+ textGenerationModelList,+ }+}diff --git a/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/__tests__/utils.spec.ts b/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/__tests__/utils.spec.tsnew file mode 100644index 00000000000..4648f90c238--- /dev/null+++ b/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/__tests__/utils.spec.ts@@ -0,0 +1,57 @@+import type { OutputDraft } from '../utils'+import { describe, expect, it } from 'vitest'+import {+ createOutputFromDraft,+ getDefaultValueErrorKey,+} from '../utils'++const createDraft = (overrides: Partial<OutputDraft> = {}): OutputDraft => ({+ defaultValue: '',+ description: '',+ name: 'summary',+ required: false,+ type: 'string',+ ...overrides,+})++describe('agent output variables utils', () => {+ it('should build a declared output from the editable draft', () => {+ expect(createOutputFromDraft(createDraft({+ defaultValue: '42',+ description: 'A numeric score',+ required: true,+ type: 'number',+ }))).toEqual({+ name: 'summary',+ type: 'number',+ required: true,+ description: 'A numeric score',+ failure_strategy: {+ on_failure: 'default_value',+ default_value: 42,+ },+ })+ })++ it('should validate default values against the declared output type', () => {+ expect(getDefaultValueErrorKey(createDraft({+ defaultValue: 'not-json',+ type: 'object',+ }))).toBe('nodes.agent.outputVars.defaultValueObjectInvalid')++ expect(getDefaultValueErrorKey(createDraft({+ defaultValue: '{}',+ type: 'array[string]',+ }))).toBe('nodes.agent.outputVars.defaultValueArrayInvalid')++ expect(getDefaultValueErrorKey(createDraft({+ defaultValue: 'yes',+ type: 'boolean',+ }))).toBe('nodes.agent.outputVars.defaultValueBooleanInvalid')++ expect(getDefaultValueErrorKey(createDraft({+ defaultValue: '[]',+ type: 'array[file]',+ }))).toBe('nodes.agent.outputVars.defaultValueFileUnsupported')+ })+})diff --git a/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/edit-card.tsx b/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/edit-card.tsxnew file mode 100644index 00000000000..3e66f868ad9--- /dev/null+++ b/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/edit-card.tsx@@ -0,0 +1,186 @@+import type { DeclaredOutputConfig } from '@dify/contracts/api/console/apps/types.gen'+import type { EditingState, OutputDraft } from './utils'+import { Button } from '@langgenius/dify-ui/button'+import { CollapsiblePanel, CollapsibleRoot, CollapsibleTrigger } from '@langgenius/dify-ui/collapsible'+import { FieldControl, FieldError, FieldLabel, FieldRoot } from '@langgenius/dify-ui/field'+import { Form } from '@langgenius/dify-ui/form'+import { Kbd, KbdGroup } from '@langgenius/dify-ui/kbd'+import { Switch } from '@langgenius/dify-ui/switch'+import { Textarea } from '@langgenius/dify-ui/textarea'+import { formatForDisplay, useHotkey } from '@tanstack/react-hotkeys'+import { useId, useRef, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { OutputTypeSelect } from './type-select'+import {+ createOutputFromDraft,+ getDefaultValueErrorKey,+ OUTPUT_NAME_PATTERN,+ OUTPUT_NAME_PATTERN_SOURCE,+} from './utils'++const CONFIRM_HOTKEY = 'Mod+Enter'++function ConfirmHotkeyHint() {+ const displayKeys = formatForDisplay(CONFIRM_HOTKEY, { separatorToken: ' ' })+ .split(' ')+ .filter(Boolean)++ return (+ <KbdGroup aria-hidden="true">+ {displayKeys.map(key => (+ <Kbd key={key} color="white">+ {key}+ </Kbd>+ ))}+ </KbdGroup>+ )+}++export function OutputEditCard({+ existingOutputs,+ state,+ onCancel,+ onConfirm,+}: {+ existingOutputs: DeclaredOutputConfig[]+ state: EditingState+ onCancel: () => void+ onConfirm: (output: DeclaredOutputConfig, index?: number) => void+}) {+ const { t } = useTranslation()+ const nameErrorId = useId()+ const editorRef = useRef<HTMLDivElement>(null)+ const [draft, setDraft] = useState(state.draft)+ const trimmedName = draft.name.trim()+ const duplicateName = existingOutputs.some((output, index) => output.name === trimmedName && index !== state.index)+ const nameInvalid = !!trimmedName && !OUTPUT_NAME_PATTERN.test(trimmedName)+ const hasNameError = duplicateName || nameInvalid+ const defaultValueErrorKey = getDefaultValueErrorKey(draft)+ const confirmDisabled = !trimmedName || nameInvalid || duplicateName || !!defaultValueErrorKey+ function updateDraft(next: Partial<OutputDraft>) {+ setDraft(prev => ({ ...prev, ...next }))+ }+ function handleConfirm() {+ if (confirmDisabled)+ return+ onConfirm(createOutputFromDraft(draft), state.index)+ }+ useHotkey(CONFIRM_HOTKEY, handleConfirm, { target: editorRef, ignoreInputs: false })+ useHotkey('Escape', onCancel, { target: editorRef, ignoreInputs: false })+ return (+ <div ref={editorRef}>+ <Form+ aria-label={t('nodes.agent.outputVars.editorLabel', { ns: 'workflow' })}+ className="flex flex-col overflow-hidden rounded-xl border border-components-panel-border bg-components-panel-bg shadow-md shadow-shadow-shadow-4"+ onSubmit={(event) => {+ event.preventDefault()+ handleConfirm()+ }}+ >+ <div className="px-2 pt-2">+ <div className="flex h-6 items-center gap-x-2">+ <FieldRoot name="name" invalid={hasNameError} className="contents">+ <FieldLabel className="sr-only">+ {t('nodes.agent.outputVars.nameLabel', { ns: 'workflow' })}+ </FieldLabel>+ <FieldControl+ aria-describedby={hasNameError ? nameErrorId : undefined}+ // eslint-disable-next-line jsx-a11y/no-autofocus -- Inline editor opens from an explicit user action and should focus the first editable field.+ autoFocus+ required+ pattern={OUTPUT_NAME_PATTERN_SOURCE}+ size="small"+ value={draft.name}+ placeholder={t('nodes.agent.outputVars.namePlaceholder', { ns: 'workflow' })}+ className="h-6 w-24 px-1.5 py-0 code-sm-semibold"+ onChange={event => updateDraft({ name: event.currentTarget.value })}+ />+ </FieldRoot>+ <OutputTypeSelect+ value={draft.type}+ onChange={value => updateDraft({ type: value })}+ />+ <FieldRoot name="required" className="contents">+ <FieldLabel className="flex h-6 items-center gap-x-1 system-xs-regular text-text-tertiary">+ <Switch+ aria-label={t('nodes.agent.outputVars.requiredLabel', { ns: 'workflow' })}+ size="xs"+ checked={draft.required}+ onCheckedChange={required => updateDraft({ required })}+ />+ {t('nodes.agent.outputVars.requiredLabel', { ns: 'workflow' })}+ </FieldLabel>+ </FieldRoot>+ </div>+ {hasNameError && (+ <FieldRoot name="nameError" invalid className="contents">+ <FieldError id={nameErrorId} match className="mt-1 px-1 py-0 system-xs-regular text-text-destructive">+ {duplicateName+ ? t('nodes.agent.outputVars.nameDuplicate', { ns: 'workflow' })+ : t('nodes.agent.outputVars.nameInvalid', { ns: 'workflow' })}+ </FieldError>+ </FieldRoot>+ )}+ <FieldRoot name="description" className="contents">+ <FieldLabel className="sr-only">+ {t('nodes.agent.outputVars.descriptionLabel', { ns: 'workflow' })}+ </FieldLabel>+ <FieldControl+ size="small"+ value={draft.description}+ placeholder={t('nodes.agent.outputVars.descriptionPlaceholder', { ns: 'workflow' })}+ className="mt-2 h-5 border-transparent bg-transparent px-1 py-0 system-xs-regular shadow-none hover:border-transparent hover:bg-transparent focus:bg-transparent"+ onChange={event => updateDraft({ description: event.currentTarget.value })}+ />+ </FieldRoot>+ </div>+ <CollapsibleRoot>+ <CollapsibleTrigger className="h-8 min-h-8 justify-start gap-x-0.5 rounded-none border-y border-divider-subtle pr-2 pl-2.5 system-xs-regular text-text-tertiary hover:not-data-disabled:bg-state-base-hover hover:not-data-disabled:text-text-tertiary focus-visible:bg-state-base-hover focus-visible:ring-inset data-panel-open:text-text-tertiary">+ <span+ aria-hidden="true"+ className="i-ri-arrow-down-double-line size-3 transition-transform duration-100 ease-out group-data-panel-open:rotate-180 motion-reduce:transition-none"+ />+ {t('nodes.agent.outputVars.showAdvancedOptions', { ns: 'workflow' })}+ </CollapsibleTrigger>+ <CollapsiblePanel className="border-t border-divider-subtle">+ <div className="px-3 py-2">+ <FieldRoot name="defaultValue" className="gap-1">+ <FieldLabel className="py-0 system-xs-medium text-text-secondary">+ {t('nodes.agent.outputVars.defaultValueLabel', { ns: 'workflow' })}+ </FieldLabel>+ <Textarea+ size="small"+ value={draft.defaultValue}+ placeholder={t('nodes.agent.outputVars.defaultValuePlaceholder', { ns: 'workflow' })}+ className="mt-1 min-h-6"+ onValueChange={defaultValue => updateDraft({ defaultValue })}+ />+ {defaultValueErrorKey && (+ <FieldError match className="py-0 system-xs-regular text-text-destructive">+ {t(defaultValueErrorKey, { ns: 'workflow' })}+ </FieldError>+ )}+ </FieldRoot>+ </div>+ </CollapsiblePanel>+ </CollapsibleRoot>+ <div className="flex h-12 items-center justify-end gap-x-2 px-3">+ <Button type="button" size="small" variant="secondary" onClick={onCancel}>+ {t('operation.cancel', { ns: 'common' })}+ </Button>+ <Button+ type="submit"+ size="small"+ variant="primary"+ disabled={confirmDisabled}+ aria-label={t('nodes.agent.outputVars.confirm', { ns: 'workflow' })}+ className="gap-x-1"+ >+ {t('nodes.agent.outputVars.confirm', { ns: 'workflow' })}+ <ConfirmHotkeyHint />+ </Button>+ </div>+ </Form>+ </div>+ )+}diff --git a/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/index.tsx b/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/index.tsxnew file mode 100644index 00000000000..4303a18c1bc--- /dev/null+++ b/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/index.tsx@@ -0,0 +1,151 @@+import type { DeclaredOutputConfig } from '@dify/contracts/api/console/apps/types.gen'+import type { AgentOutputVariablesProps, EditingState } from './utils'+import { Button } from '@langgenius/dify-ui/button'+import { useState } from 'react'+import { useTranslation } from 'react-i18next'+import Divider from '@/app/components/base/divider'+import OutputVars from '../../../_base/components/output-vars'+import { OutputEditCard } from './edit-card'+import {+ createDraft,+ getOutputDescription,+ getOutputDisplayType,+ getOutputTypeOptionValue,+ isDefaultOutput,+} from './utils'++function OutputRow({+ output,+ editable,+ onDelete,+ onEdit,+}: {+ output: DeclaredOutputConfig+ editable: boolean+ onDelete: () => void+ onEdit: () => void+}) {+ const { t } = useTranslation()+ const description = getOutputDescription(output, t)+ return (+ <div className="group flex min-h-12 flex-col rounded-lg py-0.5 focus-within:bg-state-base-hover hover:bg-state-base-hover">+ <div className="flex h-6 items-center gap-x-1 pr-0.5 pl-1">+ <div className="flex min-w-0 grow items-center gap-x-1">+ <span className="flex h-5 min-w-0 items-center px-1">+ <span className="truncate code-sm-semibold leading-4 text-text-primary">{output.name}</span>+ </span>+ <span className="flex h-5 shrink-0 items-center px-1 system-xs-medium text-text-tertiary">{getOutputDisplayType(output)}</span>+ {output.required && (+ <span className="flex h-3 shrink-0 items-center px-1 system-2xs-medium-uppercase text-text-warning">+ {t('nodes.agent.outputVars.requiredLabel', { ns: 'workflow' })}+ </span>+ )}+ </div>+ {editable && (+ <div className="pointer-events-none flex shrink-0 items-center gap-x-0.5 opacity-0 group-focus-within:pointer-events-auto group-focus-within:opacity-100 group-hover:pointer-events-auto group-hover:opacity-100">+ <button+ type="button"+ aria-label={t('nodes.agent.outputVars.edit', { ns: 'workflow', name: output.name })}+ className="flex size-6 items-center justify-center rounded-md text-text-tertiary hover:bg-state-base-hover-alt hover:text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"+ onClick={onEdit}+ >+ <span aria-hidden="true" className="i-ri-pencil-line size-4" />+ </button>+ <button+ type="button"+ aria-label={t('nodes.agent.outputVars.delete', { ns: 'workflow', name: output.name })}+ className="flex size-6 items-center justify-center rounded-md text-text-tertiary hover:bg-state-base-hover-alt hover:text-text-destructive focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"+ onClick={onDelete}+ >+ <span aria-hidden="true" className="i-ri-delete-bin-line size-4" />+ </button>+ </div>+ )}+ </div>+ {description && (+ <div className="truncate px-2 pb-1 system-xs-regular text-text-tertiary">+ {description}+ </div>+ )}+ </div>+ )+}+export function AgentOutputVariables({+ outputs,+ onChange,+}: AgentOutputVariablesProps) {+ const { t } = useTranslation()+ const [editingState, setEditingState] = useState<EditingState | null>(null)+ function handleNewOutput() {+ setEditingState({ draft: createDraft() })+ }+ function handleEditOutput(index: number) {+ setEditingState({ index, draft: createDraft(outputs[index]) })+ }+ function handleDeleteOutput(index: number) {+ onChange(outputs.filter((_, outputIndex) => outputIndex !== index))+ }+ function handleConfirm(output: DeclaredOutputConfig, index?: number) {+ if (typeof index === 'number') {+ onChange(outputs.map((item, outputIndex) => outputIndex === index ? output : item))+ }+ else {+ onChange([...outputs, output])+ }+ setEditingState(null)+ }+ return (+ <OutputVars>+ <div className="pb-2">+ <div className="flex flex-col">+ {outputs.map((output, index) => (+ editingState?.index === index+ ? (+ <OutputEditCard+ key={`${output.name}-editing`}+ existingOutputs={outputs}+ state={editingState}+ onCancel={() => setEditingState(null)}+ onConfirm={handleConfirm}+ />+ )+ : (+ <OutputRow+ key={`${output.name}-${getOutputTypeOptionValue(output)}`}+ output={output}+ editable={!isDefaultOutput(output)}+ onDelete={() => handleDeleteOutput(index)}+ onEdit={() => handleEditOutput(index)}+ />+ )+ ))}+ <div className="py-1">+ <Divider type="horizontal" className="h-px bg-divider-subtle" />+ </div>+ {editingState && editingState.index == null+ ? (+ <OutputEditCard+ existingOutputs={outputs}+ state={editingState}+ onCancel={() => setEditingState(null)}+ onConfirm={handleConfirm}+ />+ )+ : (+ <div className="pt-1">+ <Button+ size="small"+ variant="tertiary"+ className="h-6 w-full gap-x-1 rounded-md bg-components-input-bg-normal text-text-secondary hover:bg-state-base-hover"+ onClick={handleNewOutput}+ >+ <span aria-hidden="true" className="i-ri-add-line size-3.5" />+ {t('nodes.agent.outputVars.newOutput', { ns: 'workflow' })}+ </Button>+ </div>+ )}+ </div>+ </div>+ </OutputVars>+ )+}diff --git a/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/type-select.tsx b/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/type-select.tsxnew file mode 100644index 00000000000..ffdea9b4958--- /dev/null+++ b/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/type-select.tsx@@ -0,0 +1,51 @@+import type { OutputTypeOptionValue } from './utils'+import {+ Select,+ SelectContent,+ SelectItem,+ SelectItemIndicator,+ SelectItemText,+ SelectLabel,+ SelectTrigger,+} from '@langgenius/dify-ui/select'+import { useTranslation } from 'react-i18next'+import { getOutputTypeOption, OUTPUT_TYPE_OPTIONS } from './utils'++export function OutputTypeSelect({+ value,+ onChange,+}: {+ value: OutputTypeOptionValue+ onChange: (value: OutputTypeOptionValue) => void+}) {+ const { t } = useTranslation()+ const selected = getOutputTypeOption(value)++ return (+ <Select<OutputTypeOptionValue>+ value={value}+ onValueChange={(nextValue) => {+ if (nextValue)+ onChange(nextValue)+ }}+ >+ <SelectLabel className="sr-only">+ {t('nodes.agent.outputVars.typeLabel', { ns: 'workflow' })}+ </SelectLabel>+ <SelectTrigger+ aria-label={t('nodes.agent.outputVars.typeLabel', { ns: 'workflow' })}+ className="h-6 w-auto rounded-md bg-transparent px-1 py-0 system-xs-medium text-text-tertiary hover:bg-state-base-hover"+ >+ {selected.label}+ </SelectTrigger>+ <SelectContent popupClassName="w-40">+ {OUTPUT_TYPE_OPTIONS.map(option => (+ <SelectItem key={option.value} value={option.value}>+ <SelectItemText>{option.label}</SelectItemText>+ <SelectItemIndicator />+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )+}diff --git a/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/utils.ts b/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/utils.tsnew file mode 100644index 00000000000..39e35c64a72--- /dev/null+++ b/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/utils.ts@@ -0,0 +1,200 @@+import type { DeclaredOutputConfig, DeclaredOutputType } from '@dify/contracts/api/console/apps/types.gen'+import type { TFunction } from 'i18next'+import { defaultAgentV2DeclaredOutputs } from '../../output-variables'++export type OutputTypeOptionValue+ = DeclaredOutputType+ | 'array[boolean]'+ | 'array[file]'+ | 'array[number]'+ | 'array[object]'+ | 'array[string]'++export type OutputTypeOption = {+ label: string+ type: DeclaredOutputType+ value: OutputTypeOptionValue+ arrayItemType?: DeclaredOutputType+}++export type OutputDraft = {+ defaultValue: string+ description: string+ name: string+ required: boolean+ type: OutputTypeOptionValue+}++export type EditingState = {+ draft: OutputDraft+ index?: number+}++export type AgentOutputVariablesProps = {+ outputs: DeclaredOutputConfig[]+ onChange: (outputs: DeclaredOutputConfig[]) => void+}++export const OUTPUT_NAME_PATTERN = /^[a-z_]\w*$/i+export const OUTPUT_NAME_PATTERN_SOURCE = '[A-Za-z_][A-Za-z0-9_]*'++export const OUTPUT_TYPE_OPTIONS: OutputTypeOption[] = [+ { value: 'string', label: 'string', type: 'string' },+ { value: 'number', label: 'number', type: 'number' },+ { value: 'boolean', label: 'boolean', type: 'boolean' },+ { value: 'object', label: 'object', type: 'object' },+ { value: 'file', label: 'file', type: 'file' },+ { value: 'array[string]', label: 'array[string]', type: 'array', arrayItemType: 'string' },+ { value: 'array[number]', label: 'array[number]', type: 'array', arrayItemType: 'number' },+ { value: 'array[boolean]', label: 'array[boolean]', type: 'array', arrayItemType: 'boolean' },+ { value: 'array[object]', label: 'array[object]', type: 'array', arrayItemType: 'object' },+ { value: 'array[file]', label: 'array[file]', type: 'array', arrayItemType: 'file' },+]++export function getOutputTypeOptionValue(output: DeclaredOutputConfig): OutputTypeOptionValue {+ if (output.type !== 'array')+ return output.type++ return `array[${output.array_item?.type || 'object'}]` as OutputTypeOptionValue+}++export function getOutputTypeOption(value: OutputTypeOptionValue) {+ return OUTPUT_TYPE_OPTIONS.find(option => option.value === value) || OUTPUT_TYPE_OPTIONS[0]!+}++export function createDraft(output?: DeclaredOutputConfig): OutputDraft {+ if (!output) {+ return {+ defaultValue: '',+ description: '',+ name: '',+ required: false,+ type: 'string',+ }+ }++ return {+ defaultValue: getOutputDefaultValue(output),+ description: output.description || '',+ name: output.name,+ required: output.required ?? true,+ type: getOutputTypeOptionValue(output),+ }+}++export function createOutputFromDraft(draft: OutputDraft): DeclaredOutputConfig {+ const option = getOutputTypeOption(draft.type)+ const output: DeclaredOutputConfig = {+ name: draft.name.trim(),+ type: option.type,+ required: draft.required,+ }++ if (draft.description.trim())+ output.description = draft.description.trim()++ if (option.type === 'array') {+ output.array_item = {+ type: option.arrayItemType || 'object',+ }+ }++ if (option.type === 'file') {+ output.file = {+ extensions: [],+ mime_types: [],+ }+ }++ if (draft.defaultValue.trim()) {+ output.failure_strategy = {+ on_failure: 'default_value',+ default_value: coerceDefaultValue(draft.defaultValue, option),+ }+ }++ return output+}++export function getDefaultValueErrorKey(draft: OutputDraft) {+ const trimmed = draft.defaultValue.trim()+ if (!trimmed)+ return null++ const option = getOutputTypeOption(draft.type)+ if (option.type === 'file' || option.arrayItemType === 'file')+ return 'nodes.agent.outputVars.defaultValueFileUnsupported'++ if (option.type === 'number' && Number.isNaN(Number(trimmed)))+ return 'nodes.agent.outputVars.defaultValueNumberInvalid'++ if (option.type === 'boolean' && trimmed !== 'true' && trimmed !== 'false')+ return 'nodes.agent.outputVars.defaultValueBooleanInvalid'++ if (option.type === 'object' || option.type === 'array') {+ try {+ const parsed = JSON.parse(trimmed)+ if (option.type === 'object' && (!parsed || Array.isArray(parsed) || typeof parsed !== 'object'))+ return 'nodes.agent.outputVars.defaultValueObjectInvalid'+ if (option.type === 'array' && !Array.isArray(parsed))+ return 'nodes.agent.outputVars.defaultValueArrayInvalid'+ }+ catch {+ return option.type === 'object'+ ? 'nodes.agent.outputVars.defaultValueObjectInvalid'+ : 'nodes.agent.outputVars.defaultValueArrayInvalid'+ }+ }++ return null+}++export function isDefaultOutput(output: DeclaredOutputConfig) {+ return defaultAgentV2DeclaredOutputs.some(defaultOutput =>+ defaultOutput.name === output.name+ && defaultOutput.type === output.type+ && getOutputTypeOptionValue(defaultOutput) === getOutputTypeOptionValue(output),+ )+}++export function getOutputDescription(output: DeclaredOutputConfig, t: TFunction) {+ if (output.name === 'text')+ return t('nodes.agent.outputVars.text', { ns: 'workflow' })+ if (output.name === 'files')+ return t('nodes.agent.outputVars.files.title', { ns: 'workflow' })+ if (output.name === 'json')+ return t('nodes.agent.outputVars.json', { ns: 'workflow' })+ return output.description || ''+}++export function getOutputDisplayType(output: DeclaredOutputConfig) {+ return getOutputTypeOption(getOutputTypeOptionValue(output)).label+}++function getOutputDefaultValue(output: DeclaredOutputConfig) {+ const defaultValue = output.failure_strategy?.default_value+ if (defaultValue == null)+ return ''+ if (typeof defaultValue === 'string')+ return defaultValue+ return JSON.stringify(defaultValue)+}++function coerceDefaultValue(value: string, option: OutputTypeOption): unknown {+ const trimmed = value.trim()+ if (option.type === 'number') {+ const parsed = Number(trimmed)+ return Number.isNaN(parsed) ? trimmed : parsed+ }+ if (option.type === 'boolean')+ return trimmed === 'true'+ if (option.type === 'object' || option.type === 'array') {+ try {+ return JSON.parse(trimmed)+ }+ catch {+ return trimmed+ }+ }+ return trimmed+}diff --git a/web/app/components/workflow/nodes/agent-v2/components/agent-roster-field.tsx b/web/app/components/workflow/nodes/agent-v2/components/agent-roster-field.tsxnew file mode 100644index 00000000000..97da8b60057--- /dev/null+++ b/web/app/components/workflow/nodes/agent-v2/components/agent-roster-field.tsx@@ -0,0 +1,375 @@+import type { ReactNode, RefObject } from 'react'+import type { AgentRosterNodeData } from '@/app/components/workflow/block-selector/types'+import type { AppIconType } from '@/types/app'+import { Button } from '@langgenius/dify-ui/button'+import { cn } from '@langgenius/dify-ui/cn'+import {+ Drawer,+ DrawerCloseButton,+ DrawerContent,+ DrawerPopup,+ DrawerPortal,+ DrawerTitle,+ DrawerViewport,+} from '@langgenius/dify-ui/drawer'+import { FieldLabel, FieldRoot } from '@langgenius/dify-ui/field'+import {+ Popover,+ PopoverContent,+ PopoverTitle,+ PopoverTrigger,+} from '@langgenius/dify-ui/popover'+import { useState } from 'react'+import { useTranslation } from 'react-i18next'+import AppIcon from '@/app/components/base/app-icon'+import { AgentSelectorContent } from '@/app/components/workflow/block-selector/agent-selector'+import { getAgentDetailPath } from '@/features/agent-v2/agent-detail/routes'+import Link from '@/next/link'++const i18nPrefix = 'nodes.agent'+type AgentRosterDrawerMode = 'setup' | 'detail'++type AgentRosterDisplayData = {+ description?: string | null+ icon?: string | null+ icon_background?: string | null+ icon_type?: string | null+ id: string+ name: string+ role?: string | null+}++const getAppIconType = (iconType?: string | null): AppIconType | null => {+ if (iconType === 'emoji' || iconType === 'image' || iconType === 'link')+ return iconType++ return null+}++function AgentRosterAvatar({+ agent,+ size = 'lg',+ className,+}: {+ agent: AgentRosterDisplayData+ size?: 'xs' | 'md' | 'lg'+ className?: string+}) {+ const iconSize = size === 'md' ? 'medium' : size === 'xs' ? 'tiny' : 'small'++ return (+ <AppIcon+ size={iconSize}+ iconType={getAppIconType(agent.icon_type)}+ icon={agent.icon ?? undefined}+ background={agent.icon_background}+ imageUrl={agent.icon ?? undefined}+ className={className}+ />+ )+}++function InlineSetupAvatar({+ className,+}: {+ className?: string+}) {+ return (+ <span className={cn('flex size-8 shrink-0 items-center justify-center rounded-full bg-background-default-burn', className)}>+ <span aria-hidden className="i-custom-vender-agent-v2-robot-3 size-5 text-text-tertiary" />+ </span>+ )+}++function AgentRosterDrawer({+ agent,+ children,+ mode = 'detail',+ open,+ portalContainerRef,+ showConsoleLink = true,+ showDetailActions = true,+ onClose,+}: {+ agent: AgentRosterDisplayData+ children?: ReactNode+ mode?: AgentRosterDrawerMode+ open: boolean+ portalContainerRef: RefObject<HTMLDivElement | null>+ showConsoleLink?: boolean+ showDetailActions?: boolean+ onClose: () => void+}) {+ const { t } = useTranslation()+ const isSetup = mode === 'setup'+ const title = isSetup ? t(`${i18nPrefix}.roster.inlineSetup.title`, { ns: 'workflow' }) : agent.name+ const description = isSetup ? t(`${i18nPrefix}.roster.inlineSetup.description`, { ns: 'workflow' }) : agent.role++ return (+ <Drawer+ open={open}+ modal={false}+ disablePointerDismissal+ swipeDirection="right"+ onOpenChange={(nextOpen) => {+ if (!nextOpen)+ onClose()+ }}+ >+ <DrawerPortal container={portalContainerRef}>+ <DrawerViewport className="pointer-events-none">+ <DrawerPopup+ className="pointer-events-auto p-0 data-[swipe-direction=right]:top-14 data-[swipe-direction=right]:bottom-1 data-[swipe-direction=right]:h-auto data-[swipe-direction=right]:rounded-2xl data-[swipe-direction=right]:border-[0.5px] data-[swipe-direction=right]:border-r-[0.5px] data-[swipe-direction=right]:border-divider-subtle data-[swipe-direction=right]:shadow-2xl data-[swipe-direction=right]:shadow-shadow-shadow-5"+ style={{+ right: 'var(--workflow-node-panel-right, 4px)',+ width: 'var(--workflow-node-panel-width, 400px)',+ }}+ >+ <DrawerContent className="flex h-full min-h-0 flex-1 flex-col overflow-hidden p-0 pb-0">+ <header+ className={cn(+ 'flex shrink-0 flex-col border-b border-divider-subtle bg-components-panel-bg',+ isSetup+ ? 'h-16 px-4 py-3'+ : showDetailActions+ ? 'h-[108px] gap-3 py-3 pr-4 pl-3'+ : 'py-3 pr-4 pl-3',+ )}+ >+ <div className="flex min-w-0 items-start justify-between">+ <div className={cn('flex min-w-0 flex-1', isSetup ? 'min-w-px flex-col' : 'h-10 items-center gap-2 px-0.5 py-0.5')}>+ {!isSetup && <AgentRosterAvatar agent={agent} size="md" className="size-9" />}+ <div className={cn('flex min-w-0 flex-1 flex-col', isSetup ? '' : 'gap-0.5 py-px')}>+ <div className="flex min-w-0 items-center gap-1">+ <DrawerTitle className={cn('truncate', isSetup ? 'system-xl-semibold text-text-primary' : 'system-sm-medium text-text-secondary')}>+ {title}+ </DrawerTitle>+ {!isSetup && <span aria-hidden className="i-ri-lock-line size-3 shrink-0 text-text-tertiary" />}+ </div>+ {description && (+ <p className={cn(isSetup ? 'min-w-full' : 'truncate', 'system-xs-regular text-text-tertiary')}>+ {description}+ </p>+ )}+ </div>+ </div>+ <div className="flex shrink-0 items-center gap-1 py-1">+ <button+ type="button"+ aria-label={t(`${i18nPrefix}.roster.more`, { ns: 'workflow' })}+ className="flex size-6 cursor-pointer items-center justify-center rounded-md text-text-tertiary hover:bg-state-base-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"+ >+ <span aria-hidden className="i-ri-more-fill size-4" />+ </button>+ <div className="flex h-3.5 items-start px-1">+ <div className="h-full w-px bg-divider-regular" />+ </div>+ <DrawerCloseButton+ aria-label={t('operation.close', { ns: 'common' })}+ className="size-6 rounded-md"+ />+ </div>+ </div>+ {!isSetup && showDetailActions && (+ <div className="flex h-8 gap-2 pl-1">+ {showConsoleLink && (+ <Link+ href={getAgentDetailPath(agent.id, 'configure')}+ className="inline-flex h-8 min-w-0 flex-1 cursor-pointer items-center justify-center gap-1.5 rounded-lg border-[0.5px] border-components-button-secondary-border bg-components-button-secondary-bg px-3 text-[13px] leading-4 font-medium whitespace-nowrap text-components-button-secondary-text shadow-xs outline-hidden backdrop-blur-[5px] hover:border-components-button-secondary-border-hover hover:bg-components-button-secondary-bg-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid"+ >+ <span aria-hidden className="i-ri-external-link-line size-4 shrink-0" />+ <span className="truncate">+ {t(`${i18nPrefix}.roster.editInConsole`, { ns: 'workflow' })}+ </span>+ </Link>+ )}+ <Button+ variant="secondary"+ size="medium"+ className="min-w-0 flex-1 gap-1.5 px-3"+ >+ <span aria-hidden className="i-ri-file-copy-2-line size-4 shrink-0" />+ <span className="truncate">+ {t(`${i18nPrefix}.roster.makeCopy`, { ns: 'workflow' })}+ </span>+ </Button>+ </div>+ )}+ </header>+ <div+ role="region"+ aria-label={t(`${i18nPrefix}.roster.panelLabel`, { ns: 'workflow', name: agent.name })}+ className="min-h-0 flex-1 overflow-hidden bg-components-panel-bg"+ >+ {children ?? <div className="h-full min-h-80 bg-components-panel-bg" />}+ </div>+ </DrawerContent>+ </DrawerPopup>+ </DrawerViewport>+ </DrawerPortal>+ </Drawer>+ )+}++export function AgentRosterField({+ agent,+ agentId,+ canOpenPanel = true,+ isPanelOpen,+ isPending = false,+ isLoading = false,+ isInlineSetup = false,+ panelBody,+ panelMode = 'detail',+ showPanelDetailActions = true,+ portalContainerRef,+ onChange,+ onPanelOpenChange,+}: {+ agent?: AgentRosterDisplayData+ agentId?: string+ canOpenPanel?: boolean+ isPanelOpen?: boolean+ isLoading?: boolean+ isInlineSetup?: boolean+ isPending?: boolean+ panelBody?: ReactNode+ panelMode?: AgentRosterDrawerMode+ showPanelDetailActions?: boolean+ portalContainerRef: RefObject<HTMLDivElement | null>+ onChange: (agent: AgentRosterNodeData) => void+ onPanelOpenChange?: (open: boolean) => void+}) {+ const { t } = useTranslation()+ const [localPanelOpen, setLocalPanelOpen] = useState(false)+ const [isSelectorOpen, setIsSelectorOpen] = useState(false)+ const panelOpen = isPanelOpen ?? localPanelOpen+ const setPanelOpen = onPanelOpenChange ?? setLocalPanelOpen+ const inlineSetupName = t(`${i18nPrefix}.roster.inlineSetup.name`, { ns: 'workflow' })+ const inlineSetupType = t(`${i18nPrefix}.roster.inlineSetup.type`, { ns: 'workflow' })+ const rosterRequiredMessage = t('errorMsg.fieldRequired', {+ ns: 'workflow',+ field: t(`${i18nPrefix}.roster.label`, { ns: 'workflow' }),+ })+ const agentContent = agent+ ? (+ <>+ {isInlineSetup ? <InlineSetupAvatar /> : <AgentRosterAvatar agent={agent} />}+ <span className="flex min-w-0 flex-1 flex-col gap-0.5 py-px">+ <span className="truncate system-sm-medium text-text-secondary">+ {isInlineSetup ? inlineSetupName : agent.name}+ </span>+ <span className="truncate system-xs-regular text-text-tertiary">+ {isInlineSetup ? inlineSetupType : agent.role}+ </span>+ </span>+ </>+ )+ : null+ const loadingContent = (+ <>+ <span aria-hidden className="size-8 shrink-0 rounded-lg bg-text-quaternary/20" />+ <span aria-hidden className="flex min-w-0 flex-1 flex-col gap-1.5">+ <span className="h-2.5 w-24 rounded-xs bg-text-quaternary/20" />+ <span className="h-2 w-16 rounded-xs bg-text-quaternary/15" />+ </span>+ </>+ )++ return (+ <FieldRoot name="agent_binding" className="gap-1 px-4 py-2">+ <div className="flex h-6 items-center gap-2">+ <FieldLabel className="min-w-0 flex-1 py-1 system-sm-semibold-uppercase! text-text-secondary">+ {t('nodes.agent.roster.label', { ns: 'workflow' })}+ </FieldLabel>+ <Popover+ open={isPending ? false : isSelectorOpen}+ onOpenChange={(open) => {+ if (!isPending)+ setIsSelectorOpen(open)+ }}+ >+ <PopoverTrigger+ render={(+ <button+ type="button"+ disabled={isPending}+ className={cn('flex h-6 shrink-0 cursor-pointer items-center justify-center rounded-md px-1.5 py-1 system-xs-medium text-text-tertiary hover:bg-state-base-hover hover:text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden', isPending && 'cursor-not-allowed opacity-50 hover:bg-transparent hover:text-text-tertiary')}+ >+ {t(`${i18nPrefix}.roster.change`, { ns: 'workflow' })}+ </button>+ )}+ />+ <PopoverContent+ placement="bottom-end"+ sideOffset={4}+ popupClassName="border-none bg-transparent p-0 shadow-none backdrop-blur-none"+ >+ <PopoverTitle className="sr-only">+ {t('roster.nodeSelector.dialogLabel', { ns: 'agentV2' })}+ </PopoverTitle>+ <AgentSelectorContent+ open={isSelectorOpen}+ onOpenChange={setIsSelectorOpen}+ onSelect={(nextAgent) => {+ setIsSelectorOpen(false)+ onChange(nextAgent)+ }}+ />+ </PopoverContent>+ </Popover>+ </div>+ {agent+ ? (+ canOpenPanel+ ? (+ <>+ <button+ type="button"+ aria-label={t(`${i18nPrefix}.roster.openPanel`, { ns: 'workflow', name: isInlineSetup ? inlineSetupName : agent.name })}+ aria-busy={isLoading || undefined}+ className="flex h-13 w-full min-w-0 cursor-pointer items-center gap-2 rounded-[10px] border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg py-2 pr-4 pl-2 text-left shadow-xs shadow-shadow-shadow-3 hover:bg-components-panel-on-panel-item-bg-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"+ onClick={() => setPanelOpen(true)}+ >+ {isLoading ? loadingContent : agentContent}+ <span className="flex shrink-0 items-center text-text-tertiary">+ <span aria-hidden className="i-ri-arrow-right-line size-4" />+ </span>+ </button>+ <AgentRosterDrawer+ agent={agent}+ mode={panelMode}+ open={panelOpen}+ portalContainerRef={portalContainerRef}+ showDetailActions={showPanelDetailActions}+ onClose={() => setPanelOpen(false)}+ >+ {panelBody}+ </AgentRosterDrawer>+ </>+ )+ : (+ <div className="flex h-13 w-full min-w-0 items-center gap-2 rounded-[10px] border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg py-2 pr-4 pl-2 text-left shadow-xs shadow-shadow-shadow-3">+ {agentContent}+ </div>+ )+ )+ : isPending || agentId+ ? (+ <div aria-busy="true" className="flex h-13 w-full min-w-0 items-center gap-2 rounded-[10px] border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg py-2 pr-4 pl-2 text-left shadow-xs shadow-shadow-shadow-3">+ {loadingContent}+ </div>+ )+ : (+ <div className="flex h-13 w-full min-w-0 items-center gap-2 rounded-[10px] border-[0.5px] border-state-destructive-border bg-components-panel-on-panel-item-bg py-2 pr-4 pl-2 text-left shadow-xs shadow-shadow-shadow-3">+ <span className="flex size-8 shrink-0 items-center justify-center rounded-lg bg-state-destructive-hover text-text-destructive">+ <span aria-hidden className="i-ri-error-warning-line size-4" />+ </span>+ <span className="min-w-0 flex-1 truncate system-sm-medium text-text-destructive">+ {rosterRequiredMessage}+ </span>+ </div>+ )}+ </FieldRoot>+ )+}diff --git a/web/app/components/workflow/nodes/agent-v2/components/agent-task-field.tsx b/web/app/components/workflow/nodes/agent-v2/components/agent-task-field.tsxnew file mode 100644index 00000000000..7ae37e81dea--- /dev/null+++ b/web/app/components/workflow/nodes/agent-v2/components/agent-task-field.tsx@@ -0,0 +1,152 @@+import type { DeclaredOutputConfig } from '@dify/contracts/api/console/apps/types.gen'+import type { AgentV2NodeType } from '../types'+import type { WorkflowNodesMap } from '@/app/components/base/prompt-editor/types'+import { cn } from '@langgenius/dify-ui/cn'+import { FieldLabel, FieldRoot } from '@langgenius/dify-ui/field'+import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'+import { useBoolean } from 'ahooks'+import { $insertNodes } from 'lexical'+import { useCallback } from 'react'+import { useTranslation } from 'react-i18next'+import { Infotip } from '@/app/components/base/infotip'+import PromptEditor from '@/app/components/base/prompt-editor'+import { $createCustomTextNode } from '@/app/components/base/prompt-editor/plugins/custom-text/node'+import { useWorkflowVariableType } from '../../../hooks'+import { BlockEnum } from '../../../types'+import useAvailableVarList from '../../_base/hooks/use-available-var-list'++const i18nPrefix = 'nodes.agent'++function AgentTaskToolbar({+ taskLength,+ onInsert,+}: {+ taskLength: number+ onInsert: () => void+}) {+ const { t } = useTranslation()+ const [editor] = useLexicalComposerContext()++ const handleInsert = useCallback(() => {+ onInsert()+ editor.focus()+ editor.update(() => {+ $insertNodes([$createCustomTextNode('/')])+ })+ }, [editor, onInsert])++ return (+ <div className="flex h-8 shrink-0 items-center justify-between px-3 text-text-tertiary">+ <div className="flex min-w-0 items-center gap-3">+ <button+ type="button"+ className="flex items-center gap-1 system-xs-medium hover:text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"+ onClick={handleInsert}+ >+ <span aria-hidden className="i-ri-slash-commands-2 size-3.5" />+ {t(`${i18nPrefix}.task.insert`, { ns: 'workflow' })}+ </button>+ </div>+ <div className="rounded-sm border border-divider-regular bg-background-default px-1 system-2xs-regular text-text-tertiary">+ {taskLength}+ </div>+ </div>+ )+}++export function AgentTaskField({+ id,+ data,+ readOnly,+ onChange,+ outputs,+ onOutputsChange,+}: {+ id: string+ data: AgentV2NodeType+ readOnly?: boolean+ onChange: (value: string) => void+ outputs: DeclaredOutputConfig[]+ onOutputsChange: (outputs: DeclaredOutputConfig[], prompt?: string) => void+}) {+ const { t } = useTranslation()+ const getVarType = useWorkflowVariableType()+ const {+ availableVars,+ availableNodesWithParent,+ } = useAvailableVarList(id)+ const [isFocus, {+ setTrue: setFocus,+ setFalse: setBlur,+ }] = useBoolean(false)++ const workflowNodesMap = availableNodesWithParent.reduce<WorkflowNodesMap>((acc, node) => {+ acc[node.id] = {+ title: node.data.title,+ type: node.data.type,+ width: node.width ?? undefined,+ height: node.height ?? undefined,+ position: node.position,+ }+ if (node.data.type === BlockEnum.Start) {+ acc.sys = {+ title: t('blocks.start', { ns: 'workflow' }),+ type: BlockEnum.Start,+ }+ }+ return acc+ }, {})++ return (+ <FieldRoot name="agent_task" className="gap-1 px-4 py-2">+ <div className="flex h-6 items-center gap-1">+ <FieldLabel className="min-w-0 py-1 system-sm-semibold-uppercase! text-text-secondary">+ {t(`${i18nPrefix}.task.label`, { ns: 'workflow' })}+ </FieldLabel>+ <Infotip aria-label={t(`${i18nPrefix}.task.tooltip`, { ns: 'workflow' })}>+ {t(`${i18nPrefix}.task.tooltip`, { ns: 'workflow' })}+ </Infotip>+ </div>+ <div+ className={cn(+ 'h-80 rounded-[9px]! p-0.5',+ isFocus ? 'bg-linear-to-r from-components-input-border-active-prompt-1 to-components-input-border-active-prompt-2' : 'bg-transparent',+ readOnly && 'pointer-events-none',+ )}+ >+ <div className={cn('flex h-full flex-col rounded-lg', isFocus ? 'bg-background-default' : 'bg-components-input-bg-normal')}>+ <PromptEditor+ wrapperClassName="flex h-full flex-col"+ value={data.agent_task || ''}+ onChange={onChange}+ editable={!readOnly}+ compact+ className="min-h-0 flex-1 overflow-y-auto px-3 py-2"+ placeholderClassName="px-3 py-2"+ placeholder={t(`${i18nPrefix}.task.placeholder`, { ns: 'workflow' })}+ onFocus={setFocus}+ onBlur={setBlur}+ workflowVariableBlock={{+ show: true,+ variables: availableVars,+ getVarType,+ workflowNodesMap,+ }}+ agentOutputBlock={{+ show: true,+ outputs,+ onChange: onOutputsChange,+ }}+ >+ {isFocus && (+ <AgentTaskToolbar+ taskLength={(data.agent_task || '').length}+ onInsert={setFocus}+ />+ )}+ </PromptEditor>+ </div>+ </div>+ </FieldRoot>+ )+}diff --git a/web/app/components/workflow/nodes/agent-v2/default.ts b/web/app/components/workflow/nodes/agent-v2/default.tsnew file mode 100644index 00000000000..d1575b32f07--- /dev/null+++ b/web/app/components/workflow/nodes/agent-v2/default.ts@@ -0,0 +1,36 @@+import type { NodeDefault } from '../../types'+import type { AgentV2NodeType } from './types'+import { BlockEnum } from '../../types'+import { genNodeMetaData } from '../../utils'+import { hasValidAgentBinding } from './types'++const metaData = genNodeMetaData({+ sort: 3,+ type: BlockEnum.AgentV2,+})++const nodeDefault: NodeDefault<AgentV2NodeType> = {+ metaData,+ defaultValue: {+ agent_node_kind: 'dify_agent',+ version: '2',+ },+ checkValid(payload, t) {+ if (!hasValidAgentBinding(payload)) {+ return {+ isValid: false,+ errorMessage: t('errorMsg.fieldRequired', {+ ns: 'workflow',+ field: t('nodes.agent.roster.label', { ns: 'workflow' }),+ }),+ }+ }++ return {+ isValid: true,+ errorMessage: '',+ }+ },+}++export default nodeDefaultdiff --git a/web/app/components/workflow/nodes/agent-v2/hooks.ts b/web/app/components/workflow/nodes/agent-v2/hooks.tsnew file mode 100644index 00000000000..6d9bbbd3d44--- /dev/null+++ b/web/app/components/workflow/nodes/agent-v2/hooks.ts@@ -0,0 +1,114 @@+import type { AgentInlineBinding } from '../../block-selector/types'+import { toast } from '@langgenius/dify-ui/toast'+import { skipToken, useMutation, useQuery } from '@tanstack/react-query'+import { useCallback } from 'react'+import { useTranslation } from 'react-i18next'+import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'+import { useDefaultModel } from '@/app/components/header/account-setting/model-provider-page/hooks'+import { useHooksStore } from '@/app/components/workflow/hooks-store'+import { consoleQuery } from '@/service/client'+import { FlowType } from '@/types/common'+import { getDefaultAgentSoul } from './agent-soul-config'++type CreatedInlineAgentBinding = AgentInlineBinding & {+ agent_id: string+ current_snapshot_id: string+}++type CreateInlineAgentBindingOptions = {+ onError?: () => void+ onSuccess?: (binding: CreatedInlineAgentBinding) => void+}++export function useAgentRosterDetail(agentId?: string) {+ return useQuery(consoleQuery.agent.byAgentId.get.queryOptions({+ input: agentId+ ? {+ params: {+ agent_id: agentId,+ },+ }+ : skipToken,+ }))+}++export function useWorkflowInlineAgentDetail(nodeId?: string, agentId?: string | null) {+ const configsMap = useHooksStore(state => state.configsMap)++ return useQuery(consoleQuery.apps.byAppId.workflows.draft.nodes.byNodeId.agentComposer.get.queryOptions({+ input: configsMap?.flowId && configsMap.flowType === FlowType.appFlow && nodeId && agentId+ ? {+ params: {+ app_id: configsMap.flowId,+ node_id: nodeId,+ },+ }+ : skipToken,+ }))+}++export function useCreateInlineAgentBinding() {+ const { t } = useTranslation('agentV2')+ const configsMap = useHooksStore(state => state.configsMap)+ const { data: defaultModel } = useDefaultModel(ModelTypeEnum.textGeneration)+ const {+ isPending,+ mutate,+ } = useMutation(+ consoleQuery.apps.byAppId.workflows.draft.nodes.byNodeId.agentComposer.put.mutationOptions(),+ )++ const createInlineAgentBinding = useCallback((nodeId: string, options?: CreateInlineAgentBindingOptions) => {+ if (!configsMap?.flowId || configsMap.flowType !== FlowType.appFlow) {+ toast.error(t('roster.nodeSelector.createInlineFailed'))+ options?.onError?.()+ return+ }++ mutate(+ {+ params: {+ app_id: configsMap.flowId,+ node_id: nodeId,+ },+ body: {+ variant: 'workflow',+ save_strategy: 'node_job_only',+ soul_lock: {+ locked: false,+ },+ agent_soul: getDefaultAgentSoul(defaultModel),+ },+ },+ {+ onSuccess: (composerState) => {+ const binding = composerState.binding++ if (+ binding?.binding_type !== 'inline_agent'+ || !binding.agent_id+ || !binding.current_snapshot_id+ ) {+ toast.error(t('roster.nodeSelector.createInlineFailed'))+ options?.onError?.()+ return+ }++ options?.onSuccess?.({+ binding_type: 'inline_agent',+ agent_id: binding.agent_id,+ current_snapshot_id: binding.current_snapshot_id,+ })+ },+ onError: () => {+ options?.onError?.()+ },+ },+ )+ }, [configsMap?.flowId, configsMap?.flowType, defaultModel, mutate, t])++ return {+ createInlineAgentBinding,+ isCreatingInlineAgent: isPending,+ }+}diff --git a/web/app/components/workflow/nodes/agent-v2/node.tsx b/web/app/components/workflow/nodes/agent-v2/node.tsxnew file mode 100644index 00000000000..95e0c03ecfd--- /dev/null+++ b/web/app/components/workflow/nodes/agent-v2/node.tsx@@ -0,0 +1,126 @@+import type { NodeProps } from '../../types'+import type { AgentV2NodeType } from './types'+import type { AppIconType } from '@/types/app'+import { useTranslation } from 'react-i18next'+import AppIcon from '@/app/components/base/app-icon'+import { SettingItem } from '../_base/components/setting-item'+import { useAgentRosterDetail, useWorkflowInlineAgentDetail } from './hooks'+import { hasInlineAgentBinding, hasValidRosterAgentBinding } from './types'++const getAppIconType = (iconType?: string | null): AppIconType | null => {+ if (iconType === 'emoji' || iconType === 'image' || iconType === 'link')+ return iconType++ return null+}++function AgentNodeAvatar({+ agent,+ isInlineAgent,+}: {+ agent?: ReturnType<typeof useAgentRosterDetail>['data']+ isInlineAgent: boolean+}) {+ if (isInlineAgent) {+ return (+ <span className="flex size-8 shrink-0 items-center justify-center rounded-full bg-background-default-burn text-text-tertiary">+ <span aria-hidden className="i-custom-vender-agent-v2-robot-3 size-5" />+ </span>+ )+ }++ if (!agent)+ return <span aria-hidden className="size-8 shrink-0 rounded-full bg-text-quaternary/20" />++ return (+ <AppIcon+ size="small"+ iconType={getAppIconType(agent.icon_type)}+ icon={agent.icon ?? undefined}+ background={agent.icon_background}+ imageUrl={agent.icon ?? undefined}+ />+ )+}++function AgentNodeAvatarPlaceholder() {+ return <span aria-hidden className="size-8 shrink-0 rounded-full bg-text-quaternary/20" />+}++function AgentNodeModel({+ data,+ agent,+ inlineAgentName,+ isLoading,+}: {+ data: AgentV2NodeType+ agent?: ReturnType<typeof useAgentRosterDetail>['data']+ inlineAgentName?: string+ isLoading: boolean+}) {+ const { t } = useTranslation()+ const isInlineAgent = hasInlineAgentBinding(data)+ const name = isInlineAgent ? (inlineAgentName || t('nodes.agent.roster.inlineSetup.name', { ns: 'workflow' })) : agent?.name+ const role = isInlineAgent ? t('nodes.agent.roster.inlineSetup.type', { ns: 'workflow' }) : ''+ const showPlaceholder = isLoading || (!isInlineAgent && !agent)++ return (+ <div className="flex flex-col gap-0.5 py-1">+ <div className="px-2.5 py-0.5 system-2xs-medium-uppercase text-text-tertiary">+ {t('nodes.agent.roster.label', { ns: 'workflow' })}+ </div>+ <div className="px-2.5">+ <div className="flex min-w-0 items-center gap-1 rounded-lg bg-workflow-block-parma-bg p-1">+ {showPlaceholder+ ? <AgentNodeAvatarPlaceholder />+ : <AgentNodeAvatar agent={agent} isInlineAgent={isInlineAgent} />}+ <div className="flex min-w-0 flex-1 flex-col justify-center">+ {showPlaceholder+ ? (+ <div aria-hidden className="flex flex-col gap-1.5 py-0.5">+ <span className="h-2 w-20 rounded-xs bg-text-quaternary/20" />+ <span className="h-2 w-14 rounded-xs bg-text-quaternary/15" />+ </div>+ )+ : (+ <>+ <div className="truncate system-xs-regular text-text-secondary">+ {name}+ </div>+ <div className="truncate system-2xs-regular text-text-tertiary">+ {role}+ </div>+ </>+ )}+ </div>+ </div>+ </div>+ </div>+ )+}++export function AgentV2Node({ id, data }: NodeProps<AgentV2NodeType>) {+ const { t } = useTranslation()+ const hasValidAgent = hasValidRosterAgentBinding(data)+ const isInlineAgent = hasInlineAgentBinding(data)+ const rosterAgentId = data.agent_binding?.binding_type === 'roster_agent' ? data.agent_binding.agent_id : undefined+ const inlineAgentId = data.agent_binding?.binding_type === 'inline_agent' ? data.agent_binding.agent_id : undefined+ const rosterAgentQuery = useAgentRosterDetail(rosterAgentId)+ const inlineAgentQuery = useWorkflowInlineAgentDetail(id, inlineAgentId)+ const isInlineAgentDetailLoading = isInlineAgent && !!inlineAgentId && inlineAgentQuery.isPending++ if (isInlineAgent || hasValidAgent)+ return <AgentNodeModel data={data} agent={rosterAgentQuery.data} inlineAgentName={inlineAgentQuery.data?.agent?.name} isLoading={isInlineAgentDetailLoading} />++ return (+ <div className="mb-1 space-y-1 px-3">+ <SettingItem+ label={t('nodes.agent.roster.label', { ns: 'workflow' })}+ status={hasValidAgent ? undefined : 'error'}+ tooltip={hasValidAgent ? undefined : t('errorMsg.fieldRequired', { ns: 'workflow', field: t('nodes.agent.roster.label', { ns: 'workflow' }) })}+ >+ {rosterAgentQuery.data?.name}+ </SettingItem>+ </div>+ )+}diff --git a/web/app/components/workflow/nodes/agent-v2/output-variables.ts b/web/app/components/workflow/nodes/agent-v2/output-variables.tsnew file mode 100644index 00000000000..b2c8fec6e44--- /dev/null+++ b/web/app/components/workflow/nodes/agent-v2/output-variables.ts@@ -0,0 +1,86 @@+import type { DeclaredOutputConfig } from '@dify/contracts/api/console/apps/types.gen'+import type { AgentV2NodeType } from './types'+import type { Var } from '@/app/components/workflow/types'+import { VarType } from '@/app/components/workflow/types'++export const defaultAgentV2DeclaredOutputs: DeclaredOutputConfig[] = [+ {+ name: 'text',+ type: 'string',+ required: false,+ description: 'Free-form text answer.',+ },+ {+ name: 'files',+ type: 'array',+ required: false,+ description: 'Files produced by the agent.',+ array_item: {+ type: 'file',+ },+ },+ {+ name: 'json',+ type: 'object',+ required: false,+ description: 'Free-form JSON object.',+ },+]++const outputTypeLabels: Record<DeclaredOutputConfig['type'], string> = {+ array: 'Array',+ boolean: 'Boolean',+ file: 'File',+ number: 'Number',+ object: 'Object',+ string: 'String',+}++const outputVarTypes: Record<DeclaredOutputConfig['type'], VarType> = {+ array: VarType.array,+ boolean: VarType.boolean,+ file: VarType.file,+ number: VarType.number,+ object: VarType.object,+ string: VarType.string,+}++const arrayItemVarTypes: Record<DeclaredOutputConfig['type'], VarType> = {+ array: VarType.array,+ boolean: VarType.arrayBoolean,+ file: VarType.arrayFile,+ number: VarType.arrayNumber,+ object: VarType.arrayObject,+ string: VarType.arrayString,+}++export function getAgentV2DeclaredOutputs(data: AgentV2NodeType) {+ return data.agent_declared_outputs?.length+ ? data.agent_declared_outputs+ : defaultAgentV2DeclaredOutputs+}++/**+ * @public+ */+// TODO: Remove this marker after the output type label consumer is wired.+export function getDeclaredOutputTypeLabel(output: DeclaredOutputConfig) {+ if (output.type === 'array')+ return `Array[${output.array_item ? outputTypeLabels[output.array_item.type] : 'Object'}]`++ return outputTypeLabels[output.type]+}++function getDeclaredOutputVarType(output: DeclaredOutputConfig) {+ if (output.type === 'array')+ return output.array_item ? arrayItemVarTypes[output.array_item.type] : VarType.arrayObject++ return outputVarTypes[output.type]+}++export function getAgentV2OutputVars(data: AgentV2NodeType): Var[] {+ return getAgentV2DeclaredOutputs(data).map(output => ({+ variable: output.name,+ type: getDeclaredOutputVarType(output),+ }))+}diff --git a/web/app/components/workflow/nodes/agent-v2/panel.tsx b/web/app/components/workflow/nodes/agent-v2/panel.tsxnew file mode 100644index 00000000000..371b2d847ee--- /dev/null+++ b/web/app/components/workflow/nodes/agent-v2/panel.tsx@@ -0,0 +1,216 @@+import type { AgentRosterNodeData } from '../../block-selector/types'+import type { NodePanelProps } from '../../types'+import type { AgentV2NodeType } from './types'+import { produce } from 'immer'+import { useCallback, useEffect, useRef, useState } from 'react'+import { useTranslation } from 'react-i18next'+import {+ extractAgentOutputNames,+ replaceAgentOutputName,+} from '@/app/components/base/prompt-editor/plugins/agent-output-block/utils'+import { useNodeDataUpdate } from '@/app/components/workflow/hooks'+import { useStore } from '@/app/components/workflow/store'+import useNodeCrud from '../_base/hooks/use-node-crud'+import { AgentAdvancedSettings } from './components/agent-advanced-settings'+import { AgentOrchestrateDrawerPanel } from './components/agent-orchestrate-drawer-panel'+import { AgentOutputVariables } from './components/agent-output-variables'+import { AgentRosterField } from './components/agent-roster-field'+import { AgentTaskField } from './components/agent-task-field'+import { useAgentRosterDetail, useWorkflowInlineAgentDetail } from './hooks'+import { getAgentV2DeclaredOutputs } from './output-variables'+import { hasValidInlineAgentBinding } from './types'++export function AgentV2Panel({+ id,+ data,+}: NodePanelProps<AgentV2NodeType>) {+ const { t } = useTranslation()+ const { inputs, setInputs } = useNodeCrud<AgentV2NodeType>(id, data)+ const inputsRef = useRef(inputs)+ const promptOutputNamesRef = useRef(extractAgentOutputNames(inputs.agent_task || ''))+ const [isRosterAgentPanelOpen, setIsRosterAgentPanelOpen] = useState(false)+ const [isInlineAgentPanelOpenedFromTrigger, setIsInlineAgentPanelOpenedFromTrigger] = useState(false)+ const { handleNodeDataUpdate, handleNodeDataUpdateWithSyncDraft } = useNodeDataUpdate()+ const openInlineAgentPanelNodeId = useStore(state => state.openInlineAgentPanelNodeId)+ const setOpenInlineAgentPanelNodeId = useStore(state => state.setOpenInlineAgentPanelNodeId)+ const drawerPortalContainerRef = useRef<HTMLDivElement>(null)+ const declaredOutputs = getAgentV2DeclaredOutputs(inputs)+ const rosterAgentId = inputs.agent_binding?.binding_type === 'roster_agent' ? inputs.agent_binding.agent_id : undefined+ const inlineAgentId = inputs.agent_binding?.binding_type === 'inline_agent' ? inputs.agent_binding.agent_id : undefined+ const isInlineAgentReady = hasValidInlineAgentBinding(inputs)+ const isInlineAgentPending = inputs.agent_binding?.binding_type === 'inline_agent' && !isInlineAgentReady+ const isInlineAgentPanelOpen = isInlineAgentReady && openInlineAgentPanelNodeId === id+ const rosterAgentQuery = useAgentRosterDetail(rosterAgentId)+ const inlineAgentQuery = useWorkflowInlineAgentDetail(id, inlineAgentId)+ const inlineAgent = inlineAgentQuery.data?.agent+ const isAgentPanelOpen = isInlineAgentReady ? isInlineAgentPanelOpen : isRosterAgentPanelOpen+ const isInlineAgentLoading = isInlineAgentReady && !inlineAgent+ const displayedAgent = rosterAgentQuery.data ?? (inlineAgentId && isInlineAgentReady+ ? {+ id: inlineAgentId,+ name: inlineAgent?.name || t('nodes.agent.roster.inlineSetup.name', { ns: 'workflow' }),+ description: inlineAgent?.description,+ role: t('nodes.agent.roster.inlineSetup.type', { ns: 'workflow' }),+ }+ : undefined)++ useEffect(() => {+ inputsRef.current = inputs+ promptOutputNamesRef.current = extractAgentOutputNames(inputs.agent_task || '')+ }, [inputs])++ useEffect(() => {+ if (!inputs._openInlineAgentPanel || !isInlineAgentReady)+ return++ setOpenInlineAgentPanelNodeId(id)+ handleNodeDataUpdate({+ id,+ data: {+ _openInlineAgentPanel: false,+ },+ })+ }, [handleNodeDataUpdate, id, inputs._openInlineAgentPanel, isInlineAgentReady, setOpenInlineAgentPanelNodeId])++ const handleTaskChange = useCallback((value: string) => {+ const currentPromptOutputNames = extractAgentOutputNames(value)+ const removedPromptOutputNames = [...promptOutputNamesRef.current].filter(name => !currentPromptOutputNames.has(name))+ const newInputs = produce(inputsRef.current, (draft) => {+ draft.agent_task = value+ if (removedPromptOutputNames.length) {+ const removedNameSet = new Set(removedPromptOutputNames)+ draft.agent_declared_outputs = getAgentV2DeclaredOutputs(draft)+ .filter(output => !removedNameSet.has(output.name))+ }+ })+ inputsRef.current = newInputs+ promptOutputNamesRef.current = currentPromptOutputNames+ setInputs(newInputs)+ }, [setInputs])++ const handleRosterChange = useCallback((agent: AgentRosterNodeData) => {+ setOpenInlineAgentPanelNodeId(undefined)+ const newInputs = produce(inputs, (draft) => {+ delete (draft as AgentV2NodeType & { agent_roster?: unknown }).agent_roster+ draft.agent_binding = {+ binding_type: 'roster_agent',+ agent_id: agent.id,+ }+ })+ handleNodeDataUpdateWithSyncDraft(+ {+ id,+ data: newInputs,+ },+ {+ sync: true,+ notRefreshWhenSyncError: true,+ },+ )+ }, [handleNodeDataUpdateWithSyncDraft, id, inputs, setOpenInlineAgentPanelNodeId])++ const handleAgentPanelOpenChange = useCallback((open: boolean) => {+ if (isInlineAgentReady) {+ if (open)+ setIsInlineAgentPanelOpenedFromTrigger(true)++ setOpenInlineAgentPanelNodeId(open ? id : undefined)+ return+ }++ setIsRosterAgentPanelOpen(open)+ }, [id, isInlineAgentReady, setOpenInlineAgentPanelNodeId])++ const handleDeclaredOutputsChange = useCallback((outputs: ReturnType<typeof getAgentV2DeclaredOutputs>, agentTask?: string) => {+ const previousOutputs = getAgentV2DeclaredOutputs(inputsRef.current)+ let nextAgentTask = agentTask+ if (nextAgentTask === undefined && previousOutputs.length === outputs.length) {+ const renamedOutputs = previousOutputs+ .map((previousOutput, index) => ({+ oldName: previousOutput.name,+ nextName: outputs[index]?.name,+ }))+ .filter(({ oldName, nextName }) => nextName && oldName !== nextName)++ if (renamedOutputs.length === 1) {+ const { oldName, nextName } = renamedOutputs[0]!+ const currentAgentTask = inputsRef.current.agent_task || ''+ if (extractAgentOutputNames(currentAgentTask).has(oldName))+ nextAgentTask = replaceAgentOutputName(currentAgentTask, oldName, nextName!)+ }+ }++ const newInputs = produce(inputsRef.current, (draft) => {+ draft.agent_declared_outputs = outputs+ if (nextAgentTask !== undefined)+ draft.agent_task = nextAgentTask+ })+ inputsRef.current = newInputs+ if (nextAgentTask !== undefined)+ promptOutputNamesRef.current = extractAgentOutputNames(nextAgentTask)+ handleNodeDataUpdateWithSyncDraft(+ {+ id,+ data: newInputs,+ },+ {+ sync: true,+ notRefreshWhenSyncError: true,+ },+ )+ }, [handleNodeDataUpdateWithSyncDraft, id])++ return (+ <div ref={drawerPortalContainerRef} className="pt-2">+ <div className="border-b border-divider-subtle">+ <AgentRosterField+ agent={displayedAgent}+ agentId={rosterAgentId ?? inlineAgentId ?? undefined}+ canOpenPanel={!isInlineAgentPending}+ isInlineSetup={isInlineAgentReady}+ isLoading={isInlineAgentLoading}+ isPanelOpen={isAgentPanelOpen}+ isPending={isInlineAgentPending}+ panelBody={isAgentPanelOpen && displayedAgent+ ? (+ <AgentOrchestrateDrawerPanel+ agentId={displayedAgent.id}+ inlineComposerState={inlineAgentQuery.data}+ isInline={isInlineAgentReady}+ nodeId={id}+ open={isAgentPanelOpen}+ />+ )+ : undefined}+ panelMode={isInlineAgentReady && !isInlineAgentPanelOpenedFromTrigger ? 'setup' : 'detail'}+ portalContainerRef={drawerPortalContainerRef}+ showPanelDetailActions={!isInlineAgentReady}+ onChange={handleRosterChange}+ onPanelOpenChange={handleAgentPanelOpenChange}+ />+ </div>+ <div+ aria-disabled={isInlineAgentPending}+ inert={isInlineAgentPending ? true : undefined}+ className={isInlineAgentPending ? 'pointer-events-none' : undefined}+ >+ <div className="border-b border-divider-subtle">+ <AgentTaskField+ id={id}+ data={inputs}+ outputs={declaredOutputs}+ onChange={handleTaskChange}+ onOutputsChange={handleDeclaredOutputsChange}+ />+ </div>+ <AgentAdvancedSettings />+ <div>+ <AgentOutputVariables+ outputs={declaredOutputs}+ onChange={handleDeclaredOutputsChange}+ />+ </div>+ </div>+ </div>+ )+}diff --git a/web/app/components/workflow/nodes/agent-v2/types.ts b/web/app/components/workflow/nodes/agent-v2/types.tsnew file mode 100644index 00000000000..41989ede16b--- /dev/null+++ b/web/app/components/workflow/nodes/agent-v2/types.ts@@ -0,0 +1,45 @@+import type { DeclaredOutputConfig } from '@dify/contracts/api/console/apps/types.gen'+import type { AgentBinding } from '@/app/components/workflow/block-selector/types'+import type { CommonNodeType } from '@/app/components/workflow/types'+import { BlockEnum } from '@/app/components/workflow/types'++export type AgentV2NodeType = CommonNodeType & {+ agent_binding?: AgentBinding+ agent_declared_outputs?: DeclaredOutputConfig[]+ agent_node_kind: 'dify_agent'+ agent_task?: string+ version: '2'+}++export function isAgentV2NodeData(data: CommonNodeType): data is AgentV2NodeType {+ const payload = data as { agent_node_kind?: string, version?: string }+ return (data.type === BlockEnum.Agent || data.type === BlockEnum.AgentV2)+ && payload.agent_node_kind === 'dify_agent'+ && payload.version === '2'+}++export function hasValidRosterAgentBinding(data: AgentV2NodeType) {+ return data.agent_binding?.binding_type === 'roster_agent'+ && typeof data.agent_binding.agent_id === 'string'+ && data.agent_binding.agent_id.length > 0+}++export function hasInlineAgentBinding(data: AgentV2NodeType) {+ return data.agent_binding?.binding_type === 'inline_agent'+}++export function hasValidInlineAgentBinding(data: AgentV2NodeType) {+ return data.agent_binding?.binding_type === 'inline_agent'+ && typeof data.agent_binding.agent_id === 'string'+ && data.agent_binding.agent_id.length > 0+ && typeof data.agent_binding.current_snapshot_id === 'string'+ && data.agent_binding.current_snapshot_id.length > 0+}++export function needsInlineAgentBindingCreation(data: AgentV2NodeType) {+ return hasInlineAgentBinding(data) && !hasValidInlineAgentBinding(data)+}++export function hasValidAgentBinding(data: AgentV2NodeType) {+ return hasValidInlineAgentBinding(data) || hasValidRosterAgentBinding(data)+}diff --git a/web/app/components/workflow/nodes/components.ts b/web/app/components/workflow/nodes/components.tsindex 7c196e3f2f5..fa86c55e0c3 100644--- a/web/app/components/workflow/nodes/components.ts+++ b/web/app/components/workflow/nodes/components.ts@@ -1,5 +1,9 @@-import type { ComponentType } from 'react'+import type { ComponentProps, ComponentType } from 'react'+import { createElement } from 'react'import { BlockEnum } from '../types'+import { AgentV2Node } from './agent-v2/node'+import { AgentV2Panel } from './agent-v2/panel'+import { isAgentV2NodeData } from './agent-v2/types'import AgentNode from './agent/node'import AgentPanel from './agent/panel'import AnswerNode from './answer/node'@@ -53,7 +57,25 @@ import TriggerWebhookPanel from './trigger-webhook/panel'import VariableAssignerNode from './variable-assigner/node'import VariableAssignerPanel from './variable-assigner/panel'-export const NodeComponentMap: Record<string, ComponentType<any>> = {+type WorkflowAgentNodeProps = ComponentProps<typeof AgentNode> | ComponentProps<typeof AgentV2Node>+type WorkflowAgentPanelProps = ComponentProps<typeof AgentPanel> | ComponentProps<typeof AgentV2Panel>+type WorkflowComponentMap = Record<string, ComponentType<Record<string, never>>>++function WorkflowAgentNode(props: WorkflowAgentNodeProps) {+ if (isAgentV2NodeData(props.data))+ return createElement(AgentV2Node, props as ComponentProps<typeof AgentV2Node>)++ return createElement(AgentNode, props as ComponentProps<typeof AgentNode>)+}++function WorkflowAgentPanel(props: WorkflowAgentPanelProps) {+ if (isAgentV2NodeData(props.data))+ return createElement(AgentV2Panel, props as ComponentProps<typeof AgentV2Panel>)++ return createElement(AgentPanel, props as ComponentProps<typeof AgentPanel>)+}++export const NodeComponentMap = {[BlockEnum.Start]: StartNode,[BlockEnum.StartPlaceholder]: StartPlaceholderNode,[BlockEnum.End]: EndNode,@@ -74,16 +96,17 @@ export const NodeComponentMap: Record<string, ComponentType<any>> = {[BlockEnum.Loop]: LoopNode,[BlockEnum.DocExtractor]: DocExtractorNode,[BlockEnum.ListFilter]: ListFilterNode,- [BlockEnum.Agent]: AgentNode,+ [BlockEnum.Agent]: WorkflowAgentNode,+ [BlockEnum.AgentV2]: AgentV2Node,[BlockEnum.DataSource]: DataSourceNode,[BlockEnum.KnowledgeBase]: KnowledgeBaseNode,[BlockEnum.HumanInput]: HumanInputNode,[BlockEnum.TriggerSchedule]: TriggerScheduleNode,[BlockEnum.TriggerWebhook]: TriggerWebhookNode,[BlockEnum.TriggerPlugin]: TriggerPluginNode,-}+} as unknown as WorkflowComponentMap-export const PanelComponentMap: Record<string, ComponentType<any>> = {+export const PanelComponentMap = {[BlockEnum.Start]: StartPanel,[BlockEnum.StartPlaceholder]: StartPlaceholderPanel,[BlockEnum.End]: EndPanel,@@ -104,11 +127,12 @@ export const PanelComponentMap: Record<string, ComponentType<any>> = {[BlockEnum.Loop]: LoopPanel,[BlockEnum.DocExtractor]: DocExtractorPanel,[BlockEnum.ListFilter]: ListFilterPanel,- [BlockEnum.Agent]: AgentPanel,+ [BlockEnum.Agent]: WorkflowAgentPanel,+ [BlockEnum.AgentV2]: AgentV2Panel,[BlockEnum.DataSource]: DataSourcePanel,[BlockEnum.KnowledgeBase]: KnowledgeBasePanel,[BlockEnum.HumanInput]: HumanInputPanel,[BlockEnum.TriggerSchedule]: TriggerSchedulePanel,[BlockEnum.TriggerWebhook]: TriggerWebhookPanel,[BlockEnum.TriggerPlugin]: TriggerPluginPanel,-}+} as unknown as WorkflowComponentMapdiff --git a/web/app/components/workflow/nodes/knowledge-retrieval/components/add-dataset.tsx b/web/app/components/workflow/nodes/knowledge-retrieval/components/add-dataset.tsxindex f2537f94e16..683d18a78fe 100644--- a/web/app/components/workflow/nodes/knowledge-retrieval/components/add-dataset.tsx+++ b/web/app/components/workflow/nodes/knowledge-retrieval/components/add-dataset.tsx@@ -9,11 +9,13 @@ import SelectDataset from '@/app/components/app/configuration/dataset-config/seltype Props = Readonly<{selectedIds: string[]+ modal?: booleanonChange: (dataSets: DataSet[]) => void}>const AddDataset: FC<Props> = ({selectedIds,+ modal,onChange,}) => {const { t } = useTranslation()@@ -38,6 +40,7 @@ const AddDataset: FC<Props> = ({</button><SelectDatasetisShow={isShowModal}+ modal={modal}onClose={hideModal}selectedIds={selectedIds}onSelect={handleSelect}diff --git a/web/app/components/workflow/nodes/knowledge-retrieval/components/dataset-item.tsx b/web/app/components/workflow/nodes/knowledge-retrieval/components/dataset-item.tsxindex c2a1aff4912..59f7307a2b9 100644--- a/web/app/components/workflow/nodes/knowledge-retrieval/components/dataset-item.tsx+++ b/web/app/components/workflow/nodes/knowledge-retrieval/components/dataset-item.tsx@@ -33,6 +33,10 @@ type Props = Readonly<{onChange: (dataSet: DataSet) => voidreadonly?: booleaneditable?: boolean+ settingsDrawerBackdropClassName?: string+ settingsDrawerBackdropForceRender?: boolean+ settingsDrawerPopupClassName?: string+ settingsModalHeight?: string}>const DatasetItem: FC<Props> = ({@@ -41,6 +45,10 @@ const DatasetItem: FC<Props> = ({onChange,readonly,editable = true,+ settingsDrawerBackdropClassName,+ settingsDrawerBackdropForceRender,+ settingsDrawerPopupClassName,+ settingsModalHeight,}) => {const media = useBreakpoints()const { t } = useTranslation()@@ -147,12 +155,23 @@ const DatasetItem: FC<Props> = ({}}><DrawerPortal>- <DrawerBackdrop className={cn(!isMobile && 'bg-transparent')} />+ <DrawerBackdrop+ forceRender={settingsDrawerBackdropForceRender}+ className={cn(+ !settingsDrawerBackdropClassName && !isMobile && 'bg-transparent',+ settingsDrawerBackdropClassName,+ )}+ /><DrawerViewport>- <DrawerPopup className="p-0! data-[swipe-direction=right]:top-16 data-[swipe-direction=right]:right-2 data-[swipe-direction=right]:bottom-3 data-[swipe-direction=right]:h-auto data-[swipe-direction=right]:w-full data-[swipe-direction=right]:max-w-[640px] data-[swipe-direction=right]:rounded-xl">- <DrawerContent className="flex min-h-0 flex-1 flex-col p-0 pb-0">+ <DrawerPopup className={cn(+ 'p-0! data-[swipe-direction=right]:right-2 data-[swipe-direction=right]:h-auto data-[swipe-direction=right]:w-full data-[swipe-direction=right]:max-w-[640px] data-[swipe-direction=right]:rounded-xl',+ settingsDrawerPopupClassName ?? 'data-[swipe-direction=right]:top-16 data-[swipe-direction=right]:bottom-3',+ )}+ >+ <DrawerContent className="flex h-full min-h-0 flex-1 flex-col p-0 pb-0"><SettingsModalcurrentDataset={payload}+ height={settingsModalHeight}onCancel={hideSettingsModal}onSave={handleSave}/>diff --git a/web/app/components/workflow/nodes/knowledge-retrieval/components/dataset-list.tsx b/web/app/components/workflow/nodes/knowledge-retrieval/components/dataset-list.tsxindex 1c14b6dbea1..029c856a036 100644--- a/web/app/components/workflow/nodes/knowledge-retrieval/components/dataset-list.tsx+++ b/web/app/components/workflow/nodes/knowledge-retrieval/components/dataset-list.tsx@@ -13,12 +13,20 @@ type Props = Readonly<{list: DataSet[]onChange: (list: DataSet[]) => voidreadonly?: boolean+ settingsDrawerBackdropClassName?: string+ settingsDrawerBackdropForceRender?: boolean+ settingsDrawerPopupClassName?: string+ settingsModalHeight?: string}>const DatasetList: FC<Props> = ({list,onChange,readonly,+ settingsDrawerBackdropClassName,+ settingsDrawerBackdropForceRender,+ settingsDrawerPopupClassName,+ settingsModalHeight,}) => {const { t } = useTranslation()const userProfile = useAppContextSelector(s => s.userProfile)@@ -67,6 +75,10 @@ const DatasetList: FC<Props> = ({onChange={handleChange(index)}readonly={readonly}editable={item.editable}+ settingsDrawerBackdropClassName={settingsDrawerBackdropClassName}+ settingsDrawerBackdropForceRender={settingsDrawerBackdropForceRender}+ settingsDrawerPopupClassName={settingsDrawerPopupClassName}+ settingsModalHeight={settingsModalHeight}/>)})diff --git a/web/app/components/workflow/nodes/knowledge-retrieval/components/retrieval-config.tsx b/web/app/components/workflow/nodes/knowledge-retrieval/components/retrieval-config.tsxindex 987ee789147..12e47278597 100644--- a/web/app/components/workflow/nodes/knowledge-retrieval/components/retrieval-config.tsx+++ b/web/app/components/workflow/nodes/knowledge-retrieval/components/retrieval-config.tsx@@ -32,6 +32,7 @@ type Props = Readonly<{onSingleRetrievalModelChange?: ModelParameterModalProps['setModel']onSingleRetrievalModelParamsChange?: ModelParameterModalProps['onCompletionParamsChange']readonly?: boolean+ modal?: booleanrerankModalOpen: booleanonRerankModelOpenChange: (open: boolean) => voidselectedDatasets: DataSet[]@@ -45,6 +46,7 @@ const RetrievalConfig: FC<Props> = ({onSingleRetrievalModelChange,onSingleRetrievalModelParamsChange,readonly,+ modal,rerankModalOpen,onRerankModelOpenChange,selectedDatasets,@@ -115,6 +117,7 @@ const RetrievalConfig: FC<Props> = ({return (<Popover+ modal={modal}open={rerankModalOpen}onOpenChange={(nextOpen) => {if (readonly)diff --git a/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/import-from-tool.tsx b/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/import-from-tool.tsxindex 48240858a17..e4bf0fd2d56 100644--- a/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/import-from-tool.tsx+++ b/web/app/components/workflow/nodes/parameter-extractor/components/extract-parameter/import-from-tool.tsx@@ -3,7 +3,7 @@ import type { FC } from 'react'import type { Param, ParamType } from '../../types'import type { ToolParameter } from '@/app/components/tools/types'import type {- PluginDefaultValue,+ BlockDefaultValue,ToolDefaultValue,} from '@/app/components/workflow/block-selector/types'import type { BlockEnum } from '@/app/components/workflow/types'@@ -50,7 +50,7 @@ const ImportFromTool: FC<Props> = ({const { data: customTools } = useAllCustomTools()const { data: workflowTools } = useAllWorkflowTools()- const handleSelectTool = useCallback((_type: BlockEnum, toolInfo?: PluginDefaultValue) => {+ const handleSelectTool = useCallback((_type: BlockEnum, toolInfo?: BlockDefaultValue) => {if (!toolInfo || 'datasource_name' in toolInfo || !('tool_name' in toolInfo))returndiff --git a/web/app/components/workflow/operator/__tests__/add-block.spec.tsx b/web/app/components/workflow/operator/__tests__/add-block.spec.tsxindex 0e27d2cc155..98bdb241540 100644--- a/web/app/components/workflow/operator/__tests__/add-block.spec.tsx+++ b/web/app/components/workflow/operator/__tests__/add-block.spec.tsx@@ -26,19 +26,48 @@ type BlockSelectorMockProps = {const {mockHandlePaneContextmenuCancel,mockWorkflowStoreSetState,+ mockSetOpenInlineAgentPanelNodeId,mockGenerateNewNode,mockGetNodeCustomTypeByNodeDataType,+ mockGetNodesWithSameDefaultDataType,+ mockCreateInlineAgentBinding,+ mockHandleSyncWorkflowDraft,+ mockSaveStateToHistory,} = vi.hoisted(() => ({mockHandlePaneContextmenuCancel: vi.fn(),mockWorkflowStoreSetState: vi.fn(),+ mockSetOpenInlineAgentPanelNodeId: vi.fn(),mockGenerateNewNode: vi.fn(({ type, data }: { type: string, data: Record<string, unknown> }) => ({newNode: {id: 'generated-node',type,data,+ position: {+ x: 0,+ y: 0,+ },},})),mockGetNodeCustomTypeByNodeDataType: vi.fn((type: string) => `${type}-custom`),+ mockGetNodesWithSameDefaultDataType: vi.fn((+ nodes: Array<{ data: { agent_node_kind?: string, type?: BlockEnum, version?: string } }>,+ type: BlockEnum,+ defaultValue: { agent_node_kind?: string, type?: BlockEnum, version?: string },+ ) => {+ const dataType = defaultValue.type ?? type+ if (dataType !== type && defaultValue.version) {+ return nodes.filter(node =>+ node.data.type === dataType+ && node.data.version === defaultValue.version+ && node.data.agent_node_kind === defaultValue.agent_node_kind,+ )+ }++ return nodes.filter(node => node.data.type === dataType)+ }),+ mockCreateInlineAgentBinding: vi.fn(),+ mockHandleSyncWorkflowDraft: vi.fn(),+ mockSaveStateToHistory: vi.fn(),}))let latestBlockSelectorProps: BlockSelectorMockProps | null = null@@ -47,7 +76,7 @@ let mockIsChatMode = falselet mockFlowType: FlowType = FlowType.appFlowconst mockAvailableNextBlocks = [BlockEnum.Answer, BlockEnum.Code]-const mockNodesMetaDataMap = {+const mockNodesMetaDataMap: Partial<Record<BlockEnum, { defaultValue: Record<string, unknown> }>> = {[BlockEnum.Answer]: {defaultValue: {title: 'Answer',@@ -90,14 +119,48 @@ vi.mock('../../hooks-store', () => ({}))vi.mock('../../store', () => ({+ useStore: (selector: (state: { mousePosition: { pageX: number, pageY: number, elementX: number, elementY: number } }) => unknown) =>+ selector({+ mousePosition: {+ pageX: 120,+ pageY: 240,+ elementX: 12,+ elementY: 24,+ },+ }),useWorkflowStore: () => ({+ getState: () => ({+ setOpenInlineAgentPanelNodeId: mockSetOpenInlineAgentPanelNodeId,+ }),setState: mockWorkflowStoreSetState,}),}))+vi.mock('../../hooks/use-nodes-sync-draft', () => ({+ useNodesSyncDraft: () => ({+ handleSyncWorkflowDraft: mockHandleSyncWorkflowDraft,+ }),+}))++vi.mock('../../hooks/use-workflow-history', () => ({+ WorkflowHistoryEvent: {+ NodeAdd: 'NodeAdd',+ },+ useWorkflowHistory: () => ({+ saveStateToHistory: mockSaveStateToHistory,+ }),+}))++vi.mock('../../nodes/agent-v2/hooks', () => ({+ useCreateInlineAgentBinding: () => ({+ createInlineAgentBinding: mockCreateInlineAgentBinding,+ }),+}))+vi.mock('../../utils', () => ({generateNewNode: mockGenerateNewNode,getNodeCustomTypeByNodeDataType: mockGetNodeCustomTypeByNodeDataType,+ getNodesWithSameDefaultDataType: mockGetNodesWithSameDefaultDataType,}))vi.mock('../tip-popup', () => ({@@ -114,6 +177,17 @@ describe('AddBlock', () => {mockNodesReadOnly = falsemockIsChatMode = falsemockFlowType = FlowType.appFlow+ mockCreateInlineAgentBinding.mockImplementation((_nodeId: string, options?: { onSuccess?: (binding: {+ binding_type: 'inline_agent'+ agent_id: string+ current_snapshot_id: string+ }) => void }) => {+ options?.onSuccess?.({+ binding_type: 'inline_agent',+ agent_id: 'inline-agent-1',+ current_snapshot_id: 'snapshot-1',+ })+ })})// Rendering and selector configuration.@@ -211,7 +285,7 @@ describe('AddBlock', () => {},})expect(mockWorkflowStoreSetState).toHaveBeenCalledWith({- candidateNode: {+ candidateNode: expect.objectContaining({id: 'generated-node',type: 'answer-custom',data: {@@ -221,8 +295,92 @@ describe('AddBlock', () => {pluginId: 'plugin-1',_isCandidate: true,},+ }),+ })+ })++ it('should count Agent v2 nodes by the final default data type without counting legacy Agent nodes', async () => {+ mockNodesMetaDataMap[BlockEnum.AgentV2] = {+ defaultValue: {+ title: 'Agent',+ desc: '',+ agent_node_kind: 'dify_agent',+ type: BlockEnum.Agent,+ version: '2',},+ }+ renderWithReactFlow([+ createNode({ id: 'old-agent', position: { x: 0, y: 0 }, data: { type: BlockEnum.Agent, version: '2' } }),+ createNode({ id: 'agent-v2', position: { x: 80, y: 0 }, data: { agent_node_kind: 'dify_agent', type: BlockEnum.Agent, version: '2' } }),+ ])++ await waitFor(() => expect(latestBlockSelectorProps).not.toBeNull())++ act(() => {+ latestBlockSelectorProps?.onSelect(BlockEnum.AgentV2)+ })++ expect(mockGetNodesWithSameDefaultDataType).toHaveBeenCalledWith(+ expect.any(Array),+ BlockEnum.AgentV2,+ {+ title: 'Agent',+ desc: '',+ agent_node_kind: 'dify_agent',+ type: BlockEnum.Agent,+ version: '2',+ },+ )+ expect(mockGenerateNewNode).toHaveBeenCalledWith({+ type: 'agent-v2-custom',+ data: {+ title: 'Agent 2',+ desc: '',+ agent_node_kind: 'dify_agent',+ type: BlockEnum.Agent,+ version: '2',+ _isCandidate: true,+ },+ position: {+ x: 0,+ y: 0,+ },+ })+ })++ it('should commit start-from-scratch Agent v2 immediately and create the inline binding', async () => {+ mockNodesMetaDataMap[BlockEnum.AgentV2] = {+ defaultValue: {+ title: 'Agent',+ desc: '',+ agent_node_kind: 'dify_agent',+ type: BlockEnum.Agent,+ version: '2',+ },+ }+ renderWithReactFlow([])++ await waitFor(() => expect(latestBlockSelectorProps).not.toBeNull())++ act(() => {+ latestBlockSelectorProps?.onSelect(BlockEnum.AgentV2, {+ agent_binding: {+ binding_type: 'inline_agent',+ },+ agent_node_kind: 'dify_agent',+ version: '2',+ })+ })++ expect(mockWorkflowStoreSetState).toHaveBeenCalledWith({+ candidateNode: undefined,})+ expect(mockCreateInlineAgentBinding).toHaveBeenCalledWith('generated-node', expect.objectContaining({+ onSuccess: expect.any(Function),+ }))+ expect(mockSetOpenInlineAgentPanelNodeId).toHaveBeenCalledWith('generated-node')+ expect(mockHandleSyncWorkflowDraft).toHaveBeenCalledWith(true, true)+ expect(mockSaveStateToHistory).toHaveBeenCalledWith('NodeAdd', { nodeId: 'generated-node' })})})})diff --git a/web/app/components/workflow/operator/add-block.tsx b/web/app/components/workflow/operator/add-block.tsxindex 52b71764393..e2937f28642 100644--- a/web/app/components/workflow/operator/add-block.tsx+++ b/web/app/components/workflow/operator/add-block.tsx@@ -4,6 +4,7 @@ import type {} from '@/app/components/workflow/types'import { cn } from '@langgenius/dify-ui/cn'import { RiAddCircleFill } from '@remixicon/react'+import { produce } from 'immer'import {memo,useCallback,@@ -11,6 +12,7 @@ import {} from 'react'import { useTranslation } from 'react-i18next'import {+ useReactFlow,useStoreApi,} from 'reactflow'import BlockSelector from '@/app/components/workflow/block-selector'@@ -26,10 +28,16 @@ import {usePanelInteractions,} from '../hooks'import { useHooksStore } from '../hooks-store'-import { useWorkflowStore } from '../store'+import { useCollaborativeWorkflow } from '../hooks/use-collaborative-workflow'+import { useNodesSyncDraft } from '../hooks/use-nodes-sync-draft'+import { useWorkflowHistory, WorkflowHistoryEvent } from '../hooks/use-workflow-history'+import { useCreateInlineAgentBinding } from '../nodes/agent-v2/hooks'+import { isAgentV2NodeData, needsInlineAgentBindingCreation } from '../nodes/agent-v2/types'+import { useStore, useWorkflowStore } from '../store'import {generateNewNode,getNodeCustomTypeByNodeDataType,+ getNodesWithSameDefaultDataType,} from '../utils'import TipPopup from './tip-popup'@@ -47,10 +55,16 @@ const AddBlock = ({}: AddBlockProps) => {const { t } = useTranslation()const store = useStoreApi()+ const reactflow = useReactFlow()const workflowStore = useWorkflowStore()+ const mousePosition = useStore(s => s.mousePosition)+ const collaborativeWorkflow = useCollaborativeWorkflow()const isChatMode = useIsChatMode()const { nodesReadOnly } = useNodesReadOnly()const { handlePaneContextmenuCancel } = usePanelInteractions()+ const { handleSyncWorkflowDraft } = useNodesSyncDraft()+ const { saveStateToHistory } = useWorkflowHistory()+ const { createInlineAgentBinding } = useCreateInlineAgentBinding()const [open, setOpen] = useState(false)const { availableNextBlocks } = useAvailableBlocks(BlockEnum.Start, false)const { nodesMap: nodesMetaDataMap } = useNodesMetaData()@@ -67,11 +81,11 @@ const AddBlock = ({const {getNodes,} = store.getState()- const nodes = getNodes()- const nodesWithSameType = nodes.filter(node => node.data.type === type)const {defaultValue,} = nodesMetaDataMap![type]+ const nodes = getNodes()+ const nodesWithSameType = getNodesWithSameDefaultDataType(nodes, type, defaultValue)const { newNode } = generateNewNode({type: getNodeCustomTypeByNodeDataType(type),data: {@@ -85,10 +99,56 @@ const AddBlock = ({y: 0,},})+ if (isAgentV2NodeData(newNode.data) && needsInlineAgentBindingCreation(newNode.data)) {+ const { nodes, setNodes } = collaborativeWorkflow.getState()+ const { screenToFlowPosition } = reactflow+ const position = screenToFlowPosition({+ x: mousePosition.pageX,+ y: mousePosition.pageY,+ })+ const nodeToInsert = {+ ...newNode,+ data: {+ ...newNode.data,+ _isCandidate: false,+ _isTempNode: true,+ selected: true,+ },+ position,+ }+ setNodes(produce(nodes, (draft) => {+ draft.forEach((node) => {+ node.data.selected = false+ })+ draft.push(nodeToInsert)+ }))+ workflowStore.setState({+ candidateNode: undefined,+ })+ saveStateToHistory(WorkflowHistoryEvent.NodeAdd, { nodeId: newNode.id })+ createInlineAgentBinding(newNode.id, {+ onSuccess: (binding) => {+ const { nodes, setNodes } = collaborativeWorkflow.getState()+ setNodes(produce(nodes, (draft) => {+ const node = draft.find(node => node.id === newNode.id)+ if (node) {+ if (isAgentV2NodeData(node.data) && needsInlineAgentBindingCreation(node.data))+ node.data.agent_binding = binding+ node.data._openInlineAgentPanel = true+ delete node.data._isTempNode+ }+ }))+ workflowStore.getState().setOpenInlineAgentPanelNodeId(newNode.id)+ handleSyncWorkflowDraft(true, true)+ },+ })+ setOpen(false)+ return+ }workflowStore.setState({candidateNode: newNode,})- }, [store, workflowStore, nodesMetaDataMap])+ }, [collaborativeWorkflow, createInlineAgentBinding, handleSyncWorkflowDraft, mousePosition.pageX, mousePosition.pageY, reactflow, saveStateToHistory, store, workflowStore, nodesMetaDataMap])const renderTriggerElement = useCallback((open: boolean) => {return (diff --git a/web/app/components/workflow/panel/version-history-panel/version-history-item.tsx b/web/app/components/workflow/panel/version-history-panel/version-history-item.tsxindex efc1dfe1ecc..98e4d4f4806 100644--- a/web/app/components/workflow/panel/version-history-panel/version-history-item.tsx+++ b/web/app/components/workflow/panel/version-history-panel/version-history-item.tsx@@ -15,6 +15,7 @@ type VersionHistoryItemProps = {onClick: (item: VersionHistory) => voidhandleClickActionMenuItem: (operation: VersionHistoryContextMenuOptions) => voidisLast: boolean+ hideActionMenu?: boolean}const formatVersion = (versionHistory: VersionHistory, latestVersionId: string): string => {@@ -43,6 +44,7 @@ const VersionHistoryItem: React.FC<VersionHistoryItemProps> = ({onClick,handleClickActionMenuItem,isLast,+ hideActionMenu,}) => {const { t } = useTranslation()const [isHovering, setIsHovering] = useState(false)@@ -78,6 +80,9 @@ const VersionHistoryItem: React.FC<VersionHistoryItemProps> = ({setOpen(false)}}onContextMenu={(e) => {+ if (hideActionMenu)+ return+e.preventDefault()setOpen(true)}}@@ -123,7 +128,7 @@ const VersionHistoryItem: React.FC<VersionHistoryItemProps> = ({}</div>{/* Action Menu */}- {!isDraft && isHovering && (+ {!hideActionMenu && !isDraft && isHovering && (<div className="absolute top-1 right-1"><ActionMenuisShowDelete={!isLatest}diff --git a/web/app/components/workflow/run/__tests__/result-panel.spec.tsx b/web/app/components/workflow/run/__tests__/result-panel.spec.tsxindex ea8606d74ee..2f3ec0610ff 100644--- a/web/app/components/workflow/run/__tests__/result-panel.spec.tsx+++ b/web/app/components/workflow/run/__tests__/result-panel.spec.tsx@@ -98,7 +98,7 @@ vi.mock('@/app/components/workflow/run/retry-log', () => ({},}))-vi.mock('@/app/components/workflow/run/agent-log', () => ({+vi.mock('@/app/components/workflow/run/agent-log/agent-log-trigger', () => ({AgentLogTrigger: (props: {onShowAgentOrToolLog: (detail: unknown) => voidnodeInfo: { agentLog?: unknown }@@ -327,6 +327,19 @@ describe('ResultPanel', () => {fireEvent.click(screen.getByRole('button', { name: 'agent-trigger' }))expect(handleShowAgentOrToolLog).toHaveBeenCalledWith(agentLog)+ rerender(+ <ResultPanel+ nodeInfo={createNodeInfo({+ node_type: BlockEnum.AgentV2,+ agentLog,+ })}+ status={NodeRunningStatus.Succeeded}+ handleShowAgentOrToolLog={handleShowAgentOrToolLog}+ />,+ )++ expect(screen.queryByRole('button', { name: 'agent-trigger' })).not.toBeInTheDocument()+rerender(<ResultPanelnodeInfo={createNodeInfo({diff --git a/web/app/components/workflow/run/__tests__/special-result-panel.spec.tsx b/web/app/components/workflow/run/__tests__/special-result-panel.spec.tsxindex 8e09cf6741a..459ddf1d86e 100644--- a/web/app/components/workflow/run/__tests__/special-result-panel.spec.tsx+++ b/web/app/components/workflow/run/__tests__/special-result-panel.spec.tsx@@ -31,8 +31,8 @@ vi.mock('../loop-log', () => ({},}))-vi.mock('../agent-log', () => ({- AgentResultPanel: ({ agentOrToolLogItemStack }: { agentOrToolLogItemStack: AgentLogItemWithChildren[] }) => {+vi.mock('../agent-log/agent-result-panel', () => ({+ default: ({ agentOrToolLogItemStack }: { agentOrToolLogItemStack: AgentLogItemWithChildren[] }) => {mocks.agentPanel(agentOrToolLogItemStack)return <div data-testid="agent-result-panel">{agentOrToolLogItemStack.length}</div>},diff --git a/web/app/components/workflow/run/agent-log/__tests__/agent-log-nav.spec.tsx b/web/app/components/workflow/run/agent-log/__tests__/agent-log-nav.spec.tsxindex 43ee728eda9..bc66598e746 100644--- a/web/app/components/workflow/run/agent-log/__tests__/agent-log-nav.spec.tsx+++ b/web/app/components/workflow/run/agent-log/__tests__/agent-log-nav.spec.tsx@@ -1,7 +1,7 @@import type { AgentLogItemWithChildren } from '@/types/workflow'import { render, screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'-import AgentLogNav from '../agent-log-nav'+import { AgentLogNav } from '../agent-log-nav'const createLogItem = (overrides: Partial<AgentLogItemWithChildren> = {}): AgentLogItemWithChildren => ({message_id: 'message-1',diff --git a/web/app/components/workflow/run/agent-log/__tests__/agent-log-trigger.spec.tsx b/web/app/components/workflow/run/agent-log/__tests__/agent-log-trigger.spec.tsxindex 29919e4ccfe..d6d6c8d499c 100644--- a/web/app/components/workflow/run/agent-log/__tests__/agent-log-trigger.spec.tsx+++ b/web/app/components/workflow/run/agent-log/__tests__/agent-log-trigger.spec.tsx@@ -2,7 +2,7 @@ import type { AgentLogItemWithChildren, NodeTracing } from '@/types/workflow'import { render, screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { BlockEnum } from '../../../types'-import AgentLogTrigger from '../agent-log-trigger'+import { AgentLogTrigger } from '../agent-log-trigger'const createAgentLogItem = (overrides: Partial<AgentLogItemWithChildren> = {}): AgentLogItemWithChildren => ({node_execution_id: 'exec-1',@@ -63,7 +63,7 @@ describe('AgentLogTrigger', () => {// Agent triggers should expose strategy text and open the log stack payload.describe('User Interactions', () => {- it('should show the agent strategy and pass the log payload on click', async () => {+ it('should show the legacy agent strategy and pass the log payload on click', async () => {const user = userEvent.setup()const onShowAgentOrToolLog = vi.fn()const agentLog = [createAgentLogItem({ message_id: 'message-1' })]@@ -87,7 +87,7 @@ describe('AgentLogTrigger', () => {})})- it('should still open the detail view when no strategy label is available', async () => {+ it('should open the detail view when execution metadata is unavailable', async () => {const user = userEvent.setup()const onShowAgentOrToolLog = vi.fn()diff --git a/web/app/components/workflow/run/agent-log/agent-log-nav.tsx b/web/app/components/workflow/run/agent-log/agent-log-nav.tsxindex 2db450aee00..fc95c861f95 100644--- a/web/app/components/workflow/run/agent-log/agent-log-nav.tsx+++ b/web/app/components/workflow/run/agent-log/agent-log-nav.tsx@@ -1,6 +1,5 @@import type { AgentLogItemWithChildren } from '@/types/workflow'import { Button } from '@langgenius/dify-ui/button'-import { RiArrowLeftLine } from '@remixicon/react'import { useTranslation } from 'react-i18next'import AgentLogNavMore from './agent-log-nav-more'@@ -8,10 +7,10 @@ type AgentLogNavProps = {agentOrToolLogItemStack: AgentLogItemWithChildren[]onShowAgentOrToolLog: (detail?: AgentLogItemWithChildren) => void}-const AgentLogNav = ({+export function AgentLogNav({agentOrToolLogItemStack,onShowAgentOrToolLog,-}: AgentLogNavProps) => {+}: AgentLogNavProps) {const { t } = useTranslation()const agentOrToolLogItemStackLength = agentOrToolLogItemStack.lengthconst first = agentOrToolLogItemStack[0]@@ -28,7 +27,7 @@ const AgentLogNav = ({onShowAgentOrToolLog()}}>- <RiArrowLeftLine className="mr-1 size-3.5" />+ <span aria-hidden className="mr-1 i-ri-arrow-left-line size-3.5" />AGENT</Button><div className="mx-0.5 shrink-0 system-xs-regular text-divider-deep">/</div>@@ -45,7 +44,7 @@ const AgentLogNav = ({</Button>): (- <div className="flex items-center px-[5px] system-xs-medium-uppercase text-text-tertiary">+ <div className="flex items-center px-1.25 system-xs-medium-uppercase text-text-tertiary">{t('nodes.agent.strategy.label', { ns: 'workflow' })}</div>)@@ -74,5 +73,3 @@ const AgentLogNav = ({</div>)}--export default AgentLogNavdiff --git a/web/app/components/workflow/run/agent-log/agent-log-trigger.tsx b/web/app/components/workflow/run/agent-log/agent-log-trigger.tsxindex e1b1983050d..41a44eb67b6 100644--- a/web/app/components/workflow/run/agent-log/agent-log-trigger.tsx+++ b/web/app/components/workflow/run/agent-log/agent-log-trigger.tsx@@ -2,24 +2,24 @@ import type {AgentLogItemWithChildren,NodeTracing,} from '@/types/workflow'-import { RiArrowRightLine } from '@remixicon/react'import { useTranslation } from 'react-i18next'type AgentLogTriggerProps = {nodeInfo: NodeTracingonShowAgentOrToolLog: (detail?: AgentLogItemWithChildren) => void}-const AgentLogTrigger = ({+export function AgentLogTrigger({nodeInfo,onShowAgentOrToolLog,-}: AgentLogTriggerProps) => {+}: AgentLogTriggerProps) {const { t } = useTranslation()const { agentLog, execution_metadata } = nodeInfoconst agentStrategy = execution_metadata?.tool_info?.agent_strategyreturn (- <div- className="cursor-pointer rounded-[10px] bg-components-button-tertiary-bg"+ <button+ type="button"+ className="w-full cursor-pointer rounded-[10px] bg-components-button-tertiary-bg text-left focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"onClick={() => {onShowAgentOrToolLog({ message_id: nodeInfo.id, children: agentLog || [] } as AgentLogItemWithChildren)}}@@ -28,22 +28,20 @@ const AgentLogTrigger = ({{t('nodes.agent.strategy.label', { ns: 'workflow' })}</div><div className="flex items-center pt-1 pr-2 pb-1.5 pl-3">- {- agentStrategy && (- <div className="grow system-xs-medium text-text-secondary">- {agentStrategy}- </div>- )- }+ {agentStrategy+ ? (+ <div className="grow system-xs-medium text-text-secondary">+ {agentStrategy}+ </div>+ )+ : <div className="grow" />}<divclassName="flex shrink-0 cursor-pointer items-center px-px system-xs-regular-uppercase text-text-tertiary">{t('detail', { ns: 'runLog' })}- <RiArrowRightLine className="ml-0.5 size-3.5" />+ <span aria-hidden className="ml-0.5 i-ri-arrow-right-line size-3.5" /></div></div>- </div>+ </button>)}--export default AgentLogTriggerdiff --git a/web/app/components/workflow/run/agent-log/agent-result-panel.tsx b/web/app/components/workflow/run/agent-log/agent-result-panel.tsxindex 1ea8082276a..29520c344a9 100644--- a/web/app/components/workflow/run/agent-log/agent-result-panel.tsx+++ b/web/app/components/workflow/run/agent-log/agent-result-panel.tsx@@ -1,8 +1,7 @@import type { AgentLogItemWithChildren } from '@/types/workflow'-import { RiAlertFill } from '@remixicon/react'import { useTranslation } from 'react-i18next'import AgentLogItem from './agent-log-item'-import AgentLogNav from './agent-log-nav'+import { AgentLogNav } from './agent-log-nav'type AgentResultPanelProps = {agentOrToolLogItemStack: AgentLogItemWithChildren[]@@ -45,7 +44,7 @@ const AgentResultPanel = ({}}></div>- <RiAlertFill className="mr-1.5 size-4 text-text-warning-secondary" />+ <span aria-hidden className="mr-1.5 i-ri-alert-fill size-4 text-text-warning-secondary" /><div className="system-xs-medium text-text-primary">{t('circularInvocationTip', { ns: 'runLog' })}</div>diff --git a/web/app/components/workflow/run/agent-log/index.tsx b/web/app/components/workflow/run/agent-log/index.tsxdeleted file mode 100644index a39f5416bb4..00000000000--- a/web/app/components/workflow/run/agent-log/index.tsx+++ /dev/null@@ -1,2 +0,0 @@-export { default as AgentLogTrigger } from './agent-log-trigger'-export { default as AgentResultPanel } from './agent-result-panel'diff --git a/web/app/components/workflow/run/node.tsx b/web/app/components/workflow/run/node.tsxindex 75f57a6a961..275022323a0 100644--- a/web/app/components/workflow/run/node.tsx+++ b/web/app/components/workflow/run/node.tsx@@ -28,7 +28,7 @@ import { useDocLink } from '@/context/i18n'import BlockIcon from '../block-icon'import { BlockEnum } from '../types'import LargeDataAlert from '../variable-inspect/large-data-alert'-import { AgentLogTrigger } from './agent-log'+import { AgentLogTrigger } from './agent-log/agent-log-trigger'import { IterationLogTrigger } from './iteration-log'import { LoopLogTrigger } from './loop-log'import { RetryLogTrigger } from './retry-log'diff --git a/web/app/components/workflow/run/result-panel.tsx b/web/app/components/workflow/run/result-panel.tsxindex 699aceae781..37f2101fc92 100644--- a/web/app/components/workflow/run/result-panel.tsx+++ b/web/app/components/workflow/run/result-panel.tsx@@ -8,7 +8,7 @@ import { useTranslation } from 'react-i18next'import CodeEditor from '@/app/components/workflow/nodes/_base/components/editor/code-editor'import ErrorHandleTip from '@/app/components/workflow/nodes/_base/components/error-handle/error-handle-tip'import { CodeLanguage } from '@/app/components/workflow/nodes/code/types'-import { AgentLogTrigger } from '@/app/components/workflow/run/agent-log'+import { AgentLogTrigger } from '@/app/components/workflow/run/agent-log/agent-log-trigger'import { IterationLogTrigger } from '@/app/components/workflow/run/iteration-log'import { LoopLogTrigger } from '@/app/components/workflow/run/loop-log'import { RetryLogTrigger } from '@/app/components/workflow/run/retry-log'diff --git a/web/app/components/workflow/run/special-result-panel.tsx b/web/app/components/workflow/run/special-result-panel.tsxindex 34a9e2fb37a..94ce26e79c3 100644--- a/web/app/components/workflow/run/special-result-panel.tsx+++ b/web/app/components/workflow/run/special-result-panel.tsx@@ -5,7 +5,7 @@ import type {LoopVariableMap,NodeTracing,} from '@/types/workflow'-import { AgentResultPanel } from './agent-log'+import AgentResultPanel from './agent-log/agent-result-panel'import { IterationResultPanel } from './iteration-log'import { LoopResultPanel } from './loop-log'import { RetryResultPanel } from './retry-log'diff --git a/web/app/components/workflow/store/workflow/__tests__/node-slice.spec.ts b/web/app/components/workflow/store/workflow/__tests__/node-slice.spec.tsindex b81d793504e..87528bf6f7a 100644--- a/web/app/components/workflow/store/workflow/__tests__/node-slice.spec.ts+++ b/web/app/components/workflow/store/workflow/__tests__/node-slice.spec.ts@@ -9,6 +9,7 @@ describe('createNodeSlice', () => {expect(store.getState().iterTimes).toBe(1)expect(store.getState().loopTimes).toBe(1)expect(store.getState().iterParallelLogMap.size).toBe(0)+ expect(store.getState().openInlineAgentPanelNodeId).toBeUndefined()store.getState().setConnectingNodePayload({nodeId: 'node-1',@@ -20,6 +21,7 @@ describe('createNodeSlice', () => {nodeId: 'node-1',action: 'run',})+ store.getState().setOpenInlineAgentPanelNodeId('agent-node-1')expect(store.getState().connectingNodePayload).toEqual({nodeId: 'node-1',@@ -31,5 +33,6 @@ describe('createNodeSlice', () => {nodeId: 'node-1',action: 'run',})+ expect(store.getState().openInlineAgentPanelNodeId).toBe('agent-node-1')})})diff --git a/web/app/components/workflow/store/workflow/node-slice.ts b/web/app/components/workflow/store/workflow/node-slice.tsindex be8580eae5a..31f5231c715 100644--- a/web/app/components/workflow/store/workflow/node-slice.ts+++ b/web/app/components/workflow/store/workflow/node-slice.ts@@ -18,6 +18,8 @@ export type NodeSliceShape = {setNodeAnimation: (nodeAnimation: boolean) => voidcandidateNode?: NodesetCandidateNode: (candidateNode?: Node) => void+ openInlineAgentPanelNodeId?: string+ setOpenInlineAgentPanelNodeId: (nodeId?: string) => voidshowAssignVariablePopup?: {nodeId: stringnodeData: Node['data']@@ -59,6 +61,8 @@ export const createNodeSlice: StateCreator<NodeSliceShape> = set => ({setNodeAnimation: nodeAnimation => set(() => ({ nodeAnimation })),candidateNode: undefined,setCandidateNode: candidateNode => set(() => ({ candidateNode })),+ openInlineAgentPanelNodeId: undefined,+ setOpenInlineAgentPanelNodeId: nodeId => set(() => ({ openInlineAgentPanelNodeId: nodeId })),showAssignVariablePopup: undefined,setShowAssignVariablePopup: showAssignVariablePopup => set(() => ({ showAssignVariablePopup })),hoveringAssignVariableGroupId: undefined,diff --git a/web/app/components/workflow/types.ts b/web/app/components/workflow/types.tsindex 8835d3e45b2..b122a0666d7 100644--- a/web/app/components/workflow/types.ts+++ b/web/app/components/workflow/types.ts@@ -6,7 +6,7 @@ import type {} from 'reactflow'import type { Plugin, PluginMeta } from '@/app/components/plugins/types'import type { Collection, Tool } from '@/app/components/tools/types'-import type { BlockClassificationEnum, PluginDefaultValue } from '@/app/components/workflow/block-selector/types'+import type { BlockClassificationEnum, BlockDefaultValue, PluginDefaultValue } from '@/app/components/workflow/block-selector/types'import type {DefaultValueForm,ErrorHandleTypeEnum,@@ -47,6 +47,7 @@ export enum BlockEnum {IterationStart = 'iteration-start',Assigner = 'assigner', // is now named as VariableAssignerAgent = 'agent',+ AgentV2 = 'agent-v2',Loop = 'loop',LoopStart = 'loop-start',LoopEnd = 'loop-end',@@ -94,6 +95,7 @@ export type CommonNodeType<T = {}> = {_retryIndex?: number_dataSourceStartToAdd?: boolean_isTempNode?: boolean+ _openInlineAgentPanel?: booleanisInIteration?: booleaniteration_id?: stringselected?: boolean@@ -344,7 +346,7 @@ export type NodeDefault<T = {}> = {}) => Var[]}-export type OnSelectBlock = (type: BlockEnum, pluginDefaultValue?: PluginDefaultValue) => void+export type OnSelectBlock = (type: BlockEnum, defaultValue?: BlockDefaultValue) => voidexport enum WorkflowRunningStatus {Waiting = 'waiting',@@ -378,7 +380,7 @@ export type OnNodeAdd = (nodeType: BlockEnumsourceHandle?: stringtargetHandle?: string- pluginDefaultValue?: PluginDefaultValue+ pluginDefaultValue?: BlockDefaultValue},oldNodesPayload: {prevNodeId?: stringdiff --git a/web/app/components/workflow/utils/node.ts b/web/app/components/workflow/utils/node.tsindex d6163ea1c83..7432591f899 100644--- a/web/app/components/workflow/utils/node.ts+++ b/web/app/components/workflow/utils/node.ts@@ -142,6 +142,26 @@ export const getNestedNodePosition = (node: Node, parentNode: Node) => {}}+export const getNodesWithSameDefaultDataType = (+ nodes: Node[],+ nodeType: BlockEnum,+ defaultValue: Partial<Node['data']>,+) => {+ const dataType = (defaultValue.type as BlockEnum | undefined) ?? nodeType+ const discriminatorEntries = (['agent_node_kind', 'version'] as const)+ .map(key => [key, (defaultValue as Record<string, unknown>)[key]] as const)+ .filter(([, value]) => value !== undefined)++ if (dataType !== nodeType && discriminatorEntries.length > 0) {+ return nodes.filter(node =>+ node.data.type === dataType+ && discriminatorEntries.every(([key, value]) => (node.data as Record<string, unknown>)[key] === value),+ )+ }++ return nodes.filter(node => node.data.type === dataType)+}+export const hasRetryNode = (nodeType?: BlockEnum) => {return nodeType === BlockEnum.LLM || nodeType === BlockEnum.Tool || nodeType === BlockEnum.HttpRequest || nodeType === BlockEnum.Code}diff --git a/web/app/components/workflow/utils/workflow.ts b/web/app/components/workflow/utils/workflow.tsindex 0a1de2991eb..f976968feea 100644--- a/web/app/components/workflow/utils/workflow.ts+++ b/web/app/components/workflow/utils/workflow.ts@@ -27,6 +27,7 @@ export const canRunBySingle = (nodeType: BlockEnum, isChildNode: boolean) => {|| nodeType === BlockEnum.ParameterExtractor|| nodeType === BlockEnum.Iteration|| nodeType === BlockEnum.Agent+ || nodeType === BlockEnum.AgentV2|| nodeType === BlockEnum.DocExtractor|| nodeType === BlockEnum.Loop|| nodeType === BlockEnum.Start@@ -184,5 +185,5 @@ export const changeNodesAndEdgesId = (nodes: Node[], edges: Edge[]) => {}export const hasErrorHandleNode = (nodeType?: BlockEnum) => {- return nodeType === BlockEnum.LLM || nodeType === BlockEnum.Tool || nodeType === BlockEnum.HttpRequest || nodeType === BlockEnum.Code || nodeType === BlockEnum.Agent+ return nodeType === BlockEnum.LLM || nodeType === BlockEnum.Tool || nodeType === BlockEnum.HttpRequest || nodeType === BlockEnum.Code || nodeType === BlockEnum.Agent || nodeType === BlockEnum.AgentV2}diff --git a/web/app/components/workflow/variable-inspect/right.tsx b/web/app/components/workflow/variable-inspect/right.tsxindex 97768c63949..98a86d089c1 100644--- a/web/app/components/workflow/variable-inspect/right.tsx+++ b/web/app/components/workflow/variable-inspect/right.tsx@@ -111,9 +111,6 @@ const Right = ({if (blockType === BlockEnum.LLM)return node?.data?.prompt_template?.text || node?.data?.prompt_template?.[0].text- // if (blockType === BlockEnum.Agent) {- // return node?.data?.agent_parameters?.instruction?.value- // }if (blockType === BlockEnum.Code)return node?.data?.code}, [canShowPromptGenerator])@@ -139,12 +136,6 @@ const Right = ({}break- // Agent is a plugin, may has many instructions, can not locate which one to update- // case BlockEnum.Agent:- // if (draft?.agent_parameters?.instruction) {- // draft.agent_parameters.instruction.value = res.modified- // }- // breakcase BlockEnum.Code:draft.code = res.modifiedbreakdiff --git a/web/context/modal-context-provider.tsx b/web/context/modal-context-provider.tsxindex 78fdcf8c130..7f22cddfa1b 100644--- a/web/context/modal-context-provider.tsx+++ b/web/context/modal-context-provider.tsx@@ -269,6 +269,7 @@ export const ModalContextProvider = ({integrationSettingModalSection && (<IntegrationsSettingModalsection={integrationSettingModalSection}+ source={accountSettingCallbacksRef.current?.source}onCancel={handleCancelAccountSettingModal}onSectionChange={section => setUrlAccountModalState({ payload: section })}/>diff --git a/web/context/modal-context.ts b/web/context/modal-context.tsindex ed7289e6216..89c337a041c 100644--- a/web/context/modal-context.ts+++ b/web/context/modal-context.ts@@ -26,6 +26,7 @@ import { createContext, useContext, useContextSelector } from 'use-context-selecexport type ModalState<T> = {payload: T+ source?: 'agent'onCancelCallback?: () => voidonSaveCallback?: (newPayload?: T, formValues?: Record<string, unknown>) => voidonRemoveCallback?: (newPayload?: T, formValues?: Record<string, unknown>) => voiddiff --git a/web/contract/console/files.ts b/web/contract/console/files.tsnew file mode 100644index 00000000000..fb7b97b8a38--- /dev/null+++ b/web/contract/console/files.ts@@ -0,0 +1,16 @@+import type { PostFilesUploadResponse } from '@dify/contracts/api/console/files/types.gen'+import { type } from '@orpc/contract'+import { base } from '../base'++export const fileUploadContract = base+ .route({+ path: '/files/upload',+ method: 'POST',+ successStatus: 201,+ })+ .input(type<{+ body: {+ file: File+ }+ }>())+ .output(type<PostFilesUploadResponse>())diff --git a/web/contract/router.ts b/web/contract/router.tsindex 84df265e918..662857332ca 100644--- a/web/contract/router.ts+++ b/web/contract/router.ts@@ -23,6 +23,7 @@ import {exploreInstalledAppUninstallContract,learnDifyAppsContract,} from './console/explore'+import { fileUploadContract } from './console/files'import { changePreferredProviderTypeContract, modelProvidersModelsContract } from './console/model-providers'import { notificationContract, notificationDismissContract } from './console/notification'import { pluginCheckInstalledContract, pluginLatestVersionsContract } from './console/plugins'@@ -99,11 +100,6 @@ export const marketplaceRouterContract = {export type MarketPlaceInputs = InferContractRouterInputs<typeof marketplaceRouterContract>-// Hand-written console contracts below are temporary overrides for gaps in the-// generated community contract. Prefer fixing backend OpenAPI annotations so-// generated contracts include accurate method, path, input, and output types;-// once generated contracts are correct, the matching hand-written contracts-// should be removed instead of kept in parallel.export const consoleRouterContract = {enterprise: enterpriseContract,...communityContract,@@ -115,7 +111,11 @@ export const consoleRouterContract = {star: appStarContract,unstar: appUnstarContract,workflowOnlineUsers: workflowOnlineUsersContract,+ byAppId: {+ ...communityContract.apps.byAppId,+ },},+ agent: communityContract.agent,explore: {...communityContract.explore,apps: exploreAppsContract,@@ -137,6 +137,13 @@ export const consoleRouterContract = {parameters: trialAppParametersContract,workflows: trialAppWorkflowsContract,},+ files: {+ ...communityContract.files,+ upload: {+ ...communityContract.files.upload,+ post: fileUploadContract,+ },+ },modelProviders: {models: modelProvidersModelsContract,changePreferredProviderType: changePreferredProviderTypeContract,diff --git a/web/docker/entrypoint.sh b/web/docker/entrypoint.shindex 1ace4590655..31872154d70 100755--- a/web/docker/entrypoint.sh+++ b/web/docker/entrypoint.sh@@ -56,6 +56,7 @@ export NEXT_PUBLIC_ENABLE_WEBSITE_FIRECRAWL=${ENABLE_WEBSITE_FIRECRAWL:-true}export NEXT_PUBLIC_ENABLE_WEBSITE_WATERCRAWL=${ENABLE_WEBSITE_WATERCRAWL:-true}export NEXT_PUBLIC_ENABLE_SINGLE_DOLLAR_LATEX=${NEXT_PUBLIC_ENABLE_SINGLE_DOLLAR_LATEX:-false}export NEXT_PUBLIC_ENABLE_FEATURE_PREVIEW=${NEXT_PUBLIC_ENABLE_FEATURE_PREVIEW:-false}+export NEXT_PUBLIC_ENABLE_AGENT_V2=${NEXT_PUBLIC_ENABLE_AGENT_V2:-${ENABLE_AGENT_V2:-false}}export NEXT_PUBLIC_LOOP_NODE_MAX_COUNT=${LOOP_NODE_MAX_COUNT}export NEXT_PUBLIC_MAX_PARALLEL_LIMIT=${MAX_PARALLEL_LIMIT}export NEXT_PUBLIC_MAX_ITERATIONS_NUM=${MAX_ITERATIONS_NUM}diff --git a/web/env.ts b/web/env.tsindex 0bf5d4c3132..01610267b6d 100644--- a/web/env.ts+++ b/web/env.ts@@ -63,6 +63,7 @@ const clientSchema = {* The deployment edition, SELF_HOSTED*/NEXT_PUBLIC_EDITION: z.enum(['SELF_HOSTED', 'CLOUD']).default('SELF_HOSTED'),+ NEXT_PUBLIC_ENABLE_AGENT_V2: coercedBoolean.default(false),/*** Enable preview features that are still in development.* Currently gates the `/create` and `/refine` slash commands in the@@ -196,6 +197,7 @@ export const env = createEnv({NEXT_PUBLIC_DEPLOY_ENV: isServer ? process.env.NEXT_PUBLIC_DEPLOY_ENV : getRuntimeEnvFromBody('deployEnv'),NEXT_PUBLIC_DISABLE_UPLOAD_IMAGE_AS_ICON: isServer ? process.env.NEXT_PUBLIC_DISABLE_UPLOAD_IMAGE_AS_ICON : getRuntimeEnvFromBody('disableUploadImageAsIcon'),NEXT_PUBLIC_EDITION: isServer ? process.env.NEXT_PUBLIC_EDITION : getRuntimeEnvFromBody('edition'),+ NEXT_PUBLIC_ENABLE_AGENT_V2: isServer ? process.env.NEXT_PUBLIC_ENABLE_AGENT_V2 : getRuntimeEnvFromBody('enableAgentV2'),NEXT_PUBLIC_ENABLE_FEATURE_PREVIEW: isServer ? process.env.NEXT_PUBLIC_ENABLE_FEATURE_PREVIEW : getRuntimeEnvFromBody('enableFeaturePreview'),/**@@ -252,6 +254,11 @@ export const env = createEnv({type ClientEnvKey = keyof typeof clientSchematype DatasetKey = CamelCase<Replace<ClientEnvKey, typeof CLIENT_ENV_PREFIX>>+function getDatasetAttributeName(envKey: ClientEnvKey) {+ const datasetName = kebabCase(slice(envKey, length(CLIENT_ENV_PREFIX))).replace(/-(\d)/g, '$1')+ return concat('data-', datasetName)+}+/*** Browser-only function to get runtime env value from HTML body dataset.*/@@ -274,7 +281,7 @@ export function getDatasetMap() {return ObjectFromEntries(ObjectKeys(clientSchema).map(envKey => [- concat('data-', kebabCase(slice(envKey, length(CLIENT_ENV_PREFIX)))),+ getDatasetAttributeName(envKey),env[envKey],]),)diff --git a/web/features/agent-v2/__tests__/feature-flag.spec.ts b/web/features/agent-v2/__tests__/feature-flag.spec.tsnew file mode 100644index 00000000000..1789543cf7d--- /dev/null+++ b/web/features/agent-v2/__tests__/feature-flag.spec.ts@@ -0,0 +1,18 @@+describe('Agent v2 feature flags', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ vi.resetModules()+ })++ it('reads the client-visible Agent v2 flag from NEXT_PUBLIC_ENABLE_AGENT_V2', async () => {+ vi.doMock('@/env', () => ({+ env: {+ NEXT_PUBLIC_ENABLE_AGENT_V2: true,+ },+ }))++ const { isAgentV2Enabled } = await import('../feature-flag')++ expect(isAgentV2Enabled()).toBe(true)+ })+})diff --git a/web/features/agent-v2/agent-composer/__tests__/store.spec.ts b/web/features/agent-v2/agent-composer/__tests__/store.spec.tsnew file mode 100644index 00000000000..623a00f474d--- /dev/null+++ b/web/features/agent-v2/agent-composer/__tests__/store.spec.ts@@ -0,0 +1,444 @@+import type { AgentSoulConfig } from '@dify/contracts/api/console/agent/types.gen'+import { describe, expect, it } from 'vitest'+import { agentSoulConfigToFormState, formStateToAgentSoulConfig } from '../conversions'+import { defaultAgentSoulConfigFormState } from '../form-state'++describe('agent composer store conversions', () => {+ it('should hydrate editable form state from an AgentSoulConfig and preserve it in publish payload', () => {+ const baseConfig: AgentSoulConfig = {+ app_features: {+ opening_statement: 'Hello',+ suggested_questions: ['What changed?'],+ },+ env: {+ variables: [+ {+ key: 'REGION',+ value: 'us-east-1',+ },+ ],+ secret_refs: [+ {+ id: 'secret-1',+ key: 'OPENAI_API_KEY',+ ref: 'credential-1',+ },+ ],+ },+ knowledge: {+ datasets: [+ {+ id: 'dataset-1',+ name: 'Product Docs',+ description: 'Docs corpus',+ },+ ],+ query_config: {+ query: 'release notes',+ score_threshold: 0.72,+ score_threshold_enabled: true,+ top_k: 8,+ },+ query_mode: 'user_query',+ },+ model: {+ model: 'gpt-4.1',+ model_provider: 'openai',+ plugin_id: 'openai',+ },+ prompt: {+ system_prompt: 'Be precise.',+ },+ skills_files: {+ files: [+ {+ id: 'file-1',+ name: 'guide.md',+ type: 'markdown',+ },+ ],+ skills: [+ {+ id: 'skill-1',+ file_id: 'archive-file-1',+ full_archive_file_id: 'archive-file-1',+ full_archive_key: 'research-skill/.DIFY-SKILL-FULL.zip',+ name: 'Research Skill',+ path: 'research-skill',+ skill_md_file_id: 'skill-md-file-1',+ skill_md_key: 'research-skill/SKILL.md',+ },+ ],+ },+ tools: {+ cli_tools: [+ {+ tool_name: 'run-tests',+ name: 'Run Tests',+ install_command: 'pnpm install',+ pre_authorized: true,+ env: {+ variables: [+ {+ key: 'NODE_ENV',+ value: 'test',+ },+ ],+ },+ },+ ],+ dify_tools: [+ {+ provider: 'DuckDuckGo',+ provider_id: 'duckduckgo',+ provider_type: 'builtin',+ tool_name: 'ddg_search',+ name: 'DuckDuckGo Search',+ description: 'Search the web.',+ runtime_parameters: {+ query: 'latest docs',+ used_in_agent_nodes: true,+ },+ },+ ],+ },+ }++ const formState = agentSoulConfigToFormState(baseConfig)+ const publishConfig = formStateToAgentSoulConfig({+ baseConfig,+ formState,+ currentModel: formState.model,+ })++ expect(formState).toMatchObject({+ prompt: 'Be precise.',+ model: {+ model: 'gpt-4.1',+ provider: 'openai',+ plugin_id: 'openai',+ },+ skills: [+ {+ fileId: 'archive-file-1',+ fullArchiveFileId: 'archive-file-1',+ fullArchiveKey: 'research-skill/.DIFY-SKILL-FULL.zip',+ id: 'skill-1',+ name: 'Research Skill',+ path: 'research-skill',+ skillMdFileId: 'skill-md-file-1',+ skillMdKey: 'research-skill/SKILL.md',+ },+ ],+ files: [+ {+ id: 'file-1',+ name: 'guide.md',+ icon: 'markdown',+ },+ ],+ knowledgeRetrievals: [+ expect.objectContaining({+ id: 'dataset-1',+ name: 'Product Docs',+ queryMode: 'custom',+ customQuery: 'release notes',+ }),+ ],+ envVariables: [+ expect.objectContaining({+ key: 'REGION',+ scope: 'plain',+ value: 'us-east-1',+ }),+ expect.objectContaining({+ key: 'OPENAI_API_KEY',+ masked: true,+ scope: 'secret',+ }),+ ],+ })+ expect(formState.tools).toEqual(expect.arrayContaining([+ expect.objectContaining({+ id: 'duckduckgo',+ kind: 'provider',+ actions: [+ expect.objectContaining({+ toolName: 'ddg_search',+ }),+ ],+ }),+ expect.objectContaining({+ id: 'run-tests',+ kind: 'cli',+ installCommand: 'pnpm install',+ }),+ ]))+ expect(formState.toolSettings['duckduckgo:ddg_search']).toEqual({+ query: 'latest docs',+ used_in_agent_nodes: true,+ })++ expect(publishConfig.skills_files).toMatchObject(baseConfig.skills_files!)+ expect(publishConfig.tools?.dify_tools).toEqual([+ expect.objectContaining({+ provider: 'DuckDuckGo',+ provider_id: 'duckduckgo',+ provider_type: 'builtin',+ tool_name: 'ddg_search',+ credential_type: 'unauthorized',+ runtime_parameters: {+ query: 'latest docs',+ used_in_agent_nodes: true,+ },+ }),+ ])+ expect(publishConfig.tools?.dify_tools?.[0]).not.toHaveProperty('name')+ expect(publishConfig.tools?.cli_tools).toEqual([+ expect.objectContaining({+ name: 'Run Tests',+ tool_name: 'run-tests',+ install_command: 'pnpm install',+ enabled: false,+ pre_authorized: false,+ }),+ ])+ expect(publishConfig.knowledge).toMatchObject({+ datasets: [+ {+ id: 'dataset-1',+ name: 'Product Docs',+ description: 'Docs corpus',+ },+ ],+ query_config: {+ query: 'release notes',+ score_threshold: 0.72,+ score_threshold_enabled: true,+ top_k: 8,+ },+ query_mode: 'user_query',+ })+ expect(publishConfig.env).toMatchObject({+ variables: [+ expect.objectContaining({+ key: 'REGION',+ value: 'us-east-1',+ }),+ ],+ secret_refs: [+ expect.objectContaining({+ key: 'OPENAI_API_KEY',+ ref: 'secret-1',+ }),+ ],+ })+ })++ it('should keep unauthorized credential type when no-auth tool settings change', () => {+ const publishConfig = formStateToAgentSoulConfig({+ formState: {+ ...defaultAgentSoulConfigFormState,+ tools: [+ {+ id: 'duckduckgo',+ kind: 'provider',+ name: 'duckduckgo',+ iconClassName: 'i-custom-public-other-default-tool-icon text-text-tertiary',+ credentialVariant: 'none',+ actions: [+ {+ id: 'duckduckgo:ddg_search',+ name: 'DuckDuckGo Search',+ toolName: 'ddg_search',+ description: 'Search the web.',+ },+ ],+ },+ ],+ toolSettings: {+ 'duckduckgo:ddg_search': {+ query: 'updated query',+ },+ },+ },+ })++ expect(publishConfig.tools?.dify_tools).toEqual([+ expect.objectContaining({+ provider_id: 'duckduckgo',+ tool_name: 'ddg_search',+ credential_type: 'unauthorized',+ runtime_parameters: {+ query: 'updated query',+ },+ }),+ ])+ })++ it('should derive model plugin_id from the selected provider when publishing', () => {+ const publishConfig = formStateToAgentSoulConfig({+ baseConfig: {+ model: {+ model: 'gpt-4.1',+ model_provider: 'langgenius/openai/openai',+ plugin_id: 'langgenius/openai',+ },+ },+ formState: defaultAgentSoulConfigFormState,+ currentModel: {+ provider: 'langgenius/anthropic/anthropic',+ model: 'claude-sonnet-4',+ },+ })++ expect(publishConfig.model).toMatchObject({+ model: 'claude-sonnet-4',+ model_provider: 'langgenius/anthropic/anthropic',+ plugin_id: 'langgenius/anthropic',+ })+ })++ it('should not hydrate a knowledge retrieval row when the config has no datasets', () => {+ const formState = agentSoulConfigToFormState({+ knowledge: {+ datasets: [],+ query_config: {+ top_k: 4,+ },+ query_mode: 'generated_query',+ },+ })++ expect(formState.knowledgeRetrievals).toEqual([])+ })++ it('should omit incomplete environment variables from the publish payload', () => {+ const publishConfig = formStateToAgentSoulConfig({+ formState: {+ ...defaultAgentSoulConfigFormState,+ envVariables: [+ {+ id: 'empty-env',+ key: '',+ value: '',+ scope: 'plain',+ },+ {+ id: 'empty-value-env',+ key: 'EMPTY_VALUE',+ value: '',+ scope: 'plain',+ },+ {+ id: 'empty-key-env',+ key: '',+ value: 'secret',+ scope: 'plain',+ },+ {+ id: 'invalid-key-env',+ key: '1BAD',+ value: 'secret',+ scope: 'plain',+ },+ {+ id: 'valid-env',+ key: ' REGION ',+ value: 'us-east-1',+ scope: 'plain',+ },+ {+ id: 'empty-secret',+ key: '',+ value: '',+ scope: 'secret',+ },+ {+ id: 'empty-secret-value',+ key: 'EMPTY_SECRET_VALUE',+ value: '',+ scope: 'secret',+ },+ {+ id: 'invalid-secret-key',+ key: 'BAD-SECRET',+ value: 'secret',+ scope: 'secret',+ },+ {+ id: 'valid-secret',+ key: ' OPENAI_API_KEY ',+ value: '********',+ scope: 'secret',+ masked: true,+ },+ ],+ tools: [+ {+ id: 'run-tests',+ name: 'Run Tests',+ kind: 'cli',+ envVariables: [+ {+ id: 'empty-cli-env',+ key: '',+ value: '',+ scope: 'plain',+ },+ {+ id: 'invalid-cli-env',+ key: 'BAD-CLI',+ value: 'test',+ scope: 'plain',+ },+ {+ id: 'valid-cli-env',+ key: 'NODE_ENV',+ value: 'test',+ scope: 'plain',+ },+ ],+ },+ ],+ },+ })++ expect(publishConfig.env).toEqual({+ variables: [+ {+ id: 'valid-env',+ key: 'REGION',+ name: 'REGION',+ value: 'us-east-1',+ variable: 'REGION',+ },+ ],+ secret_refs: [+ {+ id: 'valid-secret',+ key: 'OPENAI_API_KEY',+ name: 'OPENAI_API_KEY',+ ref: 'valid-secret',+ variable: 'OPENAI_API_KEY',+ },+ ],+ })+ expect(publishConfig.tools?.cli_tools?.[0]?.env).toEqual({+ variables: [+ {+ id: 'valid-cli-env',+ key: 'NODE_ENV',+ name: 'NODE_ENV',+ value: 'test',+ variable: 'NODE_ENV',+ },+ ],+ secret_refs: [],+ })+ expect(publishConfig.tools?.cli_tools?.[0]).toMatchObject({+ enabled: false,+ pre_authorized: false,+ })+ })+})diff --git a/web/features/agent-v2/agent-composer/conversions.ts b/web/features/agent-v2/agent-composer/conversions.tsnew file mode 100644index 00000000000..d194b63af3f--- /dev/null+++ b/web/features/agent-v2/agent-composer/conversions.ts@@ -0,0 +1,497 @@+import type { AgentSoulConfig } from '@dify/contracts/api/console/agent/types.gen'+import type {+ AgentCliTool,+ AgentFileNode,+ AgentKnowledgeRetrievalItem,+ AgentProviderTool,+ AgentSkill,+ AgentSoulConfigFormState,+ AgentTool,+ EnvVariable,+} from './form-state'+import type { DefaultModel } from '@/app/components/header/account-setting/model-provider-page/declarations'+import { checkKey } from '@/utils/var'+import { defaultAgentSoulConfigFormState } from './form-state'++type AgentSoulDifyToolConfig = NonNullable<NonNullable<AgentSoulConfig['tools']>['dify_tools']>[number]+type AgentSoulCliToolConfig = NonNullable<NonNullable<AgentSoulConfig['tools']>['cli_tools']>[number]+type AgentSoulToolRuntimeParameterValue = NonNullable<AgentSoulDifyToolConfig['runtime_parameters']>[string]+type AgentSoulFileRefConfig = NonNullable<NonNullable<AgentSoulConfig['skills_files']>['files']>[number]+type AgentSoulEnvVariableConfig = NonNullable<NonNullable<AgentSoulConfig['env']>['variables']>[number]++const flattenFileNodes = (files: AgentFileNode[]): AgentFileNode[] => files.flatMap(file => [+ file,+ ...flattenFileNodes(file.children ?? []),+])++const toSkillRefs = (skills: AgentSkill[]) => skills.map(skill => ({+ description: skill.description,+ file_id: skill.fileId,+ full_archive_file_id: skill.fullArchiveFileId,+ full_archive_key: skill.fullArchiveKey,+ id: skill.id,+ manifest_files: skill.files,+ name: skill.name,+ path: skill.path,+ skill_md_file_id: skill.skillMdFileId,+ skill_md_key: skill.skillMdKey,+}))++const toSkillFormState = (config?: AgentSoulConfig): AgentSkill[] => (+ config?.skills_files?.skills ?? []+).flatMap((skill) => {+ const id = skill.id ?? skill.file_id ?? skill.path+ if (!id)+ return []++ return [{+ description: skill.description ?? undefined,+ fileId: skill.file_id ?? undefined,+ files: skill.manifest_files ?? undefined,+ fullArchiveFileId: skill.full_archive_file_id ?? undefined,+ fullArchiveKey: skill.full_archive_key ?? undefined,+ id,+ name: skill.name ?? id,+ path: skill.path ?? undefined,+ skillMdFileId: skill.skill_md_file_id ?? undefined,+ skillMdKey: skill.skill_md_key ?? undefined,+ }]+})++const toFileIcon = (file: AgentSoulFileRefConfig): AgentFileNode['icon'] => {+ const type = file.type?.toLowerCase()++ if (type === 'image' || type === 'pdf' || type === 'markdown' || type === 'json' || type === 'table' || type === 'archive' || type === 'code' || type === 'text' || type === 'folder')+ return type++ return 'file'+}++const toFileFormState = (config?: AgentSoulConfig): AgentFileNode[] => (+ config?.skills_files?.files ?? []+).flatMap((file) => {+ const id = file.id ?? file.file_id ?? file.upload_file_id ?? file.reference ?? file.remote_url ?? file.url+ if (!id)+ return []++ return [{+ id,+ name: file.name ?? id,+ icon: toFileIcon(file),+ }]+})++const toFileRefs = (files: AgentFileNode[]) => flattenFileNodes(files).map(file => ({+ id: file.id,+ name: file.name,+ type: file.icon,+}))++const getKnowledgeRetrievalName = (item: AgentKnowledgeRetrievalItem) => item.name ?? item.nameKey ?? item.id++const toKnowledgeDatasets = (knowledgeRetrievals: AgentKnowledgeRetrievalItem[]) => knowledgeRetrievals.flatMap((item) => {+ if (item.selectedDatasets?.length) {+ return item.selectedDatasets.map(dataset => ({+ description: dataset.description,+ id: dataset.id,+ name: dataset.name,+ }))+ }+ if (item.datasetRefs?.length)+ return item.datasetRefs++ return [{+ id: item.id,+ name: getKnowledgeRetrievalName(item),+ }]+})++const toKnowledgeRetrievalFormState = (config?: AgentSoulConfig): AgentKnowledgeRetrievalItem[] => {+ const knowledge = config?.knowledge+ const datasets = knowledge?.datasets ?? []++ if (datasets.length === 0)+ return []++ return [{+ id: datasets[0]?.id ?? 'knowledge-retrieval',+ name: datasets[0]?.name ?? 'Knowledge Retrieval',+ queryMode: knowledge?.query_mode === 'user_query' ? 'custom' : 'agent',+ customQuery: knowledge?.query_config?.query ?? undefined,+ datasetRefs: datasets,+ multipleRetrievalConfig: {+ top_k: knowledge?.query_config?.top_k ?? 4,+ score_threshold: knowledge?.query_config?.score_threshold ?? null,+ reranking_enable: false,+ },+ }]+}++const toKnowledgeConfig = (+ baseKnowledge: AgentSoulConfig['knowledge'],+ knowledgeRetrievals: AgentKnowledgeRetrievalItem[],+): AgentSoulConfig['knowledge'] => {+ const primaryRetrieval = knowledgeRetrievals.find(retrieval =>+ retrieval.queryMode === 'custom'+ || retrieval.customQuery+ || retrieval.multipleRetrievalConfig+ || retrieval.selectedDatasets?.length,+ ) ?? knowledgeRetrievals[0]+ const multipleRetrievalConfig = primaryRetrieval?.multipleRetrievalConfig+ const scoreThreshold = multipleRetrievalConfig?.score_threshold++ return {+ ...baseKnowledge,+ datasets: toKnowledgeDatasets(knowledgeRetrievals),+ query_mode: primaryRetrieval?.queryMode === 'custom' ? 'user_query' : 'generated_query',+ query_config: {+ ...baseKnowledge?.query_config,+ query: primaryRetrieval?.queryMode === 'custom' ? primaryRetrieval.customQuery : null,+ score_threshold: scoreThreshold,+ score_threshold_enabled: scoreThreshold !== undefined && scoreThreshold !== null,+ top_k: multipleRetrievalConfig?.top_k ?? baseKnowledge?.query_config?.top_k,+ },+ }+}++const isToolRuntimeParameterValue = (value: unknown): value is AgentSoulToolRuntimeParameterValue => {+ if (value === null || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean')+ return true++ if (!Array.isArray(value))+ return false++ return value.every(item => typeof item === 'string')+ || value.every(item => typeof item === 'number')+ || value.every(item => typeof item === 'boolean')+}++const toToolRuntimeParameters = (settings: Record<string, unknown> | undefined) => {+ const runtimeParameters: Record<string, AgentSoulToolRuntimeParameterValue> = {}++ Object.entries(settings ?? {}).forEach(([key, value]) => {+ if (isToolRuntimeParameterValue(value))+ runtimeParameters[key] = value+ })++ return runtimeParameters+}++const getDifyToolActionId = (tool: AgentSoulDifyToolConfig) => `${tool.provider_id ?? tool.provider ?? tool.plugin_id ?? 'provider'}:${tool.tool_name ?? tool.name ?? 'tool'}`++const toCredentialVariant = (credentialType: AgentSoulDifyToolConfig['credential_type']) => {+ if (credentialType === 'api-key')+ return 'authorized' as const++ if (credentialType === 'unauthorized')+ return 'unauthorized' as const++ return 'none' as const+}++const toProviderToolFormState = (config?: AgentSoulConfig): {+ tools: AgentProviderTool[]+ toolSettings: AgentSoulConfigFormState['toolSettings']+} => {+ const toolByProviderId = new Map<string, AgentProviderTool>()+ const toolSettings: AgentSoulConfigFormState['toolSettings'] = {}++ for (const tool of config?.tools?.dify_tools ?? []) {+ const providerId = tool.provider_id ?? tool.provider ?? tool.plugin_id ?? ''+ const toolName = tool.tool_name ?? tool.name ?? ''+ if (!providerId || !toolName)+ continue++ const actionId = getDifyToolActionId(tool)+ const existingTool = toolByProviderId.get(providerId)+ const action = {+ id: actionId,+ name: tool.name ?? toolName,+ toolName,+ description: tool.description ?? '',+ }++ toolSettings[actionId] = tool.runtime_parameters ?? {}++ if (existingTool) {+ existingTool.actions.push(action)+ continue+ }++ toolByProviderId.set(providerId, {+ id: providerId,+ name: tool.provider ?? providerId,+ kind: 'provider',+ iconClassName: 'i-custom-public-other-default-tool-icon text-text-tertiary',+ providerType: tool.provider_type,+ allowDelete: tool.credential_type === 'api-key' || tool.credential_type === 'unauthorized',+ credentialId: tool.credential_ref?.id ?? undefined,+ credentialKey: tool.credential_type === 'api-key'+ ? 'agentDetail.configure.tools.credential.authOne'+ : undefined,+ credentialType: tool.credential_type,+ credentialVariant: toCredentialVariant(tool.credential_type),+ actions: [action],+ })+ }++ return {+ tools: Array.from(toolByProviderId.values()),+ toolSettings,+ }+}++const toDifyToolConfigs = (+ tools: AgentTool[],+ toolSettings: Record<string, Record<string, unknown>>,+) => tools.flatMap((tool) => {+ if (tool.kind !== 'provider')+ return []++ return tool.actions.map(action => ({+ enabled: true,+ provider: tool.name,+ provider_id: tool.id,+ provider_type: tool.providerType ?? 'builtin',+ tool_name: action.toolName,+ runtime_parameters: toToolRuntimeParameters(toolSettings[action.id]),+ credential_type: tool.credentialType ?? (tool.credentialVariant === 'authorized' ? 'api-key' as const : 'unauthorized' as const),+ credential_ref: tool.credentialId+ ? {+ id: tool.credentialId,+ provider: tool.id,+ type: 'provider' as const,+ }+ : undefined,+ }))+})++const toEnvVariableValue = (variable: AgentSoulEnvVariableConfig) => {+ const value = variable.value ?? variable.default ?? ''+ if (value === null)+ return ''++ if (typeof value === 'string')+ return value++ return JSON.stringify(value)+}++const toCliEnvVariables = (tool: AgentSoulCliToolConfig): EnvVariable[] => [+ ...(tool.env?.variables ?? []).map((variable): EnvVariable => {+ const key = variable.key ?? variable.name ?? variable.variable ?? variable.env_name ?? ''+ return {+ id: variable.env_name ?? variable.key ?? variable.name ?? variable.variable ?? key,+ key,+ value: toEnvVariableValue(variable),+ scope: 'plain',+ }+ }),+ ...(tool.env?.secret_refs ?? []).map((secret): EnvVariable => {+ const key = secret.key ?? secret.name ?? secret.variable ?? secret.env_name ?? ''+ return {+ id: secret.id ?? secret.ref ?? secret.credential_id ?? key,+ key,+ value: '••••••••••••',+ scope: 'secret',+ masked: true,+ }+ }),+].filter(variable => variable.key)++const toCliToolFormState = (config?: AgentSoulConfig): AgentCliTool[] => (+ config?.tools?.cli_tools ?? []+).flatMap((tool) => {+ const id = tool.tool_name ?? tool.id ?? tool.name+ if (!id)+ return []++ return [{+ id,+ name: tool.name ?? tool.label ?? tool.tool_name ?? id,+ kind: 'cli',+ action: tool.pre_authorized ? 'preAuthorize' : undefined,+ installCommand: tool.install_command ?? tool.install_commands?.[0] ?? tool.install ?? tool.setup_command ?? undefined,+ envVariables: toCliEnvVariables(tool),+ }]+})++const hasValidEnvKey = (variable: EnvVariable) => checkKey(variable.key.trim(), false) === true++const hasEnvValue = (variable: EnvVariable) => variable.value.trim().length > 0++const isPublishablePlainEnvVariable = (variable: EnvVariable) => (+ variable.scope === 'plain' && hasValidEnvKey(variable) && hasEnvValue(variable)+)++const isPublishableSecretEnvVariable = (variable: EnvVariable) => (+ variable.scope === 'secret' && hasValidEnvKey(variable) && hasEnvValue(variable)+)++const toCliToolConfigs = (tools: AgentTool[]) => tools.flatMap((tool) => {+ if (tool.kind !== 'cli')+ return []++ const envVariables = tool.envVariables ?? []++ return [{+ enabled: false,+ env: {+ variables: envVariables+ .filter(isPublishablePlainEnvVariable)+ .map(variable => ({+ id: variable.id,+ key: variable.key.trim(),+ name: variable.key.trim(),+ value: variable.value,+ variable: variable.key.trim(),+ })),+ secret_refs: envVariables+ .filter(isPublishableSecretEnvVariable)+ .map(variable => ({+ id: variable.id,+ key: variable.key.trim(),+ name: variable.key.trim(),+ ref: variable.id,+ variable: variable.key.trim(),+ })),+ },+ install_command: tool.installCommand,+ install_commands: tool.installCommand ? [tool.installCommand] : [],+ name: tool.name,+ tool_name: tool.id,+ pre_authorized: false,+ }]+})++const toEnvVariableFormState = (config?: AgentSoulConfig): EnvVariable[] => [+ ...(config?.env?.variables ?? []).map((variable): EnvVariable => {+ const key = variable.key ?? variable.name ?? variable.variable ?? variable.env_name ?? ''+ return {+ id: variable.env_name ?? variable.key ?? variable.name ?? variable.variable ?? key,+ key,+ value: toEnvVariableValue(variable),+ scope: 'plain',+ }+ }),+ ...(config?.env?.secret_refs ?? []).map((secret): EnvVariable => {+ const key = secret.key ?? secret.name ?? secret.variable ?? secret.env_name ?? ''+ return {+ id: secret.id ?? secret.ref ?? secret.credential_id ?? key,+ key,+ value: '••••••••••••',+ scope: 'secret',+ masked: true,+ }+ }),+].filter(variable => variable.key)++const toEnvConfig = (variables: EnvVariable[]): AgentSoulConfig['env'] => ({+ variables: variables+ .filter(isPublishablePlainEnvVariable)+ .map(variable => ({+ id: variable.id,+ key: variable.key.trim(),+ name: variable.key.trim(),+ value: variable.value,+ variable: variable.key.trim(),+ })),+ secret_refs: variables+ .filter(isPublishableSecretEnvVariable)+ .map(variable => ({+ id: variable.id,+ key: variable.key.trim(),+ name: variable.key.trim(),+ ref: variable.id,+ variable: variable.key.trim(),+ })),+})++const toDraftModel = (config?: AgentSoulConfig): DefaultModel | undefined => {+ const modelProvider = config?.model?.model_provider+ const model = config?.model?.model++ if (!modelProvider || !model)+ return undefined++ return {+ provider: modelProvider,+ model,+ plugin_id: config?.model?.plugin_id,+ }+}++const getModelProviderPluginId = (model: DefaultModel, baseModel?: AgentSoulConfig['model']) => {+ if (model.plugin_id)+ return model.plugin_id++ if (baseModel?.model_provider === model.provider && baseModel.plugin_id)+ return baseModel.plugin_id++ const [organization, pluginName] = model.provider.split('/').filter(Boolean)++ if (organization && pluginName)+ return `${organization}/${pluginName}`++ return model.provider ? `langgenius/${model.provider}` : ''+}++export const formStateToAgentSoulConfig = ({+ baseConfig,+ formState,+ currentModel,+}: {+ baseConfig?: AgentSoulConfig+ formState: AgentSoulConfigFormState+ currentModel?: DefaultModel+}): AgentSoulConfig => ({+ ...baseConfig,+ prompt: {+ ...baseConfig?.prompt,+ system_prompt: formState.prompt,+ },+ model: currentModel+ ? {+ ...baseConfig?.model,+ model_provider: currentModel.provider,+ model: currentModel.model,+ plugin_id: getModelProviderPluginId(currentModel, baseConfig?.model),+ }+ : baseConfig?.model,+ skills_files: {+ ...baseConfig?.skills_files,+ skills: toSkillRefs(formState.skills),+ files: toFileRefs(formState.files),+ },+ tools: {+ ...baseConfig?.tools,+ dify_tools: toDifyToolConfigs(formState.tools, formState.toolSettings),+ cli_tools: toCliToolConfigs(formState.tools),+ },+ app_features: formState.appFeatures ?? baseConfig?.app_features,+ knowledge: toKnowledgeConfig(baseConfig?.knowledge, formState.knowledgeRetrievals),+ env: toEnvConfig(formState.envVariables),+})++export const agentSoulConfigToFormState = (+ config?: AgentSoulConfig,+ baseDraft: AgentSoulConfigFormState = defaultAgentSoulConfigFormState,+): AgentSoulConfigFormState => {+ const providerToolState = toProviderToolFormState(config)++ return {+ ...baseDraft,+ prompt: config?.prompt?.system_prompt ?? '',+ model: toDraftModel(config),+ appFeatures: config?.app_features,+ skills: toSkillFormState(config),+ files: toFileFormState(config),+ tools: [+ ...providerToolState.tools,+ ...toCliToolFormState(config),+ ],+ knowledgeRetrievals: toKnowledgeRetrievalFormState(config),+ envVariables: toEnvVariableFormState(config),+ toolSettings: providerToolState.toolSettings,+ }+}diff --git a/web/features/agent-v2/agent-composer/form-state.ts b/web/features/agent-v2/agent-composer/form-state.tsnew file mode 100644index 00000000000..26ad4b39501--- /dev/null+++ b/web/features/agent-v2/agent-composer/form-state.ts@@ -0,0 +1,118 @@+import type { AgentKnowledgeDatasetConfig, AgentSoulAppFeaturesConfig } from '@dify/contracts/api/console/agent/types.gen'+import type { FileTreeIconType } from '@langgenius/dify-ui/file-tree'+import type { DefaultModel } from '@/app/components/header/account-setting/model-provider-page/declarations'+import type { ToolDefaultValue } from '@/app/components/workflow/block-selector/types'+import type {+ MetadataFilteringConditions,+ MetadataFilteringModeEnum,+ MultipleRetrievalConfig,+} from '@/app/components/workflow/nodes/knowledge-retrieval/types'+import type { ModelConfig } from '@/app/components/workflow/types'+import type { DataSet } from '@/models/datasets'+import type { RETRIEVE_TYPE } from '@/types/app'+import type { I18nKeysWithPrefix } from '@/types/i18n'++export type EnvScope = 'secret' | 'plain'++export type EnvVariable = {+ id: string+ key: string+ value: string+ scope: EnvScope+ masked?: boolean+}++export type AgentSkill = {+ description?: string+ files?: string[]+ fileId?: string+ fullArchiveFileId?: string+ fullArchiveKey?: string+ id: string+ name: string+ path?: string+ skillMdFileId?: string+ skillMdKey?: string+}++export type AgentFileNode = {+ id: string+ name: string+ icon: FileTreeIconType+ children?: AgentFileNode[]+}++export type AgentKnowledgeRetrievalItem = {+ id: string+ name?: string+ nameKey?: I18nKeysWithPrefix<'agentV2', 'agentDetail.configure.knowledgeRetrieval.'>+ queryMode?: 'agent' | 'custom'+ customQuery?: string+ datasetRefs?: AgentKnowledgeDatasetConfig[]+ selectedDatasets?: DataSet[]+ retrievalMode?: RETRIEVE_TYPE+ multipleRetrievalConfig?: MultipleRetrievalConfig+ metadataFilterMode?: MetadataFilteringModeEnum+ metadataFilteringConditions?: MetadataFilteringConditions+ metadataModelConfig?: ModelConfig+}++type AgentToolBase = {+ id: string+ name: string+}++export type AgentToolAction = {+ id: string+ name: string+ toolName: string+ description: string+}++type AgentProviderToolCredentialType = 'api-key' | 'oauth2' | 'unauthorized'++export type AgentProviderTool = AgentToolBase & {+ kind: 'provider'+ displayName?: string+ iconClassName: string+ icon?: ToolDefaultValue['provider_icon']+ iconDark?: ToolDefaultValue['provider_icon_dark']+ providerType?: string+ allowDelete?: boolean+ credentialId?: string+ credentialKey?: I18nKeysWithPrefix<'agentV2', 'agentDetail.configure.tools.'>+ credentialType?: AgentProviderToolCredentialType+ credentialVariant: 'authorized' | 'unauthorized' | 'none'+ actions: AgentToolAction[]+}++export type AgentCliTool = AgentToolBase & {+ kind: 'cli'+ action?: 'preAuthorize'+ installCommand?: string+ envVariables?: EnvVariable[]+}++export type AgentTool = AgentProviderTool | AgentCliTool++export type AgentSoulConfigFormState = {+ prompt: string+ model?: DefaultModel+ appFeatures?: AgentSoulAppFeaturesConfig+ skills: AgentSkill[]+ files: AgentFileNode[]+ tools: AgentTool[]+ knowledgeRetrievals: AgentKnowledgeRetrievalItem[]+ envVariables: EnvVariable[]+ toolSettings: Record<string, Record<string, unknown>>+}++export const defaultAgentSoulConfigFormState: AgentSoulConfigFormState = {+ prompt: '',+ skills: [],+ files: [],+ tools: [],+ knowledgeRetrievals: [],+ envVariables: [],+ toolSettings: {},+}diff --git a/web/features/agent-v2/agent-composer/provider.tsx b/web/features/agent-v2/agent-composer/provider.tsxnew file mode 100644index 00000000000..189d828b45e--- /dev/null+++ b/web/features/agent-v2/agent-composer/provider.tsx@@ -0,0 +1,37 @@+'use client'++import type { ReactNode } from 'react'+import type { AgentSoulConfigFormState } from './form-state'+import { createStore, Provider as JotaiProvider } from 'jotai'+import { useRef } from 'react'+import { agentComposerDraftAtom, agentComposerOriginalDraftAtom } from './store'++function createAgentComposerStore(initialDraft?: AgentSoulConfigFormState) {+ const store = createStore()++ if (initialDraft)+ store.set(agentComposerDraftAtom, initialDraft)+ if (initialDraft)+ store.set(agentComposerOriginalDraftAtom, initialDraft)++ return store+}++export function AgentComposerProvider({+ children,+ initialDraft,+}: {+ children: ReactNode+ initialDraft?: AgentSoulConfigFormState+}) {+ const storeRef = useRef<ReturnType<typeof createAgentComposerStore> | null>(null)+ if (!storeRef.current)+ storeRef.current = createAgentComposerStore(initialDraft)+ const store = storeRef.current++ return (+ <JotaiProvider store={store}>+ {children}+ </JotaiProvider>+ )+}diff --git a/web/features/agent-v2/agent-composer/reference-labels.ts b/web/features/agent-v2/agent-composer/reference-labels.tsnew file mode 100644index 00000000000..25eaa9c7063--- /dev/null+++ b/web/features/agent-v2/agent-composer/reference-labels.ts@@ -0,0 +1,75 @@+import type { AgentKnowledgeRetrievalItem, AgentTool } from './form-state'++const getKnowledgeRetrievalName = (item: AgentKnowledgeRetrievalItem) => item.name ?? item.nameKey ?? item.id++const escapeRegExp = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')++const createReferenceToken = (kind: string, id: string, label: string) => (+ `[§${kind}:${id}${label ? `:${label}` : ''}§]`+)++const syncReferenceLabels = ({+ prompt,+ kind,+ currentItems,+ nextItems,+}: {+ prompt: string+ kind: string+ currentItems: Array<{ id: string, name: string }>+ nextItems: Array<{ id: string, name: string }>+}) => {+ const currentItemById = new Map(currentItems.map(item => [item.id, item]))++ return nextItems.reduce((nextPrompt, nextItem) => {+ const currentItem = currentItemById.get(nextItem.id)+ if (!currentItem)+ return nextPrompt++ if (currentItem.name === nextItem.name)+ return nextPrompt++ return nextPrompt.replace(+ new RegExp(`\\[§${escapeRegExp(kind)}:${escapeRegExp(nextItem.id)}(?::[^§\\]]*)?§\\]`, 'g'),+ createReferenceToken(kind, nextItem.id, nextItem.name),+ )+ }, prompt)+}++const toReferenceLabelItems = <Item extends { id: string }>(+ items: Item[],+ getName: (item: Item) => string,+) => items.map(item => ({+ id: item.id,+ name: getName(item),+}))++export const syncKnowledgeReferenceLabels = ({+ prompt,+ currentRetrievals,+ nextRetrievals,+}: {+ prompt: string+ currentRetrievals: AgentKnowledgeRetrievalItem[]+ nextRetrievals: AgentKnowledgeRetrievalItem[]+}) => syncReferenceLabels({+ prompt,+ kind: 'knowledge',+ currentItems: toReferenceLabelItems(currentRetrievals, getKnowledgeRetrievalName),+ nextItems: toReferenceLabelItems(nextRetrievals, getKnowledgeRetrievalName),+})++export const syncCliToolReferenceLabels = ({+ prompt,+ currentTools,+ nextTools,+}: {+ prompt: string+ currentTools: AgentTool[]+ nextTools: AgentTool[]+}) => syncReferenceLabels({+ prompt,+ kind: 'cli_tool',+ currentItems: toReferenceLabelItems(currentTools.filter(tool => tool.kind === 'cli'), tool => tool.name),+ nextItems: toReferenceLabelItems(nextTools.filter(tool => tool.kind === 'cli'), tool => tool.name),+})diff --git a/web/features/agent-v2/agent-composer/store-modules/app-features.ts b/web/features/agent-v2/agent-composer/store-modules/app-features.tsnew file mode 100644index 00000000000..27a037901cf--- /dev/null+++ b/web/features/agent-v2/agent-composer/store-modules/app-features.ts@@ -0,0 +1,25 @@+import type { AgentSoulAppFeaturesConfig } from '@dify/contracts/api/console/agent/types.gen'+import type { DraftFieldUpdate } from './utils'+import { atom, useAtomValue, useSetAtom } from 'jotai'+import { agentComposerDraftAtom } from '../store'+import { resolveDraftFieldUpdate } from './utils'++export const agentComposerAppFeaturesAtom = atom(+ get => get(agentComposerDraftAtom).appFeatures,+ (get, set, appFeaturesUpdate: DraftFieldUpdate<AgentSoulAppFeaturesConfig | undefined>) => {+ const draft = get(agentComposerDraftAtom)++ set(agentComposerDraftAtom, {+ ...draft,+ appFeatures: resolveDraftFieldUpdate(draft.appFeatures, appFeaturesUpdate),+ })+ },+)++export function useAppFeatures() {+ return useAtomValue(agentComposerAppFeaturesAtom)+}++export function useSetAppFeatures() {+ return useSetAtom(agentComposerAppFeaturesAtom)+}diff --git a/web/features/agent-v2/agent-composer/store-modules/env.ts b/web/features/agent-v2/agent-composer/store-modules/env.tsnew file mode 100644index 00000000000..8fcdd75b499--- /dev/null+++ b/web/features/agent-v2/agent-composer/store-modules/env.ts@@ -0,0 +1,17 @@+import type { EnvVariable } from '../form-state'+import type { DraftFieldUpdate } from './utils'+import { atom } from 'jotai'+import { agentComposerDraftAtom } from '../store'+import { resolveDraftFieldUpdate } from './utils'++export const agentComposerEnvVariablesAtom = atom(+ get => get(agentComposerDraftAtom).envVariables,+ (get, set, envVariablesUpdate: DraftFieldUpdate<EnvVariable[]>) => {+ const draft = get(agentComposerDraftAtom)++ set(agentComposerDraftAtom, {+ ...draft,+ envVariables: resolveDraftFieldUpdate(draft.envVariables, envVariablesUpdate),+ })+ },+)diff --git a/web/features/agent-v2/agent-composer/store-modules/files.ts b/web/features/agent-v2/agent-composer/store-modules/files.tsnew file mode 100644index 00000000000..b54f28f1c49--- /dev/null+++ b/web/features/agent-v2/agent-composer/store-modules/files.ts@@ -0,0 +1,17 @@+import type { AgentFileNode } from '../form-state'+import type { DraftFieldUpdate } from './utils'+import { atom } from 'jotai'+import { agentComposerDraftAtom } from '../store'+import { resolveDraftFieldUpdate } from './utils'++export const agentComposerFilesAtom = atom(+ get => get(agentComposerDraftAtom).files,+ (get, set, filesUpdate: DraftFieldUpdate<AgentFileNode[]>) => {+ const draft = get(agentComposerDraftAtom)++ set(agentComposerDraftAtom, {+ ...draft,+ files: resolveDraftFieldUpdate(draft.files, filesUpdate),+ })+ },+)diff --git a/web/features/agent-v2/agent-composer/store-modules/knowledge.ts b/web/features/agent-v2/agent-composer/store-modules/knowledge.tsnew file mode 100644index 00000000000..b33b4f6e951--- /dev/null+++ b/web/features/agent-v2/agent-composer/store-modules/knowledge.ts@@ -0,0 +1,24 @@+import type { AgentKnowledgeRetrievalItem } from '../form-state'+import type { DraftFieldUpdate } from './utils'+import { atom } from 'jotai'+import { syncKnowledgeReferenceLabels } from '../reference-labels'+import { agentComposerDraftAtom } from '../store'+import { resolveDraftFieldUpdate } from './utils'++export const agentComposerKnowledgeRetrievalsAtom = atom(+ get => get(agentComposerDraftAtom).knowledgeRetrievals,+ (get, set, knowledgeRetrievalsUpdate: DraftFieldUpdate<AgentKnowledgeRetrievalItem[]>) => {+ const draft = get(agentComposerDraftAtom)+ const knowledgeRetrievals = resolveDraftFieldUpdate(draft.knowledgeRetrievals, knowledgeRetrievalsUpdate)++ set(agentComposerDraftAtom, {+ ...draft,+ prompt: syncKnowledgeReferenceLabels({+ prompt: draft.prompt,+ currentRetrievals: draft.knowledgeRetrievals,+ nextRetrievals: knowledgeRetrievals,+ }),+ knowledgeRetrievals,+ })+ },+)diff --git a/web/features/agent-v2/agent-composer/store-modules/model.ts b/web/features/agent-v2/agent-composer/store-modules/model.tsnew file mode 100644index 00000000000..c44359633a6--- /dev/null+++ b/web/features/agent-v2/agent-composer/store-modules/model.ts@@ -0,0 +1,17 @@+import type { DraftFieldUpdate } from './utils'+import type { DefaultModel } from '@/app/components/header/account-setting/model-provider-page/declarations'+import { atom } from 'jotai'+import { agentComposerDraftAtom } from '../store'+import { resolveDraftFieldUpdate } from './utils'++export const agentComposerModelAtom = atom(+ get => get(agentComposerDraftAtom).model,+ (get, set, modelUpdate: DraftFieldUpdate<DefaultModel | undefined>) => {+ const draft = get(agentComposerDraftAtom)++ set(agentComposerDraftAtom, {+ ...draft,+ model: resolveDraftFieldUpdate(draft.model, modelUpdate),+ })+ },+)diff --git a/web/features/agent-v2/agent-composer/store-modules/prompt.ts b/web/features/agent-v2/agent-composer/store-modules/prompt.tsnew file mode 100644index 00000000000..3b4cb2b528c--- /dev/null+++ b/web/features/agent-v2/agent-composer/store-modules/prompt.ts@@ -0,0 +1,16 @@+import type { DraftFieldUpdate } from './utils'+import { atom } from 'jotai'+import { agentComposerDraftAtom } from '../store'+import { resolveDraftFieldUpdate } from './utils'++export const agentComposerPromptAtom = atom(+ get => get(agentComposerDraftAtom).prompt,+ (get, set, promptUpdate: DraftFieldUpdate<string>) => {+ const draft = get(agentComposerDraftAtom)++ set(agentComposerDraftAtom, {+ ...draft,+ prompt: resolveDraftFieldUpdate(draft.prompt, promptUpdate),+ })+ },+)diff --git a/web/features/agent-v2/agent-composer/store-modules/skills.ts b/web/features/agent-v2/agent-composer/store-modules/skills.tsnew file mode 100644index 00000000000..e35c03d3aec--- /dev/null+++ b/web/features/agent-v2/agent-composer/store-modules/skills.ts@@ -0,0 +1,26 @@+import type { AgentSkill } from '../form-state'+import type { DraftFieldUpdate } from './utils'+import { atom, useSetAtom } from 'jotai'+import { useCallback } from 'react'+import { agentComposerDraftAtom } from '../store'+import { resolveDraftFieldUpdate } from './utils'++export const agentComposerSkillsAtom = atom(+ get => get(agentComposerDraftAtom).skills,+ (get, set, skillsUpdate: DraftFieldUpdate<AgentSkill[]>) => {+ const draft = get(agentComposerDraftAtom)++ set(agentComposerDraftAtom, {+ ...draft,+ skills: resolveDraftFieldUpdate(draft.skills, skillsUpdate),+ })+ },+)++export function useRemoveSkill() {+ const setSkills = useSetAtom(agentComposerSkillsAtom)++ return useCallback((skillId: string) => {+ setSkills(skills => skills.filter(skill => skill.id !== skillId))+ }, [setSkills])+}diff --git a/web/features/agent-v2/agent-composer/store-modules/tools.ts b/web/features/agent-v2/agent-composer/store-modules/tools.tsnew file mode 100644index 00000000000..c1d8c64082c--- /dev/null+++ b/web/features/agent-v2/agent-composer/store-modules/tools.ts@@ -0,0 +1,107 @@+import type { AgentSoulConfigFormState, AgentTool } from '../form-state'+import type { DraftFieldUpdate } from './utils'+import { atom, useSetAtom } from 'jotai'+import { useCallback } from 'react'+import { syncCliToolReferenceLabels } from '../reference-labels'+import { agentComposerDraftAtom } from '../store'+import { resolveDraftFieldUpdate } from './utils'++export const agentComposerToolsAtom = atom(+ get => get(agentComposerDraftAtom).tools,+ (get, set, toolsUpdate: DraftFieldUpdate<AgentTool[]>) => {+ const draft = get(agentComposerDraftAtom)+ const tools = resolveDraftFieldUpdate(draft.tools, toolsUpdate)++ set(agentComposerDraftAtom, {+ ...draft,+ prompt: syncCliToolReferenceLabels({+ prompt: draft.prompt,+ currentTools: draft.tools,+ nextTools: tools,+ }),+ tools,+ })+ },+)++export const agentComposerToolSettingsAtom = atom(+ get => get(agentComposerDraftAtom).toolSettings,+ (get, set, toolSettingsUpdate: DraftFieldUpdate<Record<string, Record<string, unknown>>>) => {+ const draft = get(agentComposerDraftAtom)++ set(agentComposerDraftAtom, {+ ...draft,+ toolSettings: resolveDraftFieldUpdate(draft.toolSettings, toolSettingsUpdate),+ })+ },+)++const omitToolSettings = (+ toolSettings: AgentSoulConfigFormState['toolSettings'],+ actionIds: string[],+) => {+ const nextToolSettings = { ...toolSettings }++ actionIds.forEach((actionId) => {+ delete nextToolSettings[actionId]+ })++ return nextToolSettings+}++export function useRemoveProviderTool() {+ const setDraft = useSetAtom(agentComposerDraftAtom)++ return useCallback((toolId: string) => {+ setDraft((draft) => {+ const toolToRemove = draft.tools.find(tool => tool.kind === 'provider' && tool.id === toolId)+ const actionIds = toolToRemove?.kind === 'provider'+ ? toolToRemove.actions.map(action => action.id)+ : []++ return {+ ...draft,+ tools: draft.tools.filter(tool => tool.id !== toolId),+ toolSettings: omitToolSettings(draft.toolSettings, actionIds),+ }+ })+ }, [setDraft])+}++export function useRemoveProviderToolAction() {+ const setDraft = useSetAtom(agentComposerDraftAtom)++ return useCallback((toolId: string, actionId: string) => {+ setDraft(draft => ({+ ...draft,+ tools: draft.tools.flatMap((tool) => {+ if (tool.kind !== 'provider' || tool.id !== toolId)+ return [tool]++ const nextActions = tool.actions.filter(action => action.id !== actionId)+ return nextActions.length > 0+ ? [{ ...tool, actions: nextActions }]+ : []+ }),+ toolSettings: omitToolSettings(draft.toolSettings, [actionId]),+ }))+ }, [setDraft])+}++export function useSetProviderToolCredential() {+ const setTools = useSetAtom(agentComposerToolsAtom)++ return useCallback((toolId: string, credentialId?: string) => {+ setTools(tools => tools.map((tool) => {+ if (tool.kind !== 'provider' || tool.id !== toolId)+ return tool++ return {+ ...tool,+ credentialId,+ credentialType: 'api-key',+ credentialVariant: 'authorized',+ }+ }))+ }, [setTools])+}diff --git a/web/features/agent-v2/agent-composer/store-modules/utils.ts b/web/features/agent-v2/agent-composer/store-modules/utils.tsnew file mode 100644index 00000000000..c5272001e3a--- /dev/null+++ b/web/features/agent-v2/agent-composer/store-modules/utils.ts@@ -0,0 +1,10 @@+export type DraftFieldUpdate<Value> = Value | ((currentValue: Value) => Value)++export const resolveDraftFieldUpdate = <Value>(+ currentValue: Value,+ update: DraftFieldUpdate<Value>,+) => (+ typeof update === 'function'+ ? (update as (currentValue: Value) => Value)(currentValue)+ : update+)diff --git a/web/features/agent-v2/agent-composer/store.ts b/web/features/agent-v2/agent-composer/store.tsnew file mode 100644index 00000000000..446529ba556--- /dev/null+++ b/web/features/agent-v2/agent-composer/store.ts@@ -0,0 +1,132 @@+import type { AgentSoulConfig } from '@dify/contracts/api/console/agent/types.gen'+import type { AgentSoulConfigFormState } from './form-state'+import type { DefaultModel } from '@/app/components/header/account-setting/model-provider-page/declarations'+import isEqual from 'fast-deep-equal'+import { atom, useAtomValue, useSetAtom } from 'jotai'+import { useEffect, useMemo, useRef } from 'react'+import { agentSoulConfigToFormState, formStateToAgentSoulConfig } from './conversions'+import { defaultAgentSoulConfigFormState } from './form-state'++export const agentComposerOriginalConfigAtom = atom<AgentSoulConfig | undefined>(undefined)+export const agentComposerOriginalDraftAtom = atom<AgentSoulConfigFormState | undefined>(defaultAgentSoulConfigFormState)+export const agentComposerPublishedDraftAtom = atom<AgentSoulConfigFormState | undefined>(defaultAgentSoulConfigFormState)+export const agentComposerDraftAtom = atom<AgentSoulConfigFormState>(defaultAgentSoulConfigFormState)++export const isAgentComposerDirtyAtom = atom((get) => {+ const originalDraft = get(agentComposerOriginalDraftAtom)+ const draft = get(agentComposerDraftAtom)++ return !isEqual(draft, originalDraft ?? defaultAgentSoulConfigFormState)+})++const hasAgentComposerUnpublishedChangesAtom = atom((get) => {+ const publishedDraft = get(agentComposerPublishedDraftAtom)+ const draft = get(agentComposerDraftAtom)++ return !isEqual(draft, publishedDraft ?? defaultAgentSoulConfigFormState)+})++function useHydrate({+ defaultDraft = defaultAgentSoulConfigFormState,+ instanceKey,+ draft,+ originalConfig,+ waitForDraft,+}: {+ defaultDraft?: AgentSoulConfigFormState+ instanceKey: string+ draft?: AgentSoulConfigFormState+ originalConfig?: AgentSoulConfig+ waitForDraft?: boolean+}) {+ const setOriginalDraft = useSetAtom(agentComposerOriginalDraftAtom)+ const setPublishedDraft = useSetAtom(agentComposerPublishedDraftAtom)+ const setOriginalConfig = useSetAtom(agentComposerOriginalConfigAtom)+ const setDraft = useSetAtom(agentComposerDraftAtom)+ const resetKeyRef = useRef<string | undefined>(undefined)+ const hydratedKeyRef = useRef<string | undefined>(undefined)++ useEffect(() => {+ if (resetKeyRef.current !== instanceKey) {+ resetKeyRef.current = instanceKey+ hydratedKeyRef.current = undefined+ setOriginalConfig(undefined)+ setOriginalDraft(defaultDraft)+ setPublishedDraft(defaultDraft)+ setDraft(defaultDraft)+ }++ if (waitForDraft && !draft)+ return++ if (hydratedKeyRef.current === instanceKey)+ return++ hydratedKeyRef.current = instanceKey+ setOriginalConfig(originalConfig)+ setOriginalDraft(draft ?? defaultDraft)+ setPublishedDraft(draft ?? defaultDraft)+ setDraft(draft ?? defaultDraft)+ }, [defaultDraft, draft, instanceKey, originalConfig, setDraft, setOriginalConfig, setOriginalDraft, setPublishedDraft, waitForDraft])+}++export function useHydrateAgentSoulConfigDraft({+ agentId,+ activeVersionId,+ baseDraft = defaultAgentSoulConfigFormState,+ config,+}: {+ agentId: string+ activeVersionId?: string | null+ baseDraft?: AgentSoulConfigFormState+ config?: AgentSoulConfig+}) {+ const routeKey = `${agentId}:${activeVersionId ?? 'draft'}`+ useHydrate({+ defaultDraft: baseDraft,+ instanceKey: routeKey,+ draft: agentSoulConfigToFormState(config, baseDraft),+ originalConfig: config,+ waitForDraft: !!activeVersionId && !config,+ })+}++export function useHasAgentComposerUnpublishedChanges() {+ return useAtomValue(hasAgentComposerUnpublishedChangesAtom)+}++export function useAgentComposerConfigSnapshot({+ baseConfig,+ currentModel,+}: {+ baseConfig?: AgentSoulConfig+ currentModel?: DefaultModel+}) {+ const draft = useAtomValue(agentComposerDraftAtom)++ return useMemo(() => formStateToAgentSoulConfig({+ baseConfig,+ formState: draft,+ currentModel,+ }), [baseConfig, currentModel, draft])+}++export function useConfigPublishPayload({+ agentId,+ baseConfig,+ currentModel,+}: {+ agentId: string+ baseConfig?: AgentSoulConfig+ currentModel?: DefaultModel+}) {+ const configSnapshot = useAgentComposerConfigSnapshot({+ baseConfig,+ currentModel,+ })++ return useMemo(() => ({+ agent_id: agentId,+ config_snapshot: configSnapshot,+ }), [agentId, configSnapshot])+}diff --git a/web/features/agent-v2/agent-detail/__tests__/navigation.spec.tsx b/web/features/agent-v2/agent-detail/__tests__/navigation.spec.tsxnew file mode 100644index 00000000000..b5f3f48b6e1--- /dev/null+++ b/web/features/agent-v2/agent-detail/__tests__/navigation.spec.tsx@@ -0,0 +1,73 @@+import type { AgentAppDetailWithSite } from '@dify/contracts/api/console/agent/types.gen'+import { render, screen } from '@testing-library/react'+import { AgentDetailSection } from '../navigation'++const mocks = vi.hoisted(() => ({+ pathname: '/roster/agent/agent-1/configure',+ queryData: undefined as AgentAppDetailWithSite | undefined,+}))++vi.mock('@tanstack/react-query', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@tanstack/react-query')>()++ return {+ ...actual,+ useQuery: () => ({+ data: mocks.queryData,+ isPending: !mocks.queryData,+ }),+ }+})++vi.mock('@/next/navigation', () => ({+ usePathname: () => mocks.pathname,+ useRouter: () => ({+ back: vi.fn(),+ }),+}))++vi.mock('@/app/components/app-sidebar/nav-link', () => ({+ default: ({ href, name }: { href: string, name: string }) => <a href={href}>{name}</a>,+}))++vi.mock('@/app/components/base/divider', () => ({+ default: () => <div data-testid="divider" />,+}))++const createAgent = (overrides: Partial<AgentAppDetailWithSite> = {}): AgentAppDetailWithSite => ({+ description: 'Find and summarize market materials.',+ enable_api: true,+ enable_site: true,+ icon: '🧪',+ icon_background: '#E0F2FE',+ icon_type: 'emoji',+ id: 'agent-1',+ icon_url: null,+ mode: 'agent',+ name: 'Research Agent',+ role: 'Research Assistant',+ ...overrides,+})++describe('AgentDetailSection', () => {+ beforeEach(() => {+ mocks.pathname = '/roster/agent/agent-1/configure'+ mocks.queryData = createAgent()+ })++ it('renders the current agent avatar, name, and role', () => {+ const { container } = render(<AgentDetailSection />)+ const agentName = screen.getByText('Research Agent')+ const agentAvatar = container.querySelector('em-emoji')?.parentElement++ expect(agentName).toBeInTheDocument()+ expect(screen.getByText('Research Assistant')).toBeInTheDocument()+ expect(screen.queryByText('agent')).not.toBeInTheDocument()+ expect(screen.queryByText('agentV2.agentDetail.title')).not.toBeInTheDocument()+ expect(container.querySelector('em-emoji')).toHaveAttribute('id', '🧪')+ expect(agentAvatar).toHaveClass('h-10', 'w-10', 'rounded-full')+ expect(agentAvatar?.parentElement?.parentElement).toHaveClass('mr-2')+ expect(agentName.parentElement).toHaveClass('h-10')+ expect(agentName.parentElement?.parentElement).toHaveClass('h-13', 'py-1.5', 'pl-1.5', 'pr-2')+ })+})diff --git a/web/features/agent-v2/agent-detail/access/access-sources.ts b/web/features/agent-v2/agent-detail/access/access-sources.tsnew file mode 100644index 00000000000..b3e758e4e10--- /dev/null+++ b/web/features/agent-v2/agent-detail/access/access-sources.ts@@ -0,0 +1,34 @@+import type { AgentAppDetailWithSite } from '@dify/contracts/api/console/agent/types.gen'+import type { I18nKeysWithPrefix } from '@/types/i18n'++export type AgentAccessSource = {+ id: string+ nameKey: I18nKeysWithPrefix<'agentV2', 'agentDetail.access.entries.'>+ descriptionKey: I18nKeysWithPrefix<'agentV2', 'agentDetail.access.entries.'>+ reference: string+ status: 'enabled' | 'disabled'+ icon: string+}++const getStatus = (agent: AgentAppDetailWithSite): AgentAccessSource['status'] =>+ agent.id ? 'enabled' : 'disabled'++export const getAgentAccessSources = (agent?: AgentAppDetailWithSite): AgentAccessSource[] => {+ if (!agent)+ return []++ const sources: AgentAccessSource[] = []++ if (agent.id) {+ sources.push({+ id: 'agent-app',+ nameKey: 'agentDetail.access.entries.agentApp.name',+ descriptionKey: 'agentDetail.access.entries.agentApp.description',+ reference: agent.id,+ status: getStatus(agent),+ icon: 'i-ri-window-line',+ })+ }++ return sources+}diff --git a/web/features/agent-v2/agent-detail/access/components/__tests__/workflow-references-table.spec.tsx b/web/features/agent-v2/agent-detail/access/components/__tests__/workflow-references-table.spec.tsxnew file mode 100644index 00000000000..a201666c869--- /dev/null+++ b/web/features/agent-v2/agent-detail/access/components/__tests__/workflow-references-table.spec.tsx@@ -0,0 +1,138 @@+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { render, screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { WorkflowReferencesTable } from '../workflow-references-table'++const mocks = vi.hoisted(() => ({+ queryFn: vi.fn(),+ queryOptions: vi.fn((input: unknown) => ({+ queryKey: ['agent-referencing-workflows', input],+ queryFn: () => mocks.queryFn(input),+ })),+}))++vi.mock('@/service/client', () => ({+ consoleQuery: {+ agent: {+ byAgentId: {+ referencingWorkflows: {+ get: {+ queryOptions: mocks.queryOptions,+ },+ },+ },+ },+ },+}))++vi.mock('@/hooks/use-timestamp', () => ({+ default: () => ({+ formatTime: (value: number) => `formatted-${value}`,+ }),+}))++const renderTable = () => {+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: {+ retry: false,+ },+ },+ })++ render(+ <QueryClientProvider client={queryClient}>+ <WorkflowReferencesTable agentId="agent-1" />+ </QueryClientProvider>,+ )++ return queryClient+}++describe('WorkflowReferencesTable', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ describe('Query contract', () => {+ it('should request workflow references for the current agent', async () => {+ mocks.queryFn.mockResolvedValueOnce({ data: [] })++ renderTable()++ await waitFor(() => {+ expect(mocks.queryOptions).toHaveBeenCalledWith({+ input: {+ params: {+ agent_id: 'agent-1',+ },+ },+ })+ })+ })+ })++ describe('Rendering', () => {+ it('should render workflow reference rows from the generated contract response', async () => {+ mocks.queryFn.mockResolvedValueOnce({+ data: [+ {+ app_icon: 'A',+ app_icon_background: '#E0F2FE',+ app_icon_type: 'emoji',+ app_id: 'workflow-app-id',+ app_mode: 'workflow',+ app_name: 'Support Workflow',+ app_updated_at: 1781660000,+ node_ids: ['agent-node-a', 'agent-node-b'],+ workflow_id: 'workflow-id',+ workflow_version: 'v3',+ },+ ],+ })++ renderTable()++ expect(await screen.findByText('Support Workflow')).toBeInTheDocument()+ expect(screen.getByText('v3')).toBeInTheDocument()+ expect(screen.getByText('agentV2.agentDetail.access.workflow.nodeCount:{"count":2}')).toBeInTheDocument()+ expect(screen.getByText('formatted-1781660000')).toBeInTheDocument()+ expect(screen.getByRole('link', { name: 'agentV2.agentDetail.access.workflow.openInStudioFor:{"name":"Support Workflow"}' }))+ .toHaveAttribute('href', '/app/workflow-app-id/workflow')+ })++ it('should render an empty state when the agent has no workflow references', async () => {+ mocks.queryFn.mockResolvedValueOnce({ data: [] })++ renderTable()++ expect(await screen.findByText('agentV2.agentDetail.access.workflow.empty')).toBeInTheDocument()+ })++ it('should render a loading row while workflow references are pending', () => {+ mocks.queryFn.mockReturnValueOnce(new Promise<never>(() => undefined))++ renderTable()++ expect(screen.getByText('agentV2.agentDetail.access.workflow.loading')).toBeInTheDocument()+ })+ })++ describe('Error state', () => {+ it('should render a retry action when loading workflow references fails', async () => {+ const user = userEvent.setup()+ mocks.queryFn+ .mockRejectedValueOnce(new Error('failed'))+ .mockResolvedValueOnce({ data: [] })++ renderTable()++ expect(await screen.findByText('agentV2.agentDetail.access.workflow.loadFailed')).toBeInTheDocument()+ await user.click(screen.getByRole('button', { name: 'common.operation.retry' }))++ await waitFor(() => {+ expect(mocks.queryFn).toHaveBeenCalledTimes(2)+ })+ })+ })+})diff --git a/web/features/agent-v2/agent-detail/access/components/workflow-references-table.tsx b/web/features/agent-v2/agent-detail/access/components/workflow-references-table.tsxnew file mode 100644index 00000000000..0113fd5e45b--- /dev/null+++ b/web/features/agent-v2/agent-detail/access/components/workflow-references-table.tsx@@ -0,0 +1,171 @@+'use client'++import type { AgentIconType, AgentReferencingWorkflowResponse } from '@dify/contracts/api/console/agent/types.gen'+import type { ReactNode } from 'react'+import { Button } from '@langgenius/dify-ui/button'+import { useQuery } from '@tanstack/react-query'+import { useTranslation } from 'react-i18next'+import AppIcon from '@/app/components/base/app-icon'+import useTimestamp from '@/hooks/use-timestamp'+import Link from '@/next/link'+import { consoleQuery } from '@/service/client'++type WorkflowReferencesTableProps = {+ agentId: string+}++const workflowTableColSpan = 5++const getWorkflowReferenceHref = (reference: AgentReferencingWorkflowResponse) => `/app/${reference.app_id}/workflow`++export function WorkflowReferencesTable({+ agentId,+}: WorkflowReferencesTableProps) {+ const { t } = useTranslation('agentV2')+ const { t: tCommon } = useTranslation('common')+ const workflowReferencesQuery = useQuery(consoleQuery.agent.byAgentId.referencingWorkflows.get.queryOptions({+ input: {+ params: {+ agent_id: agentId,+ },+ },+ }))+ const workflowReferences = workflowReferencesQuery.data?.data ?? []++ return (+ <div className="overflow-x-auto">+ <table className="w-full min-w-[1212px] table-fixed border-collapse">+ <colgroup>+ <col className="w-[572px]" />+ <col className="w-40" />+ <col className="w-32" />+ <col className="w-[204px]" />+ <col className="w-36" />+ </colgroup>+ <thead>+ <tr className="h-7 rounded-lg bg-background-section-burn text-left system-xs-semibold-uppercase text-text-tertiary">+ <th scope="col" className="rounded-l-lg px-3 font-semibold">+ {t('agentDetail.access.workflow.table.name')}+ </th>+ <th scope="col" className="px-3 font-semibold">+ {t('agentDetail.access.workflow.table.version')}+ </th>+ <th scope="col" className="px-3 font-semibold">+ {t('agentDetail.access.workflow.table.nodes')}+ </th>+ <th scope="col" className="px-3 font-semibold">+ {t('agentDetail.access.workflow.table.lastUpdated')}+ </th>+ <th scope="col" className="rounded-r-lg px-3 font-semibold">+ {t('agentDetail.access.workflow.table.actions')}+ </th>+ </tr>+ </thead>+ <tbody className="system-sm-regular text-text-secondary">+ {workflowReferencesQuery.isPending && (+ <WorkflowAccessStateRow>+ {t('agentDetail.access.workflow.loading')}+ </WorkflowAccessStateRow>+ )}+ {workflowReferencesQuery.isError && (+ <WorkflowAccessStateRow>+ <div className="flex items-center justify-center gap-2">+ <span>{t('agentDetail.access.workflow.loadFailed')}</span>+ <Button+ variant="secondary"+ size="small"+ onClick={() => {+ void workflowReferencesQuery.refetch()+ }}+ >+ {tCommon('operation.retry')}+ </Button>+ </div>+ </WorkflowAccessStateRow>+ )}+ {workflowReferencesQuery.isSuccess && workflowReferences.length === 0 && (+ <WorkflowAccessStateRow>+ {t('agentDetail.access.workflow.empty')}+ </WorkflowAccessStateRow>+ )}+ {workflowReferencesQuery.isSuccess && workflowReferences.map(reference => (+ <WorkflowAccessRow+ key={`${reference.app_id}:${reference.workflow_id}`}+ reference={reference}+ />+ ))}+ </tbody>+ </table>+ </div>+ )+}++function WorkflowAccessRow({+ reference,+}: {+ reference: AgentReferencingWorkflowResponse+}) {+ const { t } = useTranslation('agentV2')+ const { formatTime } = useTimestamp()+ const imageUrl = (reference.app_icon_type === 'image' || reference.app_icon_type === 'link') ? reference.app_icon : undefined+ const iconType = (imageUrl ? 'image' : reference.app_icon_type) as AgentIconType | null | undefined+ const updatedAt = reference.app_updated_at != null+ ? formatTime(reference.app_updated_at, t('roster.dateTimeFormat'))+ : t('agentDetail.access.workflow.notAvailable')+ const nodeCount = reference.node_ids?.length ?? 0++ return (+ <tr className="h-10 border-b border-divider-subtle hover:bg-background-default-hover">+ <td className="px-3">+ <div className="flex min-w-0 items-center gap-2.5">+ <span aria-hidden className="shrink-0">+ <AppIcon+ size="small"+ rounded+ iconType={iconType}+ icon={reference.app_icon ?? undefined}+ background={reference.app_icon_background}+ imageUrl={imageUrl}+ />+ </span>+ <span className="truncate">+ {reference.app_name}+ </span>+ </div>+ </td>+ <td className="truncate px-3" translate="no">+ {reference.workflow_version}+ </td>+ <td className="px-3 tabular-nums">+ {t('agentDetail.access.workflow.nodeCount', { count: nodeCount })}+ </td>+ <td className="px-3 tabular-nums" translate="no">+ {updatedAt}+ </td>+ <td className="px-3">+ <Link+ href={getWorkflowReferenceHref(reference)}+ aria-label={t('agentDetail.access.workflow.openInStudioFor', { name: reference.app_name })}+ className="inline-flex items-center gap-0.5 rounded-sm text-text-secondary hover:text-text-accent hover:underline focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"+ >+ {t('agentDetail.access.workflow.openInStudio')}+ <span aria-hidden className="i-ri-external-link-line size-4" />+ </Link>+ </td>+ </tr>+ )+}++function WorkflowAccessStateRow({+ children,+}: {+ children: ReactNode+}) {+ return (+ <tr className="h-20 border-b border-divider-subtle">+ <td colSpan={workflowTableColSpan} aria-live="polite" className="px-3 text-center text-text-tertiary">+ {children}+ </td>+ </tr>+ )+}diff --git a/web/features/agent-v2/agent-detail/access/page.tsx b/web/features/agent-v2/agent-detail/access/page.tsxnew file mode 100644index 00000000000..6b3e2af6a06--- /dev/null+++ b/web/features/agent-v2/agent-detail/access/page.tsx@@ -0,0 +1,308 @@+'use client'++import type { AgentAppDetailWithSite } from '@dify/contracts/api/console/agent/types.gen'+import type { ReactNode } from 'react'+import { Button } from '@langgenius/dify-ui/button'+import { cn } from '@langgenius/dify-ui/cn'+import { ScrollArea } from '@langgenius/dify-ui/scroll-area'+import { StatusDot } from '@langgenius/dify-ui/status-dot'+import { Switch } from '@langgenius/dify-ui/switch'+import { toast } from '@langgenius/dify-ui/toast'+import { useQuery } from '@tanstack/react-query'+import { useClipboard } from 'foxact/use-clipboard'+import { useState } from 'react'+import { useTranslation } from 'react-i18next'+import { useDocLink } from '@/context/i18n'+import { consoleQuery } from '@/service/client'+import { WorkflowReferencesTable } from './components/workflow-references-table'++type AgentAccessPageProps = {+ agentId: string+}++const serviceApiEndpoint = 'https://api.dify.ai/v1'++type AgentWebAppSite = NonNullable<AgentAppDetailWithSite['site']> & {+ access_token?: string | null+ app_base_url?: string | null+ code?: string | null+}++type AccessSurfaceCardProps = {+ title: string+ icon: string+ iconClassName: string+ endpointLabel: string+ endpoint: string+ enabled: boolean+ onEnabledChange: (enabled: boolean) => void+ copyLabel: string+ children: ReactNode+ badge?: ReactNode+ onUnavailableAction: () => void+}++const getAgentWebAppUrl = (agent?: AgentAppDetailWithSite) => {+ const site = agent?.site as AgentWebAppSite | null | undefined+ const token = site?.access_token ?? site?.code+ if (!token)+ return ''++ const baseUrl = site?.app_base_url || (typeof window === 'undefined' ? '' : window.location.origin)+ return `${baseUrl.replace(/\/$/, '')}/agent/${token}`+}++export function AgentAccessPage({+ agentId,+}: AgentAccessPageProps) {+ const { t } = useTranslation('agentV2')+ const docLink = useDocLink()+ const agentQuery = useQuery(consoleQuery.agent.byAgentId.get.queryOptions({+ input: {+ params: {+ agent_id: agentId,+ },+ },+ }))+ const [isWebAppEnabled, setIsWebAppEnabled] = useState(true)+ const [isServiceApiEnabled, setIsServiceApiEnabled] = useState(true)+ const webAppUrl = getAgentWebAppUrl(agentQuery.data)+ const handleUnavailableAction = () => {+ toast.info(t('agentDetail.access.actionUnavailable'))+ }++ return (+ <section+ aria-label={t('agentDetail.sections.access')}+ className="flex h-full min-w-0 flex-1 flex-col overflow-hidden bg-components-panel-bg-blur"+ >+ <header className="h-15.5 shrink-0 px-6 pt-3 pb-2">+ <div className="min-w-0">+ <h2 className="system-xl-semibold text-text-primary">+ {t('agentDetail.access.title')}+ </h2>+ <p className="mt-1 flex min-w-0 flex-wrap items-center gap-x-0.5 system-xs-regular text-text-tertiary">+ <span>{t('agentDetail.access.description')}</span>+ <a+ href={docLink('/use-dify/publish/webapp/web-app-access')}+ target="_blank"+ rel="noreferrer"+ className="inline-flex shrink-0 items-center gap-0.5 rounded-sm text-text-accent hover:underline focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"+ >+ {t('agentDetail.access.learnMore')}+ <span aria-hidden className="i-ri-external-link-line size-3" />+ </a>+ </p>+ </div>+ </header>++ <ScrollArea+ className="min-h-0 flex-1 overflow-hidden"+ slotClassNames={{+ content: 'px-6 pt-2 pb-8',+ }}+ >+ <div className="w-full min-w-0 space-y-6">+ <div className="grid w-full grid-cols-1 gap-3 xl:grid-cols-2">+ <AccessSurfaceCard+ title={t('agentDetail.access.webApp.title')}+ icon="i-ri-window-line"+ iconClassName="bg-state-accent-solid text-text-primary-on-surface"+ endpointLabel={t('agentDetail.access.webApp.accessUrl')}+ endpoint={webAppUrl}+ enabled={isWebAppEnabled}+ onEnabledChange={setIsWebAppEnabled}+ copyLabel={t('agentDetail.access.copyAccessUrl')}+ badge={<SsoBadge />}+ onUnavailableAction={handleUnavailableAction}+ >+ <Button+ variant="secondary"+ size="medium"+ nativeButton={false}+ className="gap-1.5 px-3"+ render={<a href={webAppUrl} target="_blank" rel="noreferrer" aria-label={t('agentDetail.access.webApp.actions.launch')} />}+ >+ <span aria-hidden className="i-ri-external-link-line size-4" />+ {t('agentDetail.access.webApp.actions.launch')}+ </Button>+ <Button variant="secondary" size="medium" className="gap-1.5 px-3" onClick={handleUnavailableAction}>+ <span aria-hidden className="i-ri-window-line size-4" />+ {t('agentDetail.access.webApp.actions.embedded')}+ </Button>+ <Button variant="secondary" size="medium" className="gap-1.5 px-3" onClick={handleUnavailableAction}>+ <span aria-hidden className="i-ri-paint-brush-line size-4" />+ {t('agentDetail.access.webApp.actions.customize')}+ </Button>+ <Button variant="secondary" size="medium" className="gap-1.5 px-3" onClick={handleUnavailableAction}>+ <span aria-hidden className="i-ri-equalizer-line size-4" />+ {t('agentDetail.access.webApp.actions.settings')}+ </Button>+ </AccessSurfaceCard>++ <AccessSurfaceCard+ title={t('agentDetail.access.serviceApi.title')}+ icon="i-ri-node-tree"+ iconClassName="bg-state-accent-solid text-text-primary-on-surface"+ endpointLabel={t('agentDetail.access.serviceApi.endpoint')}+ endpoint={serviceApiEndpoint}+ enabled={isServiceApiEnabled}+ onEnabledChange={setIsServiceApiEnabled}+ copyLabel={t('agentDetail.access.copyServiceEndpoint')}+ onUnavailableAction={handleUnavailableAction}+ >+ <Button variant="secondary" size="medium" className="gap-1.5 px-3" onClick={handleUnavailableAction}>+ <span aria-hidden className="i-ri-key-2-line size-4" />+ {t('agentDetail.access.serviceApi.actions.apiKey')}+ <span className="rounded-md bg-components-badge-bg-gray-soft px-1.5 code-xs-regular text-text-tertiary">+ 21+ </span>+ </Button>+ <Button+ variant="secondary"+ size="medium"+ nativeButton={false}+ className="gap-1.5 px-3"+ render={<a href={docLink('/use-dify/publish/developing-with-apis')} target="_blank" rel="noreferrer" aria-label={t('agentDetail.access.serviceApi.actions.apiReference')} />}+ >+ <span aria-hidden className="i-ri-book-open-line size-4" />+ {t('agentDetail.access.serviceApi.actions.apiReference')}+ </Button>+ </AccessSurfaceCard>+ </div>++ <section aria-labelledby="agent-workflow-access-title">+ <div className="mb-3">+ <h3 id="agent-workflow-access-title" className="system-md-semibold text-text-primary">+ {t('agentDetail.access.workflow.title')}+ </h3>+ <p className="mt-0.5 system-xs-regular text-text-tertiary">+ {t('agentDetail.access.workflow.description')}+ </p>+ </div>++ <WorkflowReferencesTable agentId={agentId} />+ </section>+ </div>+ </ScrollArea>+ </section>+ )+}++function AccessSurfaceCard({+ title,+ icon,+ iconClassName,+ endpointLabel,+ endpoint,+ enabled,+ onEnabledChange,+ copyLabel,+ children,+ badge,+ onUnavailableAction,+}: AccessSurfaceCardProps) {+ const { t } = useTranslation('agentV2')+ const { copy } = useClipboard({+ onCopyError: () => {+ toast.error(t('agentDetail.access.copyFailed'))+ },+ })++ const handleCopyEndpoint = () => {+ void copy(endpoint)+ }++ return (+ <article className="overflow-hidden rounded-xl border border-components-panel-border bg-components-panel-bg shadow-xs">+ <div className="px-4 pt-4 pb-4">+ <div className="flex min-w-0 items-center gap-3">+ <div className="flex min-w-0 flex-1 items-center gap-2">+ <span className={cn('flex size-6 shrink-0 items-center justify-center rounded-lg', iconClassName)}>+ <span aria-hidden className={cn(icon, 'size-4')} />+ </span>+ <h3 className="truncate system-md-semibold text-text-secondary">+ {title}+ </h3>+ {badge}+ </div>++ <div className="flex shrink-0 items-center gap-3">+ <span className={cn(+ 'inline-flex items-center gap-1 system-xs-semibold-uppercase',+ enabled ? 'text-util-colors-green-green-700' : 'text-text-tertiary',+ )}+ >+ <StatusDot status={enabled ? 'success' : 'disabled'} size="small" />+ {t(enabled ? 'agentDetail.access.status.inService' : 'agentDetail.access.status.outOfService')}+ </span>+ <Switch+ size="md"+ checked={enabled}+ aria-label={t('agentDetail.access.toggleSurface', { name: title })}+ onCheckedChange={onEnabledChange}+ />+ </div>+ </div>++ <div className="mt-3">+ <div className="system-xs-medium text-text-tertiary">+ {endpointLabel}+ </div>+ <div className="mt-1 flex h-8 min-w-0 items-center rounded-lg bg-components-input-bg-normal px-2">+ <span className="min-w-0 flex-1 truncate system-sm-regular text-text-secondary" translate="no">+ {endpoint}+ </span>+ <Button+ variant="ghost"+ size="small"+ className="size-6 shrink-0 px-0 text-text-tertiary hover:text-text-secondary"+ aria-label={copyLabel}+ onClick={handleCopyEndpoint}+ >+ <span aria-hidden className="i-ri-file-copy-line size-4" />+ </Button>+ {badge !== undefined && badge !== null && (+ <>+ <span className="mx-1.5 h-3.5 w-px shrink-0 bg-divider-regular" />+ <Button+ variant="ghost"+ size="small"+ className="size-6 shrink-0 px-0 text-text-tertiary hover:text-text-secondary"+ aria-label={t('agentDetail.access.webApp.showQrCode')}+ onClick={onUnavailableAction}+ >+ <span aria-hidden className="i-ri-qr-code-line size-4" />+ </Button>+ <Button+ variant="ghost"+ size="small"+ className="size-6 shrink-0 px-0 text-text-tertiary hover:text-text-secondary"+ aria-label={t('agentDetail.access.webApp.refreshUrl')}+ onClick={onUnavailableAction}+ >+ <span aria-hidden className="i-ri-refresh-line size-4" />+ </Button>+ </>+ )}+ </div>+ </div>+ </div>++ <div className="flex min-h-16 flex-wrap items-center gap-2 border-t border-divider-subtle px-4 py-4">+ {children}+ </div>+ </article>+ )+}++function SsoBadge() {+ const { t } = useTranslation('agentV2')++ return (+ <span className="inline-flex h-4.5 shrink-0 items-center gap-1 rounded-sm border border-divider-deep px-1.5 system-2xs-semibold-uppercase text-text-tertiary">+ <span aria-hidden className="i-ri-shield-check-line size-3" />+ {t('agentDetail.access.webApp.ssoEnabled')}+ </span>+ )+}diff --git a/web/features/agent-v2/agent-detail/configure/__tests__/page.spec.tsx b/web/features/agent-v2/agent-detail/configure/__tests__/page.spec.tsxnew file mode 100644index 00000000000..1214f186497--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/__tests__/page.spec.tsx@@ -0,0 +1,144 @@+import { render, screen } from '@testing-library/react'+import { AgentConfigurePage } from '../page'++const mocks = vi.hoisted(() => ({+ queryState: {+ agent: {+ data: {+ icon: 'agent',+ icon_background: '#E0F2FE',+ icon_type: 'emoji',+ name: 'Research Agent',+ },+ isFetching: false,+ isPending: false,+ isSuccess: true,+ },+ composer: {+ data: undefined,+ isFetching: true,+ isPending: true,+ isSuccess: false,+ },+ version: {+ data: undefined,+ isFetching: false,+ isPending: false,+ isSuccess: false,+ },+ },+}))++vi.mock('@tanstack/react-query', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@tanstack/react-query')>()++ return {+ ...actual,+ useQuery: vi.fn((options: { queryKey?: readonly string[] }) => {+ const queryKey = options.queryKey?.[0]++ if (queryKey === 'agent')+ return mocks.queryState.agent+ if (queryKey === 'composer')+ return mocks.queryState.composer+ if (queryKey === 'version')+ return mocks.queryState.version++ return {+ data: undefined,+ isFetching: false,+ isPending: false,+ isSuccess: false,+ }+ }),+ }+})++vi.mock('@/service/client', () => ({+ consoleQuery: {+ agent: {+ byAgentId: {+ get: {+ queryOptions: () => ({ queryKey: ['agent'] }),+ },+ composer: {+ get: {+ queryOptions: () => ({ queryKey: ['composer'] }),+ },+ },+ versions: {+ byVersionId: {+ get: {+ queryOptions: () => ({ queryKey: ['version'] }),+ },+ },+ },+ },+ },+ },+}))++vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({+ useDefaultModel: () => ({ data: undefined }),+ useTextGenerationCurrentProviderAndModelAndModelList: () => ({+ textGenerationModelList: [],+ }),+}))++vi.mock('../components/orchestrate', () => ({+ AgentOrchestratePanel: () => <div role="region" aria-label="orchestrate-panel" />,+}))++vi.mock('../components/preview/chat', () => ({+ AgentPreviewChat: () => <div role="region" aria-label="preview-chat" />,+}))++vi.mock('../components/preview/chat-features-panel', () => ({+ AgentChatFeaturesPanel: () => null,+}))++vi.mock('../components/preview/header', () => ({+ AgentPreviewHeader: () => <div role="banner" />,+}))++vi.mock('../components/preview/versions-panel', () => ({+ AgentPreviewVersionsPanel: () => null,+}))++describe('AgentConfigurePage', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mocks.queryState.agent = {+ data: {+ icon: 'agent',+ icon_background: '#E0F2FE',+ icon_type: 'emoji',+ name: 'Research Agent',+ },+ isFetching: false,+ isPending: false,+ isSuccess: true,+ }+ mocks.queryState.composer = {+ data: undefined,+ isFetching: true,+ isPending: true,+ isSuccess: false,+ }+ mocks.queryState.version = {+ data: undefined,+ isFetching: false,+ isPending: false,+ isSuccess: false,+ }+ })++ describe('Loading state', () => {+ it('should show loading instead of the configure panels while composer data is pending', () => {+ render(<AgentConfigurePage agentId="agent-1" />)++ expect(screen.getByRole('status', { name: 'appApi.loading' })).toBeInTheDocument()+ expect(screen.queryByRole('region', { name: 'orchestrate-panel' })).not.toBeInTheDocument()+ })+ })+})diff --git a/web/features/agent-v2/agent-detail/configure/__tests__/use-agent-configure-sync.spec.tsx b/web/features/agent-v2/agent-detail/configure/__tests__/use-agent-configure-sync.spec.tsxnew file mode 100644index 00000000000..787120dd3cf--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/__tests__/use-agent-configure-sync.spec.tsx@@ -0,0 +1,202 @@+import type { PropsWithChildren } from 'react'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { act, renderHook } from '@testing-library/react'+import { createStore, Provider as JotaiProvider } from 'jotai'+import { defaultAgentSoulConfigFormState } from '@/features/agent-v2/agent-composer/form-state'+import { agentComposerDraftAtom } from '@/features/agent-v2/agent-composer/store'+import { useAgentConfigureSync } from '../use-agent-configure-sync'++const composerPutMutationFn = vi.hoisted(() => vi.fn(async (variables: {+ body: {+ agent_soul: Record<string, unknown>+ }+}) => ({+ agent_soul: variables.body.agent_soul,+})))++const composerPutMutationOptions = vi.hoisted(() => vi.fn((options?: {+ onSuccess?: (data: { agent_soul: Record<string, unknown> }, variables: {+ params: { agent_id: string }+ body: {+ agent_soul: Record<string, unknown>+ }+ }) => void+}) => ({+ mutationFn: async (variables: {+ params: { agent_id: string }+ body: {+ agent_soul: Record<string, unknown>+ }+ }) => {+ const data = await composerPutMutationFn(variables)+ options?.onSuccess?.(data, variables)+ return data+ },+})))++vi.mock('@/service/client', () => ({+ consoleQuery: {+ agent: {+ byAgentId: {+ composer: {+ get: {+ queryKey: ({ input }: { input: { params: { agent_id: string } } }) => [+ 'agent-composer',+ input.params.agent_id,+ ],+ },+ put: {+ mutationOptions: composerPutMutationOptions,+ },+ },+ versions: {+ get: {+ key: () => ['agent-versions'],+ },+ },+ },+ },+ },+}))++function renderUseAgentConfigureSync() {+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: { retry: false },+ mutations: { retry: false },+ },+ })+ const store = createStore()+ const wrapper = ({ children }: PropsWithChildren) => (+ <QueryClientProvider client={queryClient}>+ <JotaiProvider store={store}>+ {children}+ </JotaiProvider>+ </QueryClientProvider>+ )++ return {+ ...renderHook(() => useAgentConfigureSync({+ agentId: 'agent-1',+ enabled: true,+ }), { wrapper }),+ queryClient,+ store,+ }+}++describe('useAgentConfigureSync', () => {+ beforeEach(() => {+ vi.useFakeTimers()+ vi.clearAllMocks()+ })++ afterEach(() => {+ vi.useRealTimers()+ })++ it('should automatically save configure page changes to draft', async () => {+ vi.setSystemTime(1710000100000)+ const { queryClient, result, store } = renderUseAgentConfigureSync()++ expect(result.current.draftSavedAt).toBeUndefined()++ act(() => {+ store.set(agentComposerDraftAtom, {+ ...defaultAgentSoulConfigFormState,+ prompt: 'Draft only prompt',+ })+ })++ await act(async () => {+ await vi.advanceTimersByTimeAsync(5000)+ })++ expect(composerPutMutationFn).toHaveBeenCalledWith(expect.objectContaining({+ params: {+ agent_id: 'agent-1',+ },+ body: expect.objectContaining({+ variant: 'agent_app',+ save_strategy: 'save_to_current_version',+ agent_soul: expect.objectContaining({+ prompt: expect.objectContaining({+ system_prompt: 'Draft only prompt',+ }),+ }),+ }),+ }))+ expect(queryClient.getQueryData(['agent-composer', 'agent-1'])).toBeUndefined()+ expect(result.current.draftSavedAt).toBe(1710000105000)+ })++ it('should save the latest draft immediately when requested', async () => {+ vi.setSystemTime(1710000200000)+ const { result, store } = renderUseAgentConfigureSync()++ act(() => {+ store.set(agentComposerDraftAtom, {+ ...defaultAgentSoulConfigFormState,+ prompt: 'Run prompt',+ })+ })++ await act(async () => {+ await result.current.saveDraft()+ })++ expect(composerPutMutationFn).toHaveBeenCalledTimes(1)+ expect(composerPutMutationFn).toHaveBeenCalledWith(expect.objectContaining({+ params: {+ agent_id: 'agent-1',+ },+ body: expect.objectContaining({+ variant: 'agent_app',+ save_strategy: 'save_to_current_version',+ agent_soul: expect.objectContaining({+ prompt: expect.objectContaining({+ system_prompt: 'Run prompt',+ }),+ }),+ }),+ }))+ expect(result.current.draftSavedAt).toBe(1710000200000)+ })++ it('should publish only when publishDraft is called explicitly', async () => {+ const { queryClient, result } = renderUseAgentConfigureSync()++ await act(async () => {+ await result.current.publishDraft({+ agent_id: 'agent-1',+ config_snapshot: {+ prompt: {+ system_prompt: 'Published prompt',+ },+ },+ })+ })++ expect(composerPutMutationFn).toHaveBeenCalledWith(expect.objectContaining({+ params: {+ agent_id: 'agent-1',+ },+ body: expect.objectContaining({+ variant: 'agent_app',+ save_strategy: 'save_as_new_version',+ agent_soul: {+ prompt: {+ system_prompt: 'Published prompt',+ },+ },+ }),+ }))+ expect(queryClient.getQueryData(['agent-composer', 'agent-1'])).toEqual({+ agent_soul: {+ prompt: {+ system_prompt: 'Published prompt',+ },+ },+ })+ })+})diff --git a/web/features/agent-v2/agent-detail/configure/components/__tests__/agent-prompt-editor.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/__tests__/agent-prompt-editor.spec.tsxnew file mode 100644index 00000000000..7043cda75f0--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/__tests__/agent-prompt-editor.spec.tsx@@ -0,0 +1,445 @@+import type { ReactNode } from 'react'+import type { PromptEditorProps } from '@/app/components/base/prompt-editor'+import type { AgentTool } from '@/features/agent-v2/agent-composer/form-state'+import { fireEvent, render, screen, waitFor } from '@testing-library/react'+import { createStore, Provider as JotaiProvider } from 'jotai'+import { defaultAgentSoulConfigFormState } from '@/features/agent-v2/agent-composer/form-state'+import { agentComposerDraftAtom } from '@/features/agent-v2/agent-composer/store'+import { agentComposerKnowledgeRetrievalsAtom } from '@/features/agent-v2/agent-composer/store-modules/knowledge'+import { agentComposerPromptAtom } from '@/features/agent-v2/agent-composer/store-modules/prompt'+import { agentComposerToolsAtom } from '@/features/agent-v2/agent-composer/store-modules/tools'+import { AgentPromptEditor } from '../orchestrate/prompt-editor'+import { AgentPromptSlashMenu } from '../orchestrate/prompt-editor/slash'++const mockPromptEditor = vi.hoisted(() => vi.fn())+const mockCopy = vi.hoisted(() => vi.fn())+const mockReset = vi.hoisted(() => vi.fn())+const mockBuiltInTools = vi.hoisted(() => [+ {+ id: 'duckduckgo',+ name: 'DuckDuckGo',+ author: 'Dify',+ description: { en_US: 'DuckDuckGo tools' },+ icon: '/duckduckgo.svg',+ label: { en_US: 'DuckDuckGo' },+ type: 'builtin',+ team_credentials: {},+ is_team_authorization: true,+ allow_delete: false,+ labels: [],+ meta: {},+ tools: [+ {+ name: 'ddg_search',+ author: 'Dify',+ label: { en_US: 'DuckDuckGo Search' },+ description: { en_US: 'Search the web.' },+ parameters: [],+ labels: [],+ output_schema: {},+ },+ {+ name: 'ddg_translate',+ author: 'Dify',+ label: { en_US: 'DuckDuckGo Translate' },+ description: { en_US: 'Translate search results.' },+ parameters: [],+ labels: [],+ output_schema: {},+ },+ ],+ },+])++vi.mock('@/app/components/base/prompt-editor', () => ({+ __esModule: true,+ default: (props: PromptEditorProps) => {+ mockPromptEditor(props)++ return (+ <div>+ <div role="textbox" aria-label={String(props.placeholder)} />+ </div>+ )+ },+}))++vi.mock('@/app/components/base/infotip', () => ({+ Infotip: ({ children }: { children: ReactNode }) => <span>{children}</span>,+}))++vi.mock('foxact/use-clipboard', () => ({+ useClipboard: () => ({+ copied: false,+ copy: mockCopy,+ reset: mockReset,+ }),+}))++vi.mock('@/context/i18n', () => ({+ useGetLanguage: () => 'en_US',+}))++vi.mock('@/service/use-tools', () => ({+ useAllBuiltInTools: () => ({ data: mockBuiltInTools }),+ useAllCustomTools: () => ({ data: [] }),+ useAllWorkflowTools: () => ({ data: [] }),+ useAllMCPTools: () => ({ data: [] }),+}))++vi.mock('@/hooks/use-theme', () => ({+ default: () => ({ theme: 'light' }),+}))++const duckDuckGoSearchAction = {+ id: 'duckduckgo-search',+ name: 'DuckDuckGo Search',+ toolName: 'ddg_search',+ description: 'Search the web.',+}++const duckDuckGoProviderTool: AgentTool = {+ id: 'duckduckgo',+ name: 'DuckDuckGo',+ kind: 'provider',+ iconClassName: 'i-simple-icons-duckduckgo',+ credentialKey: 'agentDetail.configure.tools.credential.authOne',+ credentialVariant: 'authorized',+ actions: [+ duckDuckGoSearchAction,+ ],+}++const promptEditorDraft = {+ ...defaultAgentSoulConfigFormState,+ skills: [+ {+ id: 'playwright',+ name: 'Playwright',+ },+ ],+ tools: [duckDuckGoProviderTool],+} satisfies typeof defaultAgentSoulConfigFormState++const renderAgentPromptEditor = (+ value: string,+ draftOverrides: Partial<typeof defaultAgentSoulConfigFormState> = {},+) => {+ const store = createStore()+ store.set(agentComposerDraftAtom, {+ ...promptEditorDraft,+ ...draftOverrides,+ prompt: value,+ })++ const view = render(+ <JotaiProvider store={store}>+ <AgentPromptEditor />+ </JotaiProvider>,+ )++ return {+ store,+ ...view,+ rerenderWithValue: (nextValue: string) => {+ store.set(agentComposerPromptAtom, nextValue)+ view.rerender(+ <JotaiProvider store={store}>+ <AgentPromptEditor />+ </JotaiProvider>,+ )+ },+ }+}++describe('AgentPromptEditor', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ // Prompt actions should expose the designed copy control and copy the current draft prompt.+ describe('Prompt Actions', () => {+ it('should copy the current prompt when the copy button is clicked', () => {+ renderAgentPromptEditor('Review these tenders')++ fireEvent.click(screen.getByRole('button', { name: /agentDetail\.configure\.prompt\.copy/i }))++ expect(mockCopy).toHaveBeenCalledWith('Review these tenders')+ })++ it('should update knowledge reference labels when the retrieval title changes', () => {+ const store = createStore()+ store.set(agentComposerDraftAtom, {+ ...defaultAgentSoulConfigFormState,+ prompt: 'Use [§knowledge:retrieval-1:Old Search§] and [§knowledge:retrieval-2:Keep Search§]',+ knowledgeRetrievals: [+ { id: 'retrieval-1', name: 'Old Search' },+ { id: 'retrieval-2', name: 'Keep Search' },+ ],+ })++ store.set(agentComposerKnowledgeRetrievalsAtom, [+ { id: 'retrieval-1', name: 'Release Search' },+ { id: 'retrieval-2', name: 'Keep Search' },+ ])++ expect(store.get(agentComposerPromptAtom)).toBe('Use [§knowledge:retrieval-1:Release Search§] and [§knowledge:retrieval-2:Keep Search§]')+ })++ it('should update CLI tool reference labels when the tool title changes', () => {+ const store = createStore()+ store.set(agentComposerDraftAtom, {+ ...defaultAgentSoulConfigFormState,+ prompt: 'Run [§cli_tool:cli-1:Old CLI§] and [§tool:duckduckgo/ddg_search:DuckDuckGo Search§]',+ tools: [+ { id: 'cli-1', kind: 'cli', name: 'Old CLI' },+ duckDuckGoProviderTool,+ ],+ })++ store.set(agentComposerToolsAtom, [+ { id: 'cli-1', kind: 'cli', name: 'Release CLI' },+ {+ ...duckDuckGoProviderTool,+ actions: [+ {+ ...duckDuckGoSearchAction,+ name: 'Renamed Provider Action',+ },+ ],+ },+ ])++ expect(store.get(agentComposerPromptAtom)).toBe('Run [§cli_tool:cli-1:Release CLI§] and [§tool:duckduckgo/ddg_search:DuckDuckGo Search§]')+ })++ it('should render selected tool reference icons from configured tools', () => {+ renderAgentPromptEditor('Run tools')++ const promptEditorProps = mockPromptEditor.mock.calls.at(-1)?.[0] as PromptEditorProps+ const renderIcon = promptEditorProps.rosterReferenceBlock?.renderIcon+ expect(renderIcon).toBeDefined()++ const { container, rerender } = render(+ <>+ {renderIcon?.({+ kind: 'tool',+ id: 'duckduckgo/ddg_search',+ label: 'DuckDuckGo Search',+ })}+ </>,+ )++ expect(container.querySelector('.i-simple-icons-duckduckgo')).toBeInTheDocument()++ rerender(+ <>+ {renderIcon?.({+ kind: 'cli_tool',+ id: 'cli-1',+ label: 'Lark CLI',+ })}+ </>,+ )++ expect(container.querySelector('.i-ri-terminal-box-line')).toBeInTheDocument()+ })+ })++ // Prompt slash commands should use the Agent Roster category menu and replace it with submenus.+ describe('Slash Commands', () => {+ it('should open category menu, show skill submenu, and append the selected reference', async () => {+ const { store, rerenderWithValue } = renderAgentPromptEditor('Review these tenders')++ expect(mockPromptEditor).toHaveBeenCalledWith(expect.objectContaining({+ disableBracePicker: true,+ disableSlashPicker: true,+ rosterReferenceBlock: expect.objectContaining({+ show: true,+ }),+ }))++ expect(fireEvent.keyDown(screen.getByRole('textbox'), { key: '/' })).toBe(true)+ rerenderWithValue('Review these tenders/')+ expect(screen.getByRole('button', { name: /agentDetail\.configure\.skills\.label/i })).toBeInTheDocument()++ fireEvent.click(screen.getByRole('button', { name: /agentDetail\.configure\.skills\.label/i }))+ expect(screen.queryByRole('button', { name: /agentDetail\.configure\.files\.label/i })).not.toBeInTheDocument()++ fireEvent.click(screen.getByRole('button', { name: /Playwright/i }))++ expect(store.get(agentComposerPromptAtom)).toBe('Review these tenders [§skill:playwright:Playwright§]')+ await waitFor(() => {+ expect(screen.queryByRole('button', { name: /Playwright/i })).not.toBeInTheDocument()+ })+ })++ it('should insert slash from the focused footer insert action', () => {+ const { store } = renderAgentPromptEditor('Review these tenders')++ fireEvent.focus(screen.getByRole('textbox'))+ const insertButton = screen.getByRole('button', { name: /agentDetail\.configure\.prompt\.insert\.label/i })+ fireEvent.pointerDown(insertButton)+ fireEvent.click(insertButton)+ fireEvent.pointerUp(insertButton)++ expect(store.get(agentComposerPromptAtom)).toBe('Review these tenders/')+ expect(screen.getByRole('button', { name: /agentDetail\.configure\.skills\.label/i })).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: /agentDetail\.configure\.prompt\.mention\.label/i })).not.toBeInTheDocument()+ })++ it('should insert references after prompt add actions create skills, files, CLI tools, or knowledge retrievals', () => {+ const onSelect = vi.fn()+ const categories = [+ { key: 'skills' as const, label: 'Skills', icon: 'i-ri-box-3-line' },+ { key: 'files' as const, label: 'Files', icon: 'i-ri-file-line' },+ { key: 'tools' as const, label: 'Tools', icon: 'i-ri-box-3-line' },+ { key: 'knowledge' as const, label: 'Knowledge', icon: 'i-ri-book-open-line' },+ ]++ const { rerender } = render(+ <AgentPromptSlashMenu+ view="skills"+ categories={categories}+ skills={[]}+ files={[]}+ tools={[]}+ onToolsChange={vi.fn()}+ onAddSkill={options => options?.onAdded?.({ id: 'skill-1', name: 'Skill One' })}+ retrievals={[]}+ onBack={vi.fn()}+ onOpenCategory={vi.fn()}+ onSelect={onSelect}+ />,+ )+ fireEvent.click(screen.getByRole('button', { name: /agentDetail\.configure\.skills\.add/i }))+ expect(onSelect).toHaveBeenCalledWith('[§skill:skill-1:Skill One§]')++ rerender(+ <AgentPromptSlashMenu+ view="files"+ categories={categories}+ skills={[]}+ files={[]}+ tools={[]}+ onToolsChange={vi.fn()}+ onAddFile={options => options?.onAdded?.({ id: 'file-1', name: 'Guide.md', icon: 'markdown' })}+ retrievals={[]}+ onBack={vi.fn()}+ onOpenCategory={vi.fn()}+ onSelect={onSelect}+ />,+ )+ fireEvent.click(screen.getByRole('button', { name: /agentDetail\.configure\.files\.add/i }))+ expect(onSelect).toHaveBeenCalledWith('[§file:file-1:Guide.md§]')++ rerender(+ <AgentPromptSlashMenu+ view="knowledge"+ categories={categories}+ skills={[]}+ files={[]}+ tools={[]}+ onToolsChange={vi.fn()}+ onAddKnowledge={options => options?.onAdded?.({ id: 'retrieval-1', name: 'Retrieval One', queryMode: 'agent' })}+ retrievals={[]}+ onBack={vi.fn()}+ onOpenCategory={vi.fn()}+ onSelect={onSelect}+ />,+ )+ fireEvent.click(screen.getByRole('button', { name: /agentDetail\.configure\.knowledgeRetrieval\.add/i }))+ expect(onSelect).toHaveBeenCalledWith('[§knowledge:retrieval-1:Retrieval One§]')++ rerender(+ <AgentPromptSlashMenu+ view="tools"+ categories={categories}+ skills={[]}+ files={[]}+ tools={[]}+ onToolsChange={vi.fn()}+ onAddCliTool={options => options?.onAdded?.({ id: 'cli-1', kind: 'cli', name: 'Lark CLI' })}+ retrievals={[]}+ onBack={vi.fn()}+ onOpenCategory={vi.fn()}+ onSelect={onSelect}+ />,+ )+ fireEvent.click(screen.getByRole('button', { name: /agentDetail\.configure\.tools\.cliDialog\.title/i }))+ expect(onSelect).toHaveBeenCalledWith('[§cli_tool:cli-1:Lark CLI§]')+ })++ it('should append available provider tool references and add missing tools to the configuration', () => {+ const { store, rerenderWithValue } = renderAgentPromptEditor('Research/', { tools: [] })++ fireEvent.keyDown(screen.getByRole('textbox'), { key: '/' })+ fireEvent.click(screen.getByRole('button', { name: /agentDetail\.configure\.tools\.label/i }))+ fireEvent.click(screen.getByRole('button', { name: 'DuckDuckGo' }))+ fireEvent.click(screen.getByRole('button', { name: /DuckDuckGo Search/i }))++ expect(store.get(agentComposerPromptAtom)).toBe('Research [§tool:duckduckgo/ddg_search:DuckDuckGo Search§]')+ expect(store.get(agentComposerDraftAtom).tools).toEqual([+ expect.objectContaining({+ id: 'duckduckgo',+ actions: [+ expect.objectContaining({+ name: 'DuckDuckGo Search',+ toolName: 'ddg_search',+ }),+ ],+ }),+ ])++ rerenderWithValue('Research/')+ fireEvent.keyDown(screen.getByRole('textbox'), { key: '/' })+ fireEvent.click(screen.getByRole('button', { name: /agentDetail\.configure\.tools\.label/i }))+ fireEvent.click(screen.getByRole('button', { name: /DuckDuckGo.*agentDetail\.configure\.tools\.toolTabs\.plugins/i }))++ expect(store.get(agentComposerPromptAtom)).toBe('Research [§tool:duckduckgo/*:DuckDuckGo§]')+ expect(store.get(agentComposerDraftAtom).tools).toEqual([+ expect.objectContaining({+ id: 'duckduckgo',+ actions: [+ expect.objectContaining({ toolName: 'ddg_search' }),+ expect.objectContaining({ toolName: 'ddg_translate' }),+ ],+ }),+ ])+ })++ it('should close slash menu when slash is deleted or the user clicks outside', async () => {+ const { rerenderWithValue } = renderAgentPromptEditor('Review/')++ fireEvent.keyDown(screen.getByRole('textbox'), { key: '/' })+ expect(screen.getByRole('button', { name: /agentDetail\.configure\.skills\.label/i })).toBeInTheDocument()++ rerenderWithValue('Review')+ fireEvent.keyUp(screen.getByRole('textbox'), { key: 'Backspace' })++ await waitFor(() => {+ expect(screen.queryByRole('button', { name: /agentDetail\.configure\.skills\.label/i })).not.toBeInTheDocument()+ })++ rerenderWithValue('Review/')+ fireEvent.keyDown(screen.getByRole('textbox'), { key: '/' })+ expect(screen.getByRole('button', { name: /agentDetail\.configure\.skills\.label/i })).toBeInTheDocument()++ fireEvent.pointerDown(document.body)++ await waitFor(() => {+ expect(screen.queryByRole('button', { name: /agentDetail\.configure\.skills\.label/i })).not.toBeInTheDocument()+ })+ })++ it('should reopen slash menu when the cursor is positioned after slash', async () => {+ renderAgentPromptEditor('Review/')++ fireEvent.keyUp(screen.getByRole('textbox'), { key: 'ArrowRight' })++ await waitFor(() => {+ expect(screen.getByRole('button', { name: /agentDetail\.configure\.skills\.label/i })).toBeInTheDocument()+ })+ })+ })+})diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/__tests__/add-actions.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/__tests__/add-actions.spec.tsxnew file mode 100644index 00000000000..9e168f3eeb2--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/__tests__/add-actions.spec.tsx@@ -0,0 +1,65 @@+import { fireEvent, render, screen, waitFor } from '@testing-library/react'+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { AgentOrchestrateAddActionsProvider } from '../add-actions'+import { useAgentOrchestrateAddActions, useRegisterAgentOrchestrateAddAction } from '../add-actions-context'++function InlineActionRegisterer({+ label,+ onAction,+}: {+ label: string+ onAction: (label: string) => void+}) {+ useRegisterAgentOrchestrateAddAction('knowledge', () => {+ onAction(label)+ })++ return null+}++function RegisteredActionTrigger() {+ const actions = useAgentOrchestrateAddActions()++ return (+ <button type="button" disabled={!actions.knowledge} onClick={() => actions.knowledge?.()}>+ Run action+ </button>+ )+}++describe('AgentOrchestrateAddActionsProvider', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ describe('Registration', () => {+ it('should keep the registered action stable while calling the latest callback when the action prop changes every render', async () => {+ const handleAction = vi.fn()++ const { rerender } = render(+ <AgentOrchestrateAddActionsProvider>+ <InlineActionRegisterer label="first" onAction={handleAction} />+ <RegisteredActionTrigger />+ </AgentOrchestrateAddActionsProvider>,+ )++ await waitFor(() => {+ expect(screen.getByRole('button', { name: 'Run action' })).toBeEnabled()+ })++ fireEvent.click(screen.getByRole('button', { name: 'Run action' }))++ rerender(+ <AgentOrchestrateAddActionsProvider>+ <InlineActionRegisterer label="second" onAction={handleAction} />+ <RegisteredActionTrigger />+ </AgentOrchestrateAddActionsProvider>,+ )++ fireEvent.click(screen.getByRole('button', { name: 'Run action' }))++ expect(handleAction).toHaveBeenNthCalledWith(1, 'first')+ expect(handleAction).toHaveBeenNthCalledWith(2, 'second')+ })+ })+})diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/__tests__/empty-sections.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/__tests__/empty-sections.spec.tsxnew file mode 100644index 00000000000..2660d6d3aec--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/__tests__/empty-sections.spec.tsx@@ -0,0 +1,52 @@+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { render, screen } from '@testing-library/react'+import { describe, expect, it, vi } from 'vitest'+import { defaultAgentSoulConfigFormState } from '@/features/agent-v2/agent-composer/form-state'+import { AgentComposerProvider } from '@/features/agent-v2/agent-composer/provider'+import { AgentFiles } from '../files'+import { AgentKnowledgeRetrieval } from '../knowledge'+import { AgentSkills } from '../skills'+import { AgentTools } from '../tools'++function renderEmptySections() {+ const queryClient = new QueryClient()++ return render(+ <QueryClientProvider client={queryClient}>+ <AgentComposerProvider+ initialDraft={{+ ...defaultAgentSoulConfigFormState,+ files: [],+ knowledgeRetrievals: [],+ skills: [],+ tools: [],+ }}+ >+ <AgentSkills agentId="agent-1" />+ <AgentFiles />+ <AgentTools />+ <AgentKnowledgeRetrieval />+ </AgentComposerProvider>+ </QueryClientProvider>,+ )+}++describe('Agent configure empty sections', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ // Empty composer resources should still render scannable placeholders in each section.+ it('should render placeholders when resources are empty', () => {+ renderEmptySections()++ expect(screen.getByText('agentV2.agentDetail.configure.skills.empty.title')).toBeInTheDocument()+ expect(screen.getByText('agentV2.agentDetail.configure.skills.empty.description')).toBeInTheDocument()+ expect(screen.getByText('agentV2.agentDetail.configure.files.empty.title')).toBeInTheDocument()+ expect(screen.getByText('agentV2.agentDetail.configure.files.empty.description')).toBeInTheDocument()+ expect(screen.getByText('agentV2.agentDetail.configure.tools.empty.title')).toBeInTheDocument()+ expect(screen.getByText('agentV2.agentDetail.configure.tools.empty.description')).toBeInTheDocument()+ expect(screen.getByText('agentV2.agentDetail.configure.knowledgeRetrieval.empty.title')).toBeInTheDocument()+ expect(screen.getByText('agentV2.agentDetail.configure.knowledgeRetrieval.empty.description')).toBeInTheDocument()+ })+})diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/__tests__/publish-bar.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/__tests__/publish-bar.spec.tsxnew file mode 100644index 00000000000..d5f3a4dec13--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/__tests__/publish-bar.spec.tsx@@ -0,0 +1,320 @@+import type { AgentConfigSnapshotSummaryResponse, AgentPublishedReferenceResponse } from '@dify/contracts/api/console/agent/types.gen'+import type { ComponentProps } from 'react'+import type { Mock } from 'vitest'+import { fireEvent, render, screen, within } from '@testing-library/react'+import { createStore, Provider as JotaiProvider } from 'jotai'+import { defaultAgentSoulConfigFormState } from '@/features/agent-v2/agent-composer/form-state'+import { agentComposerDraftAtom, agentComposerOriginalDraftAtom, agentComposerPublishedDraftAtom } from '@/features/agent-v2/agent-composer/store'+import { agentComposerPromptAtom } from '@/features/agent-v2/agent-composer/store-modules/prompt'+import { AgentConfigurePublishBar } from '../publish-bar'++type PublishHandler = NonNullable<ComponentProps<typeof AgentConfigurePublishBar>['onPublish']>+type PublishMock = Mock<PublishHandler>++const hotkeyRegistrations = vi.hoisted(() => new Map<string, {+ callback: (event: { preventDefault: () => void }) => void+ options?: { enabled?: boolean, ignoreInputs?: boolean }+}>())++const mockFormatForDisplay = vi.hoisted(() => vi.fn((hotkey: string) => `display:${hotkey}`))+const mockFormatTimeFromNow = vi.hoisted(() => vi.fn(() => 'just now'))++vi.mock('@tanstack/react-hotkeys', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@tanstack/react-hotkeys')>()+ return {+ ...actual,+ formatForDisplay: mockFormatForDisplay,+ useHotkey: (hotkey: string, callback: (event: { preventDefault: () => void }) => void, options?: { enabled?: boolean, ignoreInputs?: boolean }) => {+ hotkeyRegistrations.set(hotkey, { callback, options })+ },+ }+})++vi.mock('@/hooks/use-format-time-from-now', () => ({+ useFormatTimeFromNow: () => ({+ formatTimeFromNow: mockFormatTimeFromNow,+ }),+}))++vi.mock('@langgenius/dify-ui/popover', async () => {+ const React = await import('react')+ const PopoverContext = React.createContext<{+ open: boolean+ onOpenChange?: (open: boolean) => void+ }>({+ open: false,+ })++ return {+ Popover: ({+ children,+ open,+ onOpenChange,+ }: {+ children: React.ReactNode+ open?: boolean+ onOpenChange?: (open: boolean) => void+ }) => (+ <PopoverContext value={{ open: !!open, onOpenChange }}>+ {children}+ </PopoverContext>+ ),+ PopoverContent: ({+ children,+ }: {+ children: React.ReactNode+ }) => {+ const context = React.use(PopoverContext)+ if (!context.open)+ return null++ return <div data-testid="publish-impact-popover">{children}</div>+ },+ PopoverTrigger: ({+ render: trigger,+ }: {+ render: React.ReactElement+ }) => trigger,+ }+})++const activeConfigSnapshot: AgentConfigSnapshotSummaryResponse = {+ id: 'snapshot-1',+ agent_id: 'agent-1',+ version: 1,+ created_at: 1710000000,+}++const originalDraftWithFile = {+ ...defaultAgentSoulConfigFormState,+ files: [+ {+ id: 'preview-image',+ name: 'agent-roster-skill-detail-dialog-preview-image.png',+ icon: 'image',+ },+ ],+} satisfies typeof defaultAgentSoulConfigFormState++const publishedReferences: AgentPublishedReferenceResponse[] = [+ {+ app_id: 'app-python',+ app_mode: 'workflow',+ app_name: 'Python bug fixer',+ workflow_id: 'workflow-python',+ workflow_version: '1',+ },+ {+ app_id: 'app-translation',+ app_mode: 'workflow',+ app_name: 'Translation Workflow',+ workflow_id: 'workflow-translation',+ workflow_version: '1',+ },+]++function renderPublishBar({+ activeConfigSnapshot,+ draftSavedAt,+ isPublishing,+ onPublish = vi.fn<PublishHandler>(),+ prompt = '',+ publishedReferenceCount,+ publishedReferences,+ setupStore,+}: {+ activeConfigSnapshot?: AgentConfigSnapshotSummaryResponse | null+ draftSavedAt?: number+ isPublishing?: boolean+ onPublish?: PublishMock+ prompt?: string+ publishedReferenceCount?: number+ publishedReferences?: AgentPublishedReferenceResponse[]+ setupStore?: (store: ReturnType<typeof createStore>) => void+} = {}) {+ const store = createStore()+ store.set(agentComposerPromptAtom, prompt)+ setupStore?.(store)++ render(+ <JotaiProvider store={store}>+ <AgentConfigurePublishBar+ agentId="agent-1"+ activeConfigSnapshot={activeConfigSnapshot}+ draftSavedAt={draftSavedAt}+ agentName="Iris"+ isPublishing={isPublishing}+ publishedReferenceCount={publishedReferenceCount}+ publishedReferences={publishedReferences}+ onPublish={onPublish}+ onOpenVersions={vi.fn()}+ />+ </JotaiProvider>,+ )++ return {+ onPublish,+ }+}++describe('AgentConfigurePublishBar', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ hotkeyRegistrations.clear()+ vi.spyOn(console, 'log').mockImplementation(() => {})+ })++ afterEach(() => {+ vi.restoreAllMocks()+ })++ it('should render draft state with a formatted publish shortcut', () => {+ renderPublishBar()++ expect(screen.getByText('agentV2.agentDetail.configure.publishBar.draft')).toBeInTheDocument()+ expect(screen.getByText('agentV2.agentDetail.configure.publishBar.saved')).toBeInTheDocument()+ expect(screen.getByRole('button', { name: /agentV2\.agentDetail\.publish/ })).toBeInTheDocument()+ expect(screen.getByText('display:Mod')).toBeInTheDocument()+ expect(screen.getByText('display:Shift')).toBeInTheDocument()+ expect(screen.getByText('display:P')).toBeInTheDocument()+ expect(mockFormatForDisplay).toHaveBeenCalledWith('Mod')+ expect(hotkeyRegistrations.get('Mod+Shift+P')?.options).toEqual(+ expect.objectContaining({ enabled: true, ignoreInputs: false }),+ )+ })++ it('should render saved time from the latest draft save timestamp', () => {+ renderPublishBar({ draftSavedAt: 1710000100000 })++ expect(screen.getByText(/agentV2\.agentDetail\.configure\.publishBar\.savedAt/)).toBeInTheDocument()+ expect(mockFormatTimeFromNow).toHaveBeenCalledWith(1710000100000)+ })++ it('should render published state from the active snapshot and disable publish logic', () => {+ const { onPublish } = renderPublishBar({ activeConfigSnapshot })++ expect(screen.getByText('agentV2.agentDetail.configure.publishBar.upToDate')).toBeInTheDocument()+ expect(screen.getByText(/agentV2\.agentDetail\.configure\.publishBar\.publishedAt/)).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.publishBar.published' })).toHaveAttribute('aria-disabled', 'true')+ expect(screen.queryByText('display:Mod')).not.toBeInTheDocument()+ expect(mockFormatTimeFromNow).toHaveBeenCalledWith(1710000000 * 1000)+ expect(hotkeyRegistrations.get('Mod+Shift+P')?.options).toEqual(+ expect.objectContaining({ enabled: false, ignoreInputs: false }),+ )++ fireEvent.click(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.publishBar.published' }))++ expect(onPublish).not.toHaveBeenCalled()+ })++ it('should publish the current draft payload from the unpublished changes state', () => {+ const { onPublish } = renderPublishBar({+ activeConfigSnapshot,+ prompt: 'Updated system prompt',+ })++ expect(screen.getByText('agentV2.agentDetail.configure.publishBar.unpublishedChanges')).toBeInTheDocument()++ fireEvent.click(screen.getByRole('button', { name: /agentV2\.agentDetail\.configure\.publishBar\.publishUpdate/ }))++ expect(onPublish).toHaveBeenCalledWith(expect.objectContaining({+ agent_id: 'agent-1',+ config_snapshot: expect.objectContaining({+ prompt: expect.objectContaining({+ system_prompt: 'Updated system prompt',+ }),+ }),+ }))+ })++ it('should mark non-prompt draft changes as unpublished', () => {+ renderPublishBar({+ activeConfigSnapshot,+ setupStore: (store) => {+ store.set(agentComposerPublishedDraftAtom, originalDraftWithFile)+ store.set(agentComposerOriginalDraftAtom, originalDraftWithFile)+ store.set(agentComposerDraftAtom, {+ ...originalDraftWithFile,+ files: [],+ })+ },+ })++ expect(screen.getByText('agentV2.agentDetail.configure.publishBar.unpublishedChanges')).toBeInTheDocument()+ })++ it('should keep unpublished state after draft autosave updates the saved draft baseline', () => {+ const publishedDraft = {+ ...defaultAgentSoulConfigFormState,+ prompt: 'Published prompt',+ }+ const savedDraft = {+ ...defaultAgentSoulConfigFormState,+ prompt: 'Autosaved draft prompt',+ }++ renderPublishBar({+ activeConfigSnapshot,+ setupStore: (store) => {+ store.set(agentComposerPublishedDraftAtom, publishedDraft)+ store.set(agentComposerOriginalDraftAtom, savedDraft)+ store.set(agentComposerDraftAtom, savedDraft)+ },+ })++ expect(screen.getByText('agentV2.agentDetail.configure.publishBar.unpublishedChanges')).toBeInTheDocument()+ expect(screen.getByRole('button', { name: /agentV2\.agentDetail\.configure\.publishBar\.publishUpdate/ })).toBeInTheDocument()+ })++ it('should render publishing as a single disabled action state', () => {+ renderPublishBar({ isPublishing: true, prompt: 'Updated system prompt' })++ expect(screen.getByText('agentV2.agentDetail.configure.publishBar.publishing')).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.publishBar.publishing' })).toHaveAttribute('aria-disabled', 'true')+ expect(screen.queryByText('display:Mod')).not.toBeInTheDocument()+ expect(hotkeyRegistrations.get('Mod+Shift+P')?.options).toEqual(+ expect.objectContaining({ enabled: false, ignoreInputs: false }),+ )+ })++ it('should show affected workflow references when clicking a publishable agent in use', () => {+ const { onPublish } = renderPublishBar({+ activeConfigSnapshot,+ prompt: 'Updated system prompt',+ publishedReferenceCount: 2,+ publishedReferences,+ })++ expect(screen.queryByTestId('publish-impact-popover')).not.toBeInTheDocument()++ fireEvent.click(screen.getByRole('button', { name: /agentV2\.agentDetail\.configure\.publishBar\.publishUpdate/ }))++ expect(onPublish).not.toHaveBeenCalled()+ expect(screen.getByTestId('publish-impact-popover')).toBeInTheDocument()+ expect(screen.getByText(/agentV2\.agentDetail\.configure\.publishImpact\.title/)).toBeInTheDocument()+ expect(screen.getByText(/agentV2\.agentDetail\.configure\.publishImpact\.descriptionPrefix/)).toBeInTheDocument()+ expect(screen.getByText(/agentV2\.agentDetail\.configure\.publishImpact\.workflowCount/)).toBeInTheDocument()+ expect(screen.getByText('Python bug fixer')).toBeInTheDocument()+ expect(screen.getByText('Translation Workflow')).toBeInTheDocument()+ expect(screen.getByRole('link', { name: 'Python bug fixer' })).toHaveAttribute('target', '_blank')+ expect(screen.getByRole('link', { name: 'Python bug fixer' })).toHaveAttribute('rel', 'noopener noreferrer')+ })++ it('should publish from the affected workflow popover action', () => {+ const { onPublish } = renderPublishBar({+ activeConfigSnapshot,+ prompt: 'Updated system prompt',+ publishedReferenceCount: 2,+ publishedReferences,+ })++ fireEvent.click(screen.getByRole('button', { name: /agentV2\.agentDetail\.configure\.publishBar\.publishUpdate/ }))+ fireEvent.click(within(screen.getByTestId('publish-impact-popover')).getByRole('button', {+ name: /agentV2\.agentDetail\.configure\.publishBar\.publishUpdate/,+ }))++ expect(onPublish).toHaveBeenCalledWith(expect.objectContaining({+ agent_id: 'agent-1',+ }))+ })+})diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/add-actions-context.ts b/web/features/agent-v2/agent-detail/configure/components/orchestrate/add-actions-context.tsnew file mode 100644index 00000000000..3017c2c5fa9--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/add-actions-context.ts@@ -0,0 +1,51 @@+import type { AgentCliTool, AgentFileNode, AgentKnowledgeRetrievalItem, AgentSkill } from '@/features/agent-v2/agent-composer/form-state'+import { createContext, use, useCallback, useEffect, useRef } from 'react'++export type AgentOrchestrateAddActionKey = 'cli' | 'files' | 'knowledge' | 'skills'++export type AgentOrchestrateAddedItem = AgentCliTool | AgentFileNode | AgentKnowledgeRetrievalItem | AgentSkill++export type AgentOrchestrateAddActionOptions = {+ onAdded?: (item: AgentOrchestrateAddedItem) => void+}++export type AgentOrchestrateAddAction = (options?: AgentOrchestrateAddActionOptions) => void++export type AgentOrchestrateAddActions = Partial<Record<AgentOrchestrateAddActionKey, AgentOrchestrateAddAction>>++export type AgentOrchestrateAddActionsContextValue = {+ actions: AgentOrchestrateAddActions+ registerAction: (key: AgentOrchestrateAddActionKey, action: AgentOrchestrateAddAction) => () => void+}++export const AgentOrchestrateAddActionsContext = createContext<AgentOrchestrateAddActionsContextValue | null>(null)++export function useAgentOrchestrateAddActions() {+ const context = use(AgentOrchestrateAddActionsContext)+ if (!context)+ return {}++ return context.actions+}++export function useRegisterAgentOrchestrateAddAction(+ key: AgentOrchestrateAddActionKey,+ action: AgentOrchestrateAddAction,+) {+ const context = use(AgentOrchestrateAddActionsContext)+ const registerAction = context?.registerAction+ const actionRef = useRef(action)++ actionRef.current = action++ const stableAction = useCallback<AgentOrchestrateAddAction>((options) => {+ actionRef.current(options)+ }, [])++ useEffect(() => {+ if (!registerAction)+ return++ return registerAction(key, stableAction)+ }, [key, registerAction, stableAction])+}diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/add-actions.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/add-actions.tsxnew file mode 100644index 00000000000..2d2b952c3b6--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/add-actions.tsx@@ -0,0 +1,53 @@+'use client'++import type { ReactNode } from 'react'+import type { AgentOrchestrateAddAction, AgentOrchestrateAddActionKey, AgentOrchestrateAddActions } from './add-actions-context'+import { useCallback, useMemo, useState } from 'react'+import { AgentOrchestrateAddActionsContext } from './add-actions-context'+import { useAgentOrchestrateReadOnly } from './read-only-context'++export function AgentOrchestrateAddActionsProvider({+ children,+}: {+ children: ReactNode+}) {+ const readOnly = useAgentOrchestrateReadOnly()+ const [actions, setActions] = useState<AgentOrchestrateAddActions>({})++ const registerAction = useCallback((key: AgentOrchestrateAddActionKey, action: AgentOrchestrateAddAction) => {+ if (readOnly)+ return () => undefined++ setActions((currentActions) => {+ if (currentActions[key] === action)+ return currentActions++ return {+ ...currentActions,+ [key]: action,+ }+ })++ return () => {+ setActions((currentActions) => {+ if (currentActions[key] !== action)+ return currentActions++ const nextActions = { ...currentActions }+ delete nextActions[key]+ return nextActions+ })+ }+ }, [readOnly])++ const value = useMemo(() => ({+ actions: readOnly ? {} : actions,+ registerAction,+ }), [actions, readOnly, registerAction])++ return (+ <AgentOrchestrateAddActionsContext value={value}>+ {children}+ </AgentOrchestrateAddActionsContext>+ )+}diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/advanced/__tests__/env.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/advanced/__tests__/env.spec.tsxnew file mode 100644index 00000000000..27d923f7379--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/advanced/__tests__/env.spec.tsx@@ -0,0 +1,191 @@+import { toast } from '@langgenius/dify-ui/toast'+import { fireEvent, render, screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { defaultAgentSoulConfigFormState } from '@/features/agent-v2/agent-composer/form-state'+import { AgentComposerProvider } from '@/features/agent-v2/agent-composer/provider'+import { AgentOrchestrateReadOnlyContext } from '../../read-only-context'+import { AgentEnvEditor, EnvVariablesTable } from '../env'+import { getEnvImportPlatform, parseEnvVariables } from '../env-utils'++vi.mock('@langgenius/dify-ui/toast', () => ({+ toast: {+ error: vi.fn(),+ },+}))++const mockToastError = vi.mocked(toast.error)++function renderAgentEnvEditor() {+ return render(+ <AgentComposerProvider initialDraft={defaultAgentSoulConfigFormState}>+ <AgentEnvEditor />+ </AgentComposerProvider>,+ )+}++function renderReadonlyAgentEnvEditor() {+ return render(+ <AgentComposerProvider+ initialDraft={{+ ...defaultAgentSoulConfigFormState,+ envVariables: [{+ id: 'env-1',+ key: 'API_KEY',+ value: 'secret-value',+ scope: 'secret',+ }],+ }}+ >+ <AgentOrchestrateReadOnlyContext value>+ <AgentEnvEditor />+ </AgentOrchestrateReadOnlyContext>+ </AgentComposerProvider>,+ )+}++describe('AgentEnvEditor', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ describe('Env parsing', () => {+ it('should parse dotenv entries from supported line formats', () => {+ expect(parseEnvVariables([+ '# ignored',+ 'API_KEY=abc123',+ 'export BASE_URL="https://example.com"',+ 'PASSWORD=secret # inline comment',+ 'MULTILINE="first\\nsecond"',+ 'INVALID_LINE',+ ].join('\n'))).toEqual([+ { key: 'API_KEY', value: 'abc123' },+ { key: 'BASE_URL', value: 'https://example.com' },+ { key: 'PASSWORD', value: 'secret' },+ { key: 'MULTILINE', value: 'first\nsecond' },+ ])+ })+ })++ describe('Platform Detection', () => {+ it('should detect the hidden-file help platform from browser values', () => {+ expect(getEnvImportPlatform({ platform: 'MacIntel' })).toBe('mac')+ expect(getEnvImportPlatform({ platform: 'Win32' })).toBe('windows')+ expect(getEnvImportPlatform({ userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)' })).toBe('windows')+ expect(getEnvImportPlatform({ platform: 'Linux x86_64' })).toBe('other')+ })+ })++ describe('User Interactions', () => {+ it('should edit the initial environment variable row directly', async () => {+ const user = userEvent.setup()+ renderAgentEnvEditor()++ const keyInput = screen.getByPlaceholderText('agentV2.agentDetail.configure.advancedSettings.envEditor.keyPlaceholder')+ const valueInput = screen.getByPlaceholderText('agentV2.agentDetail.configure.advancedSettings.envEditor.valuePlaceholder')++ await user.type(keyInput, 'API KEY')+ await user.type(valueInput, 'secret-value')++ expect(screen.getByDisplayValue('API_KEY')).toBeInTheDocument()+ expect(screen.getByDisplayValue('secret-value')).toBeInTheDocument()+ })++ it('should reject environment variable keys that do not match workflow variable rules', () => {+ renderAgentEnvEditor()++ const keyInput = screen.getByPlaceholderText('agentV2.agentDetail.configure.advancedSettings.envEditor.keyPlaceholder')++ fireEvent.change(keyInput, {+ target: { value: '1BAD' },+ })++ expect(keyInput).toHaveValue('')+ expect(mockToastError).toHaveBeenCalledWith('appDebug.varKeyError.notStartWithNumber:{"key":"agentV2.agentDetail.configure.advancedSettings.envEditor.keyColumn"}')+ })++ it('should add another editable variable row from the add button', async () => {+ const user = userEvent.setup()+ renderAgentEnvEditor()++ await user.click(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.advancedSettings.envEditor.add' }))++ const keyInputs = screen.getAllByPlaceholderText('agentV2.agentDetail.configure.advancedSettings.envEditor.keyPlaceholder')+ expect(keyInputs).toHaveLength(2)+ const newKeyInput = keyInputs[1]!+ expect(newKeyInput).toHaveFocus()++ await user.type(newKeyInput, 'SECOND_KEY')++ expect(screen.getByDisplayValue('SECOND_KEY')).toBeInTheDocument()+ })++ it('should import dotenv variables into the env table when a file is selected', async () => {+ const user = userEvent.setup()+ const { container } = renderAgentEnvEditor()+ const input = container.querySelector('input[type="file"]') as HTMLInputElement++ expect(input).not.toHaveAttribute('accept')++ const file = new File([+ 'API_KEY=abc123\n',+ 'export BASE_URL="https://example.com"\n',+ ], '.env', { type: 'text/plain' })++ await user.upload(+ input,+ file,+ )++ await waitFor(() => {+ expect(screen.getByDisplayValue('API_KEY')).toBeInTheDocument()+ })+ expect(screen.getByDisplayValue('abc123')).toBeInTheDocument()+ expect(screen.getByDisplayValue('BASE_URL')).toBeInTheDocument()+ expect(screen.getByDisplayValue('https://example.com')).toBeInTheDocument()+ })++ it('should hide import, add, edit, and delete controls when readonly', () => {+ renderReadonlyAgentEnvEditor()++ expect(screen.getByText('API_KEY')).toBeInTheDocument()+ expect(screen.getByText('secret-value')).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'agentV2.agentDetail.configure.advancedSettings.envEditor.importEnv' })).not.toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'agentV2.agentDetail.configure.advancedSettings.envEditor.add' })).not.toBeInTheDocument()+ expect(screen.queryByRole('button', {+ name: 'agentV2.agentDetail.configure.advancedSettings.envEditor.deleteVariable:{"key":"API_KEY"}',+ })).not.toBeInTheDocument()+ expect(screen.queryByDisplayValue('API_KEY')).not.toBeInTheDocument()+ })++ it('should reveal and hide masked variable values from the eye button', async () => {+ const user = userEvent.setup()++ render(+ <EnvVariablesTable+ editable+ envVariables={[{+ id: 'env-1',+ key: 'API_KEY',+ value: 'sk-original',+ scope: 'secret',+ masked: true,+ }]}+ onDelete={vi.fn()}+ onScopeChange={vi.fn()}+ showDraftRow={false}+ />,+ )++ expect(screen.queryByDisplayValue('sk-original')).not.toBeInTheDocument()++ await user.click(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.advancedSettings.envEditor.revealValue:{"key":"API_KEY"}' }))++ expect(screen.getByDisplayValue('sk-original')).toBeInTheDocument()++ await user.click(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.advancedSettings.envEditor.hideValue:{"key":"API_KEY"}' }))++ expect(screen.queryByDisplayValue('sk-original')).not.toBeInTheDocument()+ })+ })+})diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/advanced/content-moderation.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/advanced/content-moderation.tsxnew file mode 100644index 00000000000..532627f25dd--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/advanced/content-moderation.tsx@@ -0,0 +1,184 @@+'use client'++import type { AgentSoulAppFeaturesConfig } from '@dify/contracts/api/console/agent/types.gen'+import type { Features } from '@/app/components/base/features/types'+import type { ModerationConfig } from '@/models/debug'+import { Button } from '@langgenius/dify-ui/button'+import { Switch } from '@langgenius/dify-ui/switch'+import { useCallback, useMemo } from 'react'+import { useTranslation } from 'react-i18next'+import { FeaturesProvider } from '@/app/components/base/features'+import { useFeatures, useFeaturesStore } from '@/app/components/base/features/hooks'+import { useLocale } from '@/context/i18n'+import { useModalContext } from '@/context/modal-context'+import { useAppFeatures, useSetAppFeatures } from '@/features/agent-v2/agent-composer/store-modules/app-features'+import { useCodeBasedExtensions } from '@/service/use-common'+import { ConfigureSection } from '../common/section'++const defaultModerationConfig: ModerationConfig = {+ enabled: true,+ type: 'openai_moderation',+ config: {+ inputs_config: {+ enabled: true,+ preset_response: '',+ },+ },+}++function AgentContentModerationSettingsContent() {+ const { t } = useTranslation()+ const locale = useLocale()+ const featuresStore = useFeaturesStore()+ const setAppFeatures = useSetAppFeatures()+ const { setShowModerationSettingModal } = useModalContext()+ const moderation = useFeatures(state => state.features.moderation)+ const { data: codeBasedExtensionList } = useCodeBasedExtensions('moderation')+ const panelId = 'agent-configure-content-moderation-panel'++ const persistModeration = useCallback((nextModeration?: ModerationConfig) => {+ if (!nextModeration)+ return++ const store = featuresStore?.getState()+ if (!store)+ return++ store.setFeatures({+ ...store.features,+ moderation: nextModeration,+ })+ setAppFeatures(appFeatures => ({+ ...appFeatures,+ sensitive_word_avoidance: nextModeration as AgentSoulAppFeaturesConfig['sensitive_word_avoidance'],+ }))+ }, [featuresStore, setAppFeatures])++ const openSettings = useCallback((payload: ModerationConfig = moderation as ModerationConfig) => {+ setShowModerationSettingModal({+ payload,+ onSaveCallback: persistModeration,+ onCancelCallback: () => {},+ })+ }, [moderation, persistModeration, setShowModerationSettingModal])++ const handleEnabledChange = useCallback((enabled: boolean) => {+ if (enabled) {+ if (!moderation?.type) {+ openSettings(defaultModerationConfig)+ return+ }++ persistModeration({+ ...(moderation as ModerationConfig),+ enabled: true,+ })+ return+ }++ persistModeration({ enabled: false })+ }, [moderation, openSettings, persistModeration])++ const providerContent = useMemo(() => {+ if (moderation?.type === 'openai_moderation')+ return t('feature.moderation.modal.provider.openai', { ns: 'appDebug' })+ if (moderation?.type === 'keywords')+ return t('feature.moderation.modal.provider.keywords', { ns: 'appDebug' })+ if (moderation?.type === 'api')+ return t('apiBasedExtension.selector.title', { ns: 'common' })++ return codeBasedExtensionList?.data.find(item => item.name === moderation?.type)?.label[locale] || '-'+ }, [codeBasedExtensionList?.data, locale, moderation?.type, t])++ const enabledContent = useMemo(() => {+ if (moderation?.config?.inputs_config?.enabled && moderation.config?.outputs_config?.enabled)+ return t('feature.moderation.allEnabled', { ns: 'appDebug' })+ if (moderation?.config?.inputs_config?.enabled)+ return t('feature.moderation.inputEnabled', { ns: 'appDebug' })+ if (moderation?.config?.outputs_config?.enabled)+ return t('feature.moderation.outputEnabled', { ns: 'appDebug' })++ return '-'+ }, [moderation?.config?.inputs_config?.enabled, moderation?.config?.outputs_config?.enabled, t])++ return (+ <ConfigureSection+ label={t('feature.moderation.title', { ns: 'appDebug' })}+ labelId="agent-configure-content-moderation-label"+ headingLevel="h4"+ panelId={panelId}+ tip={t('feature.moderation.description', { ns: 'appDebug' })}+ tipAriaLabel={t('feature.moderation.description', { ns: 'appDebug' })}+ rootClassName="gap-1 border-t border-divider-subtle py-3"+ headerClassName="mb-0 gap-1 px-3"+ panelContentClassName="px-3 pt-1"+ actions={(+ <div className="flex shrink-0 items-center gap-2">+ {!!moderation?.enabled && (+ <Button+ size="small"+ variant="ghost"+ className="h-6 gap-0.5 px-1.5 py-1 text-text-tertiary"+ onClick={() => openSettings()}+ >+ <span className="i-ri-equalizer-2-line size-3.5" aria-hidden />+ <span className="px-0.5 system-xs-medium">+ {t('operation.settings', { ns: 'common' })}+ </span>+ </Button>+ )}+ <div className="h-3 w-px bg-divider-regular" />+ <Switch checked={!!moderation?.enabled} onCheckedChange={handleEnabledChange} size="sm" />+ </div>+ )}+ >+ {moderation?.enabled+ ? (+ <div className="flex min-w-0 items-center gap-4">+ <div className="min-w-0">+ <div className="mb-0.5 truncate system-2xs-medium-uppercase text-text-tertiary">+ {t('feature.moderation.modal.provider.title', { ns: 'appDebug' })}+ </div>+ <div className="truncate system-xs-regular text-text-secondary">+ {providerContent}+ </div>+ </div>+ <div className="h-[27px] w-px shrink-0 rotate-12 bg-divider-subtle" />+ <div className="min-w-0">+ <div className="mb-0.5 truncate system-2xs-medium-uppercase text-text-tertiary">+ {t('feature.moderation.contentEnableLabel', { ns: 'appDebug' })}+ </div>+ <div className="truncate system-xs-regular text-text-secondary">+ {enabledContent}+ </div>+ </div>+ </div>+ )+ : (+ <p className="system-xs-regular text-text-tertiary">+ {t('feature.moderation.description', { ns: 'appDebug' })}+ </p>+ )}+ </ConfigureSection>+ )+}++export function AgentContentModerationSettings() {+ const appFeatures = useAppFeatures()+ const moderation = appFeatures?.sensitive_word_avoidance+ const features = useMemo<Features>(() => ({+ moderation: moderation+ ? {+ ...moderation,+ type: moderation.type ?? undefined,+ }+ : { enabled: false },+ }), [moderation])+ const featuresKey = useMemo(() => JSON.stringify(moderation ?? {}), [moderation])++ return (+ <FeaturesProvider key={featuresKey} features={features}>+ <AgentContentModerationSettingsContent />+ </FeaturesProvider>+ )+}diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/advanced/env-utils.ts b/web/features/agent-v2/agent-detail/configure/components/orchestrate/advanced/env-utils.tsnew file mode 100644index 00000000000..4a6b0242e72--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/advanced/env-utils.ts@@ -0,0 +1,80 @@+const stripInlineComment = (value: string) => {+ for (let index = 0; index < value.length; index++) {+ const previousChar = value[index - 1] ?? ''++ if (value[index] === '#' && (index === 0 || /\s/.test(previousChar)))+ return value.slice(0, index).trimEnd()+ }++ return value+}++const parseEnvValue = (rawValue: string) => {+ const value = rawValue.trim()+ const quote = value[0]++ if ((quote === '"' || quote === '\'') && value.endsWith(quote)) {+ const unquotedValue = value.slice(1, -1)++ if (quote === '"') {+ return unquotedValue+ .replaceAll('\\n', '\n')+ .replaceAll('\\r', '\r')+ .replaceAll('\\t', '\t')+ .replaceAll('\\"', '"')+ .replaceAll('\\\\', '\\')+ }++ return unquotedValue.replaceAll('\\\'', '\'')+ }++ return stripInlineComment(value).trim()+}++export const parseEnvVariables = (content: string) => {+ return content.split(/\r?\n/).flatMap((line) => {+ const trimmedLine = line.trim()++ if (!trimmedLine || trimmedLine.startsWith('#'))+ return []++ const envLine = trimmedLine.startsWith('export ')+ ? trimmedLine.slice('export '.length).trimStart()+ : trimmedLine+ const separatorIndex = envLine.indexOf('=')++ if (separatorIndex <= 0)+ return []++ const key = envLine.slice(0, separatorIndex).trim()++ if (!/^[\w.-]+$/.test(key))+ return []++ return [{+ key,+ value: parseEnvValue(envLine.slice(separatorIndex + 1)),+ }]+ })+}++export type EnvImportPlatform = 'mac' | 'windows' | 'other'++export const getEnvImportPlatform = ({+ platform,+ userAgent,+}: {+ platform?: string+ userAgent?: string+}): EnvImportPlatform => {+ const normalizedPlatform = platform?.toLowerCase() ?? ''+ const normalizedUserAgent = userAgent?.toLowerCase() ?? ''++ if (normalizedPlatform.includes('mac') || normalizedUserAgent.includes('mac os'))+ return 'mac'++ if (normalizedPlatform.includes('win') || normalizedUserAgent.includes('windows'))+ return 'windows'++ return 'other'+}diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/advanced/env.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/advanced/env.tsxnew file mode 100644index 00000000000..cd8044c3030--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/advanced/env.tsx@@ -0,0 +1,539 @@+'use client'++import type { EnvScope, EnvVariable } from '@/features/agent-v2/agent-composer/form-state'+import type { I18nKeysWithPrefix } from '@/types/i18n'+import { cn } from '@langgenius/dify-ui/cn'+import { Input } from '@langgenius/dify-ui/input'+import { Select, SelectContent, SelectItem, SelectItemIndicator, SelectItemText, SelectTrigger } from '@langgenius/dify-ui/select'+import { toast } from '@langgenius/dify-ui/toast'+import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'+import { useAtom } from 'jotai'+import { useEffect, useRef, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { agentComposerEnvVariablesAtom } from '@/features/agent-v2/agent-composer/store-modules/env'+import { checkKeys } from '@/utils/var'+import { ConfigureSection } from '../common/section'+import { useAgentOrchestrateReadOnly } from '../read-only-context'+import { getEnvImportPlatform, parseEnvVariables } from './env-utils'++const scopeLabelKeys: Record<EnvScope, I18nKeysWithPrefix<'agentV2', 'agentDetail.configure.advancedSettings.envEditor.'>> = {+ plain: 'agentDetail.configure.advancedSettings.envEditor.scopePlain',+ secret: 'agentDetail.configure.advancedSettings.envEditor.scopeSecret',+}++const envScopeOptions: EnvScope[] = ['secret', 'plain']++const envImportTipKeys = {+ mac: 'agentDetail.configure.advancedSettings.envEditor.importEnvTip.mac',+ windows: 'agentDetail.configure.advancedSettings.envEditor.importEnvTip.windows',+ other: 'agentDetail.configure.advancedSettings.envEditor.importEnvTip.other',+} as const++const maskedEnvValue = '••••••••••••'++const getCurrentEnvImportPlatform = () => {+ if (typeof navigator === 'undefined')+ return 'other'++ const userAgentData = (navigator as Navigator & { userAgentData?: { platform?: string } }).userAgentData++ return getEnvImportPlatform({+ platform: userAgentData?.platform ?? navigator.platform,+ userAgent: navigator.userAgent,+ })+}++const createEnvVariable = (): EnvVariable => ({+ id: globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random()}`,+ key: '',+ value: '',+ scope: 'plain',+})++const createEnvVariableFromEntry = ({+ key,+ value,+}: {+ key: string+ value: string+}): EnvVariable => ({+ ...createEnvVariable(),+ key,+ value,+})++function EnvEditorScope({+ editable,+ scope,+ onChange,+}: {+ editable?: boolean+ scope: EnvScope+ onChange?: (scope: EnvScope) => void+}) {+ const { t } = useTranslation('agentV2')++ if (!editable) {+ return (+ <span className="min-w-0 truncate px-3 system-xs-regular text-text-secondary">+ {t(scopeLabelKeys[scope])}+ </span>+ )+ }++ return (+ <Select+ value={scope}+ onValueChange={(nextValue) => {+ if (!nextValue)+ return++ onChange?.(nextValue as EnvScope)+ }}+ >+ <SelectTrigger+ aria-label={t('agentDetail.configure.advancedSettings.envEditor.scopeSelector')}+ className="h-full w-full max-w-none rounded-none bg-transparent px-3 py-0 system-xs-regular text-text-secondary hover:bg-state-base-hover focus-visible:bg-state-base-hover data-popup-open:bg-state-base-hover [&>*:last-child]:size-3.5"+ >+ {t(scopeLabelKeys[scope])}+ </SelectTrigger>+ <SelectContent placement="bottom-start" popupClassName="min-w-24">+ {envScopeOptions.map(option => (+ <SelectItem key={option} value={option} className="h-7 system-xs-regular">+ <SelectItemText>{t(scopeLabelKeys[option])}</SelectItemText>+ <SelectItemIndicator />+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )+}++function EnvEditorCell({+ children,+ className,+}: {+ children?: React.ReactNode+ className?: string+}) {+ return (+ <div className={cn('flex min-h-7 min-w-0 items-center border-r border-divider-subtle last:border-r-0', className)}>+ {children}+ </div>+ )+}++function EnvEditorInput({+ 'aria-label': ariaLabel,+ placeholder,+ shouldFocus,+ value,+ onValueChange,+}: {+ 'aria-label': string+ 'placeholder': string+ 'shouldFocus'?: boolean+ 'value': string+ 'onValueChange': (value: string) => void+}) {+ const inputRef = useRef<HTMLInputElement>(null)++ useEffect(() => {+ if (shouldFocus)+ inputRef.current?.focus()+ }, [shouldFocus])++ return (+ <Input+ ref={inputRef}+ aria-label={ariaLabel}+ className="h-full rounded-none bg-transparent px-3 py-0 system-xs-regular text-text-secondary shadow-none hover:bg-state-base-hover focus-visible:bg-state-base-hover"+ placeholder={placeholder}+ value={value}+ onValueChange={onValueChange}+ />+ )+}++function EnvEditorRow({+ autoFocusField,+ variable,+ editable = false,+ isHighlighted,+ onDelete,+ onKeyChange,+ onScopeChange,+ onValueChange,+ showScope = true,+}: {+ autoFocusField?: 'key' | 'value'+ variable: EnvVariable+ editable?: boolean+ isHighlighted?: boolean+ onDelete: () => void+ onKeyChange?: (key: string) => void+ onScopeChange: (scope: EnvScope) => void+ onValueChange?: (value: string) => void+ showScope?: boolean+}) {+ const { t } = useTranslation('agentV2')+ const [isValueRevealed, setIsValueRevealed] = useState(false)+ const gridClassName = showScope+ ? 'grid-cols-[minmax(76px,1fr)_minmax(84px,1.25fr)_72px_28px]'+ : 'grid-cols-[minmax(120px,180px)_minmax(160px,1fr)_28px]'+ const shouldMaskValue = variable.masked && !isValueRevealed+ const displayedValue = shouldMaskValue ? maskedEnvValue : variable.value++ return (+ <div className={cn('grid min-h-7 border-t border-divider-subtle', gridClassName, isHighlighted && 'bg-background-default-hover')}>+ <EnvEditorCell>+ {editable+ ? (+ <EnvEditorInput+ aria-label={t('agentDetail.configure.advancedSettings.envEditor.keyColumn')}+ placeholder={t('agentDetail.configure.advancedSettings.envEditor.keyPlaceholder')}+ shouldFocus={autoFocusField === 'key'}+ value={variable.key}+ onValueChange={onKeyChange ?? (() => {})}+ />+ )+ : (+ <span className={cn('min-w-0 truncate px-3 system-xs-regular text-text-secondary', isHighlighted && 'text-text-primary')}>+ {variable.key}+ </span>+ )}+ </EnvEditorCell>+ <EnvEditorCell>+ {editable && !shouldMaskValue+ ? (+ <EnvEditorInput+ aria-label={t('agentDetail.configure.advancedSettings.envEditor.valueColumn')}+ placeholder={t('agentDetail.configure.advancedSettings.envEditor.valuePlaceholder')}+ shouldFocus={autoFocusField === 'value'}+ value={displayedValue}+ onValueChange={onValueChange ?? (() => {})}+ />+ )+ : (+ <span className="min-w-0 truncate px-3 system-xs-regular text-text-secondary">+ {displayedValue}+ </span>+ )}+ {variable.masked && (+ <button+ type="button"+ aria-label={t(isValueRevealed ? 'agentDetail.configure.advancedSettings.envEditor.hideValue' : 'agentDetail.configure.advancedSettings.envEditor.revealValue', { key: variable.key })}+ onClick={() => setIsValueRevealed(revealed => !revealed)}+ className="mr-2 ml-auto flex size-5 shrink-0 items-center justify-center rounded-md text-text-tertiary hover:bg-state-base-hover hover:text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"+ >+ <span aria-hidden className={cn(isValueRevealed ? 'i-ri-eye-off-line' : 'i-ri-eye-line', 'size-4')} />+ </button>+ )}+ </EnvEditorCell>+ {showScope && (+ <EnvEditorCell>+ <EnvEditorScope editable={editable} scope={variable.scope} onChange={onScopeChange} />+ </EnvEditorCell>+ )}+ <EnvEditorCell className="justify-center">+ {editable && (+ <button+ type="button"+ aria-label={t('agentDetail.configure.advancedSettings.envEditor.deleteVariable', { key: variable.key || t('agentDetail.configure.advancedSettings.envEditor.keyPlaceholder') })}+ onClick={onDelete}+ className="flex size-6 items-center justify-center rounded-md text-text-tertiary hover:bg-state-destructive-hover hover:text-text-destructive focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"+ >+ <span aria-hidden className="i-ri-delete-bin-line size-4" />+ </button>+ )}+ </EnvEditorCell>+ </div>+ )+}++function EnvEditorDraftRow({+ onAdd,+ showScope = true,+}: {+ onAdd?: (options?: { focusField?: 'key' | 'value', scope?: EnvScope }) => void+ showScope?: boolean+}) {+ const { t } = useTranslation('agentV2')+ const gridClassName = showScope+ ? 'grid-cols-[minmax(76px,1fr)_minmax(84px,1.25fr)_72px_28px]'+ : 'grid-cols-[minmax(120px,180px)_minmax(160px,1fr)_28px]'+ const keyPlaceholder = t('agentDetail.configure.advancedSettings.envEditor.keyPlaceholder')+ const valuePlaceholder = t('agentDetail.configure.advancedSettings.envEditor.valuePlaceholder')++ const renderDraftPlaceholder = (label: string) => (+ <span className="min-w-0 truncate px-3 system-xs-regular text-components-input-text-placeholder">+ {label}+ </span>+ )++ const renderDraftValueCell = () => {+ if (!onAdd)+ return renderDraftPlaceholder(valuePlaceholder)++ return (+ <button+ type="button"+ aria-label={t('agentDetail.configure.advancedSettings.envEditor.add')}+ onClick={() => onAdd({ focusField: 'value' })}+ className="flex h-full w-full min-w-0 items-center px-3 text-left system-xs-regular text-components-input-text-placeholder hover:bg-state-base-hover focus-visible:bg-state-base-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"+ >+ {valuePlaceholder}+ </button>+ )+ }++ return (+ <div className={cn('grid min-h-7 border-t border-divider-subtle', gridClassName)}>+ <EnvEditorCell>+ {renderDraftPlaceholder(keyPlaceholder)}+ </EnvEditorCell>+ <EnvEditorCell>+ {renderDraftValueCell()}+ </EnvEditorCell>+ {showScope && (+ <EnvEditorCell>+ <EnvEditorScope scope="plain" />+ </EnvEditorCell>+ )}+ <EnvEditorCell />+ </div>+ )+}++export function EnvVariablesTable({+ editable = false,+ envVariables,+ focusedVariable,+ highlightedIndex,+ onAdd,+ onDelete,+ onKeyChange,+ onScopeChange,+ onValueChange,+ showDraftRow = true,+ showScope = true,+}: {+ editable?: boolean+ envVariables: EnvVariable[]+ focusedVariable?: { id: string, field: 'key' | 'value' }+ highlightedIndex?: number+ onAdd?: (options?: { focusField?: 'key' | 'value', scope?: EnvScope }) => void+ onDelete: (id: string) => void+ onKeyChange?: (id: string, key: string) => void+ onScopeChange: (id: string, scope: EnvScope) => void+ onValueChange?: (id: string, value: string) => void+ showDraftRow?: boolean+ showScope?: boolean+}) {+ const { t } = useTranslation('agentV2')+ const gridClassName = showScope+ ? 'grid-cols-[minmax(76px,1fr)_minmax(84px,1.25fr)_72px_28px]'+ : 'grid-cols-[minmax(120px,180px)_minmax(160px,1fr)_28px]'+ const checkEnvVariableKey = (key: string) => {+ const { isValid, errorMessageKey } = checkKeys([key], false)+ if (!isValid) {+ toast.error(t(`varKeyError.${errorMessageKey}`, {+ ns: 'appDebug',+ key: t('agentDetail.configure.advancedSettings.envEditor.keyColumn'),+ }))+ return false+ }++ return true+ }+ const handleKeyChange = (id: string, key: string) => {+ const normalizedKey = key.replaceAll(' ', '_')+ if (normalizedKey && !checkEnvVariableKey(normalizedKey))+ return++ onKeyChange?.(id, normalizedKey)+ }++ return (+ <div className="overflow-hidden rounded-lg border border-divider-regular bg-components-panel-on-panel-item-bg shadow-xs shadow-shadow-shadow-3">+ <div className={cn('grid min-h-7 text-text-tertiary', gridClassName)}>+ <EnvEditorCell>+ <span className="px-3 system-xs-medium-uppercase">+ {t('agentDetail.configure.advancedSettings.envEditor.keyColumn')}+ </span>+ </EnvEditorCell>+ <EnvEditorCell>+ <span className="px-3 system-xs-medium-uppercase">+ {t('agentDetail.configure.advancedSettings.envEditor.valueColumn')}+ </span>+ </EnvEditorCell>+ {showScope && (+ <EnvEditorCell>+ <span className="px-3 system-xs-medium-uppercase">+ {t('agentDetail.configure.advancedSettings.envEditor.scopeColumn')}+ </span>+ </EnvEditorCell>+ )}+ <EnvEditorCell className="justify-center">+ {onAdd && (+ <button+ type="button"+ aria-label={t('agentDetail.configure.advancedSettings.envEditor.add')}+ onClick={() => onAdd()}+ className="flex size-6 items-center justify-center rounded-md text-text-tertiary hover:bg-state-base-hover hover:text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"+ >+ <span aria-hidden className="i-ri-add-line size-4" />+ </button>+ )}+ </EnvEditorCell>+ </div>+ {envVariables.map((variable, index) => (+ <EnvEditorRow+ key={variable.id}+ autoFocusField={focusedVariable?.id === variable.id ? focusedVariable.field : undefined}+ variable={variable}+ editable={editable}+ isHighlighted={index === highlightedIndex}+ onDelete={() => onDelete(variable.id)}+ onKeyChange={key => handleKeyChange(variable.id, key)}+ onScopeChange={scope => onScopeChange(variable.id, scope)}+ onValueChange={value => onValueChange?.(variable.id, value)}+ showScope={showScope}+ />+ ))}+ {showDraftRow && <EnvEditorDraftRow onAdd={onAdd} showScope={showScope} />}+ </div>+ )+}++export function AgentEnvEditor() {+ const { t } = useTranslation('agentV2')+ const readOnly = useAgentOrchestrateReadOnly()+ const [envVariables, setEnvVariables] = useAtom(agentComposerEnvVariablesAtom)+ const starterVariableRef = useRef<EnvVariable | undefined>(undefined)+ if (!starterVariableRef.current)+ starterVariableRef.current = createEnvVariable()+ const starterVariable = starterVariableRef.current+ const [focusedVariable, setFocusedVariable] = useState<{ id: string, field: 'key' | 'value' }>()+ const envImportInputRef = useRef<HTMLInputElement>(null)+ const envEditorTip = t('agentDetail.configure.advancedSettings.envEditor.tip')+ const envImportTip = t(envImportTipKeys[getCurrentEnvImportPlatform()])+ const envEditorTableId = 'agent-configure-env-editor-table'+ const visibleEnvVariables = envVariables.length > 0 ? envVariables : [starterVariable]++ const updateVariable = (id: string, updater: (variable: EnvVariable) => EnvVariable) => {+ const existingVariable = envVariables.find(variable => variable.id === id)++ if (existingVariable) {+ setEnvVariables(envVariables.map(variable => (+ variable.id === id ? updater(variable) : variable+ )))+ return+ }++ if (id === starterVariable.id)+ setEnvVariables([updater(starterVariable)])+ }++ const addVariable = ({+ focusField = 'key',+ scope,+ }: {+ focusField?: 'key' | 'value'+ scope?: EnvScope+ } = {}) => {+ const variable = {+ ...createEnvVariable(),+ ...(scope ? { scope } : {}),+ }++ setEnvVariables([+ ...(envVariables.length > 0 ? envVariables : [starterVariable]),+ variable,+ ])+ setFocusedVariable({ id: variable.id, field: focusField })+ }+ const importEnvVariables = async (file: File) => {+ const importedVariables = parseEnvVariables(await file.text()).map(createEnvVariableFromEntry)++ if (importedVariables.length === 0)+ return++ setEnvVariables([...envVariables, ...importedVariables])+ }+ const updateVariableKey = (id: string, key: string) => {+ updateVariable(id, variable => ({ ...variable, key }))+ }+ const updateVariableScope = (id: string, scope: EnvScope) => {+ updateVariable(id, variable => ({ ...variable, scope }))+ }+ const updateVariableValue = (id: string, value: string) => {+ updateVariable(id, variable => ({ ...variable, value }))+ }+ const deleteVariable = (id: string) => {+ setEnvVariables(envVariables.filter(variable => variable.id !== id))+ }++ return (+ <ConfigureSection+ label={t('agentDetail.configure.advancedSettings.envEditor.label')}+ labelId="agent-configure-env-editor-label"+ headingLevel="h4"+ panelId={envEditorTableId}+ tip={envEditorTip}+ tipAriaLabel={envEditorTip}+ rootClassName="gap-1 pt-3"+ headerClassName="mb-0 gap-1 px-3"+ panelContentClassName="px-3 pb-3"+ actions={!readOnly+ ? (+ <>+ <input+ ref={envImportInputRef}+ className="hidden"+ type="file"+ onChange={(event) => {+ const file = event.target.files?.[0]+ event.target.value = ''++ if (file)+ void importEnvVariables(file)+ }}+ />+ <Tooltip>+ <TooltipTrigger+ render={(+ <button+ type="button"+ aria-label={t('agentDetail.configure.advancedSettings.envEditor.importEnv')}+ onClick={() => envImportInputRef.current?.click()}+ className="flex h-6 shrink-0 items-center gap-1 rounded-md px-1.5 py-1 text-text-tertiary hover:bg-state-base-hover hover:text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"+ >+ <span aria-hidden className="i-ri-file-upload-line size-3.5" />+ <span className="system-xs-medium">{t('agentDetail.configure.advancedSettings.envEditor.importEnv')}</span>+ </button>+ )}+ />+ <TooltipContent className="max-w-72">+ {envImportTip}+ </TooltipContent>+ </Tooltip>+ </>+ )+ : undefined}+ >+ <EnvVariablesTable+ editable={!readOnly}+ envVariables={visibleEnvVariables}+ focusedVariable={focusedVariable}+ highlightedIndex={1}+ onAdd={readOnly ? undefined : addVariable}+ onDelete={deleteVariable}+ onKeyChange={updateVariableKey}+ onScopeChange={updateVariableScope}+ onValueChange={updateVariableValue}+ showDraftRow={false}+ />+ </ConfigureSection>+ )+}diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/advanced/index.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/advanced/index.tsxnew file mode 100644index 00000000000..92b8950fdce--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/advanced/index.tsx@@ -0,0 +1,27 @@+'use client'++import { useTranslation } from 'react-i18next'+import { ConfigureSection } from '../common/section'+import { AgentContentModerationSettings } from './content-moderation'+import { AgentEnvEditor } from './env'++export function AgentAdvancedSettings() {+ const { t } = useTranslation('agentV2')+ const advancedSettingsPanelId = 'agent-configure-advanced-settings-panel'++ return (+ <ConfigureSection+ label={t('agentDetail.configure.advancedSettings.label')}+ labelId="agent-configure-advanced-settings-label"+ panelId={advancedSettingsPanelId}+ description={t('agentDetail.configure.advancedSettings.description')}+ rootClassName="gap-2 pt-1 pb-3"+ headerClassName="mb-0 pt-2"+ titleRowClassName="min-h-6"+ panelContentClassName="flex flex-col rounded-lg bg-background-section"+ >+ <AgentEnvEditor />+ <AgentContentModerationSettings />+ </ConfigureSection>+ )+}diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/common/add-button.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/common/add-button.tsxnew file mode 100644index 00000000000..4d728e20044--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/common/add-button.tsx@@ -0,0 +1,36 @@+'use client'++import type { ButtonProps } from '@langgenius/dify-ui/button'+import { Button } from '@langgenius/dify-ui/button'+import { cn } from '@langgenius/dify-ui/cn'+import { useTranslation } from 'react-i18next'+import { useAgentOrchestrateReadOnly } from '../read-only-context'++type ConfigureSectionAddButtonProps = Omit<ButtonProps, 'aria-label' | 'children' | 'size' | 'variant'> & {+ ariaLabel: string+}++export function ConfigureSectionAddButton({+ ariaLabel,+ className,+ ...props+}: ConfigureSectionAddButtonProps) {+ const { t } = useTranslation('common')+ const readOnly = useAgentOrchestrateReadOnly()++ if (readOnly)+ return null++ return (+ <Button+ {...props}+ aria-label={ariaLabel}+ variant="ghost"+ size="small"+ className={cn('shrink-0 gap-1 px-2', className)}+ >+ <span aria-hidden className="i-ri-add-line size-3.5" />+ <span>{t('operation.add')}</span>+ </Button>+ )+}diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/common/configurable-item.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/common/configurable-item.tsxnew file mode 100644index 00000000000..ee56d237cdd--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/common/configurable-item.tsx@@ -0,0 +1,61 @@+'use client'++import type { ReactNode } from 'react'+import { useAgentOrchestrateReadOnly } from '../read-only-context'++export function ConfigureSectionConfigurableItem({+ badge,+ editAriaLabel,+ icon,+ label,+ removeAriaLabel,+ onEdit,+ onRemove,+}: {+ badge?: ReactNode+ editAriaLabel: string+ icon: ReactNode+ label: ReactNode+ removeAriaLabel: string+ onEdit: () => void+ onRemove: () => void+}) {+ const readOnly = useAgentOrchestrateReadOnly()+ const hasBadge = badge !== undefined && badge !== null++ return (+ <div className="group flex min-h-8 items-center gap-1 overflow-hidden rounded-lg border-[0.5px] border-components-panel-border-subtle bg-components-panel-on-panel-item-bg py-1.5 pr-1.5 pl-2 shadow-xs shadow-shadow-shadow-3 focus-within:border-components-panel-border focus-within:bg-components-panel-on-panel-item-bg-hover focus-within:shadow-sm hover:border-components-panel-border hover:bg-components-panel-on-panel-item-bg-hover hover:shadow-sm">+ <div className="flex min-w-0 flex-1 items-center gap-2 py-0.5 pr-1">+ {icon}+ <span className="min-w-0 truncate system-sm-medium text-text-primary">+ {label}+ </span>+ </div>+ {!readOnly && (+ <div className="hidden shrink-0 items-center gap-1 group-focus-within:flex group-hover:flex">+ <button+ type="button"+ aria-label={editAriaLabel}+ onClick={onEdit}+ className="flex size-6 items-center justify-center rounded-md text-text-tertiary hover:bg-state-base-hover hover:text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"+ >+ <span aria-hidden className="i-ri-equalizer-2-line size-4" />+ </button>+ <button+ type="button"+ aria-label={removeAriaLabel}+ onClick={onRemove}+ className="flex size-6 items-center justify-center rounded-md text-text-tertiary hover:bg-state-destructive-hover hover:text-text-destructive focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"+ >+ <span aria-hidden className="i-ri-delete-bin-line size-4" />+ </button>+ </div>+ )}+ {hasBadge && (+ <span className="shrink-0 rounded-[5px] border border-divider-deep bg-components-badge-bg-dimm px-1 py-0.5 system-2xs-medium-uppercase text-text-tertiary group-focus-within:hidden group-hover:hidden">+ {badge}+ </span>+ )}+ </div>+ )+}diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/common/empty.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/common/empty.tsxnew file mode 100644index 00000000000..8631c885be3--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/common/empty.tsx@@ -0,0 +1,20 @@+'use client'++export function ConfigureSectionEmpty({+ description,+ title,+}: {+ description: string+ title: string+}) {+ return (+ <div className="flex w-full flex-col items-start gap-1 rounded-xl bg-background-section p-3 text-text-tertiary">+ <p className="w-full system-xs-medium">+ {title}+ </p>+ <p className="w-full system-xs-regular">+ {description}+ </p>+ </div>+ )+}diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/common/section.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/common/section.tsxnew file mode 100644index 00000000000..49b43817d82--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/common/section.tsx@@ -0,0 +1,105 @@+'use client'++import type { ReactNode } from 'react'+import { cn } from '@langgenius/dify-ui/cn'+import {+ CollapsiblePanel,+ CollapsibleRoot,+ CollapsibleTrigger,+} from '@langgenius/dify-ui/collapsible'+import { Infotip } from '@/app/components/base/infotip'++type ConfigureSectionBaseProps = {+ label: ReactNode+ labelId: string+ children: ReactNode+ actions?: ReactNode+ description?: ReactNode+ headingLevel?: 'h3' | 'h4'+ panelId?: string+ rootClassName?: string+ headerClassName?: string+ titleRowClassName?: string+ panelContentClassName?: string+}++type ConfigureSectionProps = ConfigureSectionBaseProps & (+ | {+ tip: ReactNode+ tipAriaLabel: string+ }+ | {+ tip?: undefined+ tipAriaLabel?: undefined+ }+)++export function ConfigureSection({+ label,+ labelId,+ children,+ actions,+ description,+ headingLevel = 'h3',+ panelId,+ tip,+ tipAriaLabel,+ rootClassName,+ headerClassName,+ titleRowClassName,+ panelContentClassName,+}: ConfigureSectionProps) {+ const Heading = headingLevel+ const hasDescription = description !== undefined && description !== null+ const hasTip = tip !== undefined && tip !== null++ return (+ <CollapsibleRoot+ render={<section />}+ defaultOpen+ className={rootClassName}+ aria-labelledby={labelId}+ >+ <div className={cn('mb-2 flex min-h-6 items-center gap-2', headerClassName)}>+ <div className="min-w-0 flex-1">+ <div className={cn('flex min-w-0 items-center', titleRowClassName)}>+ <Heading id={labelId} className="min-w-0 shrink-0">+ <CollapsibleTrigger+ className="h-6 min-h-0 w-auto max-w-full justify-start gap-0 rounded-sm px-0 text-text-secondary hover:not-data-disabled:bg-transparent hover:not-data-disabled:text-text-secondary data-panel-open:text-text-secondary"+ >+ <span className="min-w-0 truncate system-sm-semibold-uppercase">+ {label}+ </span>+ </CollapsibleTrigger>+ </Heading>+ {hasTip && (+ <Infotip aria-label={tipAriaLabel} className="ml-0.5 size-3.5" popupClassName="max-w-64">+ {tip}+ </Infotip>+ )}+ <CollapsibleTrigger+ aria-labelledby={labelId}+ className="group/collapse-icon size-3.5 min-h-0 shrink-0 justify-center rounded-sm p-0 text-text-quaternary hover:not-data-disabled:bg-transparent hover:not-data-disabled:text-text-secondary data-panel-open:text-text-quaternary"+ >+ <span+ aria-hidden="true"+ className="i-custom-vender-solid-general-arrow-down-round-fill size-3.5 rotate-270 transition-transform group-data-panel-open/collapse-icon:rotate-0 motion-reduce:transition-none"+ />+ </CollapsibleTrigger>+ </div>+ {hasDescription && (+ <p className="system-xs-regular text-text-tertiary">+ {description}+ </p>+ )}+ </div>+ {actions}+ </div>+ <CollapsiblePanel id={panelId}>+ <div className={panelContentClassName}>+ {children}+ </div>+ </CollapsiblePanel>+ </CollapsibleRoot>+ )+}diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/__tests__/index.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/__tests__/index.spec.tsxnew file mode 100644index 00000000000..3476c890b3b--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/__tests__/index.spec.tsx@@ -0,0 +1,162 @@+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { fireEvent, render, screen, within } from '@testing-library/react'+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { defaultAgentSoulConfigFormState } from '@/features/agent-v2/agent-composer/form-state'+import { AgentComposerProvider } from '@/features/agent-v2/agent-composer/provider'+import { AgentOrchestrateReadOnlyContext } from '../../read-only-context'+import { AgentFiles } from '../index'++const mocks = vi.hoisted(() => ({+ filePreviewQueryOptions: vi.fn(),+ uploadFileMutationOptions: vi.fn(),+}))++vi.mock('@/service/client', () => ({+ consoleQuery: {+ files: {+ byFileId: {+ preview: {+ get: {+ queryOptions: mocks.filePreviewQueryOptions,+ },+ },+ },+ upload: {+ post: {+ mutationOptions: mocks.uploadFileMutationOptions,+ },+ },+ },+ },+}))++const agentFilesDraft = {+ ...defaultAgentSoulConfigFormState,+ files: [+ {+ id: 'preview-image',+ name: 'agent-roster-skill-detail-dialog-preview-image.png',+ icon: 'image',+ },+ {+ id: 'brief',+ name: 'brief.md',+ icon: 'markdown',+ },+ ],+} satisfies typeof defaultAgentSoulConfigFormState++function renderAgentFiles() {+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: {+ retry: false,+ },+ },+ })++ return render(+ <QueryClientProvider client={queryClient}>+ <AgentComposerProvider initialDraft={agentFilesDraft}>+ <AgentFiles />+ </AgentComposerProvider>+ </QueryClientProvider>,+ )+}++function renderReadonlyAgentFiles() {+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: {+ retry: false,+ },+ },+ })++ return render(+ <QueryClientProvider client={queryClient}>+ <AgentComposerProvider initialDraft={agentFilesDraft}>+ <AgentOrchestrateReadOnlyContext value>+ <AgentFiles />+ </AgentOrchestrateReadOnlyContext>+ </AgentComposerProvider>+ </QueryClientProvider>,+ )+}++describe('AgentFiles', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mocks.filePreviewQueryOptions.mockImplementation(({ input }) => ({+ queryKey: ['file-preview', input],+ queryFn: async () => ({+ content: `Preview content for ${input.params.file_id}`,+ }),+ }))+ mocks.uploadFileMutationOptions.mockReturnValue({+ mutationFn: vi.fn(),+ mutationKey: ['upload-file'],+ })+ })++ it('should open the shared detail dialog with the full file tree when the file row is clicked', async () => {+ renderAgentFiles()++ fireEvent.click(screen.getByRole('button', {+ name: 'agent-roster-skill-detail-dialog-preview-image.png',+ }))++ const dialog = screen.getByRole('dialog')++ expect(dialog).toBeInTheDocument()+ expect(within(dialog).getAllByText('agent-roster-skill-detail-dialog-preview-image.png')).toHaveLength(2)+ expect(within(dialog).getByText('brief.md')).toBeInTheDocument()+ expect(mocks.filePreviewQueryOptions).toHaveBeenCalledWith({+ input: {+ params: {+ file_id: 'preview-image',+ },+ },+ })+ expect(await within(dialog).findByText('Preview content for preview-image')).toBeInTheDocument()+ })++ // File rows expose a hover/focus remove action that updates the composer draft.+ it('should remove the file from the list when the remove action is clicked', () => {+ renderAgentFiles()++ expect(screen.getByText('agent-roster-skill-detail-dialog-preview-image.png')).toBeInTheDocument()++ fireEvent.click(screen.getByRole('button', {+ name: /agentV2\.agentDetail\.configure\.files\.remove.*agent-roster-skill-detail-dialog-preview-image\.png/,+ }))++ expect(screen.queryByText('agent-roster-skill-detail-dialog-preview-image.png')).not.toBeInTheDocument()+ expect(screen.getByText('brief.md')).toBeInTheDocument()+ })++ it('should render the empty state after removing every file', () => {+ renderAgentFiles()++ fireEvent.click(screen.getByRole('button', {+ name: /agentV2\.agentDetail\.configure\.files\.remove.*agent-roster-skill-detail-dialog-preview-image\.png/,+ }))+ fireEvent.click(screen.getByRole('button', {+ name: /agentV2\.agentDetail\.configure\.files\.remove.*brief\.md/,+ }))++ expect(screen.getByText('agentV2.agentDetail.configure.files.empty.title')).toBeInTheDocument()+ })++ it('should hide add and remove actions when readonly', () => {+ renderReadonlyAgentFiles()++ expect(screen.getByRole('button', {+ name: 'agent-roster-skill-detail-dialog-preview-image.png',+ })).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'agentV2.agentDetail.configure.files.add' })).not.toBeInTheDocument()+ expect(screen.queryByRole('button', {+ name: /agentV2\.agentDetail\.configure\.files\.remove.*agent-roster-skill-detail-dialog-preview-image\.png/,+ })).not.toBeInTheDocument()+ })+})diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/index.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/index.tsxnew file mode 100644index 00000000000..7a0930bca87--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/index.tsx@@ -0,0 +1,192 @@+'use client'++import type { ReactNode } from 'react'+import type { AgentOrchestrateAddActionOptions } from '../add-actions-context'+import type { AgentFileNode } from '@/features/agent-v2/agent-composer/form-state'+import {+ Dialog,+} from '@langgenius/dify-ui/dialog'+import {+ FileTreeGuide,+} from '@langgenius/dify-ui/file-tree'+import { useQuery } from '@tanstack/react-query'+import { useAtom } from 'jotai'+import { useCallback, useRef, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { agentComposerFilesAtom } from '@/features/agent-v2/agent-composer/store-modules/files'+import { consoleQuery } from '@/service/client'+import { useRegisterAgentOrchestrateAddAction } from '../add-actions-context'+import { ConfigureSectionAddButton } from '../common/add-button'+import { ConfigureSectionEmpty } from '../common/empty'+import { ConfigureSection } from '../common/section'+import { useAgentOrchestrateReadOnly } from '../read-only-context'+import { AgentSkillDetailDialog } from '../skills/detail-dialog'+import { AgentFileTree } from './tree'+import { AgentFileUploadDialog } from './upload-dialog'++const removeFileNode = (files: AgentFileNode[], fileId: string): AgentFileNode[] => files+ .filter(file => file.id !== fileId)+ .map(file => ({+ ...file,+ children: file.children ? removeFileNode(file.children, fileId) : undefined,+ }))++function AgentFileItem({+ children,+ depth,+ file,+ files,+ onRemove,+ selected,+}: {+ children: ReactNode+ depth: number+ file: AgentFileNode+ files: AgentFileNode[]+ onRemove: (fileId: string) => void+ selected: boolean+}) {+ const { t } = useTranslation('agentV2')+ const readOnly = useAgentOrchestrateReadOnly()+ const [isPreviewOpen, setIsPreviewOpen] = useState(false)+ const previewQuery = useQuery({+ ...consoleQuery.files.byFileId.preview.get.queryOptions({+ input: {+ params: {+ file_id: file.id,+ },+ },+ }),+ enabled: isPreviewOpen,+ })+ const handleRemove = useCallback(() => {+ onRemove(file.id)+ }, [file.id, onRemove])++ return (+ <li className="group/file-row relative min-w-0">+ <Dialog open={isPreviewOpen} onOpenChange={setIsPreviewOpen}>+ <button+ type="button"+ data-selected={selected || undefined}+ aria-current={selected ? 'true' : undefined}+ className="group/file-tree-row relative flex h-6 w-full min-w-0 cursor-pointer items-center rounded-md pr-7 pl-2 text-left outline-hidden select-none hover:bg-state-base-hover focus-visible:bg-state-base-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid data-[selected]:bg-state-base-active"+ onClick={() => setIsPreviewOpen(true)}+ >+ {Array.from({ length: Math.max(depth - 1, 0) }, (_, index) => (+ <FileTreeGuide key={index} />+ ))}+ <div className="flex min-w-0 flex-[1_0_0] items-center py-0.5">+ {children}+ </div>+ </button>+ {isPreviewOpen && (+ <AgentSkillDetailDialog+ skillName={file.name}+ detail={{+ description: t('agentDetail.configure.files.tip'),+ files,+ filePreview: {+ content: previewQuery.data?.content,+ isError: previewQuery.isError,+ isLoading: previewQuery.isPending,+ },+ selectedFileId: file.id,+ sections: [],+ }}+ />+ )}+ </Dialog>+ {!readOnly && (+ <button+ type="button"+ data-agent-file-remove-button+ aria-label={t('agentDetail.configure.files.remove', { name: file.name })}+ onClick={handleRemove}+ className="pointer-events-none absolute top-1/2 right-1 z-10 flex size-5 -translate-y-1/2 items-center justify-center rounded-md text-text-tertiary opacity-0 group-focus-within/file-row:pointer-events-auto group-focus-within/file-row:opacity-100 group-hover/file-row:pointer-events-auto group-hover/file-row:opacity-100 hover:bg-state-destructive-hover hover:text-text-destructive focus-visible:bg-state-destructive-hover focus-visible:text-text-destructive focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"+ >+ <span aria-hidden className="i-ri-delete-bin-line size-4" />+ </button>+ )}+ </li>+ )+}++export function AgentFiles() {+ const { t } = useTranslation('agentV2')+ const [files, setFiles] = useAtom(agentComposerFilesAtom)+ const filesTip = t('agentDetail.configure.files.tip')+ const filesTreeId = 'agent-configure-files-tree'+ const [isUploadOpen, setIsUploadOpen] = useState(false)+ const promptAddCallbackRef = useRef<AgentOrchestrateAddActionOptions['onAdded']>(undefined)+ const removeFile = useCallback((fileId: string) => {+ setFiles(removeFileNode(files, fileId))+ }, [files, setFiles])+ const handleOpenUpload = useCallback((options?: AgentOrchestrateAddActionOptions) => {+ promptAddCallbackRef.current = options?.onAdded+ setIsUploadOpen(true)+ }, [])+ useRegisterAgentOrchestrateAddAction('files', handleOpenUpload)+ const handleUploaded = useCallback((file: AgentFileNode) => {+ setFiles([...files, file])+ promptAddCallbackRef.current?.(file)+ promptAddCallbackRef.current = undefined+ }, [files, setFiles])+ const handleUploadOpenChange = useCallback((open: boolean) => {+ if (!open)+ promptAddCallbackRef.current = undefined+ setIsUploadOpen(open)+ }, [])++ return (+ <>+ <ConfigureSection+ label={t('agentDetail.configure.files.label')}+ labelId="agent-configure-files-label"+ tip={filesTip}+ tipAriaLabel={filesTip}+ rootClassName="border-b border-divider-subtle pt-4"+ panelContentClassName="pb-4"+ actions={(+ <ConfigureSectionAddButton+ ariaLabel={t('agentDetail.configure.files.add')}+ onClick={() => handleOpenUpload()}+ />+ )}+ >+ {files.length === 0+ ? (+ <ConfigureSectionEmpty+ title={t('agentDetail.configure.files.empty.title')}+ description={t('agentDetail.configure.files.empty.description')}+ />+ )+ : (+ <AgentFileTree+ id={filesTreeId}+ files={files}+ treeLabel={t('agentDetail.configure.files.treeLabel')}+ className="rounded-lg border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg p-1 shadow-xs shadow-shadow-shadow-3"+ scrollAreaClassName="max-h-[250px] flex-none"+ renderFile={({ depth, file, selected, children }) => (+ <AgentFileItem+ depth={depth}+ file={file}+ files={files}+ selected={selected}+ onRemove={removeFile}+ >+ {children}+ </AgentFileItem>+ )}+ />+ )}+ </ConfigureSection>+ <AgentFileUploadDialog+ open={isUploadOpen}+ onOpenChange={handleUploadOpenChange}+ onUploaded={handleUploaded}+ />+ </>+ )+}diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/tree.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/tree.tsxnew file mode 100644index 00000000000..6732d5a180b--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/tree.tsx@@ -0,0 +1,156 @@+'use client'++import type { ReactNode } from 'react'+import type { AgentFileNode } from '@/features/agent-v2/agent-composer/form-state'+import { cn } from '@langgenius/dify-ui/cn'+import {+ FileTreeFile,+ FileTreeFolder,+ FileTreeFolderPanel,+ FileTreeFolderTrigger,+ FileTreeIcon,+ FileTreeLabel,+ FileTreeList,+ FileTreeRoot,+} from '@langgenius/dify-ui/file-tree'+import { ScrollArea } from '@langgenius/dify-ui/scroll-area'+import { Fragment } from 'react'++type AgentFileTreeFolderOpenStrategy = (context: {+ file: AgentFileNode+ depth: number+}) => boolean++type AgentFileTreeRenderFile = (context: {+ depth: number+ file: AgentFileNode+ selected: boolean+ children: ReactNode+}) => ReactNode++const firstLevelFolderOpenStrategy: AgentFileTreeFolderOpenStrategy = ({ depth }) => depth === 1++function AgentFileTreeRows({+ files,+ selectedFileId,+ depth,+ folderOpenStrategy,+ renderFile,+}: {+ files: AgentFileNode[]+ selectedFileId?: string+ depth: number+ folderOpenStrategy: AgentFileTreeFolderOpenStrategy+ renderFile: AgentFileTreeRenderFile+}) {+ return files.map((file) => {+ const children = (+ <>+ <FileTreeIcon type={file.icon} />+ <FileTreeLabel className="max-w-full" title={file.name}>{file.name}</FileTreeLabel>+ </>+ )++ if (file.children?.length) {+ return (+ <FileTreeFolder+ key={file.id}+ defaultOpen={folderOpenStrategy({ file, depth })}+ >+ <FileTreeFolderTrigger>+ <FileTreeIcon type="folder" />+ <FileTreeLabel className="max-w-full" title={file.name}>{file.name}</FileTreeLabel>+ </FileTreeFolderTrigger>+ <FileTreeFolderPanel>+ <AgentFileTreeRows+ files={file.children}+ selectedFileId={selectedFileId}+ depth={depth + 1}+ folderOpenStrategy={folderOpenStrategy}+ renderFile={renderFile}+ />+ </FileTreeFolderPanel>+ </FileTreeFolder>+ )+ }++ return (+ <Fragment key={file.id}>+ {renderFile({+ depth,+ file,+ selected: file.id === selectedFileId,+ children,+ })}+ </Fragment>+ )+ })+}++const defaultRenderFile: AgentFileTreeRenderFile = ({ selected, children }) => (+ <FileTreeFile selected={selected}>+ {children}+ </FileTreeFile>+)++export function AgentFileTree({+ files,+ selectedFileId,+ id,+ treeLabel,+ label,+ labelledBy,+ header,+ className,+ scrollAreaClassName,+ rootClassName,+ listClassName,+ folderOpenStrategy = firstLevelFolderOpenStrategy,+ renderFile = defaultRenderFile,+}: {+ files: AgentFileNode[]+ selectedFileId?: string+ id?: string+ treeLabel?: string+ label?: string+ labelledBy?: string+ header?: ReactNode+ className?: string+ scrollAreaClassName?: string+ rootClassName?: string+ listClassName?: string+ folderOpenStrategy?: AgentFileTreeFolderOpenStrategy+ renderFile?: AgentFileTreeRenderFile+}) {+ return (+ <div className={cn('flex min-h-0 w-full max-w-full min-w-0 flex-col overflow-clip', className)}>+ {header}+ <ScrollArea+ className={cn('min-h-0 w-full max-w-full flex-1 overflow-hidden', scrollAreaClassName)}+ label={label}+ labelledBy={labelledBy}+ slotClassNames={{+ viewport: 'max-h-[inherit] overscroll-contain',+ content: 'w-full max-w-full min-w-0!',+ scrollbar: 'hidden',+ }}+ >+ <FileTreeRoot+ id={id}+ aria-label={treeLabel}+ className={cn('w-full max-w-full min-w-0 p-0', rootClassName)}+ >+ <FileTreeList className={cn('w-full max-w-full min-w-0', listClassName)}>+ <AgentFileTreeRows+ files={files}+ selectedFileId={selectedFileId}+ depth={1}+ folderOpenStrategy={folderOpenStrategy}+ renderFile={renderFile}+ />+ </FileTreeList>+ </FileTreeRoot>+ </ScrollArea>+ </div>+ )+}diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/upload-dialog.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/upload-dialog.tsxnew file mode 100644index 00000000000..454d58c6886--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/upload-dialog.tsx@@ -0,0 +1,244 @@+'use client'++import type { FileResponse } from '@dify/contracts/api/console/files/types.gen'+import type { FileTreeIconType } from '@langgenius/dify-ui/file-tree'+import type { AgentFileNode } from '@/features/agent-v2/agent-composer/form-state'+import { Button } from '@langgenius/dify-ui/button'+import { cn } from '@langgenius/dify-ui/cn'+import { Dialog, DialogCloseButton, DialogContent, DialogDescription, DialogTitle } from '@langgenius/dify-ui/dialog'+import { FileTreeIcon } from '@langgenius/dify-ui/file-tree'+import { toast } from '@langgenius/dify-ui/toast'+import { useMutation } from '@tanstack/react-query'+import { useRef, useState } from 'react'+import { useTranslation } from 'react-i18next'+import ActionButton from '@/app/components/base/action-button'+import { consoleQuery } from '@/service/client'+import { formatFileSize } from '@/utils/format'++const codeFileExtensions = new Set([+ 'css',+ 'go',+ 'html',+ 'js',+ 'jsx',+ 'py',+ 'rb',+ 'rs',+ 'scss',+ 'sh',+ 'ts',+ 'tsx',+ 'vue',+ 'yaml',+ 'yml',+])+const tableFileExtensions = new Set(['csv', 'xls', 'xlsx'])+const archiveFileExtensions = new Set(['7z', 'gz', 'rar', 'tar', 'zip'])++function getFileExtension(fileName: string) {+ return fileName.split('.').pop()?.toLowerCase() ?? ''+}++function getFileIconType(fileName: string, mimeType?: string | null): FileTreeIconType {+ const extension = getFileExtension(fileName)++ if (mimeType?.startsWith('image/'))+ return 'image'+ if (mimeType === 'application/pdf' || extension === 'pdf')+ return 'pdf'+ if (extension === 'md' || extension === 'markdown' || extension === 'mdx')+ return 'markdown'+ if (extension === 'json')+ return 'json'+ if (tableFileExtensions.has(extension))+ return 'table'+ if (archiveFileExtensions.has(extension))+ return 'archive'+ if (codeFileExtensions.has(extension))+ return 'code'+ if (mimeType?.startsWith('text/'))+ return 'text'++ return 'file'+}++function toAgentFileNode(uploadedFile: FileResponse): AgentFileNode {+ return {+ id: uploadedFile.id,+ name: uploadedFile.name,+ icon: getFileIconType(uploadedFile.name, uploadedFile.mime_type),+ }+}++function AgentFileUploader({+ file,+ onChange,+}: {+ file?: File+ onChange: (file?: File) => void+}) {+ const { t } = useTranslation('agentV2')+ const fileInputRef = useRef<HTMLInputElement>(null)+ const [dragging, setDragging] = useState(false)++ const setUploadFiles = (files: File[]) => {+ const [uploadFile] = files+ if (files.length !== 1 || !uploadFile) {+ toast.error(t('agentDetail.configure.files.upload.invalidFile'))+ return+ }++ onChange(uploadFile)+ }++ const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {+ const files = Array.from(event.target.files ?? [])+ event.target.value = ''+ setUploadFiles(files)+ }++ const handleDrop = (event: React.DragEvent<HTMLDivElement>) => {+ event.preventDefault()+ event.stopPropagation()+ setDragging(false)++ setUploadFiles(Array.from(event.dataTransfer.files))+ }++ return (+ <div className="mt-6">+ <input+ ref={fileInputRef}+ className="hidden"+ type="file"+ onChange={handleFileChange}+ />+ {!file && (+ <div+ className={cn(+ 'relative flex h-16 items-center rounded-[10px] border border-dashed border-components-dropzone-border bg-components-dropzone-bg text-sm font-normal',+ dragging && 'border-components-dropzone-border-accent bg-components-dropzone-bg-accent',+ )}+ onDragEnter={(event) => {+ event.preventDefault()+ setDragging(true)+ }}+ onDragOver={event => event.preventDefault()}+ onDragLeave={() => setDragging(false)}+ onDrop={handleDrop}+ >+ <div className="flex w-full items-center justify-center space-x-2">+ <span aria-hidden className="i-ri-upload-cloud-2-line size-6 text-text-tertiary" />+ <div className="text-text-tertiary">+ {t('agentDetail.configure.files.upload.dropzone')}+ <button+ type="button"+ className="inline cursor-pointer border-none bg-transparent p-0 pl-1 text-left text-text-accent focus-visible:ring-1 focus-visible:ring-components-input-border-active focus-visible:outline-hidden"+ onClick={() => fileInputRef.current?.click()}+ >+ {t('agentDetail.configure.files.upload.browse')}+ </button>+ </div>+ </div>+ {dragging && <div className="absolute top-0 left-0 size-full" />}+ </div>+ )}+ {file && (+ <div className="group flex items-center rounded-lg border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg shadow-xs hover:bg-components-panel-on-panel-item-bg-hover">+ <div className="flex items-center justify-center p-3">+ <FileTreeIcon type={getFileIconType(file.name, file.type)} />+ </div>+ <div className="flex grow flex-col items-start gap-0.5 py-1 pr-2">+ <span className="max-w-[calc(100%-30px)] overflow-hidden text-[12px] leading-4 font-medium text-ellipsis whitespace-nowrap text-text-secondary">{file.name}</span>+ <div className="flex h-3 items-center gap-1 self-stretch text-[10px] leading-3 font-medium text-text-tertiary uppercase">+ <span>{t('agentDetail.configure.files.upload.fileType')}</span>+ <span className="text-text-quaternary">·</span>+ <span>{formatFileSize(file.size)}</span>+ </div>+ </div>+ <div className="hidden items-center pr-3 group-hover:flex">+ <ActionButton onClick={() => onChange(undefined)}>+ <span aria-hidden className="i-ri-delete-bin-line size-4 text-text-tertiary" />+ </ActionButton>+ </div>+ </div>+ )}+ </div>+ )+}++export function AgentFileUploadDialog({+ open,+ onOpenChange,+ onUploaded,+}: {+ open: boolean+ onOpenChange: (open: boolean) => void+ onUploaded: (file: AgentFileNode) => void+}) {+ const { t } = useTranslation('agentV2')+ const { t: tCommon } = useTranslation('common')+ const [file, setFile] = useState<File>()+ const uploadFileMutation = useMutation(consoleQuery.files.upload.post.mutationOptions())++ const handleUpload = () => {+ if (!file || uploadFileMutation.isPending)+ return++ uploadFileMutation.mutate({+ body: {+ file,+ },+ }, {+ onSuccess: (uploadedFile) => {+ toast.success(t('agentDetail.configure.files.upload.success'))+ onUploaded(toAgentFileNode(uploadedFile))+ setFile(undefined)+ onOpenChange(false)+ },+ onError: () => {+ toast.error(t('agentDetail.configure.files.upload.failed'))+ },+ })+ }++ const handleOpenChange = (nextOpen: boolean) => {+ if (!nextOpen) {+ uploadFileMutation.reset()+ setFile(undefined)+ }+ onOpenChange(nextOpen)+ }++ return (+ <Dialog open={open} onOpenChange={handleOpenChange}>+ <DialogContent>+ <DialogCloseButton />+ <DialogTitle className="title-2xl-semi-bold text-text-primary">+ {t('agentDetail.configure.files.upload.title')}+ </DialogTitle>+ <DialogDescription className="mt-1 system-sm-regular text-text-tertiary">+ {t('agentDetail.configure.files.upload.description')}+ </DialogDescription>+ <AgentFileUploader+ file={file}+ onChange={setFile}+ />+ <div className="flex justify-end gap-2 pt-6">+ <Button type="button" onClick={() => handleOpenChange(false)} disabled={uploadFileMutation.isPending}>+ {tCommon('operation.cancel')}+ </Button>+ <Button+ type="button"+ variant="primary"+ disabled={!file}+ loading={uploadFileMutation.isPending}+ onClick={handleUpload}+ >+ {t('agentDetail.configure.files.upload.action')}+ </Button>+ </div>+ </DialogContent>+ </Dialog>+ )+}diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/header.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/header.tsxnew file mode 100644index 00000000000..36d11483928--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/header.tsx@@ -0,0 +1,23 @@+'use client'++import { useTranslation } from 'react-i18next'++type AgentOrchestrateHeaderProps = {+ headingId: string+}++export function AgentOrchestrateHeader({+ headingId,+}: AgentOrchestrateHeaderProps) {+ const { t } = useTranslation('agentV2')++ return (+ <div className="flex shrink-0 items-center gap-1 px-4 py-2">+ <div className="flex min-w-0 flex-1 flex-col justify-center">+ <h2 id={headingId} className="truncate title-xl-semi-bold text-text-primary">+ {t('agentDetail.configure.orchestrate')}+ </h2>+ </div>+ </div>+ )+}diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/index.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/index.tsxnew file mode 100644index 00000000000..9243540586f--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/index.tsx@@ -0,0 +1,116 @@+'use client'++import type { AgentConfigSnapshotDetailResponse, AgentConfigSnapshotSummaryResponse, AgentPublishedReferenceResponse } from '@dify/contracts/api/console/agent/types.gen'+import type { AgentConfigurePublishPayload } from './publish-bar'+import type { DefaultModel, Model } from '@/app/components/header/account-setting/model-provider-page/declarations'+import { cn } from '@langgenius/dify-ui/cn'+import { ScrollArea } from '@langgenius/dify-ui/scroll-area'+import { useTranslation } from 'react-i18next'+import { AgentOrchestrateAddActionsProvider } from './add-actions'+import { AgentAdvancedSettings } from './advanced'+import { AgentFiles } from './files'+import { AgentOrchestrateHeader } from './header'+import { AgentKnowledgeRetrieval } from './knowledge'+import { AgentModelField } from './model-config/field'+import { AgentPromptEditor } from './prompt-editor'+import { AgentConfigurePublishBar } from './publish-bar'+import { AgentOrchestrateReadOnlyContext } from './read-only-context'+import { AgentSkills } from './skills'+import { AgentTools } from './tools'++type AgentOrchestratePanelProps = {+ agentId: string+ activeConfigSnapshot?: AgentConfigSnapshotSummaryResponse | null+ agentSoulConfig?: AgentConfigSnapshotDetailResponse['config_snapshot']+ agentName?: string | null+ currentModel?: DefaultModel+ textGenerationModelList: Model[]+ draftSavedAt?: number+ isPublishing?: boolean+ publishedReferenceCount?: number+ publishedReferences?: AgentPublishedReferenceResponse[]+ className?: string+ readOnly?: boolean+ showHeader?: boolean+ showPublishBar?: boolean+ onSelectModel: (model: DefaultModel) => void+ onPublish: (payload: AgentConfigurePublishPayload) => void | Promise<void>+ onOpenVersions: () => void+}++export function AgentOrchestratePanel({+ agentId,+ activeConfigSnapshot,+ agentSoulConfig,+ agentName,+ currentModel,+ textGenerationModelList,+ draftSavedAt,+ isPublishing,+ publishedReferenceCount,+ publishedReferences,+ className,+ readOnly = false,+ showHeader = true,+ showPublishBar = true,+ onSelectModel,+ onPublish,+ onOpenVersions,+}: AgentOrchestratePanelProps) {+ const { t } = useTranslation('agentV2')+ const orchestrateHeadingId = 'agent-configure-orchestrate-heading'+ const orchestrateLabel = t('agentDetail.configure.orchestrate')++ return (+ <div className={cn('flex max-w-140 min-w-90 flex-[0_0_min(41.08280255%,560px)] flex-col overflow-hidden rounded-lg border-[0.5px] border-components-panel-border bg-components-panel-bg', className)}>+ {showHeader && <AgentOrchestrateHeader headingId={orchestrateHeadingId} />}++ <AgentOrchestrateReadOnlyContext value={readOnly}>+ <div+ aria-readonly={readOnly}+ className="flex min-h-0 flex-1 flex-col"+ >+ <ScrollArea+ className="min-h-0 flex-1 overflow-hidden"+ label={showHeader ? undefined : orchestrateLabel}+ labelledBy={showHeader ? orchestrateHeadingId : undefined}+ slotClassNames={{+ viewport: 'overscroll-contain',+ content: 'min-h-full px-4 py-3',+ }}+ >+ <AgentOrchestrateAddActionsProvider>+ <AgentModelField+ currentModel={currentModel}+ textGenerationModelList={textGenerationModelList}+ onSelect={onSelectModel}+ />+ <AgentPromptEditor />+ <AgentSkills agentId={agentId} />+ <AgentFiles />+ <AgentTools />+ <AgentKnowledgeRetrieval />+ <AgentAdvancedSettings />+ </AgentOrchestrateAddActionsProvider>+ </ScrollArea>+ </div>+ </AgentOrchestrateReadOnlyContext>++ {showPublishBar && (+ <AgentConfigurePublishBar+ agentId={agentId}+ activeConfigSnapshot={activeConfigSnapshot}+ agentSoulConfig={agentSoulConfig}+ agentName={agentName}+ currentModel={currentModel}+ draftSavedAt={draftSavedAt}+ isPublishing={isPublishing}+ publishedReferenceCount={publishedReferenceCount}+ publishedReferences={publishedReferences}+ onPublish={onPublish}+ onOpenVersions={onOpenVersions}+ />+ )}+ </div>+ )+}diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/__tests__/index.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/__tests__/index.spec.tsxnew file mode 100644index 00000000000..84f16045eb3--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/__tests__/index.spec.tsx@@ -0,0 +1,298 @@+import type { AgentSoulConfigFormState } from '@/features/agent-v2/agent-composer/form-state'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { render, screen, within } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { defaultAgentSoulConfigFormState } from '@/features/agent-v2/agent-composer/form-state'+import { AgentComposerProvider } from '@/features/agent-v2/agent-composer/provider'+import { useConfigPublishPayload } from '@/features/agent-v2/agent-composer/store'+import { AgentOrchestrateReadOnlyContext } from '../../read-only-context'+import { AgentKnowledgeRetrieval } from '../index'++const agentKnowledgeDraft = {+ ...defaultAgentSoulConfigFormState,+ knowledgeRetrievals: [+ {+ id: 'retrieval-1',+ nameKey: 'agentDetail.configure.knowledgeRetrieval.retrievalOne',+ },+ ],+} satisfies AgentSoulConfigFormState++function PublishPayloadPreview() {+ const payload = useConfigPublishPayload({ agentId: 'agent-1' })++ return (+ <output aria-label="publish payload">+ {JSON.stringify(payload.config_snapshot.knowledge)}+ </output>+ )+}++function renderKnowledgeRetrieval({+ initialDraft = agentKnowledgeDraft,+ readOnly = false,+ showPublishPayload = false,+}: {+ initialDraft?: AgentSoulConfigFormState+ readOnly?: boolean+ showPublishPayload?: boolean+} = {}) {+ const queryClient = new QueryClient()++ return render(+ <QueryClientProvider client={queryClient}>+ <AgentComposerProvider initialDraft={initialDraft}>+ <AgentOrchestrateReadOnlyContext value={readOnly}>+ <AgentKnowledgeRetrieval />+ </AgentOrchestrateReadOnlyContext>+ {showPublishPayload && <PublishPayloadPreview />}+ </AgentComposerProvider>+ </QueryClientProvider>,+ )+}++describe('AgentKnowledgeRetrieval', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ describe('Rendering', () => {+ it('should render configured retrieval rows', () => {+ renderKnowledgeRetrieval()++ expect(screen.getByText('agentV2.agentDetail.configure.knowledgeRetrieval.retrievalOne')).toBeInTheDocument()+ expect(screen.queryByText('agentV2.agentDetail.configure.knowledgeRetrieval.retrievalTwo')).not.toBeInTheDocument()+ })++ it('should hide add, edit, and remove actions when readonly', () => {+ renderKnowledgeRetrieval({ readOnly: true })++ expect(screen.getByText('agentV2.agentDetail.configure.knowledgeRetrieval.retrievalOne')).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'agentV2.agentDetail.configure.knowledgeRetrieval.add' })).not.toBeInTheDocument()+ expect(screen.queryByRole('button', {+ name: 'agentV2.agentDetail.configure.knowledgeRetrieval.edit:{"name":"agentV2.agentDetail.configure.knowledgeRetrieval.retrievalOne"}',+ })).not.toBeInTheDocument()+ expect(screen.queryByRole('button', {+ name: 'agentV2.agentDetail.configure.knowledgeRetrieval.remove:{"name":"agentV2.agentDetail.configure.knowledgeRetrieval.retrievalOne"}',+ })).not.toBeInTheDocument()+ })+ })++ describe('User Interactions', () => {+ it('should open the knowledge retrieval dialog from the add button', async () => {+ const user = userEvent.setup()+ renderKnowledgeRetrieval()++ await user.click(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.knowledgeRetrieval.add' }))++ const dialog = screen.getByRole('dialog', {+ name: 'agentV2.agentDetail.configure.knowledgeRetrieval.dialog.title',+ })+ const titleButton = within(dialog).getByRole('button', {+ name: 'agentV2.agentDetail.configure.knowledgeRetrieval.retrievalTwo',+ })+ expect(titleButton).toBeInTheDocument()+ expect(within(dialog).queryByRole('textbox', {+ name: 'agentV2.agentDetail.configure.knowledgeRetrieval.dialog.nameLabel',+ })).not.toBeInTheDocument()++ await user.click(titleButton)++ expect(within(dialog).getByRole('textbox', {+ name: 'agentV2.agentDetail.configure.knowledgeRetrieval.dialog.nameLabel',+ })).toHaveValue('agentV2.agentDetail.configure.knowledgeRetrieval.retrievalTwo')+ expect(within(dialog).getByText('appDebug.datasetConfig.knowledgeTip')).toBeInTheDocument()+ expect(within(dialog).getByRole('button', {+ name: 'common.operation.add workflow.nodes.knowledgeRetrieval.knowledge',+ })).toBeInTheDocument()+ expect(within(dialog).getByRole('button', {+ name: 'workflow.nodes.knowledgeRetrieval.metadata.options.disabled.title',+ })).toBeInTheDocument()+ })++ it('should show the custom query input when query mode changes', async () => {+ const user = userEvent.setup()+ renderKnowledgeRetrieval()++ await user.click(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.knowledgeRetrieval.add' }))+ const dialog = screen.getByRole('dialog', {+ name: 'agentV2.agentDetail.configure.knowledgeRetrieval.dialog.title',+ })++ await user.click(within(dialog).getByRole('radio', {+ name: 'agentV2.agentDetail.configure.knowledgeRetrieval.dialog.query.custom',+ }))++ const customQueryInput = within(dialog).getByRole('textbox', {+ name: 'agentV2.agentDetail.configure.knowledgeRetrieval.dialog.query.customInputLabel',+ })+ await user.type(customQueryInput, 'release notes')++ expect(customQueryInput).toHaveValue('release notes')+ expect(within(dialog).getByPlaceholderText('agentV2.agentDetail.configure.knowledgeRetrieval.dialog.query.customPlaceholder')).toBeInTheDocument()+ expect(within(dialog).getByText('agentV2.agentDetail.configure.knowledgeRetrieval.dialog.query.customDescription')).toBeInTheDocument()+ expect(within(dialog).queryByText('agentV2.agentDetail.configure.knowledgeRetrieval.dialog.query.agentDescription')).not.toBeInTheDocument()+ })++ it('should save newly added retrieval data into the publish config', async () => {+ const user = userEvent.setup()+ renderKnowledgeRetrieval({ showPublishPayload: true })++ await user.click(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.knowledgeRetrieval.add' }))+ const dialog = screen.getByRole('dialog', {+ name: 'agentV2.agentDetail.configure.knowledgeRetrieval.dialog.title',+ })++ expect(within(dialog).getByRole('button', {+ name: 'agentV2.agentDetail.configure.knowledgeRetrieval.retrievalTwo',+ })).toBeInTheDocument()++ await user.click(within(dialog).getByRole('radio', {+ name: 'agentV2.agentDetail.configure.knowledgeRetrieval.dialog.query.custom',+ }))+ await user.type(within(dialog).getByRole('textbox', {+ name: 'agentV2.agentDetail.configure.knowledgeRetrieval.dialog.query.customInputLabel',+ }), 'new release notes')++ const knowledgeConfig = JSON.parse(screen.getByLabelText('publish payload').textContent ?? '{}')+ expect(knowledgeConfig.datasets).toEqual(expect.arrayContaining([+ {+ id: 'retrieval-1',+ name: 'agentDetail.configure.knowledgeRetrieval.retrievalOne',+ },+ expect.objectContaining({+ name: 'agentV2.agentDetail.configure.knowledgeRetrieval.retrievalTwo',+ }),+ ]))+ expect(knowledgeConfig).toMatchObject({+ query_config: {+ query: 'new release notes',+ top_k: 4,+ },+ query_mode: 'user_query',+ })+ })++ it('should open the knowledge retrieval dialog from the edit button', async () => {+ const user = userEvent.setup()+ renderKnowledgeRetrieval()++ await user.click(screen.getByRole('button', {+ name: 'agentV2.agentDetail.configure.knowledgeRetrieval.edit:{"name":"agentV2.agentDetail.configure.knowledgeRetrieval.retrievalOne"}',+ }))++ const dialog = screen.getByRole('dialog', {+ name: 'agentV2.agentDetail.configure.knowledgeRetrieval.dialog.title',+ })+ await user.click(within(dialog).getByRole('button', {+ name: 'agentV2.agentDetail.configure.knowledgeRetrieval.retrievalOne',+ }))++ expect(within(dialog).getByRole('textbox', {+ name: 'agentV2.agentDetail.configure.knowledgeRetrieval.dialog.nameLabel',+ })).toHaveValue('agentV2.agentDetail.configure.knowledgeRetrieval.retrievalOne')+ })++ it('should show hydrated backend datasets in the edit dialog', async () => {+ const user = userEvent.setup()+ renderKnowledgeRetrieval({+ initialDraft: {+ ...defaultAgentSoulConfigFormState,+ knowledgeRetrievals: [+ {+ id: 'dataset-1',+ name: 'Search Docs',+ datasetRefs: [+ {+ id: 'dataset-1',+ name: 'Product Docs',+ description: 'Docs corpus',+ },+ ],+ },+ ],+ },+ })++ await user.click(screen.getByRole('button', {+ name: 'agentV2.agentDetail.configure.knowledgeRetrieval.edit:{"name":"Search Docs"}',+ }))++ const dialog = screen.getByRole('dialog', {+ name: 'agentV2.agentDetail.configure.knowledgeRetrieval.dialog.title',+ })++ expect(within(dialog).getByText('Product Docs')).toBeInTheDocument()+ expect(within(dialog).queryByText('appDebug.datasetConfig.knowledgeTip')).not.toBeInTheDocument()+ })++ it('should save edited retrieval data into the publish config', async () => {+ const user = userEvent.setup()+ renderKnowledgeRetrieval({ showPublishPayload: true })++ await user.click(screen.getByRole('button', {+ name: 'agentV2.agentDetail.configure.knowledgeRetrieval.edit:{"name":"agentV2.agentDetail.configure.knowledgeRetrieval.retrievalOne"}',+ }))+ const dialog = screen.getByRole('dialog', {+ name: 'agentV2.agentDetail.configure.knowledgeRetrieval.dialog.title',+ })++ await user.click(within(dialog).getByRole('button', {+ name: 'agentV2.agentDetail.configure.knowledgeRetrieval.retrievalOne',+ }))+ const nameInput = within(dialog).getByRole('textbox', {+ name: 'agentV2.agentDetail.configure.knowledgeRetrieval.dialog.nameLabel',+ })+ await user.clear(nameInput)+ await user.type(nameInput, 'Release Search')+ await user.click(within(dialog).getByRole('radio', {+ name: 'agentV2.agentDetail.configure.knowledgeRetrieval.dialog.query.custom',+ }))+ await user.type(within(dialog).getByRole('textbox', {+ name: 'agentV2.agentDetail.configure.knowledgeRetrieval.dialog.query.customInputLabel',+ }), 'release notes')++ const knowledgeConfig = JSON.parse(screen.getByLabelText('publish payload').textContent ?? '{}')+ expect(knowledgeConfig).toMatchObject({+ datasets: [+ {+ id: 'retrieval-1',+ name: 'Release Search',+ },+ ],+ query_config: {+ query: 'release notes',+ top_k: 4,+ },+ query_mode: 'user_query',+ })+ })++ it('should remove the knowledge retrieval row from the remove button', async () => {+ const user = userEvent.setup()+ renderKnowledgeRetrieval()++ await user.click(screen.getByRole('button', {+ name: 'agentV2.agentDetail.configure.knowledgeRetrieval.remove:{"name":"agentV2.agentDetail.configure.knowledgeRetrieval.retrievalOne"}',+ }))++ expect(screen.queryByText('agentV2.agentDetail.configure.knowledgeRetrieval.retrievalOne')).not.toBeInTheDocument()+ expect(screen.getByText('agentV2.agentDetail.configure.knowledgeRetrieval.empty.title')).toBeInTheDocument()+ })+ })++ describe('Edge Cases', () => {+ it('should close the dialog from the close button', async () => {+ const user = userEvent.setup()+ renderKnowledgeRetrieval()++ await user.click(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.knowledgeRetrieval.add' }))+ await user.click(screen.getByRole('button', { name: 'Close' }))++ expect(screen.queryByRole('dialog', {+ name: 'agentV2.agentDetail.configure.knowledgeRetrieval.dialog.title',+ })).not.toBeInTheDocument()+ })+ })+})diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/dialog.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/dialog.tsxnew file mode 100644index 00000000000..2e4de81b068--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/dialog.tsx@@ -0,0 +1,472 @@+'use client'++import type { AgentKnowledgeDatasetConfig } from '@dify/contracts/api/console/agent/types.gen'+import type { ReactNode } from 'react'+import type {+ MetadataFilteringCondition,+ MetadataFilteringModeEnum,+ MultipleRetrievalConfig,+} from '@/app/components/workflow/nodes/knowledge-retrieval/types'+import type { ModelConfig } from '@/app/components/workflow/types'+import type { AgentKnowledgeRetrievalItem } from '@/features/agent-v2/agent-composer/form-state'+import type { DataSet, MetadataInDoc } from '@/models/datasets'+import { cn } from '@langgenius/dify-ui/cn'+import { Dialog, DialogCloseButton, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'+import { Input } from '@langgenius/dify-ui/input'+import { RadioRoot } from '@langgenius/dify-ui/radio'+import { RadioGroup } from '@langgenius/dify-ui/radio-group'+import { Textarea } from '@langgenius/dify-ui/textarea'+import { intersectionBy } from 'es-toolkit/compat'+import { useEffect, useMemo, useRef, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { IndexingType } from '@/app/components/datasets/create/step-two/hooks/use-indexing-config'+import Field from '@/app/components/workflow/nodes/_base/components/field'+import AddKnowledge from '@/app/components/workflow/nodes/knowledge-retrieval/components/add-dataset'+import DatasetList from '@/app/components/workflow/nodes/knowledge-retrieval/components/dataset-list'+import MetadataFilter from '@/app/components/workflow/nodes/knowledge-retrieval/components/metadata/metadata-filter'+import RetrievalConfig from '@/app/components/workflow/nodes/knowledge-retrieval/components/retrieval-config'+import {+ ComparisonOperator,+ LogicalOperator,+ MetadataFilteringVariableType,+ MetadataFilteringModeEnum as WorkflowMetadataFilteringModeEnum,+} from '@/app/components/workflow/nodes/knowledge-retrieval/types'+import { DATASET_DEFAULT } from '@/config'+import { useDocLink } from '@/context/i18n'+import { ChunkingMode, DatasetPermission, DataSourceType } from '@/models/datasets'+import { AppModeEnum, RETRIEVE_METHOD, RETRIEVE_TYPE } from '@/types/app'++type KnowledgeRetrievalQueryMode = 'agent' | 'custom'++const queryModeOptions: KnowledgeRetrievalQueryMode[] = ['agent', 'custom']++const optionCardClassName = cn(+ 'flex h-8 flex-1 items-center justify-center rounded-lg border border-components-option-card-option-border bg-components-option-card-option-bg px-3 py-2 text-center system-sm-regular text-text-secondary transition-colors',+ 'hover:border-components-option-card-option-border-hover hover:bg-components-option-card-option-bg-hover',+ 'focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden',+ 'data-checked:border-[1.5px] data-checked:border-components-option-card-option-selected-border data-checked:bg-components-option-card-option-selected-bg data-checked:font-medium data-checked:text-text-primary data-checked:shadow-xs data-checked:shadow-shadow-shadow-3',+)++function KnowledgeRetrievalDialogIcon() {+ return (+ <span className="flex size-6 shrink-0 items-center justify-center rounded-md border-[0.5px] border-divider-subtle bg-util-colors-green-green-500 p-1 text-text-primary-on-surface shadow-md shadow-shadow-shadow-5">+ <span aria-hidden className="i-ri-book-open-line size-4" />+ </span>+ )+}++function DialogFormLabel({+ children,+ id,+}: {+ children: ReactNode+ id?: string+}) {+ return (+ <div id={id} className="flex min-h-6 items-center system-sm-semibold-uppercase text-text-secondary">+ {children}+ </div>+ )+}++const createDefaultRetrievalConfig = (): MultipleRetrievalConfig => ({+ top_k: DATASET_DEFAULT.top_k,+ score_threshold: null,+ reranking_enable: false,+})++const createDatasetFromRef = (dataset: AgentKnowledgeDatasetConfig, index: number): DataSet => {+ const id = dataset.id ?? dataset.name ?? `dataset-${index}`+ const name = dataset.name ?? id++ return {+ id,+ name,+ indexing_status: 'completed',+ icon_info: {+ icon: '📙',+ icon_type: 'emoji',+ icon_background: '#FFF4ED',+ icon_url: '',+ },+ description: dataset.description ?? '',+ permission: DatasetPermission.allTeamMembers,+ data_source_type: DataSourceType.FILE,+ indexing_technique: IndexingType.QUALIFIED,+ created_by: '',+ updated_by: '',+ updated_at: 0,+ app_count: 0,+ doc_form: ChunkingMode.text,+ document_count: 0,+ total_document_count: 0,+ word_count: 0,+ provider: '',+ embedding_model: '',+ embedding_model_provider: '',+ embedding_available: false,+ retrieval_model_dict: {+ search_method: RETRIEVE_METHOD.semantic,+ reranking_enable: false,+ reranking_model: {+ reranking_provider_name: '',+ reranking_model_name: '',+ },+ top_k: DATASET_DEFAULT.top_k,+ score_threshold_enabled: false,+ score_threshold: 0,+ },+ retrieval_model: {+ search_method: RETRIEVE_METHOD.semantic,+ reranking_enable: false,+ reranking_model: {+ reranking_provider_name: '',+ reranking_model_name: '',+ },+ top_k: DATASET_DEFAULT.top_k,+ score_threshold_enabled: false,+ score_threshold: 0,+ },+ tags: [],+ external_knowledge_info: {+ external_knowledge_id: '',+ external_knowledge_api_id: '',+ external_knowledge_api_name: '',+ external_knowledge_api_endpoint: '',+ },+ external_retrieval_model: {+ top_k: DATASET_DEFAULT.top_k,+ score_threshold: 0,+ score_threshold_enabled: false,+ },+ built_in_field_enabled: false,+ runtime_mode: 'general',+ enable_api: false,+ is_multimodal: false,+ }+}++const getSelectedDatasets = (item?: AgentKnowledgeRetrievalItem) => (+ item?.selectedDatasets ?? item?.datasetRefs?.map(createDatasetFromRef) ?? []+)++const createMetadataCondition = ({ id, name, type }: MetadataInDoc): MetadataFilteringCondition => ({+ id: globalThis.crypto?.randomUUID?.() ?? `${Date.now()}`,+ metadata_id: id,+ name,+ comparison_operator: type === MetadataFilteringVariableType.number+ ? ComparisonOperator.equal+ : ComparisonOperator.is,+})++export function AgentKnowledgeRetrievalDialog({+ item,+ initialName,+ onItemChange,+ open,+ onOpenChange,+}: {+ item?: AgentKnowledgeRetrievalItem+ initialName?: string+ onItemChange?: (item: AgentKnowledgeRetrievalItem) => void+ open: boolean+ onOpenChange: (open: boolean) => void+}) {+ const { t } = useTranslation('agentV2')+ const docLink = useDocLink()+ const [name, setName] = useState(() => item?.name ?? initialName ?? t('agentDetail.configure.knowledgeRetrieval.retrievalOne'))+ const [isEditingName, setIsEditingName] = useState(false)+ const nameInputRef = useRef<HTMLInputElement>(null)+ const [queryMode, setQueryMode] = useState<KnowledgeRetrievalQueryMode>(item?.queryMode ?? 'agent')+ const [customQuery, setCustomQuery] = useState(item?.customQuery ?? '')+ const [selectedDatasets, setSelectedDatasets] = useState<DataSet[]>(() => getSelectedDatasets(item))+ const [retrievalMode, setRetrievalMode] = useState(item?.retrievalMode ?? RETRIEVE_TYPE.multiWay)+ const [multipleRetrievalConfig, setMultipleRetrievalConfig] = useState(item?.multipleRetrievalConfig ?? createDefaultRetrievalConfig)+ const [rerankModelOpen, setRerankModelOpen] = useState(false)+ const [metadataFilterMode, setMetadataFilterMode] = useState<MetadataFilteringModeEnum>(item?.metadataFilterMode ?? WorkflowMetadataFilteringModeEnum.disabled)+ const [metadataFilteringConditions, setMetadataFilteringConditions] = useState(item?.metadataFilteringConditions ?? {+ logical_operator: LogicalOperator.and,+ conditions: [] as MetadataFilteringCondition[],+ })+ const [metadataModelConfig, setMetadataModelConfig] = useState<ModelConfig | undefined>(item?.metadataModelConfig)+ const queryModeLabelId = 'agent-knowledge-retrieval-query-mode-label'+ const updateItem = (patch: Partial<AgentKnowledgeRetrievalItem>) => {+ if (!item)+ return++ onItemChange?.({+ ...item,+ name,+ queryMode,+ customQuery,+ selectedDatasets,+ retrievalMode,+ multipleRetrievalConfig,+ metadataFilterMode,+ metadataFilteringConditions,+ metadataModelConfig,+ ...patch,+ })+ }+ const metadataList = useMemo(() => {+ const datasetsWithMetadata = selectedDatasets.filter(dataset => !!dataset.doc_metadata)++ if (datasetsWithMetadata.length === 0)+ return []++ return intersectionBy(...datasetsWithMetadata.map(dataset => dataset.doc_metadata!), 'name')+ }, [selectedDatasets])++ useEffect(() => {+ if (!isEditingName)+ return++ nameInputRef.current?.focus()+ nameInputRef.current?.select()+ }, [isEditingName])++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="flex h-[520px] max-h-[calc(100dvh-2rem)] w-[400px] flex-col overflow-hidden p-0">+ <DialogTitle className="sr-only">+ {t('agentDetail.configure.knowledgeRetrieval.dialog.title')}+ </DialogTitle>+ <div className="flex items-center gap-2 px-4 pt-3">+ <KnowledgeRetrievalDialogIcon />+ {isEditingName+ ? (+ <Input+ ref={nameInputRef}+ aria-label={t('agentDetail.configure.knowledgeRetrieval.dialog.nameLabel')}+ className="h-7 min-w-0 flex-1 rounded-md px-1 py-0 system-xl-semibold text-text-primary"+ value={name}+ onBlur={() => setIsEditingName(false)}+ onChange={(event) => {+ const nextName = event.currentTarget.value+ setName(nextName)+ updateItem({ name: nextName })+ }}+ onKeyDown={(event) => {+ if (event.key === 'Enter')+ setIsEditingName(false)+ }}+ />+ )+ : (+ <button+ type="button"+ className="flex h-7 min-w-0 flex-1 items-center rounded-md px-1 py-0 text-left system-xl-semibold text-text-primary hover:bg-components-input-bg-hover focus-visible:border focus-visible:border-components-input-border-active focus-visible:bg-components-input-bg-active focus-visible:shadow-xs focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"+ onClick={() => setIsEditingName(true)}+ >+ <span className="min-w-0 truncate">+ {name}+ </span>+ </button>+ )}+ <DialogCloseButton className="static size-7 shrink-0 rounded-md" />+ </div>++ <div className="flex min-h-0 flex-1 flex-col gap-1 py-2">+ <div className="flex flex-col gap-1 px-4 py-2">+ <DialogFormLabel id={queryModeLabelId}>+ {t('agentDetail.configure.knowledgeRetrieval.dialog.query.label')}+ </DialogFormLabel>+ <RadioGroup<KnowledgeRetrievalQueryMode>+ aria-labelledby={queryModeLabelId}+ className="w-full gap-2"+ value={queryMode}+ onValueChange={(nextMode) => {+ if (nextMode) {+ setQueryMode(nextMode)+ updateItem({ queryMode: nextMode })+ }+ }}+ >+ {queryModeOptions.map(mode => (+ <RadioRoot+ key={mode}+ value={mode}+ variant="unstyled"+ nativeButton+ render={<button type="button" className={optionCardClassName} />}+ >+ <span className="min-w-0 truncate">+ {t(`agentDetail.configure.knowledgeRetrieval.dialog.query.${mode}`)}+ </span>+ </RadioRoot>+ ))}+ </RadioGroup>+ {queryMode === 'custom'+ ? (+ <>+ <div className="pt-1">+ <Textarea+ aria-label={t('agentDetail.configure.knowledgeRetrieval.dialog.query.customInputLabel')}+ className="h-20 resize-none rounded-lg px-3 py-2 system-sm-regular"+ placeholder={t('agentDetail.configure.knowledgeRetrieval.dialog.query.customPlaceholder')}+ value={customQuery}+ onValueChange={(nextQuery) => {+ setCustomQuery(nextQuery)+ updateItem({ customQuery: nextQuery })+ }}+ />+ </div>+ <p className="system-xs-regular text-text-tertiary">+ {t('agentDetail.configure.knowledgeRetrieval.dialog.query.customDescription')}+ </p>+ </>+ )+ : (+ <p className="pt-1 system-xs-regular text-text-tertiary">+ {t('agentDetail.configure.knowledgeRetrieval.dialog.query.agentDescription')}+ </p>+ )}+ </div>++ <div className="px-4 py-2">+ <Field+ title={t('agentDetail.configure.knowledgeRetrieval.dialog.knowledge.label')}+ required+ operations={(+ <div className="flex items-center space-x-1">+ <RetrievalConfig+ payload={{+ retrieval_mode: retrievalMode,+ multiple_retrieval_config: multipleRetrievalConfig,+ }}+ onRetrievalModeChange={(nextRetrievalMode) => {+ setRetrievalMode(nextRetrievalMode)+ updateItem({ retrievalMode: nextRetrievalMode })+ }}+ onMultipleRetrievalConfigChange={(nextMultipleRetrievalConfig) => {+ setMultipleRetrievalConfig(nextMultipleRetrievalConfig)+ updateItem({ multipleRetrievalConfig: nextMultipleRetrievalConfig })+ }}+ readonly={!selectedDatasets.length}+ modal+ rerankModalOpen={rerankModelOpen}+ onRerankModelOpenChange={setRerankModelOpen}+ selectedDatasets={selectedDatasets}+ />+ <div className="h-3 w-px bg-divider-regular" />+ <AddKnowledge+ selectedIds={selectedDatasets.map(dataset => dataset.id)}+ modal+ onChange={(nextDatasets) => {+ setSelectedDatasets(nextDatasets)+ updateItem({ selectedDatasets: nextDatasets })+ }}+ />+ </div>+ )}+ >+ <DatasetList+ list={selectedDatasets}+ onChange={setSelectedDatasets}+ settingsDrawerBackdropClassName="bg-background-overlay"+ settingsDrawerBackdropForceRender+ settingsDrawerPopupClassName="data-[swipe-direction=right]:top-6 data-[swipe-direction=right]:bottom-6"+ settingsModalHeight="100%"+ />+ </Field>+ </div>++ <div className="py-2">+ <MetadataFilter+ metadataList={metadataList}+ selectedDatasetsLoaded+ metadataFilterMode={metadataFilterMode}+ metadataFilteringConditions={metadataFilteringConditions}+ handleMetadataFilterModeChange={(nextMode) => {+ setMetadataFilterMode(nextMode)+ updateItem({ metadataFilterMode: nextMode })+ }}+ handleAddCondition={(metadataItem) => {+ setMetadataFilteringConditions((current) => {+ const nextConditions = {+ ...current,+ conditions: [...current.conditions, createMetadataCondition(metadataItem)],+ }+ updateItem({ metadataFilteringConditions: nextConditions })+ return nextConditions+ })+ }}+ handleRemoveCondition={(conditionId) => {+ setMetadataFilteringConditions((current) => {+ const nextConditions = {+ ...current,+ conditions: current.conditions.filter(condition => condition.id !== conditionId),+ }+ updateItem({ metadataFilteringConditions: nextConditions })+ return nextConditions+ })+ }}+ handleToggleConditionLogicalOperator={() => {+ setMetadataFilteringConditions((current) => {+ const nextConditions = {+ ...current,+ logical_operator: current.logical_operator === LogicalOperator.and+ ? LogicalOperator.or+ : LogicalOperator.and,+ }+ updateItem({ metadataFilteringConditions: nextConditions })+ return nextConditions+ })+ }}+ handleUpdateCondition={(conditionId, nextCondition) => {+ setMetadataFilteringConditions((current) => {+ const nextConditions = {+ ...current,+ conditions: current.conditions.map(condition => condition.id === conditionId ? nextCondition : condition),+ }+ updateItem({ metadataFilteringConditions: nextConditions })+ return nextConditions+ })+ }}+ metadataModelConfig={metadataModelConfig}+ handleMetadataModelChange={(model) => {+ setMetadataModelConfig((current) => {+ const nextMetadataModelConfig = {+ provider: model.provider,+ name: model.modelId,+ mode: model.mode ?? current?.mode ?? AppModeEnum.CHAT,+ completion_params: current?.completion_params ?? { temperature: 0.7 },+ }+ updateItem({ metadataModelConfig: nextMetadataModelConfig })+ return nextMetadataModelConfig+ })+ }}+ handleMetadataCompletionParamsChange={(completionParams) => {+ setMetadataModelConfig((current) => {+ const nextMetadataModelConfig = {+ provider: current?.provider ?? '',+ name: current?.name ?? '',+ mode: current?.mode ?? AppModeEnum.CHAT,+ completion_params: completionParams,+ }+ updateItem({ metadataModelConfig: nextMetadataModelConfig })+ return nextMetadataModelConfig+ })+ }}+ />+ </div>+ </div>++ <div className="flex flex-col gap-2 px-4 pb-4">+ <div aria-hidden className="h-2 w-8 border-b border-divider-regular" />+ <a+ href={docLink('/use-dify/knowledge/create-knowledge/setting-indexing-methods')}+ target="_blank"+ rel="noopener noreferrer"+ className="inline-flex min-w-0 items-center gap-1 system-xs-regular text-text-tertiary hover:text-text-secondary hover:underline focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"+ >+ <span aria-hidden className="i-ri-book-read-line size-3 shrink-0" />+ <span className="min-w-0 truncate">+ {t('form.retrievalSetting.learnMore', { ns: 'datasetSettings' })}+ </span>+ </a>+ </div>+ </DialogContent>+ </Dialog>+ )+}diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/index.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/index.tsxnew file mode 100644index 00000000000..5f65302b23a--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/index.tsx@@ -0,0 +1,129 @@+'use client'++import type { AgentOrchestrateAddActionOptions } from '../add-actions-context'+import type { AgentKnowledgeRetrievalItem } from '@/features/agent-v2/agent-composer/form-state'+import { useAtom } from 'jotai'+import { useState } from 'react'+import { useTranslation } from 'react-i18next'+import { agentComposerKnowledgeRetrievalsAtom } from '@/features/agent-v2/agent-composer/store-modules/knowledge'+import { useRegisterAgentOrchestrateAddAction } from '../add-actions-context'+import { ConfigureSectionAddButton } from '../common/add-button'+import { ConfigureSectionConfigurableItem } from '../common/configurable-item'+import { ConfigureSectionEmpty } from '../common/empty'+import { ConfigureSection } from '../common/section'+import { AgentKnowledgeRetrievalDialog } from './dialog'++function KnowledgeRetrievalIcon() {+ return (+ <span className="flex size-5 shrink-0 items-center justify-center rounded-md border-[0.5px] border-divider-subtle bg-util-colors-green-green-500 p-[3px] text-text-primary-on-surface shadow-xs shadow-shadow-shadow-3">+ <span aria-hidden className="i-ri-book-open-line size-3.5" />+ </span>+ )+}++function AgentKnowledgeRetrievalRow({+ onDelete,+ onEdit,+ item,+}: {+ onDelete: () => void+ onEdit: () => void+ item: AgentKnowledgeRetrievalItem+}) {+ const { t } = useTranslation('agentV2')+ const itemName = item.name ?? (item.nameKey ? t(item.nameKey) : item.id)++ return (+ <ConfigureSectionConfigurableItem+ icon={<KnowledgeRetrievalIcon />}+ label={itemName}+ editAriaLabel={t('agentDetail.configure.knowledgeRetrieval.edit', { name: itemName })}+ removeAriaLabel={t('agentDetail.configure.knowledgeRetrieval.remove', { name: itemName })}+ onEdit={onEdit}+ onRemove={onDelete}+ />+ )+}++export function AgentKnowledgeRetrieval() {+ const { t } = useTranslation('agentV2')+ const [retrievals, setRetrievals] = useAtom(agentComposerKnowledgeRetrievalsAtom)+ const [isAddDialogOpen, setIsAddDialogOpen] = useState(false)+ const [editingRetrieval, setEditingRetrieval] = useState<AgentKnowledgeRetrievalItem | null>(null)+ const knowledgeRetrievalTip = t('agentDetail.configure.knowledgeRetrieval.tip')+ const retrievalListId = 'agent-configure-knowledge-retrieval-list'+ const isDialogOpen = isAddDialogOpen || !!editingRetrieval+ const updateRetrieval = (nextRetrieval: AgentKnowledgeRetrievalItem) => {+ setRetrievals(retrievals.map(retrieval => retrieval.id === nextRetrieval.id ? nextRetrieval : retrieval))+ setEditingRetrieval(nextRetrieval)+ }+ const getDefaultRetrievalName = (index: number) => {+ if (index === 1)+ return t('agentDetail.configure.knowledgeRetrieval.retrievalOne')+ if (index === 2)+ return t('agentDetail.configure.knowledgeRetrieval.retrievalTwo')++ return t('agentDetail.configure.knowledgeRetrieval.defaultName', { index })+ }+ const addRetrieval = (options?: AgentOrchestrateAddActionOptions) => {+ const nextRetrieval: AgentKnowledgeRetrievalItem = {+ id: globalThis.crypto?.randomUUID?.() ?? `retrieval-${Date.now()}`,+ name: getDefaultRetrievalName(retrievals.length + 1),+ queryMode: 'agent',+ }++ setRetrievals([...retrievals, nextRetrieval])+ setEditingRetrieval(nextRetrieval)+ setIsAddDialogOpen(true)+ options?.onAdded?.(nextRetrieval)+ }+ useRegisterAgentOrchestrateAddAction('knowledge', addRetrieval)++ return (+ <>+ <ConfigureSection+ label={t('agentDetail.configure.knowledgeRetrieval.label')}+ labelId="agent-configure-knowledge-retrieval-label"+ panelId={retrievalListId}+ tip={knowledgeRetrievalTip}+ tipAriaLabel={knowledgeRetrievalTip}+ rootClassName="border-b border-divider-subtle pt-4"+ panelContentClassName="flex flex-col gap-1 pb-4"+ actions={(+ <ConfigureSectionAddButton+ ariaLabel={t('agentDetail.configure.knowledgeRetrieval.add')}+ onClick={() => addRetrieval()}+ />+ )}+ >+ {retrievals.length === 0+ ? (+ <ConfigureSectionEmpty+ title={t('agentDetail.configure.knowledgeRetrieval.empty.title')}+ description={t('agentDetail.configure.knowledgeRetrieval.empty.description')}+ />+ )+ : retrievals.map(item => (+ <AgentKnowledgeRetrievalRow+ key={item.id}+ item={item}+ onDelete={() => setRetrievals(retrievals.filter(retrieval => retrieval.id !== item.id))}+ onEdit={() => setEditingRetrieval(item)}+ />+ ))}+ </ConfigureSection>+ <AgentKnowledgeRetrievalDialog+ key={editingRetrieval?.id ?? 'add'}+ item={editingRetrieval ?? undefined}+ initialName={editingRetrieval ? (editingRetrieval.name ?? (editingRetrieval.nameKey ? t(editingRetrieval.nameKey) : editingRetrieval.id)) : undefined}+ onItemChange={updateRetrieval}+ open={isDialogOpen}+ onOpenChange={(open) => {+ setIsAddDialogOpen(open)+ if (!open)+ setEditingRetrieval(null)+ }}+ />+ </>+ )+}diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/memory.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/memory.tsxnew file mode 100644index 00000000000..aeae40e23bb--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/memory.tsx@@ -0,0 +1,125 @@+'use client'++import type { AgentSoulMemoryConfig } from '@dify/contracts/api/console/agent/types.gen'+import { Button } from '@langgenius/dify-ui/button'+import { cn } from '@langgenius/dify-ui/cn'+import { useTranslation } from 'react-i18next'+import { SkeletonRectangle } from '@/app/components/base/skeleton'++type MemorySettingsProps = {+ isPending: boolean+ memory?: AgentSoulMemoryConfig+}++const memoryConfigFields = [+ {+ key: 'budget',+ icon: 'i-ri-scales-3-line',+ labelKey: 'agentDetail.memorySettings.budgetLabel',+ },+ {+ key: 'scope',+ icon: 'i-ri-global-line',+ labelKey: 'agentDetail.memorySettings.scopeLabel',+ },+] as const++function MemoryConfigValue({+ icon,+ isPending,+ label,+ value,+}: {+ icon: string+ isPending: boolean+ label: string+ value?: string | null+}) {+ const { t } = useTranslation('agentV2')++ return (+ <div className="flex min-h-19 min-w-0 items-start gap-3 rounded-lg border border-divider-subtle bg-background-section-burn p-3">+ <div className="flex size-8 shrink-0 items-center justify-center rounded-lg border border-divider-subtle bg-components-panel-bg text-text-tertiary">+ <span aria-hidden className={`${icon} size-4`} />+ </div>+ <div className="min-w-0 flex-1">+ <div className="system-xs-semibold-uppercase text-text-tertiary">+ {label}+ </div>+ {isPending+ ? <SkeletonRectangle className="mt-2 h-4 w-28 animate-pulse rounded-md" />+ : (+ <div+ className={cn(+ 'mt-1 truncate system-sm-semibold',+ value ? 'text-text-primary' : 'text-text-quaternary',+ )}+ translate={value ? 'no' : undefined}+ >+ {value || t('agentDetail.memorySettings.notConfigured')}+ </div>+ )}+ </div>+ </div>+ )+}++export function MemorySettings({+ isPending,+ memory,+}: MemorySettingsProps) {+ const { t } = useTranslation('agentV2')++ return (+ <div className="rounded-xl border border-components-panel-border bg-components-panel-bg p-4 shadow-xs">+ <div className="mb-4 flex items-start gap-3">+ <div className="flex size-10 shrink-0 items-center justify-center rounded-xl border bg-state-accent-hover text-text-accent-light-mode-only">+ <span aria-hidden className="i-ri-brain-line size-5" />+ </div>+ <div className="min-w-0">+ <h2 className="system-xl-semibold text-text-primary">+ {t('agentDetail.memorySettings.title')}+ </h2>+ <p className="mt-1 system-sm-regular text-text-tertiary">+ {t('agentDetail.memorySettings.description')}+ </p>+ </div>+ </div>++ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">+ {memoryConfigFields.map(field => (+ <MemoryConfigValue+ key={field.key}+ icon={field.icon}+ isPending={isPending}+ label={t(field.labelKey)}+ value={memory?.[field.key]}+ />+ ))}+ </div>++ <div className="mt-4 flex flex-wrap items-center justify-between gap-3 border-t border-divider-subtle pt-4">+ <div className="min-w-0 flex-1">+ <div className="flex min-w-0 flex-wrap items-center gap-1.5 system-xs-regular text-text-tertiary">+ <span>{t('agentDetail.memorySettings.export.title')}</span>+ <span className="inline-flex items-center gap-1 rounded-[5px] bg-components-badge-bg-dimm px-1.5 py-0.5 system-2xs-medium-uppercase text-text-tertiary">+ {t('agentDetail.memorySettings.export.soon')}+ </span>+ </div>+ <p className="mt-0.5 system-2xs-regular text-text-tertiary">+ {t('agentDetail.memorySettings.export.description')}+ </p>+ </div>+ <Button+ variant="secondary"+ size="small"+ disabled+ className="gap-1.5"+ >+ <span aria-hidden className="i-ri-download-line size-3.5" />+ {t('agentDetail.memorySettings.export.download')}+ </Button>+ </div>+ </div>+ )+}diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/model-config/field.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/model-config/field.tsxnew file mode 100644index 00000000000..a8c7697930e--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/model-config/field.tsx@@ -0,0 +1,54 @@+'use client'++import type { DefaultModel, Model } from '@/app/components/header/account-setting/model-provider-page/declarations'+import { FieldLabel, FieldRoot } from '@langgenius/dify-ui/field'+import { useTranslation } from 'react-i18next'+import ModelSelector from '@/app/components/header/account-setting/model-provider-page/model-selector'+import { useAgentOrchestrateReadOnly } from '../read-only-context'++type AgentModelFieldProps = {+ currentModel?: DefaultModel+ textGenerationModelList: Model[]+ onSelect: (model: DefaultModel) => void+}++export function AgentModelField({+ currentModel,+ textGenerationModelList,+ onSelect,+}: AgentModelFieldProps) {+ const { t } = useTranslation('agentV2')+ const readOnly = useAgentOrchestrateReadOnly()++ return (+ <FieldRoot name="model" className="gap-1 pb-4">+ <FieldLabel className="py-0 system-sm-semibold-uppercase! text-text-secondary">+ {t('agentDetail.configure.model.label')}+ </FieldLabel>+ <div className="relative h-8 min-w-0">+ {readOnly+ ? (+ <div className="flex h-8 w-full min-w-0 items-center rounded-lg bg-components-input-bg-disabled px-3 system-sm-regular text-components-input-text-filled">+ <span className="truncate">{currentModel?.model}</span>+ </div>+ )+ : (+ <>+ <ModelSelector+ defaultModel={currentModel}+ modelList={textGenerationModelList}+ triggerClassName="h-8! w-full rounded-lg! pr-10! [&_.i-ri-arrow-down-s-line]:hidden"+ popupClassName="w-(--anchor-width) max-w-[min(var(--anchor-width),var(--available-width),calc(100vw-32px))]"+ providerSettingsSource="agent"+ showModelMeta={false}+ onSelect={onSelect}+ />+ <div className="pointer-events-none absolute inset-y-0 right-0 flex w-8 items-center justify-center rounded-r-lg bg-components-button-tertiary-bg">+ <span aria-hidden="true" className="i-ri-equalizer-2-line size-4 text-text-tertiary" />+ </div>+ </>+ )}+ </div>+ </FieldRoot>+ )+}diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/index.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/index.tsxnew file mode 100644index 00000000000..3d110eb022b--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/index.tsx@@ -0,0 +1,425 @@+'use client'++import type { KeyboardEvent, MouseEvent, PointerEvent as ReactPointerEvent } from 'react'+import type { SlashMenuCategory, SlashMenuView } from './slash'+import type { RosterReferenceToken } from '@/app/components/base/prompt-editor/plugins/roster-reference-block/utils'+import type { AgentTool } from '@/features/agent-v2/agent-composer/form-state'+import { cn } from '@langgenius/dify-ui/cn'+import { Kbd } from '@langgenius/dify-ui/kbd'+import { toast } from '@langgenius/dify-ui/toast'+import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'+import { useClipboard } from 'foxact/use-clipboard'+import { useAtom, useAtomValue } from 'jotai'+import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react'+import { useTranslation } from 'react-i18next'+import { Infotip } from '@/app/components/base/infotip'+import PromptEditor from '@/app/components/base/prompt-editor'+import BlockIcon from '@/app/components/workflow/block-icon'+import { BlockEnum } from '@/app/components/workflow/types'+import { agentComposerFilesAtom } from '@/features/agent-v2/agent-composer/store-modules/files'+import { agentComposerKnowledgeRetrievalsAtom } from '@/features/agent-v2/agent-composer/store-modules/knowledge'+import { agentComposerPromptAtom } from '@/features/agent-v2/agent-composer/store-modules/prompt'+import { agentComposerSkillsAtom } from '@/features/agent-v2/agent-composer/store-modules/skills'+import { agentComposerToolsAtom } from '@/features/agent-v2/agent-composer/store-modules/tools'+import useTheme from '@/hooks/use-theme'+import { Theme } from '@/types/app'+import { useAgentOrchestrateAddActions } from '../add-actions-context'+import { useAgentOrchestrateReadOnly } from '../read-only-context'+import { replaceTrailingSlashWithToken } from './options'+import { AgentPromptSlashMenu } from './slash'++const subscribeHydrationState = () => () => {}++const useIsHydrated = () => useSyncExternalStore(+ subscribeHydrationState,+ () => true,+ () => false,+)++function AgentPromptPlaceholder({+ insertLabel,+ text,+}: {+ insertLabel: string+ text: string+}) {+ return (+ <span className="flex items-center gap-0.5 system-sm-regular whitespace-nowrap text-components-input-text-placeholder">+ <span>{text}</span>+ <Kbd className="text-text-placeholder">+ /+ </Kbd>+ <span className="underline decoration-dotted underline-offset-2">+ {insertLabel}+ </span>+ </span>+ )+}++function getProviderToolFromToken(token: RosterReferenceToken, tools: AgentTool[]) {+ if (token.kind !== 'tool' && token.kind !== 'tool-all')+ return++ return tools.find(tool =>+ tool.kind === 'provider'+ && (+ token.id === `${tool.id}/*`+ || tool.actions.some(action => token.id === `${tool.id}/${action.toolName}`)+ ),+ )+}++function AgentPromptRosterReferenceIcon({+ token,+ tools,+}: {+ token: RosterReferenceToken+ tools: AgentTool[]+}) {+ const { theme } = useTheme()++ if (token.kind === 'cli_tool') {+ return (+ <span+ aria-hidden+ className="i-ri-terminal-box-line size-3.5 shrink-0 text-text-primary-on-surface"+ />+ )+ }++ const providerTool = getProviderToolFromToken(token, tools)+ if (!providerTool || providerTool.kind !== 'provider')+ return null++ const icon = theme === Theme.dark && providerTool.iconDark ? providerTool.iconDark : providerTool.icon++ if (icon) {+ return (+ <BlockIcon+ className="shrink-0"+ type={BlockEnum.Tool}+ size="xs"+ toolIcon={icon}+ />+ )+ }++ return (+ <span+ aria-hidden+ className={cn('size-3.5 shrink-0', providerTool.iconClassName)}+ />+ )+}++const getLastTextContent = (node: Node): string => {+ if (node.nodeType === Node.TEXT_NODE)+ return node.textContent ?? ''++ const textParts: string[] = []+ const walker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT)+ let current = walker.nextNode()+ while (current) {+ textParts.push(current.textContent ?? '')+ current = walker.nextNode()+ }++ return textParts.join('')+}++const isSelectionAfterSlash = (rootElement: HTMLElement | null, fallbackValue: string) => {+ if (!rootElement)+ return fallbackValue.endsWith('/')++ const selection = window.getSelection()+ if (!selection || !selection.isCollapsed || selection.rangeCount === 0)+ return fallbackValue.endsWith('/')++ const anchorNode = selection.anchorNode+ if (!anchorNode || !rootElement.contains(anchorNode))+ return false++ if (anchorNode.nodeType === Node.TEXT_NODE)+ return (anchorNode.textContent ?? '').slice(0, selection.anchorOffset).endsWith('/')++ const element = anchorNode as Element+ const previousChild = element.childNodes.item(selection.anchorOffset - 1)+ return previousChild ? getLastTextContent(previousChild).endsWith('/') : false+}++export function AgentPromptEditor() {+ const { t } = useTranslation('agentV2')+ const readOnly = useAgentOrchestrateReadOnly()+ const [value, setValue] = useAtom(agentComposerPromptAtom)+ const skills = useAtomValue(agentComposerSkillsAtom)+ const files = useAtomValue(agentComposerFilesAtom)+ const [tools, setTools] = useAtom(agentComposerToolsAtom)+ const retrievals = useAtomValue(agentComposerKnowledgeRetrievalsAtom)+ const addActions = useAgentOrchestrateAddActions()+ const isHydrated = useIsHydrated()+ const promptTip = t('agentDetail.configure.prompt.tip')+ const promptPlaceholder = (+ <AgentPromptPlaceholder+ text={t('agentDetail.configure.prompt.placeholder')}+ insertLabel={t('agentDetail.configure.prompt.insert.label').toLocaleLowerCase()}+ />+ )+ const { copied, copy, reset } = useClipboard({+ onCopyError: () => {+ toast.error(t('agentDetail.configure.prompt.copyFailed'))+ },+ })+ const [slashMenuView, setSlashMenuView] = useState<SlashMenuView>('main')+ const [isSlashMenuOpen, setIsSlashMenuOpen] = useState(false)+ const rootRef = useRef<HTMLDivElement>(null)+ const editorRef = useRef<HTMLDivElement>(null)++ const handleCopyPrompt = useCallback(() => {+ void copy(value)+ }, [copy, value])++ const closeSlashMenu = () => {+ setIsSlashMenuOpen(false)+ setSlashMenuView('main')+ }++ const openSlashMenu = () => {+ setSlashMenuView('main')+ setIsSlashMenuOpen(true)+ }++ const syncSlashMenuWithSelection = useCallback(() => {+ if (!isHydrated || readOnly)+ return++ if (isSelectionAfterSlash(editorRef.current, value))+ openSlashMenu()+ else+ closeSlashMenu()+ }, [isHydrated, readOnly, value])++ const handleEditorKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {+ if (!isHydrated || readOnly)+ return++ if (event.key === 'Escape' && isSlashMenuOpen) {+ event.preventDefault()+ closeSlashMenu()+ return+ }++ if (event.key !== '/' || event.metaKey || event.ctrlKey || event.altKey)+ return++ openSlashMenu()+ }++ const handleEditorKeyUp = () => {+ window.requestAnimationFrame(syncSlashMenuWithSelection)+ }++ const handleEditorPointerUp = (event: ReactPointerEvent<HTMLDivElement>) => {+ const target = event.target+ if (+ target instanceof Element+ && target.closest('[data-agent-prompt-toolbar]')+ ) {+ return+ }++ window.requestAnimationFrame(syncSlashMenuWithSelection)+ }++ const handleRootPointerDown = (event: MouseEvent<HTMLDivElement>) => {+ const target = event.target+ if (!(target instanceof Node))+ return++ if (editorRef.current?.contains(target))+ return++ if (+ target instanceof Element+ && (+ target.closest('[data-agent-prompt-slash-menu]')+ || target.closest('[data-agent-prompt-toolbar]')+ )+ ) {+ return+ }++ closeSlashMenu()+ }++ const handleSlashSelect = (token: string) => {+ setValue(replaceTrailingSlashWithToken(value, token))+ closeSlashMenu()+ }++ const handleInsertSlash = () => {+ setValue(`${value}/`)+ openSlashMenu()+ }++ const renderRosterReferenceIcon = useCallback((token: RosterReferenceToken) => {+ if (token.kind !== 'tool' && token.kind !== 'tool-all' && token.kind !== 'cli_tool')+ return null++ return <AgentPromptRosterReferenceIcon token={token} tools={tools} />+ }, [tools])++ useEffect(() => {+ if (!isSlashMenuOpen)+ return++ const handlePointerDown = (event: PointerEvent) => {+ const target = event.target+ if (!(target instanceof Node))+ return++ if (!rootRef.current?.contains(target))+ closeSlashMenu()+ }++ document.addEventListener('pointerdown', handlePointerDown)+ return () => {+ document.removeEventListener('pointerdown', handlePointerDown)+ }+ }, [isSlashMenuOpen])++ const slashMenuCategories: SlashMenuCategory[] = [+ {+ key: 'skills',+ label: t('agentDetail.configure.skills.label'),+ icon: 'i-ri-box-3-line',+ },+ {+ key: 'files',+ label: t('agentDetail.configure.files.label'),+ icon: 'i-ri-file-line',+ },+ {+ key: 'tools',+ label: t('agentDetail.configure.tools.label'),+ icon: 'i-ri-box-3-line',+ },+ {+ key: 'knowledge',+ label: t('agentDetail.configure.knowledgeRetrieval.label'),+ icon: 'i-ri-book-open-line',+ },+ ]++ return (+ <section className="flex flex-col gap-1 px-0 py-0" aria-labelledby="agent-configure-prompt-label">+ <div className="flex items-center gap-2">+ <div className="flex min-h-6 min-w-0 flex-1 items-center gap-0.5">+ <h3+ id="agent-configure-prompt-label"+ className="truncate system-sm-semibold-uppercase text-text-secondary"+ >+ {t('agentDetail.configure.prompt.label')}+ </h3>+ <Infotip aria-label={promptTip} popupClassName="max-w-64">+ {promptTip}+ </Infotip>+ </div>+ <Tooltip>+ <TooltipTrigger+ render={(+ <button+ type="button"+ aria-label={copied ? t('agentDetail.configure.prompt.copied') : t('agentDetail.configure.prompt.copy')}+ className="flex size-6 shrink-0 items-center justify-center rounded-md p-0.5 text-text-tertiary hover:bg-state-base-hover hover:text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"+ onClick={handleCopyPrompt}+ onMouseLeave={reset}+ >+ <span aria-hidden className={copied ? 'i-ri-check-line size-4' : 'i-ri-clipboard-line size-4'} />+ </button>+ )}+ />+ <TooltipContent>+ {copied ? t('agentDetail.configure.prompt.copied') : t('agentDetail.configure.prompt.copy')}+ </TooltipContent>+ </Tooltip>+ </div>++ <div+ ref={rootRef}+ className="relative"+ onPointerDownCapture={handleRootPointerDown}+ >+ <div+ className="group min-h-28 overflow-hidden rounded-[10px] border-[1.5px] border-transparent bg-components-input-bg-normal pt-1 focus-within:border-components-input-border-active-prompt-1 focus-within:bg-components-input-bg-active focus-within:shadow-xs focus-within:shadow-shadow-shadow-3"+ onKeyDownCapture={handleEditorKeyDown}+ onKeyUpCapture={handleEditorKeyUp}+ onPointerUpCapture={handleEditorPointerUp}+ >+ <div ref={editorRef} className="min-h-[72px] overflow-y-auto px-3 pt-0.5">+ <PromptEditor+ instanceId="agent-configure-prompt-editor"+ compact+ wrapperClassName="min-h-[72px]"+ className="min-h-[72px] text-text-primary"+ placeholder={promptPlaceholder}+ placeholderClassName="top-0!"+ editable={!readOnly}+ value={value}+ onChange={setValue}+ variableBlock={{+ show: true,+ }}+ rosterReferenceBlock={{+ show: true,+ renderIcon: renderRosterReferenceIcon,+ }}+ disableSlashPicker+ disableBracePicker+ />+ </div>+ {!readOnly && (+ <div+ data-agent-prompt-toolbar+ className="flex h-8 shrink-0 items-center justify-between px-3 text-text-tertiary opacity-0 transition-opacity group-focus-within:opacity-100"+ >+ <div className="flex min-w-0 items-center gap-3">+ <button+ type="button"+ className="flex items-center gap-1 system-xs-medium hover:text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"+ onClick={handleInsertSlash}+ >+ <span aria-hidden className="i-ri-slash-commands-2 size-3.5" />+ {t('agentDetail.configure.prompt.insert.label')}+ </button>+ </div>+ <div className="rounded-sm border border-divider-regular bg-background-default px-1 system-2xs-regular text-text-tertiary">+ {value.length}+ </div>+ </div>+ )}+ </div>++ {isHydrated && !readOnly && isSlashMenuOpen && (+ <div data-agent-prompt-slash-menu className="absolute top-9 left-3 z-50">+ <AgentPromptSlashMenu+ view={slashMenuView}+ categories={slashMenuCategories}+ skills={skills}+ files={files}+ tools={tools}+ onToolsChange={setTools}+ onAddCliTool={addActions.cli}+ onAddFile={addActions.files}+ onAddKnowledge={addActions.knowledge}+ onAddSkill={addActions.skills}+ retrievals={retrievals}+ onBack={() => setSlashMenuView('main')}+ onOpenCategory={setSlashMenuView}+ onSelect={handleSlashSelect}+ />+ </div>+ )}+ </div>+ </section>+ )+}diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/option-menu.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/option-menu.tsxnew file mode 100644index 00000000000..d352b86ff7e--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/option-menu.tsx@@ -0,0 +1,59 @@+'use client'++import type { InsertOption } from './options'+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from '@langgenius/dify-ui/dropdown-menu'+import { useTranslation } from 'react-i18next'++type AgentPromptOptionMenuProps = {+ label: string+ icon: string+ options: InsertOption[]+ onInsert: (token: string) => void+}++export function AgentPromptOptionMenu({+ label,+ icon,+ options,+ onInsert,+}: AgentPromptOptionMenuProps) {+ const { t } = useTranslation('agentV2')++ return (+ <DropdownMenu>+ <DropdownMenuTrigger+ render={(+ <button+ type="button"+ className="flex h-6 shrink-0 items-center gap-1 rounded-md px-1.5 py-1 text-text-tertiary hover:bg-state-base-hover hover:text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"+ >+ <span aria-hidden className={`${icon} size-3.5`} />+ <span className="system-xs-medium">{label}</span>+ </button>+ )}+ />+ <DropdownMenuContent+ placement="bottom-start"+ sideOffset={4}+ popupClassName="w-60 p-1"+ >+ {options.map(option => (+ <DropdownMenuItem+ key={option.key}+ className="gap-2"+ onClick={() => onInsert(option.token)}+ >+ <span aria-hidden className={`${option.icon} size-4 text-text-tertiary`} />+ <span className="min-w-0 flex-1 truncate">{t(option.labelKey)}</span>+ <span className="code-xs-regular text-text-quaternary">{option.token}</span>+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ )+}diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/options.ts b/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/options.tsnew file mode 100644index 00000000000..bc4e0631f2f--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/options.ts@@ -0,0 +1,83 @@+/**+ * @public+ */+// TODO: Remove this marker after prompt option menus are wired.+export type AgentPromptOptionLabelKey+ = | 'agentDetail.configure.prompt.insert.tenders'+ | 'agentDetail.configure.prompt.insert.question'+ | 'agentDetail.configure.prompt.insert.reportFile'+ | 'agentDetail.configure.prompt.mention.davidHayes'+ | 'agentDetail.configure.prompt.mention.priyaRamanathan'++/**+ * @public+ */+// TODO: Remove this marker after prompt option menus are wired.+export type InsertOption = {+ key: string+ labelKey: AgentPromptOptionLabelKey+ token: string+ icon: string+}++/**+ * @public+ */+// TODO: Remove this marker after prompt option menus are wired.+export const insertOptions: InsertOption[] = [+ {+ key: 'tenders',+ labelKey: 'agentDetail.configure.prompt.insert.tenders',+ token: '{{tenders}}',+ icon: 'i-ri-home-4-line',+ },+ {+ key: 'question',+ labelKey: 'agentDetail.configure.prompt.insert.question',+ token: '{{question}}',+ icon: 'i-ri-question-answer-line',+ },+ {+ key: 'reportFile',+ labelKey: 'agentDetail.configure.prompt.insert.reportFile',+ token: '{{qna_report_pdf}}',+ icon: 'i-ri-file-pdf-2-line',+ },+]++/**+ * @public+ */+// TODO: Remove this marker after prompt option menus are wired.+export const mentionOptions: InsertOption[] = [+ {+ key: 'davidHayes',+ labelKey: 'agentDetail.configure.prompt.mention.davidHayes',+ token: '{{DavidHayes}}',+ icon: 'i-ri-user-line',+ },+ {+ key: 'priyaRamanathan',+ labelKey: 'agentDetail.configure.prompt.mention.priyaRamanathan',+ token: '{{PriyaRamanathan}}',+ icon: 'i-ri-user-line',+ },+]++const appendToken = (value: string, token: string) => {+ if (!value)+ return token++ return `${value}${value.endsWith(' ') || value.endsWith('\n') ? '' : ' '}${token}`+}++export const replaceTrailingSlashWithToken = (value: string, token: string) => {+ if (!value.endsWith('/'))+ return appendToken(value, token)++ const valueWithoutSlash = value.slice(0, -1)+ if (!valueWithoutSlash)+ return token++ return `${valueWithoutSlash}${valueWithoutSlash.endsWith(' ') || valueWithoutSlash.endsWith('\n') ? '' : ' '}${token}`+}diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/slash.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/slash.tsxnew file mode 100644index 00000000000..449ae6f7288--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/slash.tsx@@ -0,0 +1,695 @@+'use client'++import type { ReactNode } from 'react'+import type { AgentOrchestrateAddAction, AgentOrchestrateAddedItem } from '../add-actions-context'+import type { AgentProviderToolDefaultValue } from '../tools/types'+import type { Tool } from '@/app/components/tools/types'+import type { ToolTypeEnum, ToolValue } from '@/app/components/workflow/block-selector/types'+import type { ToolWithProvider } from '@/app/components/workflow/types'+import type { AgentFileNode, AgentKnowledgeRetrievalItem, AgentSkill, AgentTool } from '@/features/agent-v2/agent-composer/form-state'+import { cn } from '@langgenius/dify-ui/cn'+import { FileTreeIcon } from '@langgenius/dify-ui/file-tree'+import { useMemo, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { getMarketplaceCategoryUrl } from '@/app/components/plugins/marketplace/utils'+import { PluginCategoryEnum } from '@/app/components/plugins/types'+import { CollectionType } from '@/app/components/tools/types'+import { ToolTypeEnum as ToolTabEnum } from '@/app/components/workflow/block-selector/types'+import { useGetLanguage } from '@/context/i18n'+import {+ useAllBuiltInTools,+ useAllCustomTools,+ useAllMCPTools,+ useAllWorkflowTools,+} from '@/service/use-tools'+import { addProviderTools } from '../tools/hooks'++export type SlashMenuView = 'main' | 'skills' | 'files' | 'tools' | 'knowledge'++export type SlashMenuCategory = {+ key: Exclude<SlashMenuView, 'main'>+ label: string+ icon: string+}++type AgentPromptSlashMenuProps = {+ view: SlashMenuView+ categories: SlashMenuCategory[]+ skills: AgentSkill[]+ files: AgentFileNode[]+ tools: AgentTool[]+ onToolsChange: (tools: AgentTool[]) => void+ onAddCliTool?: AgentOrchestrateAddAction+ onAddFile?: AgentOrchestrateAddAction+ onAddKnowledge?: AgentOrchestrateAddAction+ onAddSkill?: AgentOrchestrateAddAction+ retrievals: AgentKnowledgeRetrievalItem[]+ onBack: () => void+ onOpenCategory: (view: Exclude<SlashMenuView, 'main'>) => void+ onSelect: (token: string) => void+}++const createReferenceToken = (kind: string, id: string, label?: string) => (+ `[§${kind}:${id}${label ? `:${label}` : ''}§]`+)++const isPromptReferenceItem = (item: AgentOrchestrateAddedItem): item is AgentFileNode | AgentSkill => (+ 'id' in item && 'name' in item+)++const isCliToolItem = (item: AgentOrchestrateAddedItem): item is Extract<AgentTool, { kind: 'cli' }> => (+ 'kind' in item && item.kind === 'cli'+)++const isKnowledgeRetrievalItem = (item: AgentOrchestrateAddedItem): item is AgentKnowledgeRetrievalItem => (+ 'queryMode' in item || 'customQuery' in item || 'selectedDatasets' in item || 'nameKey' in item+)++export function AgentPromptSlashMenu({+ view,+ categories,+ skills,+ files,+ tools,+ onToolsChange,+ onAddCliTool,+ onAddFile,+ onAddKnowledge,+ onAddSkill,+ retrievals,+ onBack,+ onOpenCategory,+ onSelect,+}: AgentPromptSlashMenuProps) {+ const { t } = useTranslation('agentV2')+ const title = categories.find(category => category.key === view)?.label+ const handleAddFromFooter = () => {+ if (view === 'skills') {+ onAddSkill?.({+ onAdded: (item) => {+ if (isPromptReferenceItem(item))+ onSelect(createReferenceToken('skill', item.id, item.name))+ },+ })+ return+ }++ if (view === 'files') {+ onAddFile?.({+ onAdded: (item) => {+ if (isPromptReferenceItem(item))+ onSelect(createReferenceToken('file', item.id, item.name))+ },+ })+ return+ }++ if (view === 'knowledge') {+ onAddKnowledge?.({+ onAdded: (item) => {+ if (isKnowledgeRetrievalItem(item))+ onSelect(createReferenceToken('knowledge', item.id, getKnowledgeRetrievalName(item, t)))+ },+ })+ }+ }++ if (view === 'main') {+ return (+ <AgentPromptSlashPanel className="w-[200px]">+ <div className="flex flex-col gap-px p-1">+ {categories.map(category => (+ <button+ key={category.key}+ type="button"+ className="flex h-6 w-full items-center gap-1 rounded-md pr-2 pl-3 text-left hover:bg-state-base-hover focus-visible:bg-state-base-hover focus-visible:outline-hidden"+ onClick={() => onOpenCategory(category.key)}+ >+ <span aria-hidden className={`${category.icon} size-4 shrink-0 text-text-secondary`} />+ <span className="min-w-0 flex-1 truncate system-sm-regular text-text-secondary">{category.label}</span>+ <span aria-hidden className="i-ri-arrow-right-s-line size-3.5 shrink-0 text-text-tertiary" />+ </button>+ ))}+ </div>+ </AgentPromptSlashPanel>+ )+ }++ return (+ <AgentPromptSlashPanel className="w-[360px]">+ <div className="flex flex-col p-1">+ <button+ type="button"+ className="flex h-6 w-full items-center gap-1 rounded-md pr-2 pl-3 text-left text-text-tertiary hover:bg-state-base-hover focus-visible:bg-state-base-hover focus-visible:outline-hidden"+ onClick={onBack}+ >+ <span aria-hidden className="i-ri-arrow-left-line size-4 shrink-0" />+ <span className="min-w-0 flex-1 truncate system-xs-medium-uppercase">{title}</span>+ </button>+ {view === 'skills' && (+ <AgentPromptSkillRows skills={skills} onSelect={onSelect} />+ )}+ {view === 'files' && (+ <AgentPromptFileRows files={files} onSelect={onSelect} />+ )}+ {view === 'tools' && (+ <AgentPromptToolRows+ configuredTools={tools}+ onConfiguredToolsChange={onToolsChange}+ onSelect={onSelect}+ />+ )}+ {view === 'knowledge' && (+ <AgentPromptKnowledgeRows retrievals={retrievals} onSelect={onSelect} />+ )}+ </div>+ {view === 'tools'+ ? (+ <AgentPromptToolFooter+ onAddCliTool={() => {+ onAddCliTool?.({+ onAdded: (item) => {+ if (isCliToolItem(item))+ onSelect(createReferenceToken('cli_tool', item.id, item.name))+ },+ })+ }}+ />+ )+ : (+ <div className="border-t border-divider-subtle p-1">+ <button+ type="button"+ className="flex h-6 w-full items-center gap-1 rounded-md pr-2 pl-3 text-left hover:bg-state-base-hover focus-visible:bg-state-base-hover focus-visible:outline-hidden"+ onClick={handleAddFromFooter}+ >+ <span aria-hidden className="i-ri-add-line size-4 shrink-0 text-text-secondary" />+ <span className="system-sm-regular text-text-secondary">+ {view === 'skills' && t('agentDetail.configure.skills.add')}+ {view === 'files' && t('agentDetail.configure.files.add')}+ {view === 'knowledge' && t('agentDetail.configure.knowledgeRetrieval.add')}+ </span>+ </button>+ </div>+ )}+ </AgentPromptSlashPanel>+ )+}++function AgentPromptSlashPanel({+ className,+ children,+}: {+ className: string+ children: ReactNode+}) {+ return (+ <div className={`${className} isolate overflow-hidden rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur shadow-lg backdrop-blur-[5px]`}>+ {children}+ </div>+ )+}++function AgentPromptSkillRows({+ skills,+ onSelect,+}: {+ skills: AgentSkill[]+ onSelect: (token: string) => void+}) {+ return (+ <>+ {skills.map(skill => (+ <AgentPromptSubmenuRow+ key={skill.id}+ icon="i-ri-box-3-line"+ label={skill.name}+ onClick={() => onSelect(createReferenceToken('skill', skill.id, skill.name))}+ />+ ))}+ </>+ )+}++function AgentPromptFileRows({+ files,+ depth = 0,+ onSelect,+}: {+ files: AgentFileNode[]+ depth?: number+ onSelect: (token: string) => void+}) {+ return (+ <>+ {files.map(file => (+ <div key={file.id}>+ <AgentPromptSubmenuRow+ icon={<FileTreeIcon type={file.children?.length ? 'folder' : file.icon} />}+ label={file.name}+ depth={depth}+ hasChildren={!!file.children?.length}+ onClick={() => onSelect(createReferenceToken('file', file.id, file.name))}+ />+ {!!file.children?.length && (+ <AgentPromptFileRows files={file.children} depth={depth + 1} onSelect={onSelect} />+ )}+ </div>+ ))}+ </>+ )+}++function AgentPromptToolRows({+ configuredTools,+ onConfiguredToolsChange,+ onSelect,+}: {+ configuredTools: AgentTool[]+ onConfiguredToolsChange: (tools: AgentTool[]) => void+ onSelect: (token: string) => void+}) {+ const { t } = useTranslation('agentV2')+ const language = useGetLanguage()+ const [activeTab, setActiveTab] = useState<ToolPromptTab>('all')+ const [expandedProviderIds, setExpandedProviderIds] = useState<Set<string>>(() => new Set())+ const { data: builtInTools = [] } = useAllBuiltInTools()+ const { data: customTools = [] } = useAllCustomTools()+ const { data: workflowTools = [] } = useAllWorkflowTools()+ const { data: mcpTools = [] } = useAllMCPTools()+ const configuredCliTools = configuredTools.filter(tool => tool.kind === 'cli')+ const availableProviders = useMemo(() => {+ if (activeTab === 'all')+ return [...builtInTools, ...workflowTools, ...customTools, ...mcpTools]+ if (activeTab === ToolTabEnum.BuiltIn)+ return builtInTools+ if (activeTab === ToolTabEnum.Workflow)+ return workflowTools+ if (activeTab === ToolTabEnum.Custom)+ return customTools+ if (activeTab === ToolTabEnum.MCP)+ return mcpTools++ return []+ }, [activeTab, builtInTools, customTools, mcpTools, workflowTools])++ const selectedTools = useMemo(() => configuredTools.flatMap(toSelectedToolValue), [configuredTools])+ const tabs = [+ { key: 'all' as const, label: t('agentDetail.configure.tools.toolTabs.all') },+ { key: ToolTabEnum.BuiltIn, label: t('agentDetail.configure.tools.toolTabs.plugins') },+ { key: ToolTabEnum.Workflow, label: t('agentDetail.configure.tools.toolTabs.workflow') },+ { key: ToolTabEnum.Custom, label: t('agentDetail.configure.tools.toolTabs.custom') },+ { key: ToolTabEnum.MCP, label: t('agentDetail.configure.tools.toolTabs.mcp') },+ { key: 'cli' as const, label: t('agentDetail.configure.tools.toolTabs.cli') },+ ]++ const selectTools = (tools: AgentProviderToolDefaultValue[]) => {+ onConfiguredToolsChange(addProviderTools(configuredTools, tools))+ }++ const toggleProvider = (providerId: string) => {+ setExpandedProviderIds((currentIds) => {+ const nextIds = new Set(currentIds)+ if (nextIds.has(providerId))+ nextIds.delete(providerId)+ else+ nextIds.add(providerId)++ return nextIds+ })+ }++ const handleSelectProvider = (provider: ToolWithProvider) => {+ selectTools(provider.tools.map(tool => toToolDefaultValue(provider, tool, language)))+ onSelect(createReferenceToken('tool', `${provider.id}/*`, getProviderLabel(provider, language)))+ }++ const handleSelectTool = (provider: ToolWithProvider, tool: Tool) => {+ const selectedTool = toToolDefaultValue(provider, tool, language)+ selectTools([selectedTool])+ onSelect(createReferenceToken('tool', `${provider.id}/${tool.name}`, selectedTool.tool_label))+ }++ return (+ <div>+ <div className="flex gap-1 px-2 py-1">+ {tabs.map(tab => (+ <button+ key={tab.key}+ type="button"+ className={cn(+ 'flex h-6 shrink-0 items-center rounded-md px-2 system-xs-medium text-text-tertiary hover:bg-state-base-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden',+ activeTab === tab.key && 'bg-state-base-active system-xs-semibold text-text-primary',+ )}+ onClick={() => setActiveTab(tab.key)}+ >+ {tab.label}+ </button>+ ))}+ </div>+ <div className="max-h-[464px] overflow-y-auto px-1 pb-1">+ {activeTab === 'cli'+ ? configuredCliTools.map(tool => (+ <AgentPromptCliToolRow+ key={tool.id}+ tool={tool}+ onClick={() => onSelect(createReferenceToken('cli_tool', tool.id, tool.name))}+ />+ ))+ : availableProviders.filter(provider => provider.tools.length > 0).map(provider => (+ <div key={provider.id}>+ <AgentPromptProviderToolRow+ provider={provider}+ typeLabel={getProviderTypeLabel(provider, t)}+ selectedTools={selectedTools}+ language={language}+ isExpanded={expandedProviderIds.has(provider.id)}+ onClick={() => handleSelectProvider(provider)}+ onToggle={() => toggleProvider(provider.id)}+ />+ {expandedProviderIds.has(provider.id) && provider.tools.map(tool => (+ <AgentPromptProviderToolActionRow+ key={tool.name}+ provider={provider}+ tool={tool}+ language={language}+ selectedTools={selectedTools}+ onClick={() => handleSelectTool(provider, tool)}+ />+ ))}+ </div>+ ))}+ </div>+ </div>+ )+}++type ToolPromptTab = ToolTypeEnum | 'all' | 'cli'++function getLocalizedText(text: Record<string, string> | undefined | null, language: string) {+ if (!text)+ return ''++ return text[language]+ ?? text['en-US']+ ?? text.en_US+ ?? text.zh_Hans+ ?? Object.values(text).find(Boolean)+ ?? ''+}++function toSelectedToolValue(tool: AgentTool): ToolValue[] {+ if (tool.kind !== 'provider')+ return []++ return tool.actions.map(action => ({+ provider_name: tool.id,+ tool_name: action.toolName,+ tool_label: action.name,+ tool_description: action.description,+ }))+}++function toToolDefaultValue(+ provider: ToolWithProvider,+ tool: Tool,+ language: string,+): AgentProviderToolDefaultValue {+ const params: Record<string, string> = {}+ tool.parameters?.forEach((parameter) => {+ params[parameter.name] = ''+ })++ const label = getLocalizedText(tool.label, language) || tool.name+ const description = getLocalizedText(tool.description, language)+ const providerLabel = getLocalizedText(provider.label, language) || provider.name++ return {+ provider_id: provider.id,+ provider_type: provider.type,+ provider_name: provider.name,+ provider_show_name: providerLabel,+ plugin_id: provider.plugin_id,+ plugin_unique_identifier: provider.plugin_unique_identifier,+ provider_icon: provider.icon,+ provider_icon_dark: provider.icon_dark,+ tool_name: tool.name,+ tool_label: label,+ tool_description: description,+ title: label,+ allowDelete: provider.allow_delete,+ is_team_authorization: provider.is_team_authorization,+ paramSchemas: tool.parameters,+ params,+ output_schema: tool.output_schema,+ meta: provider.meta,+ }+}++function isToolSelected(selectedTools: ToolValue[], provider: ToolWithProvider, tool: Tool) {+ return selectedTools.some(selectedTool =>+ (selectedTool.provider_name === provider.name || selectedTool.provider_name === provider.id)+ && selectedTool.tool_name === tool.name,+ )+}++function getProviderLabel(provider: ToolWithProvider, language: string) {+ return getLocalizedText(provider.label, language) || provider.name+}++function getProviderTypeLabel(+ provider: ToolWithProvider,+ t: ReturnType<typeof useTranslation>['t'],+) {+ if (provider.type === CollectionType.workflow)+ return t('agentDetail.configure.tools.toolTabs.workflow')+ if (provider.type === CollectionType.custom)+ return t('agentDetail.configure.tools.toolTabs.custom')+ if (provider.type === CollectionType.mcp)+ return t('agentDetail.configure.tools.toolTabs.mcp')++ return t('agentDetail.configure.tools.toolTabs.plugins')+}++function AgentPromptProviderToolRow({+ provider,+ typeLabel,+ selectedTools,+ language,+ isExpanded,+ onClick,+ onToggle,+}: {+ provider: ToolWithProvider+ typeLabel: string+ selectedTools: ToolValue[]+ language: string+ isExpanded: boolean+ onClick: () => void+ onToggle: () => void+}) {+ const selectedToolsCount = provider.tools.filter(tool => isToolSelected(selectedTools, provider, tool)).length+ const providerLabel = getProviderLabel(provider, language)++ return (+ <div className="flex h-7 w-full items-center gap-px overflow-hidden rounded-md">+ <button+ type="button"+ className="flex min-w-0 flex-1 items-center gap-1.5 rounded-l-md py-1 pr-1 pl-2 text-left hover:bg-state-base-hover focus-visible:bg-state-base-hover focus-visible:outline-hidden"+ onClick={onClick}+ >+ <span className="flex size-5 shrink-0 items-center justify-center overflow-hidden rounded-md border-[0.5px] border-effects-icon-border bg-background-default-dodge">+ <AgentPromptProviderIcon provider={provider} />+ </span>+ <span className="min-w-0 flex-1 truncate system-sm-regular text-text-secondary">{providerLabel}</span>+ {selectedToolsCount > 0 && selectedToolsCount < provider.tools.length && (+ <span className="shrink-0 rounded-[5px] border border-divider-deep bg-components-badge-bg-dimm px-1 py-0.5 system-2xs-medium-uppercase text-text-tertiary">+ {selectedToolsCount}+ </span>+ )}+ <span className="shrink-0 system-xs-regular text-text-quaternary">{typeLabel}</span>+ </button>+ <button+ type="button"+ aria-label={providerLabel}+ className="flex size-7 shrink-0 items-center justify-center rounded-r-md text-text-tertiary hover:bg-state-base-hover-subtle focus-visible:bg-state-base-hover-subtle focus-visible:outline-hidden"+ onClick={onToggle}+ >+ <span aria-hidden className={`${isExpanded ? 'i-ri-arrow-down-s-line' : 'i-ri-arrow-right-s-line'} size-4`} />+ </button>+ </div>+ )+}++function AgentPromptProviderIcon({+ provider,+}: {+ provider: ToolWithProvider+}) {+ if (typeof provider.icon === 'string') {+ return provider.icon.startsWith('/') || provider.icon.startsWith('http')+ ? <img src={provider.icon} alt="" className="size-full object-cover" />+ : <span aria-hidden className="i-custom-public-other-default-tool-icon size-3.5 text-text-tertiary" />+ }++ return (+ <span+ aria-hidden+ className="flex size-full items-center justify-center text-xs"+ style={{ backgroundColor: provider.icon?.background }}+ >+ {provider.icon?.content}+ </span>+ )+}++function AgentPromptToolFooter({+ onAddCliTool,+}: {+ onAddCliTool?: () => void+}) {+ const { t } = useTranslation()++ return (+ <div className="border-t border-divider-subtle p-1">+ <a+ href={getMarketplaceCategoryUrl(PluginCategoryEnum.tool)}+ target="_blank"+ rel="noreferrer"+ className="flex h-7 w-full items-center gap-1.5 rounded-md px-2 text-left hover:bg-state-base-hover focus-visible:bg-state-base-hover focus-visible:outline-hidden"+ >+ <span aria-hidden className="i-ri-store-2-line size-4 shrink-0 text-text-secondary" />+ <span className="system-sm-regular text-text-secondary">{t('findMoreInMarketplace', { ns: 'plugin' })}</span>+ </a>+ <button+ type="button"+ className="flex h-7 w-full items-center gap-1.5 rounded-md px-2 text-left hover:bg-state-base-hover focus-visible:bg-state-base-hover focus-visible:outline-hidden"+ onClick={onAddCliTool}+ >+ <span aria-hidden className="i-ri-add-line size-4 shrink-0 text-text-secondary" />+ <span className="system-sm-regular text-text-secondary">{t('agentDetail.configure.tools.cliDialog.title', { ns: 'agentV2' })}</span>+ </button>+ </div>+ )+}++function AgentPromptProviderToolActionRow({+ provider,+ tool,+ language,+ selectedTools,+ onClick,+}: {+ provider: ToolWithProvider+ tool: Tool+ language: string+ selectedTools: ToolValue[]+ onClick: () => void+}) {+ const selected = isToolSelected(selectedTools, provider, tool)++ return (+ <button+ type="button"+ className="flex h-6 w-full items-center gap-1 rounded-md text-left hover:bg-state-base-hover focus-visible:bg-state-base-hover focus-visible:outline-hidden"+ onClick={onClick}+ >+ <span className="ml-4 h-full w-px shrink-0 bg-divider-subtle" />+ <span className="flex min-w-0 flex-1 items-center gap-1 py-1 pr-2 pl-3">+ <span className="min-w-0 flex-1 truncate system-sm-regular text-text-secondary">+ {getLocalizedText(tool.label, language) || tool.name}+ </span>+ {selected && <span aria-hidden className="i-ri-check-line size-3.5 shrink-0 text-text-tertiary" />}+ </span>+ </button>+ )+}++function AgentPromptCliToolRow({+ tool,+ onClick,+}: {+ tool: Extract<AgentTool, { kind: 'cli' }>+ onClick: () => void+}) {+ const { t } = useTranslation('agentV2')++ return (+ <button+ type="button"+ className="flex h-7 w-full items-center gap-1 rounded-md text-left hover:bg-state-base-hover focus-visible:bg-state-base-hover focus-visible:outline-hidden"+ onClick={onClick}+ >+ <span className="flex min-w-0 flex-1 items-center gap-1.5 py-1 pr-8 pl-2">+ <span className="flex size-5 shrink-0 items-center justify-center rounded-md border-[0.5px] border-effects-icon-border bg-background-default-dodge">+ <span aria-hidden className="i-ri-terminal-box-line size-3.5 text-text-tertiary" />+ </span>+ <span className="min-w-0 flex-1 truncate system-sm-regular text-text-secondary">{tool.name}</span>+ <span className="shrink-0 system-xs-regular text-text-quaternary">+ {t('agentDetail.configure.tools.toolTabs.cli')}+ </span>+ </span>+ </button>+ )+}++function AgentPromptKnowledgeRows({+ retrievals,+ onSelect,+}: {+ retrievals: AgentKnowledgeRetrievalItem[]+ onSelect: (token: string) => void+}) {+ const { t } = useTranslation('agentV2')++ return (+ <>+ {retrievals.map(retrieval => (+ <AgentPromptSubmenuRow+ key={retrieval.id}+ icon="i-ri-book-open-line"+ label={getKnowledgeRetrievalName(retrieval, t)}+ onClick={() => onSelect(createReferenceToken('knowledge', retrieval.id, getKnowledgeRetrievalName(retrieval, t)))}+ />+ ))}+ </>+ )+}++function getKnowledgeRetrievalName(+ retrieval: AgentKnowledgeRetrievalItem,+ t: ReturnType<typeof useTranslation>['t'],+) {+ return retrieval.name ?? (retrieval.nameKey ? t(retrieval.nameKey) : retrieval.id)+}++function AgentPromptSubmenuRow({+ icon,+ label,+ depth = 0,+ hasChildren = false,+ onClick,+}: {+ icon?: ReactNode+ label: string+ depth?: number+ hasChildren?: boolean+ onClick: () => void+}) {+ const indent = depth === 0 ? 'pl-3' : depth === 1 ? 'pl-8' : 'pl-12'++ return (+ <button+ type="button"+ className="flex h-6 w-full items-center gap-1 rounded-md text-left hover:bg-state-base-hover focus-visible:bg-state-base-hover focus-visible:outline-hidden"+ onClick={onClick}+ >+ <span className={`flex min-w-0 flex-1 items-center gap-1 ${indent} pr-2`}>+ {typeof icon === 'string' && <span aria-hidden className={`${icon} size-4 shrink-0 text-text-secondary`} />}+ {typeof icon !== 'string' && icon}+ <span className="min-w-0 flex-1 truncate system-sm-regular text-text-secondary">{label}</span>+ </span>+ {hasChildren && <span aria-hidden className="mr-1.5 i-ri-arrow-right-s-line size-4 shrink-0 text-text-tertiary" />}+ </button>+ )+}diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/publish-bar/index.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/publish-bar/index.tsxnew file mode 100644index 00000000000..73d0fcc9b47--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/publish-bar/index.tsx@@ -0,0 +1,214 @@+'use client'++import type { AgentConfigSnapshotDetailResponse, AgentConfigSnapshotSummaryResponse, AgentPublishedReferenceResponse, AgentSoulConfig } from '@dify/contracts/api/console/agent/types.gen'+import { Button } from '@langgenius/dify-ui/button'+import { cn } from '@langgenius/dify-ui/cn'+import { Kbd, KbdGroup } from '@langgenius/dify-ui/kbd'+import { StatusDot } from '@langgenius/dify-ui/status-dot'+import { formatForDisplay, useHotkey } from '@tanstack/react-hotkeys'+import { useTranslation } from 'react-i18next'+import { useConfigPublishPayload, useHasAgentComposerUnpublishedChanges } from '@/features/agent-v2/agent-composer/store'+import { useFormatTimeFromNow } from '@/hooks/use-format-time-from-now'+import { AgentPublishImpactPopover } from './publish-impact-popover'++const PUBLISH_AGENT_HOTKEY = 'Mod+Shift+P'++export type AgentConfigurePublishPayload = {+ agent_id: string+ config_snapshot: AgentSoulConfig+}++type AgentConfigurePublishState = 'draft' | 'publishing' | 'published' | 'unpublished'++type AgentConfigurePublishBarProps = {+ agentId: string+ activeConfigSnapshot?: AgentConfigSnapshotSummaryResponse | null+ agentSoulConfig?: AgentConfigSnapshotDetailResponse['config_snapshot']+ agentName?: string | null+ currentModel?: {+ provider: string+ model: string+ }+ draftSavedAt?: number+ isPublishing?: boolean+ publishedReferenceCount?: number+ publishedReferences?: AgentPublishedReferenceResponse[]+ onPublish?: (payload: AgentConfigurePublishPayload) => void | Promise<void>+ onOpenVersions: () => void+}++function getPublishState({+ activeConfigSnapshot,+ isDirty,+ isPublishing,+}: {+ activeConfigSnapshot?: AgentConfigSnapshotSummaryResponse | null+ isDirty: boolean+ isPublishing: boolean+}): AgentConfigurePublishState {+ if (isPublishing)+ return 'publishing'++ if (!activeConfigSnapshot)+ return 'draft'++ if (isDirty)+ return 'unpublished'++ return 'published'+}++function PublishShortcut() {+ return (+ <KbdGroup aria-hidden>+ {PUBLISH_AGENT_HOTKEY.split('+').map(key => (+ <Kbd key={key} color="white">{formatForDisplay(key)}</Kbd>+ ))}+ </KbdGroup>+ )+}++export function AgentConfigurePublishBar({+ agentId,+ activeConfigSnapshot,+ agentSoulConfig,+ agentName,+ currentModel,+ draftSavedAt,+ isPublishing = false,+ publishedReferenceCount = 0,+ publishedReferences = [],+ onPublish,+ onOpenVersions,+}: AgentConfigurePublishBarProps) {+ const { t } = useTranslation('agentV2')+ const { formatTimeFromNow } = useFormatTimeFromNow()+ const hasUnpublishedChanges = useHasAgentComposerUnpublishedChanges()+ const publishPayload = useConfigPublishPayload({+ agentId,+ baseConfig: agentSoulConfig,+ currentModel,+ })+ const publishState = getPublishState({+ activeConfigSnapshot,+ isDirty: hasUnpublishedChanges,+ isPublishing,+ })+ const canPublish = publishState === 'draft' || publishState === 'unpublished'++ const handlePublish = () => {+ if (!canPublish)+ return++ void onPublish?.(publishPayload)+ }++ useHotkey(PUBLISH_AGENT_HOTKEY, (event) => {+ event.preventDefault()+ handlePublish()+ }, {+ enabled: canPublish,+ ignoreInputs: false,+ })++ const publishedMeta = activeConfigSnapshot?.created_at+ ? t('agentDetail.configure.publishBar.publishedAt', {+ time: formatTimeFromNow(activeConfigSnapshot.created_at * 1000),+ })+ : t('agentDetail.configure.publishBar.published')+ const savedMeta = draftSavedAt+ ? t('agentDetail.configure.publishBar.savedAt', {+ time: formatTimeFromNow(draftSavedAt),+ })+ : t('agentDetail.configure.publishBar.saved')+ const stateMeta = {+ draft: {+ actionIcon: null,+ actionLabel: t('agentDetail.publish'),+ dotStatus: 'disabled',+ metaLabel: savedMeta,+ showShortcut: true,+ statusLabel: t('agentDetail.configure.publishBar.draft'),+ },+ publishing: {+ actionIcon: 'i-ri-loader-2-line animate-spin motion-reduce:animate-none',+ actionLabel: t('agentDetail.configure.publishBar.publishing'),+ dotStatus: 'disabled',+ metaLabel: savedMeta,+ showShortcut: false,+ statusLabel: t('agentDetail.configure.publishBar.draft'),+ },+ published: {+ actionIcon: 'i-ri-check-line',+ actionLabel: t('agentDetail.configure.publishBar.published'),+ dotStatus: 'success',+ metaLabel: publishedMeta,+ showShortcut: false,+ statusLabel: t('agentDetail.configure.publishBar.upToDate'),+ },+ unpublished: {+ actionIcon: null,+ actionLabel: t('agentDetail.configure.publishBar.publishUpdate'),+ dotStatus: 'warning',+ metaLabel: savedMeta,+ showShortcut: true,+ statusLabel: t('agentDetail.configure.publishBar.unpublishedChanges'),+ },+ } satisfies Record<AgentConfigurePublishState, {+ actionIcon: string | null+ actionLabel: string+ dotStatus: 'disabled' | 'success' | 'warning'+ metaLabel: string+ showShortcut: boolean+ statusLabel: string+ }>+ const currentStateMeta = stateMeta[publishState]++ return (+ <div className="flex h-16 shrink-0 items-center justify-center px-4 pt-2 pb-3">+ <div className="flex max-w-full min-w-0 items-center gap-2 rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur p-2 shadow-lg shadow-shadow-shadow-5 backdrop-blur-[5px]">+ <div className="flex min-w-0 items-center gap-1 px-2 system-xs-regular text-text-tertiary">+ <span className="flex size-4 shrink-0 items-center justify-center">+ <StatusDot size="small" status={currentStateMeta.dotStatus} />+ </span>+ <span className="shrink-0">{currentStateMeta.statusLabel}</span>+ <span aria-hidden className="shrink-0">·</span>+ <span className="min-w-0 truncate">+ {currentStateMeta.metaLabel}+ </span>+ </div>+ <button+ type="button"+ aria-label={t('agentDetail.configure.publishBar.versionHistory')}+ className="flex size-8 shrink-0 items-center justify-center rounded-lg text-text-tertiary hover:bg-state-base-hover hover:text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"+ onClick={onOpenVersions}+ >+ <span aria-hidden className="i-ri-history-line size-4" />+ </button>+ <AgentPublishImpactPopover+ actionLabel={currentStateMeta.actionLabel}+ agentName={agentName}+ disabled={!canPublish}+ publishedReferenceCount={publishedReferenceCount}+ publishedReferences={publishedReferences}+ onPublish={handlePublish}+ trigger={(+ <Button+ type="button"+ variant="primary"+ aria-disabled={!canPublish}+ className="h-8 gap-1 rounded-lg px-3 aria-disabled:cursor-not-allowed"+ onClick={handlePublish}+ >+ {currentStateMeta.actionIcon && (+ <span aria-hidden className={cn('size-4 shrink-0', currentStateMeta.actionIcon)} />+ )}+ <span className="shrink-0">{currentStateMeta.actionLabel}</span>+ {currentStateMeta.showShortcut && <PublishShortcut />}+ </Button>+ )}+ />+ </div>+ </div>+ )+}diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/publish-bar/publish-impact-popover.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/publish-bar/publish-impact-popover.tsxnew file mode 100644index 00000000000..16409321ae2--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/publish-bar/publish-impact-popover.tsx@@ -0,0 +1,155 @@+'use client'++import type { AgentPublishedReferenceResponse } from '@dify/contracts/api/console/agent/types.gen'+import type { MouseEvent, ReactElement } from 'react'+import { Button } from '@langgenius/dify-ui/button'+import { cn } from '@langgenius/dify-ui/cn'+import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'+import { cloneElement, useState } from 'react'+import { useTranslation } from 'react-i18next'+import Link from '@/next/link'++type AgentPublishImpactPopoverProps = {+ actionLabel: string+ agentName?: string | null+ disabled?: boolean+ publishedReferenceCount?: number+ publishedReferences?: AgentPublishedReferenceResponse[]+ trigger: ReactElement<{+ onClick?: (event: MouseEvent<HTMLElement>) => void+ }>+ onPublish: () => void+}++const workflowReferenceAvatarClassNames = [+ 'bg-components-icon-bg-green-soft text-components-icon-bg-green-solid',+ 'bg-components-icon-bg-orange-dark-soft text-components-icon-bg-orange-dark-solid',+ 'bg-components-icon-bg-pink-soft text-components-icon-bg-pink-solid',+ 'bg-components-icon-bg-blue-soft text-components-icon-bg-blue-solid',+] as const++const getWorkflowReferenceHref = (reference: AgentPublishedReferenceResponse) => `/app/${reference.app_id}/workflow`++const getWorkflowReferenceInitial = (name: string) => {+ return name.trim().charAt(0).toUpperCase() || '?'+}++export function AgentPublishImpactPopover({+ actionLabel,+ agentName,+ disabled = false,+ publishedReferenceCount = 0,+ publishedReferences = [],+ trigger,+ onPublish,+}: AgentPublishImpactPopoverProps) {+ const { t } = useTranslation('agentV2')+ const [open, setOpen] = useState(false)+ const hasPublishedReferences = publishedReferenceCount > 0 && publishedReferences.length > 0++ if (!hasPublishedReferences || disabled)+ return trigger++ const triggerWithImpact = cloneElement(trigger, {+ onClick: (event: MouseEvent<HTMLElement>) => {+ event.preventDefault()+ setOpen(true)+ },+ })++ const handlePublish = () => {+ setOpen(false)+ onPublish()+ }++ return (+ <Popover open={open} onOpenChange={setOpen}>+ <PopoverTrigger+ render={triggerWithImpact}+ />+ <PopoverContent+ placement="top-end"+ sideOffset={-40}+ popupClassName="w-96 overflow-hidden rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur p-0 shadow-lg shadow-shadow-shadow-5 backdrop-blur-[5px]"+ >+ <div className="flex flex-col gap-0">+ <div className="flex flex-col gap-0.5 px-3 pt-3.5 pb-1">+ <h2 className="px-1 system-xl-semibold text-text-primary">+ {t('agentDetail.configure.publishImpact.title', {+ action: actionLabel,+ name: agentName || t('agentDetail.configure.publishImpact.fallbackAgentName'),+ })}+ </h2>+ <p className="px-1 system-xs-regular text-text-warning">+ {t('agentDetail.configure.publishImpact.descriptionPrefix')}+ {' '}+ <span className="system-xs-medium">+ {t('agentDetail.configure.publishImpact.workflowCount', { count: publishedReferenceCount })}+ </span>+ {t('agentDetail.configure.publishImpact.descriptionSuffix')}+ </p>+ </div>++ <div className="flex w-full flex-col gap-1 px-4 py-2">+ <div className="flex min-h-6 items-center system-sm-medium text-text-secondary">+ {t('agentDetail.configure.publishImpact.affectedWorkflows')}+ </div>+ <div className="flex max-h-44 flex-col gap-px overflow-y-auto rounded-xl border border-components-panel-border p-1">+ {publishedReferences.map((reference, index) => (+ <ReferenceLink key={`${reference.app_id}-${reference.workflow_id}`} reference={reference} index={index} />+ ))}+ </div>+ </div>++ <div className="flex justify-end gap-2 px-4 pt-2 pb-4">+ <Button+ type="button"+ variant="secondary"+ className="h-8 min-w-18 rounded-lg px-3"+ onClick={() => setOpen(false)}+ >+ {t('agentDetail.configure.publishImpact.cancel')}+ </Button>+ <Button+ type="button"+ variant="primary"+ className="h-8 min-w-18 rounded-lg px-3"+ onClick={handlePublish}+ >+ {actionLabel}+ </Button>+ </div>+ </div>+ </PopoverContent>+ </Popover>+ )+}++function ReferenceLink({+ reference,+ index,+}: {+ reference: AgentPublishedReferenceResponse+ index: number+}) {+ return (+ <Link+ href={getWorkflowReferenceHref(reference)}+ target="_blank"+ rel="noopener noreferrer"+ className="flex min-w-0 items-center gap-2 rounded-lg py-1 pr-2.5 pl-2 system-sm-regular text-text-secondary hover:bg-state-base-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"+ >+ <span+ aria-hidden+ className={cn(+ 'flex size-5 shrink-0 items-center justify-center rounded-md border-[0.5px] border-divider-regular system-xs-medium',+ workflowReferenceAvatarClassNames[index % workflowReferenceAvatarClassNames.length],+ )}+ >+ {getWorkflowReferenceInitial(reference.app_name)}+ </span>+ <span className="min-w-0 flex-1 truncate">{reference.app_name}</span>+ <span aria-hidden className="i-ri-external-link-line size-3 shrink-0 text-text-tertiary" />+ </Link>+ )+}diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/read-only-context.ts b/web/features/agent-v2/agent-detail/configure/components/orchestrate/read-only-context.tsnew file mode 100644index 00000000000..fb62bd1a4a9--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/read-only-context.ts@@ -0,0 +1,7 @@+import { createContext, use } from 'react'++export const AgentOrchestrateReadOnlyContext = createContext(false)++export function useAgentOrchestrateReadOnly() {+ return use(AgentOrchestrateReadOnlyContext)+}diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/__tests__/index.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/__tests__/index.spec.tsxnew file mode 100644index 00000000000..eec25d009f2--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/__tests__/index.spec.tsx@@ -0,0 +1,309 @@+import { toast } from '@langgenius/dify-ui/toast'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { defaultAgentSoulConfigFormState } from '@/features/agent-v2/agent-composer/form-state'+import { AgentComposerProvider } from '@/features/agent-v2/agent-composer/provider'+import { useAgentComposerConfigSnapshot } from '@/features/agent-v2/agent-composer/store'+import { AgentOrchestrateReadOnlyContext } from '../../read-only-context'+import { AgentSkills } from '../index'++const mocks = vi.hoisted(() => ({+ driveFilesQueryOptions: vi.fn(),+ uploadSkillMutationOptions: vi.fn(),+}))++vi.mock('@langgenius/dify-ui/toast', () => ({+ toast: {+ success: vi.fn(),+ error: vi.fn(),+ },+}))++vi.mock('@/service/client', () => ({+ consoleQuery: {+ agent: {+ byAgentId: {+ drive: {+ files: {+ get: {+ queryOptions: mocks.driveFilesQueryOptions,+ },+ },+ },+ skills: {+ upload: {+ post: {+ mutationOptions: mocks.uploadSkillMutationOptions,+ },+ },+ },+ },+ },+ },+}))++const agentSkillsDraft = {+ ...defaultAgentSoulConfigFormState,+ skills: [+ {+ id: 'tender-analyzer',+ name: 'Tender Analyzer',+ description: 'Extracts tender requirements and scoring criteria.',+ files: ['SKILL.md', 'schema.json'],+ path: 'tender-analyzer',+ skillMdKey: 'tender-analyzer/SKILL.md',+ },+ {+ id: 'meeting-brief',+ name: 'Meeting Brief',+ path: 'meeting-brief',+ },+ ],+} satisfies typeof defaultAgentSoulConfigFormState++function renderAgentSkills() {+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: {+ retry: false,+ },+ },+ })++ return render(+ <QueryClientProvider client={queryClient}>+ <AgentComposerProvider initialDraft={agentSkillsDraft}>+ <AgentSkills agentId="agent-1" />+ </AgentComposerProvider>+ </QueryClientProvider>,+ )+}++function renderReadonlyAgentSkills() {+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: {+ retry: false,+ },+ },+ })++ return render(+ <QueryClientProvider client={queryClient}>+ <AgentComposerProvider initialDraft={agentSkillsDraft}>+ <AgentOrchestrateReadOnlyContext value>+ <AgentSkills agentId="agent-1" />+ </AgentOrchestrateReadOnlyContext>+ </AgentComposerProvider>+ </QueryClientProvider>,+ )+}++function ConfigSnapshotProbe() {+ const configSnapshot = useAgentComposerConfigSnapshot({})++ return (+ <pre data-testid="config-snapshot-probe">+ {JSON.stringify(configSnapshot.skills_files?.skills ?? [])}+ </pre>+ )+}++describe('AgentSkills', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mocks.driveFilesQueryOptions.mockImplementation(({ input }) => ({+ queryKey: ['agent-drive-files', input],+ queryFn: async () => ({+ items: [+ {+ file_kind: 'file',+ key: 'tender-analyzer/SKILL.md',+ },+ {+ file_kind: 'file',+ key: 'tender-analyzer/scripts/extract.py',+ },+ ],+ }),+ }))+ mocks.uploadSkillMutationOptions.mockReturnValue({+ mutationFn: vi.fn(),+ mutationKey: ['upload-skill'],+ })+ })++ // Skill rows load their preview from the agent drive and render the shared detail dialog.+ it('should fetch drive files and open the skill detail dialog when the skill row is clicked', async () => {+ renderAgentSkills()++ fireEvent.click(screen.getByRole('button', {+ name: 'Tender Analyzer',+ }))++ const dialog = screen.getByRole('dialog')++ expect(dialog).toBeInTheDocument()+ expect(mocks.driveFilesQueryOptions).toHaveBeenCalledWith({+ input: {+ params: {+ agent_id: 'agent-1',+ },+ query: {+ prefix: 'tender-analyzer',+ },+ },+ })+ expect(within(dialog).getByText('Tender Analyzer')).toBeInTheDocument()+ expect(within(dialog).getByText('Extracts tender requirements and scoring criteria.')).toBeInTheDocument()+ expect(await within(dialog).findByText('scripts/extract.py')).toBeInTheDocument()+ expect(within(dialog).getByText('SKILL.md')).toBeInTheDocument()+ })++ // The hover/focus remove action updates the composer draft without opening preview.+ it('should remove the skill without opening the detail dialog when the remove action is clicked', () => {+ renderAgentSkills()++ fireEvent.click(screen.getByRole('button', {+ name: /agentV2\.agentDetail\.configure\.skills\.remove.*Tender Analyzer/,+ }))++ expect(screen.queryByText('Tender Analyzer')).not.toBeInTheDocument()+ expect(screen.getByText('Meeting Brief')).toBeInTheDocument()+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ })++ it('should hide add and remove actions when readonly', () => {+ renderReadonlyAgentSkills()++ expect(screen.getByRole('button', { name: 'Tender Analyzer' })).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'agentV2.agentDetail.configure.skills.add' })).not.toBeInTheDocument()+ expect(screen.queryByRole('button', {+ name: /agentV2\.agentDetail\.configure\.skills\.remove.*Tender Analyzer/,+ })).not.toBeInTheDocument()+ })++ // Upload uses the drive-backed response so the added skill can be reloaded from agent drive paths.+ it('should add an uploaded skill with drive-backed keys when the upload succeeds', async () => {+ const user = userEvent.setup()+ const uploadSkill = vi.fn().mockResolvedValue({+ manifest: {+ files: ['SKILL.md', 'scripts/run.py'],+ name: 'Invoice Helper',+ },+ skill: {+ id: 'skill-hash',+ manifest_files: ['SKILL.md', 'scripts/run.py'],+ name: 'Invoice Helper',+ path: 'invoice-helper',+ skill_md_key: 'invoice-helper/SKILL.md',+ },+ })+ mocks.uploadSkillMutationOptions.mockReturnValue({+ mutationFn: uploadSkill,+ mutationKey: ['upload-skill'],+ })++ renderAgentSkills()++ await user.click(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.skills.add' }))++ const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement+ const file = new File(['skill'], 'invoice-helper.skill', { type: 'application/zip' })+ await user.upload(fileInput, file)+ await user.click(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.skills.upload.action' }))++ await waitFor(() => {+ expect(uploadSkill.mock.calls[0]?.[0]).toEqual({+ body: {+ file,+ },+ params: {+ agent_id: 'agent-1',+ },+ })+ })+ expect(await screen.findByRole('button', { name: 'Invoice Helper' })).toBeInTheDocument()++ await user.click(screen.getByRole('button', { name: 'Invoice Helper' }))++ expect(mocks.driveFilesQueryOptions).toHaveBeenCalledWith({+ input: {+ params: {+ agent_id: 'agent-1',+ },+ query: {+ prefix: 'invoice-helper',+ },+ },+ })+ expect(vi.mocked(toast.success)).toHaveBeenCalledWith('agentV2.agentDetail.configure.skills.upload.success')+ })++ // Uploaded drive-backed refs must survive insertion into draft and serialization back to config.+ it('should preserve archive and skill file ids from the upload response in the serialized draft', async () => {+ const user = userEvent.setup()+ const uploadSkill = vi.fn().mockResolvedValue({+ manifest: {+ files: ['SKILL.md', 'scripts/run.py'],+ name: 'Invoice Helper',+ },+ skill: {+ file_id: 'archive-upload-file-id',+ full_archive_file_id: 'archive-tool-file-id',+ full_archive_key: 'invoice-helper/.DIFY-SKILL-FULL.zip',+ id: 'skill-hash',+ manifest_files: ['SKILL.md', 'scripts/run.py'],+ name: 'Invoice Helper',+ path: 'invoice-helper',+ skill_md_file_id: 'skill-md-tool-file-id',+ skill_md_key: 'invoice-helper/SKILL.md',+ },+ })+ mocks.uploadSkillMutationOptions.mockReturnValue({+ mutationFn: uploadSkill,+ mutationKey: ['upload-skill'],+ })++ const queryClient = new QueryClient({+ defaultOptions: {+ queries: {+ retry: false,+ },+ },+ })++ render(+ <QueryClientProvider client={queryClient}>+ <AgentComposerProvider initialDraft={agentSkillsDraft}>+ <AgentSkills agentId="agent-1" />+ <ConfigSnapshotProbe />+ </AgentComposerProvider>+ </QueryClientProvider>,+ )++ await user.click(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.skills.add' }))++ const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement+ const file = new File(['skill'], 'invoice-helper.skill', { type: 'application/zip' })+ await user.upload(fileInput, file)+ await user.click(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.skills.upload.action' }))++ await waitFor(() => {+ const serializedSkills = JSON.parse(screen.getByTestId('config-snapshot-probe').textContent ?? '[]')+ expect(serializedSkills).toEqual(expect.arrayContaining([+ expect.objectContaining({+ file_id: 'archive-upload-file-id',+ full_archive_file_id: 'archive-tool-file-id',+ full_archive_key: 'invoice-helper/.DIFY-SKILL-FULL.zip',+ name: 'Invoice Helper',+ path: 'invoice-helper',+ skill_md_file_id: 'skill-md-tool-file-id',+ skill_md_key: 'invoice-helper/SKILL.md',+ }),+ ]))+ })+ })+})diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/detail-dialog.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/detail-dialog.tsxnew file mode 100644index 00000000000..169c1272e1d--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/detail-dialog.tsx@@ -0,0 +1,189 @@+'use client'++import type { AgentFileNode } from '@/features/agent-v2/agent-composer/form-state'+import {+ DialogCloseButton,+ DialogContent,+ DialogDescription,+ DialogTitle,+} from '@langgenius/dify-ui/dialog'+import { ScrollArea } from '@langgenius/dify-ui/scroll-area'+import { useTranslation } from 'react-i18next'+import Loading from '@/app/components/base/loading'+import { AgentFileTree } from '../files/tree'+import { countAgentFileNodes } from '../utils'++type AgentSkillFileNode = AgentFileNode++type AgentSkillDetailSection = {+ id: string+ title: string+ paragraphs?: string[]+ items?: string[]+}++export type AgentSkillDetail = {+ description: string+ fileCount?: number+ files: AgentSkillFileNode[]+ filePreview?: {+ content?: string+ isError?: boolean+ isLoading?: boolean+ }+ selectedFileId?: string+ sections: AgentSkillDetailSection[]+}++function AgentSkillFileList({+ files,+ fileCount,+ selectedFileId,+}: {+ files: AgentSkillFileNode[]+ fileCount: number+ selectedFileId?: string+}) {+ const { t } = useTranslation('agentV2')++ return (+ <AgentFileTree+ files={files}+ selectedFileId={selectedFileId}+ labelledBy="agent-skill-detail-files-heading"+ className="h-[258px] rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg p-1 shadow-xs shadow-shadow-shadow-3"+ header={(+ <>+ <h3 id="agent-skill-detail-files-heading" className="sr-only">+ {t('agentDetail.configure.skills.detail.files')}+ </h3>+ <div+ aria-hidden="true"+ className="px-2 py-1 system-2xs-semibold-uppercase text-text-tertiary"+ >+ {t('agentDetail.configure.skills.detail.fileCount', { count: fileCount })}+ </div>+ </>+ )}+ />+ )+}++function AgentSkillDetailSectionBlock({+ section,+}: {+ section: AgentSkillDetailSection+}) {+ return (+ <section className="clear-none">+ <h3 className="system-sm-semibold text-text-primary">{section.title}</h3>+ {section.paragraphs?.map(paragraph => (+ <p key={paragraph} className="mt-1 system-xs-regular text-text-secondary">+ {paragraph}+ </p>+ ))}+ {!!section.items?.length && (+ <ul className="mt-1 flex list-disc flex-col gap-0.5 pl-5 system-xs-regular text-text-secondary">+ {section.items.map(item => (+ <li key={item} className="pl-0.5">+ {item}+ </li>+ ))}+ </ul>+ )}+ </section>+ )+}++function AgentFilePreviewContent({+ content,+ isError,+ isLoading,+}: {+ content?: string+ isError?: boolean+ isLoading?: boolean+}) {+ const { t } = useTranslation('agentV2')++ if (isLoading) {+ return (+ <div className="flex min-h-40 items-center justify-center">+ <Loading type="area" />+ </div>+ )+ }++ if (isError) {+ return (+ <p className="system-sm-regular text-text-tertiary">+ {t('agentDetail.configure.files.preview.failed')}+ </p>+ )+ }++ if (!content) {+ return (+ <p className="system-sm-regular text-text-tertiary">+ {t('agentDetail.configure.files.preview.empty')}+ </p>+ )+ }++ return (+ <pre className="m-0 font-mono text-xs leading-5 break-words whitespace-pre-wrap text-text-secondary">+ {content}+ </pre>+ )+}++export function AgentSkillDetailDialog({+ skillName,+ detail,+}: {+ skillName: string+ detail: AgentSkillDetail+}) {+ const { t } = useTranslation('agentV2')+ const fileCount = detail.fileCount ?? countAgentFileNodes(detail.files)++ return (+ <DialogContent className="flex h-[min(720px,calc(100dvh-2rem))] max-h-none w-[min(960px,calc(100vw-2rem))] flex-col overflow-hidden rounded-2xl p-0">+ <DialogCloseButton className="top-5 right-5" />+ <div className="shrink-0 border-b-[0.5px] border-components-panel-border-subtle pt-6 pr-14 pb-3 pl-6">+ <DialogTitle className="title-xl-semi-bold text-text-primary">+ {skillName}+ </DialogTitle>+ <DialogDescription className="mt-1 system-xs-regular text-text-tertiary">+ {detail.description}+ </DialogDescription>+ </div>++ <div className="flex min-h-0 flex-1 items-start">+ <ScrollArea+ className="relative min-h-0 flex-1 self-stretch overflow-hidden has-[>_:first-child:focus-visible]:outline-2 has-[>_:first-child:focus-visible]:outline-offset-0 has-[>_:first-child:focus-visible]:outline-state-accent-solid"+ label={t('agentDetail.configure.skills.detail.contentRegion')}+ slotClassNames={{+ viewport: 'overscroll-contain outline-none focus-visible:outline-none mask-linear-[to_bottom,transparent_0,black_min(40px,var(--scroll-area-overflow-y-start)),black_calc(100%_-_min(40px,var(--scroll-area-overflow-y-end,40px))),transparent_100%] mask-no-repeat',+ content: 'flex min-h-full w-full max-w-full min-w-0 flex-col gap-2 px-6 pt-4 pb-0',+ scrollbar: 'data-[orientation=vertical]:my-1 data-[orientation=vertical]:me-1',+ }}+ >+ {detail.filePreview && (+ <AgentFilePreviewContent+ content={detail.filePreview.content}+ isError={detail.filePreview.isError}+ isLoading={detail.filePreview.isLoading}+ />+ )}+ {detail.sections.map(section => (+ <AgentSkillDetailSectionBlock key={section.id} section={section} />+ ))}+ </ScrollArea>+ <div className="flex w-56 max-w-56 min-w-0 shrink-0 items-start justify-center p-4 pl-2">+ <AgentSkillFileList files={detail.files} fileCount={fileCount} selectedFileId={detail.selectedFileId} />+ </div>+ </div>+ </DialogContent>+ )+}diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/index.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/index.tsxnew file mode 100644index 00000000000..5ecf687020a--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/index.tsx@@ -0,0 +1,82 @@+'use client'++import type { AgentOrchestrateAddActionOptions } from '../add-actions-context'+import type { AgentSkill } from '@/features/agent-v2/agent-composer/form-state'+import { useAtom } from 'jotai'+import { useCallback, useRef, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { agentComposerSkillsAtom, useRemoveSkill } from '@/features/agent-v2/agent-composer/store-modules/skills'+import { useRegisterAgentOrchestrateAddAction } from '../add-actions-context'+import { ConfigureSectionAddButton } from '../common/add-button'+import { ConfigureSectionEmpty } from '../common/empty'+import { ConfigureSection } from '../common/section'+import { AgentSkillItem } from './item'+import { AgentSkillUploadDialog } from './upload-dialog'++export function AgentSkills({+ agentId,+}: {+ agentId: string+}) {+ const { t } = useTranslation('agentV2')+ const [skills, setSkills] = useAtom(agentComposerSkillsAtom)+ const removeSkill = useRemoveSkill()+ const skillsTip = t('agentDetail.configure.skills.tip')+ const skillsListId = 'agent-configure-skills-list'+ const [isUploadOpen, setIsUploadOpen] = useState(false)+ const promptAddCallbackRef = useRef<AgentOrchestrateAddActionOptions['onAdded']>(undefined)+ const handleOpenUpload = useCallback((options?: AgentOrchestrateAddActionOptions) => {+ promptAddCallbackRef.current = options?.onAdded+ setIsUploadOpen(true)+ }, [])+ useRegisterAgentOrchestrateAddAction('skills', handleOpenUpload)+ const handleUploaded = useCallback((skill: AgentSkill) => {+ setSkills(skills.some(currentSkill => currentSkill.id === skill.id)+ ? skills+ : [...skills, skill])+ promptAddCallbackRef.current?.(skill)+ promptAddCallbackRef.current = undefined+ }, [setSkills, skills])+ const handleUploadOpenChange = useCallback((open: boolean) => {+ if (!open)+ promptAddCallbackRef.current = undefined+ setIsUploadOpen(open)+ }, [])++ return (+ <>+ <ConfigureSection+ label={t('agentDetail.configure.skills.label')}+ labelId="agent-configure-skills-label"+ panelId={skillsListId}+ tip={skillsTip}+ tipAriaLabel={skillsTip}+ rootClassName="border-b border-divider-subtle pt-4"+ panelContentClassName="flex flex-col gap-1 pb-4"+ actions={(+ <ConfigureSectionAddButton+ ariaLabel={t('agentDetail.configure.skills.add')}+ onClick={() => handleOpenUpload()}+ />+ )}+ >+ {skills.length === 0+ ? (+ <ConfigureSectionEmpty+ title={t('agentDetail.configure.skills.empty.title')}+ description={t('agentDetail.configure.skills.empty.description')}+ />+ )+ : skills.map(skill => (+ <AgentSkillItem key={skill.id} agentId={agentId} skill={skill} onRemove={removeSkill} />+ ))}+ </ConfigureSection>+ <AgentSkillUploadDialog+ agentId={agentId}+ open={isUploadOpen}+ onOpenChange={handleUploadOpenChange}+ onUploaded={handleUploaded}+ />+ </>+ )+}diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/item.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/item.tsxnew file mode 100644index 00000000000..67b93743fa9--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/item.tsx@@ -0,0 +1,112 @@+'use client'++import type { AgentDriveItemResponse } from '@dify/contracts/api/console/agent/types.gen'+import type { AgentSkill } from '@/features/agent-v2/agent-composer/form-state'+import {+ Dialog,+} from '@langgenius/dify-ui/dialog'+import { useQuery } from '@tanstack/react-query'+import { useCallback, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { consoleQuery } from '@/service/client'+import { useAgentOrchestrateReadOnly } from '../read-only-context'+import { AgentSkillDetailDialog } from './detail-dialog'++const getSkillDrivePath = (skill: AgentSkill) => {+ const skillMdKeySlug = skill.skillMdKey?.split('/', 1)[0]+ return skill.path ?? skillMdKeySlug ?? skill.id+}++const getSkillFileName = (key: string, skillDrivePath: string) => key.startsWith(`${skillDrivePath}/`)+ ? key.slice(skillDrivePath.length + 1)+ : key++const toSkillFileNode = (item: AgentDriveItemResponse, skillDrivePath: string) => ({+ icon: item.file_kind === 'folder' ? 'folder' as const : 'file' as const,+ id: item.key,+ name: getSkillFileName(item.key, skillDrivePath),+})++export function AgentSkillItem({+ agentId,+ skill,+ onRemove,+}: {+ agentId: string+ skill: AgentSkill+ onRemove: (skillId: string) => void+}) {+ const { t } = useTranslation('agentV2')+ const readOnly = useAgentOrchestrateReadOnly()+ const [isPreviewOpen, setIsPreviewOpen] = useState(false)+ const handleRemove = useCallback(() => {+ onRemove(skill.id)+ }, [onRemove, skill.id])+ const skillFiles = skill.files ?? []+ const skillDrivePath = getSkillDrivePath(skill)+ const driveFilesQuery = useQuery({+ ...consoleQuery.agent.byAgentId.drive.files.get.queryOptions({+ input: {+ params: {+ agent_id: agentId,+ },+ query: {+ prefix: skillDrivePath,+ },+ },+ }),+ enabled: isPreviewOpen,+ })+ const detailFiles = driveFilesQuery.isSuccess+ ? (driveFilesQuery.data.items ?? []).map(item => toSkillFileNode(item, skillDrivePath))+ : skillFiles.map(file => ({+ icon: 'file' as const,+ id: file,+ name: file,+ }))++ return (+ <Dialog open={isPreviewOpen} onOpenChange={setIsPreviewOpen}>+ <div className="group flex h-8 items-center gap-1 overflow-hidden rounded-lg border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg py-1 pr-2.5 pl-2 shadow-xs shadow-shadow-shadow-3 focus-within:bg-components-panel-on-panel-item-bg-hover focus-within:shadow-sm hover:bg-components-panel-on-panel-item-bg-hover hover:pr-1 hover:shadow-sm has-[[data-agent-skill-remove-button]:focus-visible]:border-state-destructive-border! has-[[data-agent-skill-remove-button]:focus-visible]:bg-state-destructive-hover! has-[[data-agent-skill-remove-button]:focus-visible]:shadow-xs! has-[[data-agent-skill-remove-button]:hover]:border-state-destructive-border! has-[[data-agent-skill-remove-button]:hover]:bg-state-destructive-hover! has-[[data-agent-skill-remove-button]:hover]:shadow-xs!">+ <button+ type="button"+ className="flex h-full min-w-0 flex-1 cursor-pointer items-center gap-1 rounded-md text-left outline-hidden focus-visible:ring-2 focus-visible:ring-state-accent-solid"+ onClick={() => setIsPreviewOpen(true)}+ >+ <span aria-hidden className="i-custom-public-agent-building-blocks size-4 shrink-0" />+ <span className="min-w-0 flex-1 truncate system-sm-medium text-text-secondary">+ {skill.name}+ </span>+ </button>+ {!readOnly && (+ <div className="hidden shrink-0 items-center justify-center rounded-md p-0.5 group-focus-within:flex group-hover:flex">+ <button+ type="button"+ data-agent-skill-remove-button+ aria-label={t('agentDetail.configure.skills.remove', { name: skill.name })}+ onClick={handleRemove}+ className="flex size-5 items-center justify-center rounded-md text-text-tertiary hover:bg-state-destructive-hover hover:text-text-destructive focus-visible:bg-state-destructive-hover focus-visible:text-text-destructive focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"+ >+ <span aria-hidden className="i-ri-delete-bin-line size-4" />+ </button>+ </div>+ )}+ <div className="flex shrink-0 items-center justify-center group-focus-within:hidden group-hover:hidden">+ <span className="system-xs-regular text-text-tertiary">+ {t('agentDetail.configure.skills.itemType')}+ </span>+ </div>+ </div>+ {isPreviewOpen && (+ <AgentSkillDetailDialog+ skillName={skill.name}+ detail={{+ description: skill.description ?? t('agentDetail.configure.skills.tip'),+ files: detailFiles,+ sections: [],+ }}+ />+ )}+ </Dialog>+ )+}diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/upload-dialog.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/upload-dialog.tsxnew file mode 100644index 00000000000..d95bb162b3e--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/upload-dialog.tsx@@ -0,0 +1,227 @@+'use client'++import type { PostAgentByAgentIdSkillsUploadResponse } from '@dify/contracts/api/console/agent/types.gen'+import type { AgentSkill } from '@/features/agent-v2/agent-composer/form-state'+import { Button } from '@langgenius/dify-ui/button'+import { cn } from '@langgenius/dify-ui/cn'+import { Dialog, DialogCloseButton, DialogContent, DialogDescription, DialogTitle } from '@langgenius/dify-ui/dialog'+import { toast } from '@langgenius/dify-ui/toast'+import { useMutation } from '@tanstack/react-query'+import { useRef, useState } from 'react'+import { useTranslation } from 'react-i18next'+import ActionButton from '@/app/components/base/action-button'+import { consoleQuery } from '@/service/client'+import { formatFileSize } from '@/utils/format'++const skillPackageAccept = '.zip,.skill'+const skillPackageExtensions = ['.zip', '.skill']++const getSkillNameFromFile = (file: File) => file.name.replace(/\.(?:skill|zip)$/iu, '') || file.name++const toUploadedSkill = (response: PostAgentByAgentIdSkillsUploadResponse, file: File): AgentSkill => {+ const name = response.skill?.name+ ?? response.manifest?.name+ ?? getSkillNameFromFile(file)+ const id = response.skill?.id+ ?? response.skill?.skill_md_key+ ?? response.skill?.path+ ?? name++ return {+ description: response.skill?.description ?? response.manifest?.description,+ files: response.skill?.manifest_files ?? response.manifest?.files,+ fileId: response.skill?.file_id ?? undefined,+ fullArchiveFileId: response.skill?.full_archive_file_id ?? undefined,+ fullArchiveKey: response.skill?.full_archive_key ?? undefined,+ id,+ name,+ path: response.skill?.path ?? undefined,+ skillMdFileId: response.skill?.skill_md_file_id ?? undefined,+ skillMdKey: response.skill?.skill_md_key ?? undefined,+ }+}++function isSupportedSkillPackage(file: File) {+ const fileName = file.name.toLowerCase()++ return skillPackageExtensions.some(extension => fileName.endsWith(extension))+}++function AgentSkillPackageUploader({+ file,+ onChange,+}: {+ file?: File+ onChange: (file?: File) => void+}) {+ const { t } = useTranslation('agentV2')+ const fileInputRef = useRef<HTMLInputElement>(null)+ const [dragging, setDragging] = useState(false)++ const setUploadFiles = (files: File[]) => {+ const [uploadFile] = files+ if (files.length !== 1 || !uploadFile || !isSupportedSkillPackage(uploadFile)) {+ toast.error(t('agentDetail.configure.skills.upload.invalidFile'))+ return+ }++ onChange(uploadFile)+ }++ const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {+ const files = Array.from(event.target.files ?? [])+ event.target.value = ''+ setUploadFiles(files)+ }++ const handleDrop = (event: React.DragEvent<HTMLDivElement>) => {+ event.preventDefault()+ event.stopPropagation()+ setDragging(false)++ setUploadFiles(Array.from(event.dataTransfer.files))+ }++ return (+ <div className="mt-6">+ <input+ ref={fileInputRef}+ className="hidden"+ type="file"+ accept={skillPackageAccept}+ onChange={handleFileChange}+ />+ {!file && (+ <div+ className={cn(+ 'relative flex h-16 items-center rounded-[10px] border border-dashed border-components-dropzone-border bg-components-dropzone-bg text-sm font-normal',+ dragging && 'border-components-dropzone-border-accent bg-components-dropzone-bg-accent',+ )}+ onDragEnter={(event) => {+ event.preventDefault()+ setDragging(true)+ }}+ onDragOver={event => event.preventDefault()}+ onDragLeave={() => setDragging(false)}+ onDrop={handleDrop}+ >+ <div className="flex w-full items-center justify-center space-x-2">+ <span aria-hidden className="i-ri-upload-cloud-2-line size-6 text-text-tertiary" />+ <div className="text-text-tertiary">+ {t('agentDetail.configure.skills.upload.dropzone')}+ <button+ type="button"+ className="inline cursor-pointer border-none bg-transparent p-0 pl-1 text-left text-text-accent focus-visible:ring-1 focus-visible:ring-components-input-border-active focus-visible:outline-hidden"+ onClick={() => fileInputRef.current?.click()}+ >+ {t('agentDetail.configure.skills.upload.browse')}+ </button>+ </div>+ </div>+ {dragging && <div className="absolute top-0 left-0 size-full" />}+ </div>+ )}+ {file && (+ <div className="group flex items-center rounded-lg border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg shadow-xs hover:bg-components-panel-on-panel-item-bg-hover">+ <div className="flex items-center justify-center p-3">+ <span aria-hidden className="i-custom-public-files-yaml size-6 shrink-0" />+ </div>+ <div className="flex grow flex-col items-start gap-0.5 py-1 pr-2">+ <span className="max-w-[calc(100%-30px)] overflow-hidden text-[12px] leading-4 font-medium text-ellipsis whitespace-nowrap text-text-secondary">{file.name}</span>+ <div className="flex h-3 items-center gap-1 self-stretch text-[10px] leading-3 font-medium text-text-tertiary uppercase">+ <span>{t('agentDetail.configure.skills.upload.fileType')}</span>+ <span className="text-text-quaternary">·</span>+ <span>{formatFileSize(file.size)}</span>+ </div>+ </div>+ <div className="hidden items-center pr-3 group-hover:flex">+ <ActionButton onClick={() => onChange(undefined)}>+ <span aria-hidden className="i-ri-delete-bin-line size-4 text-text-tertiary" />+ </ActionButton>+ </div>+ </div>+ )}+ </div>+ )+}++export function AgentSkillUploadDialog({+ agentId,+ onUploaded,+ open,+ onOpenChange,+}: {+ agentId: string+ onUploaded?: (skill: AgentSkill) => void+ open: boolean+ onOpenChange: (open: boolean) => void+}) {+ const { t } = useTranslation('agentV2')+ const { t: tCommon } = useTranslation('common')+ const [file, setFile] = useState<File>()+ const uploadSkillMutation = useMutation(consoleQuery.agent.byAgentId.skills.upload.post.mutationOptions())++ const handleUpload = () => {+ if (!file || uploadSkillMutation.isPending)+ return++ uploadSkillMutation.mutate({+ params: {+ agent_id: agentId,+ },+ body: {+ file,+ },+ }, {+ onSuccess: (response) => {+ toast.success(t('agentDetail.configure.skills.upload.success'))+ onUploaded?.(toUploadedSkill(response, file))+ setFile(undefined)+ onOpenChange(false)+ },+ onError: () => {+ toast.error(t('agentDetail.configure.skills.upload.failed'))+ },+ })+ }++ const handleOpenChange = (nextOpen: boolean) => {+ if (!nextOpen) {+ uploadSkillMutation.reset()+ setFile(undefined)+ }+ onOpenChange(nextOpen)+ }++ return (+ <Dialog open={open} onOpenChange={handleOpenChange}>+ <DialogContent>+ <DialogCloseButton />+ <DialogTitle className="title-2xl-semi-bold text-text-primary">+ {t('agentDetail.configure.skills.upload.title')}+ </DialogTitle>+ <DialogDescription className="mt-1 system-sm-regular text-text-tertiary">+ {t('agentDetail.configure.skills.upload.description')}+ </DialogDescription>+ <AgentSkillPackageUploader+ file={file}+ onChange={setFile}+ />+ <div className="flex justify-end gap-2 pt-6">+ <Button type="button" onClick={() => handleOpenChange(false)} disabled={uploadSkillMutation.isPending}>+ {tCommon('operation.cancel')}+ </Button>+ <Button+ type="button"+ variant="primary"+ disabled={!file}+ loading={uploadSkillMutation.isPending}+ onClick={handleUpload}+ >+ {t('agentDetail.configure.skills.upload.action')}+ </Button>+ </div>+ </DialogContent>+ </Dialog>+ )+}diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/__tests__/hooks.spec.ts b/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/__tests__/hooks.spec.tsnew file mode 100644index 00000000000..5afbb2b2771--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/__tests__/hooks.spec.ts@@ -0,0 +1,56 @@+import type { AgentProviderToolDefaultValue } from '../types'+import { addProviderTools } from '../hooks'++const noCredentialTool = {+ provider_id: 'duckduckgo',+ provider_type: 'builtin',+ provider_name: 'DuckDuckGo',+ provider_show_name: 'DuckDuckGo',+ tool_name: 'ddg_search',+ tool_label: 'DuckDuckGo Search',+ tool_description: 'Search the web.',+ title: 'DuckDuckGo Search',+ is_team_authorization: true,+ params: {},+ paramSchemas: [],+ allowDelete: false,+ credentialRequired: false,+} satisfies AgentProviderToolDefaultValue++const unauthorizedCredentialTool = {+ ...noCredentialTool,+ provider_id: 'google',+ provider_name: 'google',+ provider_show_name: 'Google',+ tool_name: 'search',+ tool_label: 'Google Search',+ title: 'Google Search',+ is_team_authorization: false,+ credentialRequired: true,+} satisfies AgentProviderToolDefaultValue++describe('addProviderTools', () => {+ it('should not mark tools that do not need credentials as unauthorized', () => {+ const nextTools = addProviderTools([], [noCredentialTool])++ expect(nextTools).toEqual([+ expect.objectContaining({+ credentialId: undefined,+ credentialType: undefined,+ credentialVariant: 'none',+ }),+ ])+ })++ it('should mark credential-required tools without credentials as unauthorized', () => {+ const nextTools = addProviderTools([], [unauthorizedCredentialTool])++ expect(nextTools).toEqual([+ expect.objectContaining({+ credentialId: undefined,+ credentialType: 'unauthorized',+ credentialVariant: 'unauthorized',+ }),+ ])+ })+})diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/__tests__/index.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/__tests__/index.spec.tsxnew file mode 100644index 00000000000..0c14cb78117--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/__tests__/index.spec.tsx@@ -0,0 +1,389 @@+import type { ToolWithProvider } from '@/app/components/workflow/types'+import type { AgentSoulConfigFormState } from '@/features/agent-v2/agent-composer/form-state'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { cleanup, render, screen } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { CollectionType } from '@/app/components/tools/types'+import { defaultAgentSoulConfigFormState } from '@/features/agent-v2/agent-composer/form-state'+import { AgentComposerProvider } from '@/features/agent-v2/agent-composer/provider'+import { AgentOrchestrateReadOnlyContext } from '../../read-only-context'+import { AgentTools } from '../index'++const toolProviderState = vi.hoisted(() => ({+ builtInTools: [] as ToolWithProvider[],+}))++vi.mock('@/app/components/workflow/block-selector/tool-picker', () => ({+ ToolPickerContent: () => (+ <div>+ Mock tool picker+ </div>+ ),+}))++vi.mock('@/app/components/workflow/block-icon', () => ({+ default: ({ toolIcon }: { toolIcon?: string | { content: string, background: string } }) => (+ <span aria-hidden data-testid="tool-icon">+ {typeof toolIcon === 'string' ? toolIcon : toolIcon?.content}+ </span>+ ),+}))++vi.mock('@/app/components/header/account-setting/model-provider-page/model-modal/Form', () => ({+ default: ({ formSchemas }: { formSchemas: Array<{ label?: Record<string, string>, variable?: string }> }) => (+ <div data-testid="tool-setting-form">+ {formSchemas.map(schema => (+ <div key={schema.variable}>{schema.label?.en_US}</div>+ ))}+ </div>+ ),+}))++vi.mock('@/service/use-tools', () => ({+ useAllBuiltInTools: () => ({ data: toolProviderState.builtInTools }),+ useAllCustomTools: () => ({ data: [] }),+ useAllWorkflowTools: () => ({ data: [] }),+ useAllMCPTools: () => ({ data: [] }),+}))++const agentToolsDraft = {+ ...defaultAgentSoulConfigFormState,+ tools: [+ {+ id: 'duckduckgo',+ kind: 'provider',+ name: 'DuckDuckGo',+ iconClassName: 'i-simple-icons-duckduckgo',+ credentialKey: 'agentDetail.configure.tools.credential.authOne',+ credentialVariant: 'none',+ actions: [+ {+ id: 'duckduckgo-search',+ name: 'DuckDuckGo Search',+ toolName: 'search',+ description: 'Search the web.',+ },+ {+ id: 'duckduckgo-image-search',+ name: 'DuckDuckGo Image Search',+ toolName: 'image_search',+ description: 'Search images.',+ },+ ],+ },+ {+ id: 'lark-cli',+ kind: 'cli',+ name: 'Lark CLI',+ },+ ],+} satisfies AgentSoulConfigFormState++const reflectedAgentToolsDraft = {+ ...defaultAgentSoulConfigFormState,+ tools: [+ {+ id: 'google',+ kind: 'provider',+ name: 'google',+ iconClassName: 'i-custom-public-other-default-tool-icon',+ credentialVariant: 'none',+ actions: [+ {+ id: 'google-search',+ name: 'search',+ toolName: 'search',+ description: '',+ },+ ],+ },+ ],+} satisfies AgentSoulConfigFormState++const reflectedUnauthorizedNoCredentialDraft = {+ ...defaultAgentSoulConfigFormState,+ tools: [+ {+ id: 'duckduckgo',+ kind: 'provider',+ name: 'duckduckgo',+ iconClassName: 'i-custom-public-other-default-tool-icon',+ credentialType: 'unauthorized',+ credentialVariant: 'unauthorized',+ actions: [+ {+ id: 'duckduckgo-search',+ name: 'search',+ toolName: 'search',+ description: '',+ },+ ],+ },+ ],+} satisfies AgentSoulConfigFormState++const googleProvider = {+ id: 'google',+ name: 'google',+ author: 'Google',+ description: {+ en_US: 'Google tools.',+ zh_Hans: 'Google 工具。',+ },+ icon: 'https://example.com/google.svg',+ icon_dark: 'https://example.com/google-dark.svg',+ label: {+ en_US: 'Google Tools',+ zh_Hans: 'Google 工具',+ },+ type: CollectionType.builtIn,+ team_credentials: {},+ is_team_authorization: true,+ allow_delete: true,+ labels: [],+ meta: {+ version: '0.0.1',+ },+ tools: [+ {+ name: 'search',+ author: 'Google',+ label: {+ en_US: 'Google Search',+ zh_Hans: 'Google 搜索',+ },+ description: {+ en_US: 'Search the web with Google.',+ zh_Hans: '使用 Google 搜索网页。',+ },+ parameters: [],+ labels: [],+ output_schema: {},+ },+ ],+} satisfies ToolWithProvider++const duckDuckGoProvider = {+ ...googleProvider,+ id: 'duckduckgo',+ name: 'duckduckgo',+ author: 'DuckDuckGo',+ icon: 'https://example.com/duckduckgo.svg',+ icon_dark: 'https://example.com/duckduckgo-dark.svg',+ label: {+ en_US: 'DuckDuckGo',+ zh_Hans: 'DuckDuckGo',+ },+ team_credentials: {},+ is_team_authorization: true,+ allow_delete: false,+ tools: [+ {+ name: 'search',+ author: 'DuckDuckGo',+ label: {+ en_US: 'DuckDuckGo Search',+ zh_Hans: 'DuckDuckGo 搜索',+ },+ description: {+ en_US: 'Search the web with DuckDuckGo.',+ zh_Hans: '使用 DuckDuckGo 搜索网页。',+ },+ parameters: [+ {+ name: 'query',+ label: {+ en_US: 'Search Query',+ zh_Hans: '搜索查询',+ },+ human_description: {+ en_US: 'The query to search for.',+ zh_Hans: '要搜索的查询。',+ },+ type: 'string',+ form: 'form',+ llm_description: '',+ required: true,+ multiple: false,+ default: '',+ },+ ],+ labels: [],+ output_schema: {},+ },+ ],+} satisfies ToolWithProvider++function renderAgentTools(initialDraft: AgentSoulConfigFormState = agentToolsDraft) {+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: {+ retry: false,+ },+ },+ })++ return render(+ <QueryClientProvider client={queryClient}>+ <AgentComposerProvider initialDraft={initialDraft}>+ <AgentTools />+ </AgentComposerProvider>+ </QueryClientProvider>,+ )+}++function renderReadonlyAgentTools(initialDraft: AgentSoulConfigFormState = agentToolsDraft) {+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: {+ retry: false,+ },+ },+ })++ return render(+ <QueryClientProvider client={queryClient}>+ <AgentComposerProvider initialDraft={initialDraft}>+ <AgentOrchestrateReadOnlyContext value>+ <AgentTools />+ </AgentOrchestrateReadOnlyContext>+ </AgentComposerProvider>+ </QueryClientProvider>,+ )+}++describe('AgentTools', () => {+ beforeEach(() => {+ cleanup()+ vi.clearAllMocks()+ toolProviderState.builtInTools = []+ })++ describe('User Interactions', () => {+ it('should remove a provider action when the remove button is clicked', async () => {+ const user = userEvent.setup()+ renderAgentTools()++ await user.click(screen.getByRole('button', {+ name: 'DuckDuckGo',+ }))++ await user.click(screen.getByRole('button', {+ name: 'agentV2.agentDetail.configure.tools.removeAction:{"name":"DuckDuckGo Image Search"}',+ }))++ expect(screen.queryByText('DuckDuckGo Image Search')).not.toBeInTheDocument()+ expect(screen.getByText('DuckDuckGo Search')).toBeInTheDocument()+ expect(screen.getByText('DuckDuckGo')).toBeInTheDocument()+ })++ it('should remove all provider tools from the provider more-actions menu', async () => {+ const user = userEvent.setup()+ renderAgentTools()++ await user.click(screen.getByRole('button', {+ name: 'agentV2.agentDetail.configure.tools.moreActions:{"name":"DuckDuckGo"}',+ }))+ await user.click(screen.getByRole('menuitem', {+ name: /agentV2\.agentDetail\.configure\.tools\.removeProvider/,+ }))++ expect(screen.queryByText('DuckDuckGo')).not.toBeInTheDocument()+ expect(screen.queryByText('DuckDuckGo Search')).not.toBeInTheDocument()+ expect(screen.getByText('Lark CLI')).toBeInTheDocument()+ })++ it('should keep the add trigger mounted while the tool picker is open', async () => {+ const user = userEvent.setup()+ renderAgentTools()++ await user.click(screen.getByRole('button', {+ name: 'agentV2.agentDetail.configure.tools.add',+ }))+ await user.click(screen.getByRole('button', {+ name: /agentV2\.agentDetail\.configure\.tools\.addMenu\.tool\.label/,+ }))++ expect(screen.getByText('Mock tool picker')).toBeInTheDocument()+ expect(screen.getByRole('button', {+ name: 'agentV2.agentDetail.configure.tools.add',+ })).toBeInTheDocument()+ })++ it('should hide add, edit, and remove actions when readonly', async () => {+ const user = userEvent.setup()+ renderReadonlyAgentTools()++ expect(screen.queryByRole('button', {+ name: 'agentV2.agentDetail.configure.tools.add',+ })).not.toBeInTheDocument()+ expect(screen.queryByRole('button', {+ name: 'agentV2.agentDetail.configure.tools.moreActions:{"name":"DuckDuckGo"}',+ })).not.toBeInTheDocument()++ await user.click(screen.getByRole('button', {+ name: 'DuckDuckGo',+ }))++ expect(screen.queryByRole('button', {+ name: 'agentV2.agentDetail.configure.tools.editAction:{"name":"DuckDuckGo Search"}',+ })).not.toBeInTheDocument()+ expect(screen.queryByRole('button', {+ name: 'agentV2.agentDetail.configure.tools.removeAction:{"name":"DuckDuckGo Image Search"}',+ })).not.toBeInTheDocument()+ expect(screen.queryByRole('button', {+ name: 'agentV2.agentDetail.configure.tools.editAction:{"name":"Lark CLI"}',+ })).not.toBeInTheDocument()+ expect(screen.queryByRole('button', {+ name: 'agentV2.agentDetail.configure.tools.removeAction:{"name":"Lark CLI"}',+ })).not.toBeInTheDocument()+ })+ })++ describe('Display Metadata', () => {+ it('should enrich reflected provider tools with provider icon and localized names', async () => {+ const user = userEvent.setup()+ toolProviderState.builtInTools = [googleProvider]+ renderAgentTools(reflectedAgentToolsDraft)++ expect(screen.getByRole('button', {+ name: 'Google Tools',+ })).toBeInTheDocument()+ expect(screen.getByText('https://example.com/google.svg')).toBeInTheDocument()++ await user.click(screen.getByRole('button', {+ name: 'Google Tools',+ }))++ expect(screen.getByText('Google Search')).toBeInTheDocument()+ })++ it('should hide unauthorized status when reflected provider tools do not require credentials', () => {+ toolProviderState.builtInTools = [duckDuckGoProvider]+ renderAgentTools(reflectedUnauthorizedNoCredentialDraft)++ expect(screen.getByRole('button', {+ name: 'DuckDuckGo',+ })).toBeInTheDocument()+ expect(screen.queryByText('tools.notAuthorized')).not.toBeInTheDocument()+ })++ it('should open provider tool settings with catalog icon and parameters', async () => {+ const user = userEvent.setup()+ toolProviderState.builtInTools = [duckDuckGoProvider]+ const { baseElement } = renderAgentTools()++ await user.click(screen.getByRole('button', {+ name: 'DuckDuckGo',+ }))+ await user.click(screen.getByRole('button', {+ name: 'agentV2.agentDetail.configure.tools.editAction:{"name":"DuckDuckGo Search"}',+ }))++ expect(baseElement.querySelector('[style*="duckduckgo.svg"]')).toBeInTheDocument()+ expect(screen.getByTestId('tool-setting-form')).toBeInTheDocument()+ expect(screen.getByText('Search Query')).toBeInTheDocument()+ })+ })+})diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/cli-tool/__tests__/dialog.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/cli-tool/__tests__/dialog.spec.tsxnew file mode 100644index 00000000000..77910c149b7--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/cli-tool/__tests__/dialog.spec.tsx@@ -0,0 +1,169 @@+import { toast } from '@langgenius/dify-ui/toast'+import { fireEvent, render, screen } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { CliToolDialog } from '../dialog'++vi.mock('@langgenius/dify-ui/toast', () => ({+ toast: {+ error: vi.fn(),+ },+}))++type CliToolDialogProps = Parameters<typeof CliToolDialog>[0]++function renderCliToolDialog(props?: Partial<CliToolDialogProps>) {+ const onOpenChange = vi.fn()+ const onSaveCliTool = vi.fn()++ render(+ <CliToolDialog+ open+ onOpenChange={onOpenChange}+ onSaveCliTool={onSaveCliTool}+ {...props}+ />,+ )++ return {+ onOpenChange,+ onSaveCliTool,+ }+}++describe('CliToolDialog', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ describe('Form Validation', () => {+ it('should show a toast error when install command is empty', async () => {+ const user = userEvent.setup()+ const { onOpenChange, onSaveCliTool } = renderCliToolDialog()++ await user.click(screen.getByRole('button', {+ name: 'common.operation.add',+ }))++ expect(onSaveCliTool).not.toHaveBeenCalled()+ expect(onOpenChange).not.toHaveBeenCalledWith(false)+ expect(toast.error).toHaveBeenCalledWith('agentV2.agentDetail.configure.tools.cliDialog.installCommand.required')+ expect(screen.queryByText('agentV2.agentDetail.configure.tools.cliDialog.installCommand.required')).not.toBeInTheDocument()+ })++ it('should show a toast error when CLI tool name is empty', async () => {+ const user = userEvent.setup()+ const { onOpenChange, onSaveCliTool } = renderCliToolDialog()++ await user.type(+ screen.getByRole('textbox', {+ name: /agentV2\.agentDetail\.configure\.tools\.cliDialog\.installCommand\.label/,+ }),+ 'npm install -g @lark/cli',+ )+ await user.click(screen.getByRole('button', {+ name: 'common.operation.add',+ }))++ expect(onSaveCliTool).not.toHaveBeenCalled()+ expect(onOpenChange).not.toHaveBeenCalledWith(false)+ expect(toast.error).toHaveBeenCalledWith('agentV2.agentDetail.configure.tools.cliDialog.name.required')+ expect(screen.queryByText('agentV2.agentDetail.configure.tools.cliDialog.name.required')).not.toBeInTheDocument()+ })++ it('should save a CLI tool when required fields are filled', async () => {+ const user = userEvent.setup()+ const { onOpenChange, onSaveCliTool } = renderCliToolDialog()++ await user.type(+ screen.getByRole('textbox', {+ name: /agentV2\.agentDetail\.configure\.tools\.cliDialog\.installCommand\.label/,+ }),+ 'npm install -g @lark/cli',+ )+ await user.type(+ screen.getByRole('textbox', {+ name: /agentV2\.agentDetail\.configure\.tools\.cliDialog\.name\.label/,+ }),+ 'Lark CLI',+ )+ await user.click(screen.getByRole('button', {+ name: 'common.operation.add',+ }))++ expect(onSaveCliTool).toHaveBeenCalledWith(expect.objectContaining({+ kind: 'cli',+ name: 'Lark CLI',+ installCommand: 'npm install -g @lark/cli',+ }))+ expect(onOpenChange).toHaveBeenCalledWith(false)+ })++ it('should reject environment variable keys using the shared env editor rules', () => {+ renderCliToolDialog()++ const keyInput = screen.getByPlaceholderText('agentV2.agentDetail.configure.advancedSettings.envEditor.keyPlaceholder')++ fireEvent.change(keyInput, {+ target: { value: '1BAD' },+ })++ expect(keyInput).toHaveValue('')+ expect(toast.error).toHaveBeenCalledWith('appDebug.varKeyError.notStartWithNumber:{"key":"agentV2.agentDetail.configure.advancedSettings.envEditor.keyColumn"}')+ })+ })++ describe('Actions', () => {+ it('should show save action when editing a CLI tool', () => {+ renderCliToolDialog({+ mode: 'edit',+ tool: {+ id: 'lark-cli',+ kind: 'cli',+ name: 'Lark CLI',+ installCommand: 'npm install -g @lark/cli',+ },+ })++ expect(screen.getByRole('button', {+ name: 'common.operation.save',+ })).toBeInTheDocument()+ expect(screen.queryByRole('button', {+ name: 'common.operation.add',+ })).not.toBeInTheDocument()+ })++ it('should remove a CLI tool from the edit footer', async () => {+ const user = userEvent.setup()+ const onDeleteCliTool = vi.fn()+ const { onOpenChange, onSaveCliTool } = renderCliToolDialog({+ mode: 'edit',+ onDeleteCliTool,+ tool: {+ id: 'lark-cli',+ kind: 'cli',+ name: 'Lark CLI',+ installCommand: 'npm install -g @lark/cli',+ },+ })++ await user.click(screen.getByRole('button', {+ name: 'common.operation.remove',+ }))++ expect(onDeleteCliTool).toHaveBeenCalledWith('lark-cli')+ expect(onOpenChange).toHaveBeenCalledWith(false)+ expect(onSaveCliTool).not.toHaveBeenCalled()+ })++ it('should hide remove action when adding a CLI tool', () => {+ renderCliToolDialog({+ onDeleteCliTool: vi.fn(),+ })++ expect(screen.queryByRole('button', {+ name: 'common.operation.remove',+ })).not.toBeInTheDocument()+ })+ })+})diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/cli-tool/dialog.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/cli-tool/dialog.tsxnew file mode 100644index 00000000000..0d3cecb68dd--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/cli-tool/dialog.tsx@@ -0,0 +1,236 @@+'use client'++import type { AgentCliTool, EnvScope, EnvVariable } from '@/features/agent-v2/agent-composer/form-state'+import { Button } from '@langgenius/dify-ui/button'+import { Dialog, DialogCloseButton, DialogContent, DialogDescription, DialogTitle } from '@langgenius/dify-ui/dialog'+import { FieldControl, FieldDescription, FieldLabel, FieldRoot } from '@langgenius/dify-ui/field'+import { Form } from '@langgenius/dify-ui/form'+import { toast } from '@langgenius/dify-ui/toast'+import { useCallback, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { EnvVariablesTable } from '../../advanced/env'++type CliToolFormValues = {+ installCommand?: string+ name?: string+}++const createCliToolId = () => `cli-tool-${globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random()}`}`++const createCliEnvVariable = (): EnvVariable => ({+ id: globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random()}`,+ key: '',+ value: '',+ scope: 'plain',+})++export function CliToolDialog({+ mode = 'add',+ onDeleteCliTool,+ onSaveCliTool,+ open,+ onOpenChange,+ tool,+}: {+ mode?: 'add' | 'edit'+ onDeleteCliTool?: (toolId: string) => void+ onSaveCliTool: (tool: AgentCliTool) => void+ open: boolean+ onOpenChange: (open: boolean) => void+ tool?: AgentCliTool | null+}) {+ const { t } = useTranslation('agentV2')+ const { t: tCommon } = useTranslation('common')+ const [installCommand, setInstallCommand] = useState(tool?.installCommand ?? '')+ const [toolName, setToolName] = useState(tool?.name ?? '')+ const [envVariables, setEnvVariables] = useState<EnvVariable[]>(() => tool?.envVariables?.length ? tool.envVariables : [createCliEnvVariable()])++ const resetForm = useCallback(() => {+ setInstallCommand(tool?.installCommand ?? '')+ setToolName(tool?.name ?? '')+ setEnvVariables(tool?.envVariables?.length ? tool.envVariables : [createCliEnvVariable()])+ }, [tool])++ const handleOpenChange = useCallback((nextOpen: boolean) => {+ if (nextOpen)+ resetForm()++ onOpenChange(nextOpen)+ }, [onOpenChange, resetForm])++ const updateEnvVariable = useCallback((id: string, updater: (variable: EnvVariable) => EnvVariable) => {+ setEnvVariables(currentVariables => currentVariables.map(variable => (+ variable.id === id ? updater(variable) : variable+ )))+ }, [])++ const addEnvVariable = useCallback(() => {+ setEnvVariables(currentVariables => [...currentVariables, createCliEnvVariable()])+ }, [])++ const deleteEnvVariable = useCallback((id: string) => {+ setEnvVariables(currentVariables => currentVariables.length > 1+ ? currentVariables.filter(variable => variable.id !== id)+ : [createCliEnvVariable()],+ )+ }, [])++ const handleKeyChange = useCallback((id: string, key: string) => {+ updateEnvVariable(id, variable => ({ ...variable, key }))+ }, [updateEnvVariable])++ const handleScopeChange = useCallback((id: string, scope: EnvScope) => {+ updateEnvVariable(id, variable => ({ ...variable, scope }))+ }, [updateEnvVariable])++ const handleValueChange = useCallback((id: string, value: string) => {+ updateEnvVariable(id, variable => ({ ...variable, value }))+ }, [updateEnvVariable])++ const handleSubmit = useCallback((formValues: CliToolFormValues) => {+ const trimmedName = formValues.name?.trim() || toolName.trim()+ const trimmedInstallCommand = formValues.installCommand?.trim() || installCommand.trim()++ if (!trimmedInstallCommand) {+ toast.error(t('agentDetail.configure.tools.cliDialog.installCommand.required'))+ return+ }+ if (!trimmedName) {+ toast.error(t('agentDetail.configure.tools.cliDialog.name.required'))+ return+ }++ onSaveCliTool({+ ...tool,+ id: tool?.id ?? createCliToolId(),+ kind: 'cli',+ name: trimmedName,+ installCommand: trimmedInstallCommand,+ envVariables,+ })+ setInstallCommand('')+ setToolName('')+ setEnvVariables([createCliEnvVariable()])+ onOpenChange(false)+ }, [envVariables, installCommand, onOpenChange, onSaveCliTool, t, tool, toolName])++ const handleCancel = useCallback(() => {+ onOpenChange(false)+ }, [onOpenChange])++ const handleDelete = useCallback(() => {+ if (!tool)+ return++ onDeleteCliTool?.(tool.id)+ onOpenChange(false)+ }, [onDeleteCliTool, onOpenChange, tool])++ return (+ <Dialog open={open} onOpenChange={handleOpenChange}>+ <DialogContent className="flex max-h-[calc(100dvh-2rem)] w-[640px] flex-col overflow-hidden p-0">+ <div className="relative px-6 pt-6 pb-3">+ <DialogCloseButton className="top-5 right-5" />+ <DialogTitle className="title-2xl-semi-bold text-text-primary">+ {t(mode === 'edit' ? 'agentDetail.configure.tools.cliDialog.editTitle' : 'agentDetail.configure.tools.cliDialog.title')}+ </DialogTitle>+ <DialogDescription className="mt-1 system-xs-regular text-text-tertiary">+ {t('agentDetail.configure.tools.cliDialog.description')}+ </DialogDescription>+ </div>+ <Form<CliToolFormValues>+ className="min-h-0 flex-1 overflow-y-auto px-6 py-3"+ onFormSubmit={handleSubmit}+ >+ <div className="flex flex-col gap-4">+ <FieldRoot name="installCommand">+ <FieldLabel>+ {t('agentDetail.configure.tools.cliDialog.installCommand.label')}+ </FieldLabel>+ <FieldDescription>+ {t('agentDetail.configure.tools.cliDialog.installCommand.description')}+ </FieldDescription>+ <FieldControl+ autoComplete="off"+ onValueChange={setInstallCommand}+ placeholder={t('agentDetail.configure.tools.cliDialog.installCommand.placeholder')}+ value={installCommand}+ />+ </FieldRoot>+ <FieldRoot name="name">+ <FieldLabel>+ {t('agentDetail.configure.tools.cliDialog.name.label')}+ </FieldLabel>+ <FieldControl+ autoComplete="off"+ onValueChange={setToolName}+ placeholder={t('agentDetail.configure.tools.cliDialog.name.placeholder')}+ value={toolName}+ />+ </FieldRoot>+ <div className="pt-1">+ <div className="mb-3 h-px bg-divider-subtle" />+ <div className="mb-1 flex min-h-6 items-center gap-1">+ <span className="system-sm-medium text-text-secondary">+ {t('agentDetail.configure.tools.cliDialog.env.label')}+ </span>+ <span className="system-xs-regular text-text-tertiary">+ {t('agentDetail.configure.tools.cliDialog.env.optional')}+ </span>+ </div>+ <p className="mb-2 body-xs-regular text-text-tertiary">+ {t('agentDetail.configure.tools.cliDialog.env.description')}+ </p>+ <EnvVariablesTable+ editable+ envVariables={envVariables}+ onAdd={addEnvVariable}+ onDelete={deleteEnvVariable}+ onKeyChange={handleKeyChange}+ onScopeChange={handleScopeChange}+ onValueChange={handleValueChange}+ showDraftRow={false}+ showScope={false}+ />+ </div>+ </div>+ <div className="flex items-center gap-3 py-8">+ <a+ href="https://docs.dify.ai/"+ target="_blank"+ rel="noreferrer"+ className="inline-flex min-w-0 flex-1 items-center gap-1 system-xs-regular text-text-accent hover:underline focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"+ >+ <span>{t('agentDetail.configure.tools.cliDialog.learnMore')}</span>+ <span aria-hidden className="i-ri-external-link-line size-3" />+ </a>+ <div className="flex shrink-0 items-center gap-3">+ {mode === 'edit' && tool && onDeleteCliTool && (+ <div className="flex items-center gap-3">+ <Button type="button" tone="destructive" onClick={handleDelete}>+ {tCommon('operation.remove')}+ </Button>+ <div className="h-4 w-px bg-divider-regular" aria-hidden />+ </div>+ )}+ <div className="flex items-center gap-2">+ <Button type="button" onClick={handleCancel}>+ {tCommon('operation.cancel')}+ </Button>+ <Button type="submit" variant="primary">+ {tCommon(mode === 'edit' ? 'operation.save' : 'operation.add')}+ </Button>+ </div>+ </div>+ </div>+ </Form>+ <div className="flex items-start justify-center gap-1 border-t-[0.5px] border-divider-subtle bg-background-soft px-2 py-3">+ <span aria-hidden className="mt-0.5 i-ri-lock-2-fill size-3 text-text-tertiary" />+ <p className="system-xs-regular text-text-tertiary">+ {t('agentDetail.configure.tools.cliDialog.securityTip')}+ </p>+ </div>+ </DialogContent>+ </Dialog>+ )+}diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/cli-tool/item.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/cli-tool/item.tsxnew file mode 100644index 00000000000..21f7604a36e--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/cli-tool/item.tsx@@ -0,0 +1,37 @@+'use client'++import type { AgentCliTool } from '@/features/agent-v2/agent-composer/form-state'+import { useTranslation } from 'react-i18next'+import { ConfigureSectionConfigurableItem } from '../../common/configurable-item'++function CliIcon() {+ return (+ <span className="flex size-5 shrink-0 items-center justify-center rounded-md border border-divider-regular bg-text-tertiary p-1 text-text-primary-on-surface">+ <span aria-hidden className="i-ri-terminal-box-line size-3.5" />+ </span>+ )+}++export function AgentCliToolItem({+ onDelete,+ onEdit,+ tool,+}: {+ onDelete: () => void+ onEdit: () => void+ tool: AgentCliTool+}) {+ const { t } = useTranslation('agentV2')++ return (+ <ConfigureSectionConfigurableItem+ icon={<CliIcon />}+ label={tool.name}+ badge={t('agentDetail.configure.tools.cliTool')}+ editAriaLabel={t('agentDetail.configure.tools.editAction', { name: tool.name })}+ removeAriaLabel={t('agentDetail.configure.tools.removeAction', { name: tool.name })}+ onEdit={onEdit}+ onRemove={onDelete}+ />+ )+}diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/hooks.ts b/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/hooks.tsnew file mode 100644index 00000000000..9be5cebfc91--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/hooks.ts@@ -0,0 +1,211 @@+'use client'++import type { AgentProviderToolDefaultValue, ToolSettingTarget } from './types'+import type { ToolValue } from '@/app/components/workflow/block-selector/types'+import type { AgentCliTool, AgentTool } from '@/features/agent-v2/agent-composer/form-state'+import { useAtom } from 'jotai'+import { useCallback, useMemo, useState } from 'react'+import { agentComposerToolsAtom, useRemoveProviderTool, useRemoveProviderToolAction } from '@/features/agent-v2/agent-composer/store-modules/tools'++const toSelectedToolValue = (tool: AgentTool): ToolValue[] => {+ if (tool.kind !== 'provider')+ return []++ return tool.actions.map(action => ({+ provider_name: tool.id,+ tool_name: action.toolName,+ tool_label: action.name,+ tool_description: action.description,+ }))+}++const toProviderToolAction = (tool: AgentProviderToolDefaultValue) => ({+ id: `${tool.provider_id}:${tool.tool_name}`,+ name: tool.tool_label || tool.title || tool.tool_name,+ toolName: tool.tool_name,+ description: tool.tool_description || '',+})++const getCredentialVariant = (tool: AgentProviderToolDefaultValue) => {+ if (!tool.credentialRequired)+ return 'none' as const++ if (!tool.allowDelete)+ return tool.credential_id ? 'authorized' as const : 'unauthorized' as const++ return tool.is_team_authorization ? 'authorized' as const : 'unauthorized' as const+}++const getCredentialType = (tool: AgentProviderToolDefaultValue) => {+ if (!tool.credentialRequired)+ return undefined++ if (!tool.allowDelete)+ return tool.credential_id ? 'api-key' as const : 'unauthorized' as const++ return tool.is_team_authorization ? 'api-key' as const : 'unauthorized' as const+}++export const addProviderTools = (+ currentTools: AgentTool[],+ selectedTools: AgentProviderToolDefaultValue[],+): AgentTool[] => {+ if (selectedTools.length === 0)+ return currentTools++ const nextTools = [...currentTools]++ selectedTools.forEach((selectedTool) => {+ const action = toProviderToolAction(selectedTool)+ const existingToolIndex = nextTools.findIndex(tool => tool.kind === 'provider' && tool.id === selectedTool.provider_id)+ const existingTool = nextTools[existingToolIndex]++ if (existingTool?.kind === 'provider') {+ if (existingTool.actions.some(existingAction => existingAction.toolName === action.toolName))+ return++ nextTools[existingToolIndex] = {+ ...existingTool,+ displayName: existingTool.displayName ?? selectedTool.provider_show_name,+ icon: existingTool.icon ?? selectedTool.provider_icon,+ iconDark: existingTool.iconDark ?? selectedTool.provider_icon_dark,+ allowDelete: existingTool.allowDelete ?? selectedTool.allowDelete,+ actions: [...existingTool.actions, action],+ }+ return+ }++ nextTools.push({+ id: selectedTool.provider_id,+ name: selectedTool.provider_name,+ kind: 'provider',+ displayName: selectedTool.provider_show_name,+ iconClassName: 'i-custom-public-other-default-tool-icon text-text-tertiary',+ icon: selectedTool.provider_icon,+ iconDark: selectedTool.provider_icon_dark,+ providerType: selectedTool.provider_type,+ allowDelete: selectedTool.allowDelete,+ credentialId: selectedTool.credential_id,+ credentialKey: selectedTool.is_team_authorization+ ? 'agentDetail.configure.tools.credential.authOne'+ : undefined,+ credentialType: getCredentialType(selectedTool),+ credentialVariant: getCredentialVariant(selectedTool),+ actions: [action],+ })+ })++ return nextTools+}++export function useAgentToolsOperations() {+ const [tools, setTools] = useAtom(agentComposerToolsAtom)+ const removeProviderTool = useRemoveProviderTool()+ const removeProviderToolAction = useRemoveProviderToolAction()+ const [expandedToolIds, setExpandedToolIds] = useState<Set<string>>(() => new Set())+ const [settingTarget, setSettingTarget] = useState<ToolSettingTarget | null>(null)+ const [isCliToolDialogOpen, setIsCliToolDialogOpen] = useState(false)+ const [editingCliTool, setEditingCliTool] = useState<AgentCliTool | null>(null)++ const setToolOpen = useCallback((tool: AgentTool, open: boolean) => {+ if (tool.kind === 'cli')+ return++ setExpandedToolIds((currentIds) => {+ const nextIds = new Set(currentIds)+ if (open)+ nextIds.add(tool.id)+ else+ nextIds.delete(tool.id)++ return nextIds+ })+ }, [])++ const addTools = useCallback((selectedTools: AgentProviderToolDefaultValue[]) => {+ setTools(addProviderTools(tools, selectedTools))+ }, [setTools, tools])++ const deleteCliTool = useCallback((toolId: string) => {+ setTools(tools.filter(tool => tool.id !== toolId))+ }, [setTools, tools])++ const openCliToolDialog = useCallback(() => {+ setEditingCliTool(null)+ setIsCliToolDialogOpen(true)+ }, [])++ const editCliTool = useCallback((tool: AgentCliTool) => {+ setEditingCliTool(tool)+ setIsCliToolDialogOpen(true)+ }, [])++ const handleCliDialogSave = useCallback((tool: AgentCliTool) => {+ if (editingCliTool)+ setTools(tools.map(currentTool => currentTool.id === tool.id ? tool : currentTool))+ else+ setTools([...tools, tool])++ setEditingCliTool(null)+ }, [editingCliTool, setTools, tools])++ const handleCliDialogOpenChange = useCallback((open: boolean) => {+ if (!open)+ setEditingCliTool(null)++ setIsCliToolDialogOpen(open)+ }, [])++ const closeSettingTargetIfRemoved = useCallback((toolId: string, actionId?: string) => {+ setSettingTarget((target) => {+ if (!target || target.tool.id !== toolId)+ return target+ if (actionId && target.action.id !== actionId)+ return target++ return null+ })+ }, [])++ const deleteProviderTool = useCallback((toolId: string) => {+ setExpandedToolIds((currentIds) => {+ const nextIds = new Set(currentIds)+ nextIds.delete(toolId)+ return nextIds+ })+ closeSettingTargetIfRemoved(toolId)+ removeProviderTool(toolId)+ }, [closeSettingTargetIfRemoved, removeProviderTool])++ const deleteProviderToolAction = useCallback((toolId: string, actionId: string) => {+ closeSettingTargetIfRemoved(toolId, actionId)+ removeProviderToolAction(toolId, actionId)+ }, [closeSettingTargetIfRemoved, removeProviderToolAction])++ const closeProviderSettingsDialog = useCallback(() => {+ setSettingTarget(null)+ }, [])++ const selectedTools = useMemo(() => tools.flatMap(toSelectedToolValue), [tools])++ return {+ tools,+ selectedTools,+ expandedToolIds,+ settingTarget,+ isCliToolDialogOpen,+ editingCliTool,+ setTools,+ setToolOpen,+ setSettingTarget,+ addTools,+ deleteCliTool,+ deleteProviderTool,+ deleteProviderToolAction,+ openCliToolDialog,+ editCliTool,+ handleCliDialogSave,+ handleCliDialogOpenChange,+ closeProviderSettingsDialog,+ }+}diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/index.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/index.tsxnew file mode 100644index 00000000000..7c8a12e8ca4--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/index.tsx@@ -0,0 +1,469 @@+'use client'++import type { AgentOrchestrateAddActionOptions } from '../add-actions-context'+import type { AgentProviderToolDefaultValue, ToolSettingTarget } from './types'+import type { ToolDefaultValue, ToolValue } from '@/app/components/workflow/block-selector/types'+import type { ToolWithProvider } from '@/app/components/workflow/types'+import type { AgentCliTool, AgentProviderTool, AgentTool } from '@/features/agent-v2/agent-composer/form-state'+import { cn } from '@langgenius/dify-ui/cn'+import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { ToolPickerContent } from '@/app/components/workflow/block-selector/tool-picker'+import { useGetLanguage } from '@/context/i18n'+import { useSetProviderToolCredential } from '@/features/agent-v2/agent-composer/store-modules/tools'+import {+ useAllBuiltInTools,+ useAllCustomTools,+ useAllMCPTools,+ useAllWorkflowTools,+} from '@/service/use-tools'+import { useRegisterAgentOrchestrateAddAction } from '../add-actions-context'+import { ConfigureSectionAddButton } from '../common/add-button'+import { ConfigureSectionEmpty } from '../common/empty'+import { ConfigureSection } from '../common/section'+import { useAgentOrchestrateReadOnly } from '../read-only-context'+import { CliToolDialog } from './cli-tool/dialog'+import { AgentCliToolItem } from './cli-tool/item'+import { useAgentToolsOperations } from './hooks'+import { ProviderToolSettingsDialog } from './provider-tool/dialog'+import { AgentProviderToolItem } from './provider-tool/item'++function AgentToolItem({+ tool,+ isExpanded,+ onOpenChange,+ onConfigureAction,+ onDeleteCliTool,+ onDeleteProviderTool,+ onDeleteProviderToolAction,+ onEditCliTool,+ onCredentialChange,+}: {+ tool: AgentTool+ isExpanded: boolean+ onOpenChange: (tool: AgentTool, open: boolean) => void+ onConfigureAction: (target: ToolSettingTarget) => void+ onDeleteCliTool: (toolId: string) => void+ onDeleteProviderTool: (toolId: string) => void+ onDeleteProviderToolAction: (toolId: string, actionId: string) => void+ onEditCliTool: (tool: AgentCliTool) => void+ onCredentialChange: (toolId: string, credentialId?: string) => void+}) {+ const handleOpenChange = useCallback((open: boolean) => {+ onOpenChange(tool, open)+ }, [onOpenChange, tool])++ const handleRemoveProvider = useCallback(() => {+ onDeleteProviderTool(tool.id)+ }, [onDeleteProviderTool, tool.id])++ const handleRemoveProviderAction = useCallback((actionId: string) => {+ onDeleteProviderToolAction(tool.id, actionId)+ }, [onDeleteProviderToolAction, tool.id])++ const handleDeleteCliTool = useCallback(() => {+ onDeleteCliTool(tool.id)+ }, [onDeleteCliTool, tool.id])++ const handleEditCliTool = useCallback(() => {+ if (tool.kind === 'cli')+ onEditCliTool(tool)+ }, [onEditCliTool, tool])++ const handleCredentialChange = useCallback((credentialId?: string) => {+ onCredentialChange(tool.id, credentialId)+ }, [onCredentialChange, tool.id])++ if (tool.kind === 'provider') {+ return (+ <AgentProviderToolItem+ tool={tool}+ isExpanded={isExpanded}+ onOpenChange={handleOpenChange}+ onConfigureAction={onConfigureAction}+ onRemoveAction={handleRemoveProviderAction}+ onRemoveProvider={handleRemoveProvider}+ onCredentialChange={handleCredentialChange}+ />+ )+ }++ return (+ <AgentCliToolItem+ tool={tool}+ onDelete={handleDeleteCliTool}+ onEdit={handleEditCliTool}+ />+ )+}++function useAgentToolProviderMap() {+ const { data: buildInTools } = useAllBuiltInTools()+ const { data: customTools } = useAllCustomTools()+ const { data: workflowTools } = useAllWorkflowTools()+ const { data: mcpTools } = useAllMCPTools()++ return useMemo(() => {+ const providers = new Map<string, ToolWithProvider>()+ const buildInToolList = Array.isArray(buildInTools) ? buildInTools : []+ const customToolList = Array.isArray(customTools) ? customTools : []+ const workflowToolList = Array.isArray(workflowTools) ? workflowTools : []+ const mcpToolList = Array.isArray(mcpTools) ? mcpTools : []+ const allProviders = [+ ...buildInToolList,+ ...customToolList,+ ...workflowToolList,+ ...mcpToolList,+ ]++ allProviders.forEach((provider) => {+ providers.set(provider.id, provider)+ providers.set(provider.name, provider)+ if (provider.plugin_id) {+ providers.set(provider.plugin_id, provider)+ providers.set(`${provider.plugin_id}/${provider.name}`, provider)+ }+ })++ return providers+ }, [buildInTools, customTools, workflowTools, mcpTools])+}++function getLocalizedText(+ text: Record<string, string> | undefined,+ language: string,+) {+ return text?.[language] ?? text?.en_US ?? text?.zh_Hans+}++function getProviderCredentialRequired(provider?: ToolWithProvider) {+ return Object.keys(provider?.team_credentials ?? {}).length > 0+}++function useDisplayTools(+ tools: AgentTool[],+ providerById: Map<string, ToolWithProvider>,+) {+ const language = useGetLanguage()++ return useMemo(() => {+ return tools.map((tool) => {+ if (tool.kind !== 'provider')+ return tool++ const provider = providerById.get(tool.id)+ ?? providerById.get(tool.name)++ if (!provider)+ return tool++ const providerToolByName = new Map(provider.tools.map(providerTool => [providerTool.name, providerTool]))+ const credentialRequired = getProviderCredentialRequired(provider)++ return {+ ...tool,+ displayName: tool.displayName ?? getLocalizedText(provider.label, language) ?? tool.name,+ icon: tool.icon ?? provider.icon,+ iconDark: tool.iconDark ?? provider.icon_dark,+ providerType: tool.providerType ?? provider.type,+ allowDelete: tool.allowDelete ?? provider.allow_delete,+ credentialKey: credentialRequired ? tool.credentialKey : undefined,+ credentialType: credentialRequired ? tool.credentialType : undefined,+ credentialVariant: credentialRequired ? tool.credentialVariant : 'none',+ actions: tool.actions.map((action) => {+ const providerTool = providerToolByName.get(action.toolName)++ if (!providerTool)+ return action++ return {+ ...action,+ name: action.name === action.toolName+ ? getLocalizedText(providerTool.label, language) ?? action.name+ : action.name,+ description: action.description || getLocalizedText(providerTool.description, language) || '',+ }+ }),+ } satisfies AgentProviderTool+ })+ }, [language, providerById, tools])+}++function AddToolMenuItem({+ badge,+ description,+ iconClassName,+ label,+ onClick,+}: {+ badge?: string+ description: string+ iconClassName: string+ label: string+ onClick?: () => void+}) {+ return (+ <button+ type="button"+ onClick={onClick}+ className="flex w-full items-start gap-2 rounded-lg py-2 pr-3 pl-2 text-left hover:bg-state-base-hover focus-visible:bg-state-base-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"+ >+ <span aria-hidden className={cn('mt-0.5 size-4 shrink-0 text-text-secondary', iconClassName)} />+ <span className="flex min-w-0 flex-1 flex-col gap-0.5">+ <span className="flex min-w-0 items-center gap-1">+ <span className="truncate system-sm-semibold text-text-secondary">+ {label}+ </span>+ {badge && (+ <span className="shrink-0 rounded-[5px] border border-divider-deep bg-components-badge-bg-dimm px-1 py-0.5 system-2xs-medium-uppercase text-text-tertiary">+ {badge}+ </span>+ )}+ </span>+ <span className="system-xs-regular text-text-tertiary">+ {description}+ </span>+ </span>+ </button>+ )+}++function AddToolMenu({+ onAddCliTool,+ onAddTools,+ selectedTools,+}: {+ onAddCliTool: () => void+ onAddTools: (tools: AgentProviderToolDefaultValue[]) => void+ selectedTools: ToolValue[]+}) {+ const { t } = useTranslation('agentV2')+ const [open, setOpen] = useState(false)+ const [view, setView] = useState<'menu' | 'tool-picker'>('menu')+ const providerById = useAgentToolProviderMap()++ const openToolPicker = useCallback(() => {+ setView('tool-picker')+ }, [])++ const openCliToolDialog = useCallback(() => {+ setOpen(false)+ onAddCliTool()+ }, [onAddCliTool])++ const handleOpenChange = useCallback((nextOpen: boolean) => {+ setOpen(nextOpen)++ if (nextOpen)+ setView('menu')+ }, [])++ const toAgentToolDefaultValue = useCallback((tool: ToolDefaultValue): AgentProviderToolDefaultValue => ({+ ...tool,+ allowDelete: (providerById.get(tool.provider_id)+ ?? providerById.get(tool.provider_name)+ ?? (tool.plugin_id ? providerById.get(tool.plugin_id) : undefined))?.allow_delete,+ credentialRequired: getProviderCredentialRequired(providerById.get(tool.provider_id)+ ?? providerById.get(tool.provider_name)+ ?? (tool.plugin_id ? providerById.get(tool.plugin_id) : undefined)),+ }), [providerById])++ const handleSelectTool = useCallback((tool: ToolDefaultValue) => {+ onAddTools([toAgentToolDefaultValue(tool)])+ }, [onAddTools, toAgentToolDefaultValue])++ const handleSelectMultipleTools = useCallback((tools: ToolDefaultValue[]) => {+ onAddTools(tools.map(toAgentToolDefaultValue))+ }, [onAddTools, toAgentToolDefaultValue])++ return (+ <Popover open={open} onOpenChange={handleOpenChange}>+ <PopoverTrigger+ render={(+ <ConfigureSectionAddButton ariaLabel={t('agentDetail.configure.tools.add')} />+ )}+ />+ <PopoverContent+ placement="bottom-end"+ sideOffset={4}+ popupClassName={view === 'menu'+ ? 'w-[280px] bg-components-panel-bg-blur p-1 shadow-lg backdrop-blur-[5px]'+ : 'w-[400px] overflow-hidden border-none bg-transparent p-0 shadow-none'}+ >+ {view === 'menu'+ ? (+ <>+ <AddToolMenuItem+ iconClassName="i-ri-box-3-line"+ label={t('agentDetail.configure.tools.addMenu.tool.label')}+ description={t('agentDetail.configure.tools.addMenu.tool.description')}+ onClick={openToolPicker}+ />+ <AddToolMenuItem+ iconClassName="i-ri-terminal-box-line"+ label={t('agentDetail.configure.tools.addMenu.cliTool.label')}+ badge={t('agentDetail.configure.tools.addMenu.cliTool.badge')}+ description={t('agentDetail.configure.tools.addMenu.cliTool.description')}+ onClick={openCliToolDialog}+ />+ </>+ )+ : (+ <ToolPickerContent+ focusSearchOnMount+ panelClassName="w-full"+ supportAddCustomTool+ selectedTools={selectedTools}+ onSelect={handleSelectTool}+ onSelectMultiple={handleSelectMultipleTools}+ />+ )}+ </PopoverContent>+ </Popover>+ )+}++export function AgentTools() {+ const { t } = useTranslation('agentV2')+ const readOnly = useAgentOrchestrateReadOnly()+ const setProviderToolCredential = useSetProviderToolCredential()+ const providerById = useAgentToolProviderMap()+ const {+ tools,+ selectedTools,+ expandedToolIds,+ settingTarget,+ isCliToolDialogOpen,+ editingCliTool,+ setTools,+ setToolOpen,+ setSettingTarget,+ addTools,+ deleteCliTool,+ deleteProviderTool,+ deleteProviderToolAction,+ openCliToolDialog,+ editCliTool,+ handleCliDialogSave,+ handleCliDialogOpenChange,+ closeProviderSettingsDialog,+ } = useAgentToolsOperations()+ const displayTools = useDisplayTools(tools, providerById)+ useEffect(() => {+ if (readOnly)+ return++ let shouldSyncCredentials = false+ const nextTools = tools.map((tool, index) => {+ const displayTool = displayTools[index]++ if (tool.kind !== 'provider' || displayTool?.kind !== 'provider')+ return tool++ if (+ tool.allowDelete === displayTool.allowDelete+ && tool.credentialKey === displayTool.credentialKey+ && tool.credentialType === displayTool.credentialType+ && tool.credentialVariant === displayTool.credentialVariant+ ) {+ return tool+ }++ shouldSyncCredentials = true+ return {+ ...tool,+ allowDelete: displayTool.allowDelete,+ credentialKey: displayTool.credentialKey,+ credentialType: displayTool.credentialType,+ credentialVariant: displayTool.credentialVariant,+ }+ })++ if (shouldSyncCredentials)+ setTools(nextTools)+ }, [displayTools, readOnly, setTools, tools])+ const promptAddCallbackRef = useRef<AgentOrchestrateAddActionOptions['onAdded']>(undefined)+ const openCliToolDialogFromPrompt = useCallback((options?: AgentOrchestrateAddActionOptions) => {+ promptAddCallbackRef.current = options?.onAdded+ openCliToolDialog()+ }, [openCliToolDialog])+ const handleCliDialogSaveWithPromptInsert = useCallback((tool: AgentCliTool) => {+ handleCliDialogSave(tool)+ if (!editingCliTool) {+ promptAddCallbackRef.current?.(tool)+ promptAddCallbackRef.current = undefined+ }+ }, [editingCliTool, handleCliDialogSave])+ const handleCliDialogOpenChangeWithPromptInsert = useCallback((open: boolean) => {+ if (!open)+ promptAddCallbackRef.current = undefined+ handleCliDialogOpenChange(open)+ }, [handleCliDialogOpenChange])+ useRegisterAgentOrchestrateAddAction('cli', openCliToolDialogFromPrompt)+ const toolsTip = t('agentDetail.configure.tools.tip')+ const toolsListId = 'agent-configure-tools-list'+ const settingTargetCollection = settingTarget+ ? providerById.get(settingTarget.tool.id)+ ?? providerById.get(settingTarget.tool.name)+ : undefined++ return (+ <>+ <ConfigureSection+ label={t('agentDetail.configure.tools.label')}+ labelId="agent-configure-tools-label"+ panelId={toolsListId}+ tip={toolsTip}+ tipAriaLabel={toolsTip}+ rootClassName="border-b border-divider-subtle pt-4"+ panelContentClassName="flex flex-col gap-1 pb-4"+ actions={!readOnly+ ? (+ <AddToolMenu+ onAddCliTool={openCliToolDialog}+ onAddTools={addTools}+ selectedTools={selectedTools}+ />+ )+ : undefined}+ >+ {displayTools.length === 0+ ? (+ <ConfigureSectionEmpty+ title={t('agentDetail.configure.tools.empty.title')}+ description={t('agentDetail.configure.tools.empty.description')}+ />+ )+ : displayTools.map(tool => (+ <AgentToolItem+ key={tool.id}+ tool={tool}+ isExpanded={tool.kind === 'provider' && expandedToolIds.has(tool.id)}+ onOpenChange={setToolOpen}+ onConfigureAction={setSettingTarget}+ onDeleteCliTool={deleteCliTool}+ onDeleteProviderTool={deleteProviderTool}+ onDeleteProviderToolAction={deleteProviderToolAction}+ onEditCliTool={editCliTool}+ onCredentialChange={setProviderToolCredential}+ />+ ))}+ </ConfigureSection>+ <ProviderToolSettingsDialog+ settingTarget={settingTarget}+ collection={settingTargetCollection}+ onClose={closeProviderSettingsDialog}+ />+ <CliToolDialog+ key={`${editingCliTool?.id ?? 'add'}:${isCliToolDialogOpen ? 'open' : 'closed'}`}+ mode={editingCliTool ? 'edit' : 'add'}+ tool={editingCliTool}+ onDeleteCliTool={deleteCliTool}+ onSaveCliTool={handleCliDialogSaveWithPromptInsert}+ open={isCliToolDialogOpen}+ onOpenChange={handleCliDialogOpenChangeWithPromptInsert}+ />+ </>+ )+}diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/provider-tool/dialog.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/provider-tool/dialog.tsxnew file mode 100644index 00000000000..53673b384da--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/provider-tool/dialog.tsx@@ -0,0 +1,86 @@+'use client'++import type { ToolSettingTarget } from '../types'+import type { Tool } from '@/app/components/tools/types'+import type { ToolWithProvider } from '@/app/components/workflow/types'+import type { AgentProviderTool } from '@/features/agent-v2/agent-composer/form-state'+import { useAtom } from 'jotai'+import { useCallback, useMemo } from 'react'+import SettingBuiltInTool from '@/app/components/app/configuration/config/agent/agent-tools/setting-built-in-tool'+import { CollectionType } from '@/app/components/tools/types'+import { agentComposerToolSettingsAtom } from '@/features/agent-v2/agent-composer/store-modules/tools'++const localize = (value: string) => ({+ en_US: value,+ zh_Hans: value,+})++const createFallbackToolCollection = (tool: AgentProviderTool): ToolWithProvider => ({+ id: tool.id,+ name: tool.id,+ author: tool.name,+ description: localize(`${tool.name} tools`),+ icon: tool.icon ?? '',+ icon_dark: tool.iconDark,+ label: localize(tool.displayName ?? tool.name),+ type: (tool.providerType as CollectionType | undefined) ?? CollectionType.builtIn,+ team_credentials: {},+ is_team_authorization: true,+ allow_delete: tool.allowDelete ?? false,+ labels: [],+ meta: {+ version: '0.0.0',+ },+ tools: tool.actions.map<Tool>(action => ({+ name: action.toolName,+ author: tool.name,+ label: localize(action.name),+ description: localize(action.description),+ parameters: [],+ labels: [],+ output_schema: {},+ })),+}) as ToolWithProvider++export function ProviderToolSettingsDialog({+ settingTarget,+ collection,+ onClose,+}: {+ settingTarget: ToolSettingTarget | null+ collection?: ToolWithProvider+ onClose: () => void+}) {+ const [toolSettings, setToolSettings] = useAtom(agentComposerToolSettingsAtom)+ const toolCollection = useMemo(() => {+ if (!settingTarget)+ return null++ return collection ?? createFallbackToolCollection(settingTarget.tool)+ }, [collection, settingTarget])+ const handleSave = useCallback((value: Record<string, unknown>) => {+ if (!settingTarget)+ return++ setToolSettings({+ ...toolSettings,+ [settingTarget.action.id]: value,+ })+ onClose()+ }, [onClose, setToolSettings, settingTarget, toolSettings])++ if (!settingTarget || !toolCollection)+ return null++ return (+ <SettingBuiltInTool+ toolName={settingTarget.action.toolName}+ setting={toolSettings[settingTarget.action.id]}+ collection={toolCollection}+ isModel={false}+ credentialId={settingTarget.tool.credentialId}+ onSave={handleSave}+ onHide={onClose}+ />+ )+}diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/provider-tool/item.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/provider-tool/item.tsxnew file mode 100644index 00000000000..8c15189c56b--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/provider-tool/item.tsx@@ -0,0 +1,292 @@+'use client'++import type { ToolSettingTarget } from '../types'+import type { AgentProviderTool, AgentToolAction } from '@/features/agent-v2/agent-composer/form-state'+import { Button } from '@langgenius/dify-ui/button'+import { cn } from '@langgenius/dify-ui/cn'+import {+ CollapsiblePanel,+ CollapsibleRoot,+ CollapsibleTrigger,+} from '@langgenius/dify-ui/collapsible'+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from '@langgenius/dify-ui/dropdown-menu'+import { StatusDot } from '@langgenius/dify-ui/status-dot'+import { useCallback, useMemo, useState } from 'react'+import { useTranslation } from 'react-i18next'+import {+ AuthCategory,+} from '@/app/components/plugins/plugin-auth'+import ApiKeyModal from '@/app/components/plugins/plugin-auth/authorize/api-key-modal'+import AuthorizedInNode from '@/app/components/plugins/plugin-auth/authorized-in-node'+import { useInvalidPluginCredentialInfoHook } from '@/app/components/plugins/plugin-auth/hooks/use-credential'+import { CollectionType } from '@/app/components/tools/types'+import BlockIcon from '@/app/components/workflow/block-icon'+import { BlockEnum } from '@/app/components/workflow/types'+import useTheme from '@/hooks/use-theme'+import { Theme } from '@/types/app'+import { useAgentOrchestrateReadOnly } from '../../read-only-context'++function ProviderIcon({+ icon,+ iconClassName,+}: {+ icon?: AgentProviderTool['icon']+ iconClassName: string+}) {+ if (icon) {+ return (+ <BlockIcon+ className="shrink-0"+ type={BlockEnum.Tool}+ toolIcon={icon}+ />+ )+ }++ return (+ <span className="flex size-5 shrink-0 items-center justify-center rounded-md border-[0.5px] border-effects-icon-border bg-background-default-dodge">+ <span aria-hidden className={cn('size-3.5', iconClassName)} />+ </span>+ )+}++function UnauthorizedCredentialStatus({+ tool,+ onCredentialChange,+}: {+ tool: AgentProviderTool+ onCredentialChange: (credentialId?: string) => void+}) {+ const { t } = useTranslation()+ const [isApiKeyModalOpen, setIsApiKeyModalOpen] = useState(false)+ const pluginPayload = useMemo(() => ({+ provider: tool.id,+ category: AuthCategory.tool,+ providerType: tool.providerType ?? CollectionType.builtIn,+ }), [tool.id, tool.providerType])+ const invalidPluginCredentialInfo = useInvalidPluginCredentialInfoHook(pluginPayload)+ const handleApiKeyModalOpen = useCallback(() => {+ setIsApiKeyModalOpen(true)+ }, [])+ const handleApiKeyModalClose = useCallback(() => {+ setIsApiKeyModalOpen(false)+ }, [])+ const handleCredentialUpdate = useCallback(() => {+ invalidPluginCredentialInfo()+ onCredentialChange()+ }, [invalidPluginCredentialInfo, onCredentialChange])++ return (+ <>+ <Button+ variant="secondary"+ size="small"+ className="shrink-0"+ onClick={handleApiKeyModalOpen}+ >+ {t('notAuthorized', { ns: 'tools' })}+ <StatusDot className="ml-2" status="warning" />+ </Button>+ <ApiKeyModal+ pluginPayload={pluginPayload}+ open={isApiKeyModalOpen}+ onOpenChange={setIsApiKeyModalOpen}+ onClose={handleApiKeyModalClose}+ onUpdate={handleCredentialUpdate}+ />+ </>+ )+}++function CredentialStatus({+ tool,+ onCredentialChange,+}: {+ tool: AgentProviderTool+ onCredentialChange: (credentialId?: string) => void+}) {+ const canSwitchCredential = (tool.providerType ?? CollectionType.builtIn) === CollectionType.builtIn && tool.allowDelete+ const handleAuthorizationItemClick = useCallback((id: string) => {+ onCredentialChange(id === '__workspace_default__' ? undefined : id || undefined)+ }, [onCredentialChange])+ const handleDefaultCredentialChange = useCallback((id?: string) => {+ if (!tool.credentialId && id)+ onCredentialChange(id)+ }, [onCredentialChange, tool.credentialId])++ if (tool.credentialVariant === 'none')+ return null++ if (tool.credentialVariant === 'unauthorized') {+ return (+ <UnauthorizedCredentialStatus+ tool={tool}+ onCredentialChange={onCredentialChange}+ />+ )+ }++ if (!canSwitchCredential)+ return null++ return (+ <div className="shrink-0">+ <AuthorizedInNode+ pluginPayload={{+ provider: tool.id,+ category: AuthCategory.tool,+ providerType: tool.providerType ?? CollectionType.builtIn,+ }}+ credentialId={tool.credentialId}+ onAuthorizationItemClick={handleAuthorizationItemClick}+ onDefaultCredentialChange={handleDefaultCredentialChange}+ />+ </div>+ )+}++function ProviderToolActionItem({+ action,+ tool,+ onConfigureAction,+ onRemoveAction,+}: {+ action: AgentToolAction+ tool: AgentProviderTool+ onConfigureAction: (target: ToolSettingTarget) => void+ onRemoveAction: (actionId: string) => void+}) {+ const { t } = useTranslation('agentV2')+ const readOnly = useAgentOrchestrateReadOnly()+ const handleConfigureAction = useCallback(() => {+ onConfigureAction({ action, tool })+ }, [action, onConfigureAction, tool])+ const handleRemoveAction = useCallback(() => {+ onRemoveAction(action.id)+ }, [action.id, onRemoveAction])++ return (+ <div className="group relative flex min-h-7 items-center gap-1 rounded-md py-px pr-0 pl-1 hover:bg-state-base-hover">+ <div className="absolute top-0 bottom-0 left-[13.5px] w-px bg-divider-regular" />+ <div className="flex min-w-0 flex-1 items-center py-1 pl-7">+ <span className="min-w-0 flex-1 truncate system-sm-regular text-text-secondary">+ {action.name}+ </span>+ </div>+ {!readOnly && (+ <div className="hidden shrink-0 items-center gap-1 px-0.5 group-focus-within:flex group-hover:flex">+ <button+ type="button"+ aria-label={t('agentDetail.configure.tools.editAction', { name: action.name })}+ onClick={handleConfigureAction}+ className="flex size-6 items-center justify-center rounded-md text-text-tertiary hover:bg-state-base-hover hover:text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"+ >+ <span aria-hidden className="i-ri-equalizer-2-line size-4" />+ </button>+ <button+ type="button"+ aria-label={t('agentDetail.configure.tools.removeAction', { name: action.name })}+ onClick={handleRemoveAction}+ className="flex size-6 items-center justify-center rounded-md text-text-tertiary hover:bg-state-destructive-hover hover:text-text-destructive focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"+ >+ <span aria-hidden className="i-ri-delete-bin-line size-4" />+ </button>+ </div>+ )}+ </div>+ )+}++export function AgentProviderToolItem({+ tool,+ isExpanded,+ onOpenChange,+ onConfigureAction,+ onRemoveAction,+ onRemoveProvider,+ onCredentialChange,+}: {+ tool: AgentProviderTool+ isExpanded: boolean+ onOpenChange: (open: boolean) => void+ onConfigureAction: (target: ToolSettingTarget) => void+ onRemoveAction: (actionId: string) => void+ onRemoveProvider: () => void+ onCredentialChange: (credentialId?: string) => void+}) {+ const { t } = useTranslation('agentV2')+ const readOnly = useAgentOrchestrateReadOnly()+ const { theme } = useTheme()+ const icon = theme === Theme.dark && tool.iconDark ? tool.iconDark : tool.icon+ const displayName = tool.displayName ?? tool.name++ return (+ <CollapsibleRoot+ open={isExpanded}+ onOpenChange={onOpenChange}+ className="overflow-hidden rounded-lg border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg p-1 shadow-xs shadow-shadow-shadow-3"+ >+ <div className="flex min-h-7 items-center gap-1 rounded-lg py-0.5 pr-0.5 pl-1">+ <CollapsibleTrigger+ className="group min-h-0 min-w-0 flex-1 justify-start gap-2 rounded-md px-0 pr-1 text-left hover:not-data-disabled:bg-transparent hover:not-data-disabled:text-text-secondary data-panel-open:text-text-secondary"+ >+ <ProviderIcon icon={icon} iconClassName={tool.iconClassName} />+ <span className="flex min-w-0 items-center">+ <span className="min-w-0 truncate system-sm-medium text-text-primary">+ {displayName}+ </span>+ <span+ aria-hidden+ className={cn(+ 'i-custom-vender-solid-arrows-arrow-down-round-fill size-4 shrink-0 -rotate-90 text-text-quaternary transition-transform group-data-panel-open:rotate-0 motion-reduce:transition-none',+ )}+ />+ </span>+ </CollapsibleTrigger>+ {!readOnly && (+ <>+ <DropdownMenu modal={false}>+ <DropdownMenuTrigger+ aria-label={t('agentDetail.configure.tools.moreActions', { name: tool.name })}+ className="flex size-6 shrink-0 items-center justify-center rounded-md text-text-tertiary hover:bg-state-base-hover hover:text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden data-popup-open:bg-state-base-hover"+ >+ <span className="sr-only">{t('agentDetail.configure.tools.moreActions', { name: tool.name })}</span>+ <span aria-hidden className="i-ri-more-fill size-4" />+ </DropdownMenuTrigger>+ <DropdownMenuContent placement="bottom-end" sideOffset={4} popupClassName="w-44">+ <DropdownMenuItem+ variant="destructive"+ className="gap-2"+ onClick={onRemoveProvider}+ >+ <span aria-hidden className="i-ri-delete-bin-line size-4 shrink-0" />+ <span>{t('agentDetail.configure.tools.removeProvider')}</span>+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ <CredentialStatus tool={tool} onCredentialChange={onCredentialChange} />+ </>+ )}+ </div>++ <CollapsiblePanel>+ <div className="flex flex-col">+ {tool.actions.map(action => (+ <ProviderToolActionItem+ key={action.id}+ action={action}+ tool={tool}+ onConfigureAction={onConfigureAction}+ onRemoveAction={onRemoveAction}+ />+ ))}+ </div>+ </CollapsiblePanel>+ </CollapsibleRoot>+ )+}diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/types.ts b/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/types.tsnew file mode 100644index 00000000000..4401994fa37--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/types.ts@@ -0,0 +1,15 @@+import type { ToolDefaultValue } from '@/app/components/workflow/block-selector/types'+import type {+ AgentProviderTool,+ AgentToolAction,+} from '@/features/agent-v2/agent-composer/form-state'++export type AgentProviderToolDefaultValue = ToolDefaultValue & {+ allowDelete?: boolean+ credentialRequired?: boolean+}++export type ToolSettingTarget = {+ action: AgentToolAction+ tool: AgentProviderTool+}diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/utils.ts b/web/features/agent-v2/agent-detail/configure/components/orchestrate/utils.tsnew file mode 100644index 00000000000..4c6a473103b--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/utils.ts@@ -0,0 +1,20 @@+import type { AgentFileNode } from '@/features/agent-v2/agent-composer/form-state'++export function countAgentFileNodes(files: AgentFileNode[]): number {+ return files.reduce((count, file) => count + 1 + (file.children ? countAgentFileNodes(file.children) : 0), 0)+}++/**+ * @public+ */+// TODO: Remove this marker after the first file selector is wired.+export function getFirstAgentFileId(files: AgentFileNode[]): string | undefined {+ for (const file of files) {+ if (!file.children?.length)+ return file.id++ const childFileId = getFirstAgentFileId(file.children)+ if (childFileId)+ return childFileId+ }+}diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/chat.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/chat.spec.tsxnew file mode 100644index 00000000000..c95ce1c635e--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/chat.spec.tsx@@ -0,0 +1,198 @@+import type { ComponentProps } from 'react'+import { fireEvent, render, screen, waitFor } from '@testing-library/react'+import { createStore, Provider as JotaiProvider } from 'jotai'+import { agentComposerModelAtom } from '@/features/agent-v2/agent-composer/store-modules/model'+import { agentComposerPromptAtom } from '@/features/agent-v2/agent-composer/store-modules/prompt'+import { AgentPreviewChat } from '../chat'++const handleSendMock = vi.hoisted(() => vi.fn())+const stopCallbackRef = vi.hoisted(() => ({+ current: undefined as undefined | ((taskId: string) => void),+}))+const chatMessagesGetMock = vi.hoisted(() => vi.fn())+const suggestedQuestionsGetMock = vi.hoisted(() => vi.fn())+const stopPostMock = vi.hoisted(() => vi.fn())++vi.mock('@/next/dynamic', () => ({+ default: () => function MockChat(props: {+ onSend: (message: string) => void+ onStopResponding: () => void+ }) {+ return (+ <div>+ <button type="button" onClick={() => props.onSend('hello')}>+ send+ </button>+ <button type="button" onClick={props.onStopResponding}>+ stop+ </button>+ </div>+ )+ },+}))++vi.mock('@/app/components/base/chat/chat/hooks', () => ({+ useChat: (+ _config: unknown,+ _formSettings: unknown,+ _chatList: unknown[],+ stopCallback: (taskId: string) => void,+ ) => {+ stopCallbackRef.current = stopCallback++ return {+ chatList: [],+ setTargetMessageId: vi.fn(),+ isResponding: false,+ handleSend: handleSendMock,+ suggestedQuestions: [],+ handleStop: () => stopCallback('task-1'),+ handleAnnotationAdded: vi.fn(),+ handleAnnotationEdited: vi.fn(),+ handleAnnotationRemoved: vi.fn(),+ }+ },+}))++vi.mock('@/context/app-context', () => ({+ useAppContext: () => ({+ userProfile: {+ avatar_url: '',+ name: 'User',+ },+ }),+}))++vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({+ useTextGenerationCurrentProviderAndModelAndModelList: () => ({+ textGenerationModelList: [+ {+ provider: 'openai',+ models: [+ {+ model: 'gpt-4',+ features: [],+ },+ ],+ },+ ],+ }),+}))++vi.mock('@/service/client', () => ({+ consoleClient: {+ agent: {+ byAgentId: {+ chatMessages: {+ get: chatMessagesGetMock,+ byMessageId: {+ suggestedQuestions: {+ get: suggestedQuestionsGetMock,+ },+ },+ byTaskId: {+ stop: {+ post: stopPostMock,+ },+ },+ },+ },+ },+ },+}))++function renderPreviewChat(props?: Partial<ComponentProps<typeof AgentPreviewChat>>) {+ const store = createStore()+ store.set(agentComposerModelAtom, {+ provider: 'openai',+ model: 'gpt-4',+ })+ store.set(agentComposerPromptAtom, 'You are helpful.')++ return render(+ <JotaiProvider store={store}>+ <AgentPreviewChat+ agentId="agent-1"+ clearChatList={false}+ onClearChatListChange={vi.fn()}+ {...props}+ />+ </JotaiProvider>,+ )+}++describe('AgentPreviewChat', () => {+ beforeEach(() => {+ handleSendMock.mockClear()+ chatMessagesGetMock.mockResolvedValue({ data: [] })+ suggestedQuestionsGetMock.mockResolvedValue({ data: [] })+ stopPostMock.mockResolvedValue({ result: 'success' })+ stopCallbackRef.current = undefined+ })++ it('should save draft before sending preview chat through the agent chat endpoints', async () => {+ const saveDraftBeforeRun = vi.fn().mockResolvedValue(undefined)+ renderPreviewChat({+ onSaveDraftBeforeRun: saveDraftBeforeRun,+ })++ fireEvent.click(screen.getByRole('button', { name: 'send' }))++ await waitFor(() => expect(handleSendMock).toHaveBeenCalledTimes(1))+ expect(saveDraftBeforeRun).toHaveBeenCalledTimes(1)+ expect(saveDraftBeforeRun.mock.invocationCallOrder[0]).toBeLessThan(handleSendMock.mock.invocationCallOrder[0]!)+ expect(handleSendMock).toHaveBeenCalledWith(+ 'agent/agent-1/chat-messages',+ expect.not.objectContaining({+ model_config: expect.anything(),+ }),+ expect.objectContaining({+ onGetConversationMessages: expect.any(Function),+ onGetSuggestedQuestions: expect.any(Function),+ }),+ )++ const firstCall = handleSendMock.mock.calls.at(0)+ expect(firstCall).toBeDefined()++ const callbacks = firstCall![2]+ await callbacks.onGetConversationMessages('conversation-1')+ await callbacks.onGetSuggestedQuestions('message-1')++ expect(chatMessagesGetMock).toHaveBeenCalledWith({+ params: {+ agent_id: 'agent-1',+ },+ query: {+ conversation_id: 'conversation-1',+ },+ })+ expect(suggestedQuestionsGetMock).toHaveBeenCalledWith({+ params: {+ agent_id: 'agent-1',+ message_id: 'message-1',+ },+ })++ fireEvent.click(screen.getByRole('button', { name: 'stop' }))++ expect(stopPostMock).toHaveBeenCalledWith({+ params: {+ agent_id: 'agent-1',+ task_id: 'task-1',+ },+ })+ })++ it('should not send preview chat when draft save fails', async () => {+ const saveDraftBeforeRun = vi.fn().mockRejectedValue(new Error('save failed'))+ renderPreviewChat({+ onSaveDraftBeforeRun: saveDraftBeforeRun,+ })++ fireEvent.click(screen.getByRole('button', { name: 'send' }))++ await waitFor(() => expect(saveDraftBeforeRun).toHaveBeenCalledTimes(1))+ expect(handleSendMock).not.toHaveBeenCalled()+ })+})diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/chat-features-panel.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/chat-features-panel.tsxnew file mode 100644index 00000000000..490f58bdb28--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/preview/chat-features-panel.tsx@@ -0,0 +1,119 @@+'use client'++import type { AgentSoulAppFeaturesConfig } from '@dify/contracts/api/console/agent/types.gen'+import type { Features } from '@/app/components/base/features/types'+import { useCallback, useMemo } from 'react'+import { useTranslation } from 'react-i18next'+import { FeaturesProvider } from '@/app/components/base/features'+import { useFeaturesStore } from '@/app/components/base/features/hooks'+import NewFeaturePanel from '@/app/components/base/features/new-feature-panel'+import { useSetAppFeatures } from '@/features/agent-v2/agent-composer/store-modules/app-features'+import { Resolution, TransferMethod } from '@/types/app'++type AgentChatFeaturesPanelProps = {+ appFeatures?: AgentSoulAppFeaturesConfig+ disabled?: boolean+ show: boolean+ onClose: () => void+}++const defaultFeatureState: Features = {+ moreLikeThis: { enabled: false },+ opening: { enabled: false },+ suggested: { enabled: false },+ text2speech: { enabled: false },+ speech2text: { enabled: false },+ citation: { enabled: false },+ moderation: { enabled: false },+ file: {+ enabled: false,+ image: {+ enabled: false,+ detail: Resolution.high,+ number_limits: 3,+ transfer_methods: [TransferMethod.local_file, TransferMethod.remote_url],+ },+ },+ annotationReply: { enabled: false },+}++function toPanelFeatures(appFeatures?: AgentSoulAppFeaturesConfig): Features {+ return {+ ...defaultFeatureState,+ opening: {+ enabled: !!(appFeatures?.opening_statement || appFeatures?.suggested_questions?.length),+ opening_statement: appFeatures?.opening_statement ?? '',+ suggested_questions: appFeatures?.suggested_questions ?? [],+ },+ suggested: (appFeatures?.suggested_questions_after_answer as Features['suggested'] | undefined) ?? defaultFeatureState.suggested,+ text2speech: (appFeatures?.text_to_speech as Features['text2speech'] | undefined) ?? defaultFeatureState.text2speech,+ speech2text: appFeatures?.speech_to_text ?? defaultFeatureState.speech2text,+ citation: appFeatures?.retriever_resource ?? defaultFeatureState.citation,+ moderation: (appFeatures?.sensitive_word_avoidance as Features['moderation'] | undefined) ?? defaultFeatureState.moderation,+ file: (appFeatures?.file_upload as Features['file'] | undefined) ?? defaultFeatureState.file,+ annotationReply: (appFeatures?.annotation_reply as Features['annotationReply'] | undefined) ?? defaultFeatureState.annotationReply,+ }+}++function toAppFeatures(features: Features, appFeatures?: AgentSoulAppFeaturesConfig): AgentSoulAppFeaturesConfig {+ return {+ ...appFeatures,+ opening_statement: features.opening?.enabled ? (features.opening.opening_statement ?? '') : '',+ suggested_questions: features.opening?.enabled ? (features.opening.suggested_questions ?? []) : [],+ suggested_questions_after_answer: features.suggested as AgentSoulAppFeaturesConfig['suggested_questions_after_answer'],+ text_to_speech: features.text2speech as AgentSoulAppFeaturesConfig['text_to_speech'],+ speech_to_text: features.speech2text,+ retriever_resource: features.citation,+ sensitive_word_avoidance: features.moderation as AgentSoulAppFeaturesConfig['sensitive_word_avoidance'],+ file_upload: features.file,+ annotation_reply: features.annotationReply,+ }+}++function AgentChatFeaturesPanelContent({+ appFeatures,+ disabled,+ show,+ onClose,+}: AgentChatFeaturesPanelProps) {+ const { t } = useTranslation('agentV2')+ const featuresStore = useFeaturesStore()+ const setAppFeatures = useSetAppFeatures()+ const handleChange = useCallback(() => {+ const features = featuresStore?.getState().features+ if (!features)+ return++ setAppFeatures(currentAppFeatures => toAppFeatures(features, currentAppFeatures ?? appFeatures))+ }, [appFeatures, featuresStore, setAppFeatures])++ return (+ <NewFeaturePanel+ show={show}+ isChatMode+ disabled={!!disabled}+ inWorkflow={false}+ showModeration={false}+ showAnnotationReply={false}+ drawerClassName="bg-components-panel-bg! data-[swipe-direction=right]:top-1! data-[swipe-direction=right]:right-0! data-[swipe-direction=right]:bottom-1! data-[swipe-direction=right]:rounded-r-none!"+ title={t('agentDetail.configure.chatFeatures.title')}+ description={t('agentDetail.configure.chatFeatures.description')}+ onChange={handleChange}+ onClose={onClose}+ />+ )+}++export function AgentChatFeaturesPanel({+ appFeatures,+ ...props+}: AgentChatFeaturesPanelProps) {+ const features = useMemo(() => toPanelFeatures(appFeatures), [appFeatures])+ const featuresKey = useMemo(() => JSON.stringify(appFeatures ?? {}), [appFeatures])++ return (+ <FeaturesProvider key={featuresKey} features={features}>+ <AgentChatFeaturesPanelContent appFeatures={appFeatures} {...props} />+ </FeaturesProvider>+ )+}diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/chat.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/chat.tsxnew file mode 100644index 00000000000..764ba65f498--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/preview/chat.tsx@@ -0,0 +1,441 @@+'use client'++import type {+ AgentCliToolConfig,+ AgentIconType,+ AgentSoulConfig,+ AgentSoulDifyToolConfig,+} from '@dify/contracts/api/console/agent/types.gen'+import type { ChatConfig, ChatItem, OnSend } from '@/app/components/base/chat/types'+import type { FileEntity } from '@/app/components/base/file-uploader/types'+import type { DefaultModel } from '@/app/components/header/account-setting/model-provider-page/declarations'+import type { Inputs } from '@/models/debug'+import { Avatar } from '@langgenius/dify-ui/avatar'+import { cn } from '@langgenius/dify-ui/cn'+import { useAtomValue } from 'jotai'+import { useCallback, useMemo } from 'react'+import { useTranslation } from 'react-i18next'+import AppIcon from '@/app/components/base/app-icon'+import { useChat } from '@/app/components/base/chat/chat/hooks'+import { getLastAnswer, isValidGeneratedAnswer } from '@/app/components/base/chat/utils'+import { ModelFeatureEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'+import { useTextGenerationCurrentProviderAndModelAndModelList } from '@/app/components/header/account-setting/model-provider-page/hooks'+import { InputVarType } from '@/app/components/workflow/types'+import { DEFAULT_CHAT_PROMPT_CONFIG, DEFAULT_COMPLETION_PROMPT_CONFIG } from '@/config'+import { useAppContext } from '@/context/app-context'+import { agentComposerModelAtom } from '@/features/agent-v2/agent-composer/store-modules/model'+import { agentComposerPromptAtom } from '@/features/agent-v2/agent-composer/store-modules/prompt'+import { PromptMode } from '@/models/debug'+import dynamic from '@/next/dynamic'+import { consoleClient } from '@/service/client'+import { AgentStrategy, ModelModeType, RETRIEVE_TYPE, TransferMethod } from '@/types/app'++const Chat = dynamic(() => import('@/app/components/base/chat/chat'), { ssr: false })++type AgentPreviewChatConfig = ChatConfig & {+ model: {+ provider: string+ name: string+ mode: ModelModeType+ completion_params: {+ max_tokens: number+ temperature: number+ top_p: number+ echo: boolean+ stop: string[]+ presence_penalty: number+ frequency_penalty: number+ }+ }+}++const defaultSystemParameters: ChatConfig['system_parameters'] = {+ audio_file_size_limit: 0,+ file_size_limit: 0,+ image_file_size_limit: 0,+ video_file_size_limit: 0,+ workflow_file_upload_limit: 0,+}++const disabledFileUploadConfig = {+ allowed_file_upload_methods: [TransferMethod.local_file, TransferMethod.remote_url],+ allowed_file_types: [],+ fileUploadConfig: defaultSystemParameters,+ image: {+ enabled: false,+ transfer_methods: [],+ number_limits: 0,+ image_file_size_limit: 0,+ detail: 'low',+ },+ max_length: 0,+ number_limits: 0,+} as ChatConfig['file_upload'] & {+ fileUploadConfig: ChatConfig['system_parameters']+}++const getModelSettings = (agentSoulConfig?: AgentSoulConfig) => agentSoulConfig?.model?.model_settings ?? {}++const toEnabledConfig = (config?: { enabled?: boolean } | null) => ({+ ...config,+ enabled: config?.enabled ?? false,+})++const toInputType = (type: string): InputVarType => {+ if (type === InputVarType.paragraph)+ return InputVarType.paragraph+ if (type === InputVarType.select)+ return InputVarType.select+ if (type === InputVarType.number)+ return InputVarType.number+ if (type === InputVarType.json || type === InputVarType.jsonObject)+ return InputVarType.json++ return InputVarType.textInput+}++const toInputForm = (variable: NonNullable<AgentSoulConfig['app_variables']>[number]) => {+ const variableKey = String(variable.name)++ return {+ ...variable,+ key: variableKey,+ label: variableKey,+ variable: variableKey,+ type: toInputType(variable.type),+ required: variable.required ?? true,+ hide: false,+ }+}++const toAgentTool = (tool: AgentSoulDifyToolConfig) => ({+ provider_id: tool.provider_id ?? tool.provider ?? tool.plugin_id ?? '',+ provider_type: tool.provider_type ?? 'builtin',+ provider_name: tool.provider ?? '',+ tool_name: tool.tool_name,+ tool_label: tool.name ?? tool.tool_name,+ tool_parameters: tool.runtime_parameters ?? {},+ enabled: tool.enabled ?? true,+ credential_id: tool.credential_ref?.id,+})++const toCliTool = (tool: AgentCliToolConfig) => ({+ provider_id: 'agent-v2-cli',+ provider_type: 'builtin',+ provider_name: 'CLI',+ tool_name: tool.tool_name ?? tool.name ?? '',+ tool_label: tool.name ?? tool.tool_name ?? '',+ tool_parameters: {+ command: tool.command,+ },+ enabled: tool.enabled ?? true,+})++const stopAgentChatMessageResponding = (agentId: string, taskId: string) => {+ return consoleClient.agent.byAgentId.chatMessages.byTaskId.stop.post({+ params: {+ agent_id: agentId,+ task_id: taskId,+ },+ })+}++const fetchAgentConversationMessages = (agentId: string, conversationId: string) => {+ return consoleClient.agent.byAgentId.chatMessages.get({+ params: {+ agent_id: agentId,+ },+ query: {+ conversation_id: conversationId,+ },+ })+}++const fetchAgentSuggestedQuestions = (agentId: string, messageId: string) => {+ return consoleClient.agent.byAgentId.chatMessages.byMessageId.suggestedQuestions.get({+ params: {+ agent_id: agentId,+ message_id: messageId,+ },+ })+}++const buildChatConfig = ({+ agentSoulConfig,+ currentModel,+ prompt,+}: {+ agentSoulConfig?: AgentSoulConfig+ currentModel?: DefaultModel+ prompt: string+}): AgentPreviewChatConfig => {+ const modelSettings = getModelSettings(agentSoulConfig)+ const appFeatures = agentSoulConfig?.app_features ?? {}+ const datasets = agentSoulConfig?.knowledge?.datasets ?? []+ const difyTools = agentSoulConfig?.tools?.dify_tools ?? []+ const cliTools = agentSoulConfig?.tools?.cli_tools ?? []++ return {+ pre_prompt: prompt || agentSoulConfig?.prompt?.system_prompt || '',+ prompt_type: PromptMode.simple,+ chat_prompt_config: DEFAULT_CHAT_PROMPT_CONFIG,+ completion_prompt_config: DEFAULT_COMPLETION_PROMPT_CONFIG,+ user_input_form: (agentSoulConfig?.app_variables ?? []).map(variable => ({+ 'text-input': {+ default: String(variable.default ?? ''),+ label: variable.name,+ variable: variable.name,+ required: variable.required ?? true,+ max_length: 48,+ hide: false,+ },+ })),+ dataset_query_variable: '',+ opening_statement: appFeatures.opening_statement ?? '',+ suggested_questions: appFeatures.suggested_questions ?? [],+ suggested_questions_after_answer: toEnabledConfig(appFeatures.suggested_questions_after_answer) as ChatConfig['suggested_questions_after_answer'],+ more_like_this: { enabled: false },+ text_to_speech: toEnabledConfig(appFeatures.text_to_speech) as ChatConfig['text_to_speech'],+ speech_to_text: toEnabledConfig(appFeatures.speech_to_text),+ retriever_resource: toEnabledConfig(appFeatures.retriever_resource),+ sensitive_word_avoidance: toEnabledConfig(appFeatures.sensitive_word_avoidance),+ annotation_reply: {+ id: '',+ enabled: false,+ score_threshold: 0.9,+ embedding_model: {+ embedding_provider_name: '',+ embedding_model_name: '',+ },+ },+ agent_mode: {+ enabled: difyTools.length > 0 || cliTools.length > 0,+ strategy: AgentStrategy.functionCall,+ tools: [+ ...difyTools.map(toAgentTool),+ ...cliTools.map(toCliTool),+ ] as ChatConfig['agent_mode']['tools'],+ },+ model: {+ provider: currentModel?.provider ?? agentSoulConfig?.model?.model_provider ?? '',+ name: currentModel?.model ?? agentSoulConfig?.model?.model ?? '',+ mode: ModelModeType.chat,+ completion_params: {+ temperature: modelSettings.temperature ?? 0.7,+ top_p: modelSettings.top_p ?? 1,+ max_tokens: modelSettings.max_tokens ?? 512,+ presence_penalty: modelSettings.presence_penalty ?? 0,+ frequency_penalty: modelSettings.frequency_penalty ?? 0,+ stop: modelSettings.stop ?? [],+ echo: false,+ },+ },+ dataset_configs: {+ retrieval_model: RETRIEVE_TYPE.multiWay,+ reranking_model: {+ reranking_provider_name: '',+ reranking_model_name: '',+ },+ top_k: agentSoulConfig?.knowledge?.query_config?.top_k ?? 4,+ score_threshold_enabled: agentSoulConfig?.knowledge?.query_config?.score_threshold_enabled ?? false,+ score_threshold: agentSoulConfig?.knowledge?.query_config?.score_threshold ?? 0.8,+ datasets: {+ datasets: datasets.map(dataset => ({+ enabled: true,+ id: dataset.id ?? '',+ })).filter(dataset => dataset.id),+ },+ },+ file_upload: disabledFileUploadConfig,+ system_parameters: defaultSystemParameters,+ supportCitationHitInfo: true,+ }+}++function AgentPreviewChatEmptyState({+ agentIcon,+ agentIconBackground,+ agentIconType,+ agentName,+ hasInstructions,+}: {+ agentIcon?: string | null+ agentIconBackground?: string | null+ agentIconType?: AgentIconType | null+ agentName?: string+ hasInstructions: boolean+}) {+ const { t } = useTranslation('agentV2')+ const imageUrl = (agentIconType === 'image' || agentIconType === 'link') ? agentIcon : undefined+ const iconType = imageUrl ? 'image' : agentIconType++ return (+ <div className="pointer-events-none absolute inset-x-12 bottom-[calc(27%+84px)] flex flex-col items-center text-center">+ <AppIcon+ size="xxl"+ rounded+ iconType={iconType}+ icon={agentIcon ?? undefined}+ background={agentIconBackground}+ imageUrl={imageUrl}+ className="bg-background-default"+ />+ <div className="mt-3 max-w-full truncate system-md-semibold text-text-secondary">+ {agentName || t('agentDetail.configure.preview.empty.defaultAgentName')}+ </div>+ <div className="mt-4 h-px w-73 max-w-full bg-divider-subtle" />+ <div className="mt-5 max-w-91 body-md-regular text-text-tertiary">+ <p>{t('agentDetail.configure.preview.empty.description')}</p>+ {!hasInstructions && (+ <p>{t('agentDetail.configure.preview.empty.noInstructionsDescription')}</p>+ )}+ </div>+ </div>+ )+}++export function AgentPreviewChat({+ agentId,+ agentIcon,+ agentIconBackground,+ agentIconType,+ agentName,+ agentSoulConfig,+ clearChatList,+ onClearChatListChange,+ onSaveDraftBeforeRun,+}: {+ agentId: string+ agentIcon?: string | null+ agentIconBackground?: string | null+ agentIconType?: AgentIconType | null+ agentName?: string+ agentSoulConfig?: AgentSoulConfig+ clearChatList: boolean+ onClearChatListChange: (clearChatList: boolean) => void+ onSaveDraftBeforeRun?: () => Promise<void>+}) {+ const { userProfile } = useAppContext()+ const prompt = useAtomValue(agentComposerPromptAtom)+ const currentModel = useAtomValue(agentComposerModelAtom)+ const config = useMemo(() => buildChatConfig({+ agentSoulConfig,+ currentModel,+ prompt,+ }), [agentSoulConfig, currentModel, prompt])+ const inputsForm = useMemo(() => (agentSoulConfig?.app_variables ?? []).map(toInputForm), [agentSoulConfig?.app_variables])+ const inputs = useMemo(() => {+ return inputsForm.reduce<Inputs>((acc, input) => {+ acc[input.variable] = (input.default ?? '') as Inputs[string]+ return acc+ }, {})+ }, [inputsForm])+ const {+ textGenerationModelList,+ } = useTextGenerationCurrentProviderAndModelAndModelList(currentModel)+ const {+ chatList,+ setTargetMessageId,+ isResponding,+ handleSend,+ suggestedQuestions,+ handleStop,+ handleAnnotationAdded,+ handleAnnotationEdited,+ handleAnnotationRemoved,+ } = useChat(+ config,+ {+ inputs,+ inputsForm,+ },+ [],+ (taskId) => {+ void stopAgentChatMessageResponding(agentId, taskId)+ },+ clearChatList,+ onClearChatListChange,+ )++ const doSend: OnSend = useCallback(async (message, files, isRegenerate = false, parentAnswer: ChatItem | null = null) => {+ try {+ await onSaveDraftBeforeRun?.()+ }+ catch {+ return+ }++ const currentProvider = textGenerationModelList.find(item => item.provider === config.model.provider)+ const selectedModel = currentProvider?.models.find(model => model.model === config.model.name)+ const supportVision = selectedModel?.features?.includes(ModelFeatureEnum.vision)+ const data: Record<string, unknown> = {+ query: message,+ inputs,+ parent_message_id: (isRegenerate ? parentAnswer?.id : getLastAnswer(chatList)?.id) || null,+ }++ if (files?.length && supportVision)+ data.files = files++ handleSend(+ `agent/${agentId}/chat-messages`,+ data as Parameters<typeof handleSend>[1],+ {+ onGetConversationMessages: conversationId => fetchAgentConversationMessages(agentId, conversationId),+ onGetSuggestedQuestions: responseItemId => fetchAgentSuggestedQuestions(agentId, responseItemId),+ },+ )+ }, [agentId, chatList, config.model.name, config.model.provider, handleSend, inputs, onSaveDraftBeforeRun, textGenerationModelList])++ const doRegenerate = useCallback((chatItem: ChatItem, editedQuestion?: { message: string, files?: FileEntity[] }) => {+ const question = editedQuestion ? chatItem : chatList.find(item => item.id === chatItem.parentMessageId)+ if (!question)+ return++ const parentAnswer = chatList.find(item => item.id === question.parentMessageId)+ doSend(+ editedQuestion ? editedQuestion.message : question.content,+ editedQuestion ? editedQuestion.files : question.message_files,+ true,+ isValidGeneratedAnswer(parentAnswer) ? parentAnswer : null,+ )+ }, [chatList, doSend])+ const isEmptyChat = chatList.length === 0+ const hasInstructions = !!config.pre_prompt.trim()++ return (+ <Chat+ config={config}+ chatList={chatList}+ isResponding={isResponding}+ chatNode={isEmptyChat && (+ <AgentPreviewChatEmptyState+ agentIcon={agentIcon}+ agentIconBackground={agentIconBackground}+ agentIconType={agentIconType}+ agentName={agentName}+ hasInstructions={hasInstructions}+ />+ )}+ chatContainerClassName={cn('pt-6', isEmptyChat ? 'px-12' : 'px-3')}+ chatFooterClassName={cn(+ 'pb-0',+ isEmptyChat ? '!bottom-[27%] px-12 pt-3' : 'px-3 pt-10',+ )}+ showFileUpload={false}+ suggestedQuestions={suggestedQuestions}+ onSend={doSend}+ inputs={inputs}+ inputsForm={inputsForm}+ onRegenerate={doRegenerate}+ switchSibling={siblingMessageId => setTargetMessageId(siblingMessageId)}+ onStopResponding={handleStop}+ showPromptLog+ questionIcon={<Avatar avatar={userProfile.avatar_url} name={userProfile.name} size="xl" />}+ onAnnotationEdited={handleAnnotationEdited}+ onAnnotationAdded={handleAnnotationAdded}+ onAnnotationRemoved={handleAnnotationRemoved}+ noSpacing+ />+ )+}diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/header.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/header.tsxnew file mode 100644index 00000000000..2598949ba21--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/preview/header.tsx@@ -0,0 +1,47 @@+'use client'++import { cn } from '@langgenius/dify-ui/cn'+import { useTranslation } from 'react-i18next'++export function AgentPreviewHeader({+ isChatFeaturesOpen,+ onToggleChatFeatures,+ onRestart,+}: {+ isChatFeaturesOpen: boolean+ onToggleChatFeatures: () => void+ onRestart: () => void+}) {+ const { t } = useTranslation('agentV2')++ return (+ <div className="flex h-12 shrink-0 items-center gap-3 py-3 pr-3 pl-6">+ <h2 className="min-w-0 flex-1 truncate title-xl-semi-bold text-text-primary">+ {t('agentDetail.configure.preview.title')}+ </h2>+ <div className="flex shrink-0 items-center gap-1">+ <button+ type="button"+ onClick={onRestart}+ className="flex size-6 items-center justify-center rounded-md p-0.5 text-text-tertiary hover:bg-state-base-hover hover:text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"+ aria-label={t('agentDetail.configure.preview.restart')}+ >+ <span aria-hidden className="i-custom-vender-other-replay-line size-4" />+ </button>+ <button+ type="button"+ aria-pressed={isChatFeaturesOpen}+ onClick={onToggleChatFeatures}+ className={cn(+ 'flex h-8 items-center justify-center gap-0.5 rounded-lg px-3 py-2 text-text-tertiary hover:bg-state-base-hover hover:text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden',+ isChatFeaturesOpen && 'bg-state-base-hover text-text-secondary',+ )}+ aria-label={t('agentDetail.configure.preview.chatFeatures')}+ >+ <span aria-hidden className="i-ri-apps-2-add-line size-4" />+ <span className="px-0.5 system-sm-medium">{t('agentDetail.configure.preview.chatFeatures')}</span>+ </button>+ </div>+ </div>+ )+}diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/versions-panel.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/versions-panel.tsxnew file mode 100644index 00000000000..45a54f14394--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/preview/versions-panel.tsx@@ -0,0 +1,201 @@+'use client'++import type { AgentConfigSnapshotSummaryResponse } from '@dify/contracts/api/console/agent/types.gen'+import { cn } from '@langgenius/dify-ui/cn'+import { useQuery } from '@tanstack/react-query'+import { useTranslation } from 'react-i18next'+import useTimestamp from '@/hooks/use-timestamp'+import { consoleQuery } from '@/service/client'++type AgentPreviewVersionsPanelProps = {+ agentId: string+ activeVersionId?: string | null+ onClose: () => void+}++function VersionTimelineDot({+ isActive,+ isFirst,+ isLast,+}: {+ isActive: boolean+ isFirst: boolean+ isLast: boolean+}) {+ return (+ <div className="relative flex w-[18px] shrink-0 justify-center pt-1.5">+ {!isFirst && <div className="absolute top-0 h-2 w-0.5 bg-divider-subtle" />}+ <span+ aria-hidden+ className={cn(+ 'relative z-1 size-2 rounded-full border-2 bg-components-panel-bg',+ isActive ? 'border-text-accent' : 'border-text-quaternary',+ )}+ />+ {!isLast && <div className="absolute top-3 bottom-[-18px] w-0.5 bg-divider-subtle" />}+ </div>+ )+}++function VersionMetadata({+ version,+}: {+ version: AgentConfigSnapshotSummaryResponse+}) {+ const { t } = useTranslation('agentV2')+ const { formatTime } = useTimestamp()++ if (version.created_at == null && !version.created_by)+ return null++ return (+ <p className="truncate system-xs-regular text-text-tertiary">+ {version.created_at != null && formatTime(version.created_at, t('roster.dateTimeFormat'))}+ {version.created_at != null && version.created_by && ' · '}+ {version.created_by}+ </p>+ )+}++function VersionItem({+ version,+ activeVersionId,+ isLatest,+ isFirst,+ isLast,+}: {+ version: AgentConfigSnapshotSummaryResponse+ activeVersionId?: string | null+ isLatest: boolean+ isFirst: boolean+ isLast: boolean+}) {+ const { t } = useTranslation('agentV2')+ const { t: tWorkflow } = useTranslation('workflow')+ const isActive = version.id === activeVersionId+ const label = version.version_note || t('agentDetail.versionHistory.versionName', { version: version.version })++ return (+ <button+ type="button"+ className={cn(+ 'group relative flex w-full items-start gap-1 rounded-lg py-1 pr-1.5 pl-2 text-left focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden',+ isActive ? 'bg-state-accent-active' : 'hover:bg-state-base-hover',+ )}+ >+ <VersionTimelineDot isActive={isActive} isFirst={isFirst} isLast={isLast} />+ <div className="min-w-0 flex-1 py-0.5">+ <div className="flex min-w-0 items-center gap-1">+ <p className={cn('truncate system-sm-semibold', isActive ? 'text-text-accent' : 'text-text-secondary')}>+ {label}+ </p>+ {isLatest && (+ <span className="shrink-0 rounded-[5px] border border-text-accent-secondary bg-components-badge-bg-dimm px-[5px] py-[3px] system-2xs-medium-uppercase text-text-accent-secondary">+ {tWorkflow('versionHistory.latest')}+ </span>+ )}+ </div>+ {isActive && version.summary && (+ <p className="mt-0.5 line-clamp-4 system-xs-regular text-text-secondary">+ {version.summary}+ </p>+ )}+ <VersionMetadata version={version} />+ </div>+ </button>+ )+}++function CurrentDraftItem({+ isLast,+}: {+ isLast: boolean+}) {+ const { t: tWorkflow } = useTranslation('workflow')++ return (+ <div className="flex w-full items-start gap-1 rounded-lg py-1 pr-1.5 pl-2">+ <VersionTimelineDot isActive={false} isFirst isLast={isLast} />+ <div className="min-w-0 flex-1 py-1">+ <p className="truncate system-sm-semibold text-text-secondary">+ {tWorkflow('versionHistory.currentDraft')}+ </p>+ </div>+ </div>+ )+}++export function AgentPreviewVersionsPanel({+ agentId,+ activeVersionId,+ onClose,+}: AgentPreviewVersionsPanelProps) {+ const { t } = useTranslation('agentV2')+ const { t: tCommon } = useTranslation('common')+ const { t: tWorkflow } = useTranslation('workflow')+ const versionsQuery = useQuery(consoleQuery.agent.byAgentId.versions.get.queryOptions({+ input: {+ params: {+ agent_id: agentId,+ },+ },+ }))+ const versions = versionsQuery.data?.data ?? []+ const latestVersionId = versions[0]?.id++ return (+ <aside className="flex h-full w-[268px] shrink-0 flex-col rounded-l-lg bg-components-panel-bg shadow-xl shadow-shadow-shadow-5">+ <div className="flex shrink-0 items-center gap-2 pt-3 pr-3 pl-4">+ <h2 className="min-w-0 flex-1 truncate system-xl-semibold text-text-primary">+ {tWorkflow('versionHistory.title')}+ </h2>+ <button+ type="button"+ aria-label={t('agentDetail.versionHistory.filter')}+ className="flex size-6 shrink-0 items-center justify-center rounded-md p-0.5 text-text-tertiary hover:bg-state-base-hover hover:text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"+ >+ <span aria-hidden className="i-ri-filter-3-line size-4" />+ </button>+ <div className="h-3.5 w-px shrink-0 bg-divider-regular" />+ <button+ type="button"+ aria-label={tCommon('operation.close')}+ onClick={onClose}+ className="flex size-6 shrink-0 items-center justify-center rounded-md p-0.5 text-text-tertiary hover:bg-state-base-hover hover:text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"+ >+ <span aria-hidden className="i-ri-close-line size-4" />+ </button>+ </div>++ <div className="min-h-0 flex-1 overflow-y-auto px-3 py-2">+ {versionsQuery.isPending && (+ <div className="space-y-1">+ <div className="h-10 animate-pulse rounded-lg bg-state-base-hover" />+ <div className="h-18 animate-pulse rounded-lg bg-state-base-hover" />+ <div className="h-10 animate-pulse rounded-lg bg-state-base-hover" />+ </div>+ )}+ {!versionsQuery.isPending && versions.length === 0 && (+ <div className="rounded-lg border border-components-panel-border bg-components-panel-on-panel-item-bg px-3 py-6 text-center system-sm-regular text-text-tertiary">+ {t('agentDetail.versionHistory.empty')}+ </div>+ )}+ {!versionsQuery.isPending && versions.length > 0 && (+ <div className="flex flex-col gap-px">+ <CurrentDraftItem isLast={versions.length === 0} />+ {versions.map((version, index) => (+ <VersionItem+ key={version.id}+ version={version}+ activeVersionId={activeVersionId}+ isLatest={version.id === latestVersionId}+ isFirst={false}+ isLast={index === versions.length - 1}+ />+ ))}+ </div>+ )}+ </div>+ </aside>+ )+}diff --git a/web/features/agent-v2/agent-detail/configure/page.tsx b/web/features/agent-v2/agent-detail/configure/page.tsxnew file mode 100644index 00000000000..993cec1b09f--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/page.tsx@@ -0,0 +1,263 @@+'use client'++import type { AgentConfigSnapshotDetailResponse, AgentIconType, AgentSoulConfig } from '@dify/contracts/api/console/agent/types.gen'+import { skipToken, useQuery } from '@tanstack/react-query'+import { useAtom, useAtomValue } from 'jotai'+import { useState } from 'react'+import { useTranslation } from 'react-i18next'+import Loading from '@/app/components/base/loading'+import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'+import { useDefaultModel, useTextGenerationCurrentProviderAndModelAndModelList } from '@/app/components/header/account-setting/model-provider-page/hooks'+import { AgentComposerProvider } from '@/features/agent-v2/agent-composer/provider'+import { useHydrateAgentSoulConfigDraft } from '@/features/agent-v2/agent-composer/store'+import { agentComposerAppFeaturesAtom } from '@/features/agent-v2/agent-composer/store-modules/app-features'+import { agentComposerModelAtom } from '@/features/agent-v2/agent-composer/store-modules/model'+import { consoleQuery } from '@/service/client'+import { AgentOrchestratePanel } from './components/orchestrate'+import { AgentPreviewChat } from './components/preview/chat'+import { AgentChatFeaturesPanel } from './components/preview/chat-features-panel'+import { AgentPreviewHeader } from './components/preview/header'+import { AgentPreviewVersionsPanel } from './components/preview/versions-panel'+import { useAgentConfigureSync } from './use-agent-configure-sync'++type AgentConfigurePageProps = {+ agentId: string+}++export function AgentConfigurePage({+ agentId,+}: AgentConfigurePageProps) {+ return (+ <AgentComposerProvider>+ <AgentConfigurePageContent agentId={agentId} />+ </AgentComposerProvider>+ )+}++function AgentConfigurePageContent({+ agentId,+}: AgentConfigurePageProps) {+ const { t } = useTranslation('agentV2')+ const configureData = useAgentConfigureData(agentId)+ const isConfigureDataPending = configureData.agentQuery.isPending+ || configureData.composerQuery.isPending+ || (configureData.shouldLoadPublishedVersion && configureData.versionQuery.isPending)++ if (isConfigureDataPending) {+ return (+ <section+ aria-label={t('agentDetail.sections.configure')}+ aria-busy+ className="flex h-full min-w-0 flex-1 items-center justify-center p-1"+ >+ <Loading type="app" />+ </section>+ )+ }++ return (+ <AgentConfigurePageLoadedContent+ agentId={agentId}+ configureData={configureData}+ />+ )+}++function AgentConfigurePageLoadedContent({+ agentId,+ configureData,+}: AgentConfigurePageProps & {+ configureData: ReturnType<typeof useAgentConfigureData>+}) {+ const { t } = useTranslation('agentV2')+ const [showChatFeatures, setShowChatFeatures] = useState(false)+ const [showPreviewVersions, setShowPreviewVersions] = useState(false)+ const [clearPreviewChat, setClearPreviewChat] = useState(false)+ const {+ agentQuery,+ composerQuery,+ versionQuery,+ activeVersionId,+ activeConfigSnapshot,+ agentSoulConfig,+ } = configureData+ const agentIconType = agentQuery.data?.icon_type as AgentIconType | null | undefined++ useHydrateAgentSoulConfigDraft({+ agentId,+ activeVersionId,+ config: agentSoulConfig,+ })+ const {+ currentModel,+ setConfigureModel,+ textGenerationModelList,+ } = useAgentConfigureModelOptions()+ const {+ draftSavedAt,+ isPublishing,+ publishDraft,+ saveDraft,+ } = useAgentConfigureSync({+ agentId,+ baseConfig: agentSoulConfig,+ currentModel,+ enabled: composerQuery.isSuccess,+ })++ return (+ <section+ aria-label={t('agentDetail.sections.configure')}+ aria-busy={agentQuery.isFetching}+ className="flex h-full min-w-0 flex-1 gap-1 overflow-hidden p-1"+ >+ <AgentOrchestratePanel+ agentId={agentId}+ activeConfigSnapshot={activeConfigSnapshot}+ agentSoulConfig={agentSoulConfig}+ agentName={agentQuery.data?.name}+ currentModel={currentModel}+ textGenerationModelList={textGenerationModelList}+ draftSavedAt={draftSavedAt}+ isPublishing={isPublishing}+ onSelectModel={setConfigureModel}+ onPublish={publishDraft}+ onOpenVersions={() => setShowPreviewVersions(true)}+ />++ {/* Preview area */}+ <div className="flex min-w-105 flex-1 gap-1 overflow-hidden">+ <div className="flex min-w-105 flex-1 flex-col overflow-hidden rounded-lg bg-background-gradient-bg-fill-chat-bg-2 shadow-xl shadow-shadow-shadow-5">+ <AgentPreviewHeader+ isChatFeaturesOpen={showChatFeatures}+ onToggleChatFeatures={() => setShowChatFeatures(open => !open)}+ onRestart={() => setClearPreviewChat(true)}+ />++ <div className="min-h-0 flex-1">+ <AgentPreviewChatWithDraftConfig+ agentId={agentId}+ agentIcon={agentQuery.data?.icon}+ agentIconBackground={agentQuery.data?.icon_background}+ agentIconType={agentIconType}+ agentName={agentQuery.data?.name}+ agentSoulConfig={agentSoulConfig}+ clearChatList={clearPreviewChat}+ onClearChatListChange={setClearPreviewChat}+ onSaveDraftBeforeRun={saveDraft}+ />+ </div>+ </div>++ {showPreviewVersions && (+ <AgentPreviewVersionsPanel+ agentId={agentId}+ activeVersionId={activeVersionId}+ onClose={() => setShowPreviewVersions(false)}+ />+ )}+ <AgentChatFeaturesPanel+ show={showChatFeatures}+ appFeatures={agentSoulConfig?.app_features}+ disabled={versionQuery.isPending}+ onClose={() => setShowChatFeatures(false)}+ />+ </div>+ </section>+ )+}++function AgentPreviewChatWithDraftConfig({+ agentSoulConfig,+ ...props+}: Omit<Parameters<typeof AgentPreviewChat>[0], 'agentSoulConfig'> & {+ agentSoulConfig?: AgentSoulConfig+}) {+ const draftAppFeatures = useAtomValue(agentComposerAppFeaturesAtom)+ const previewAgentSoulConfig = getPreviewAgentSoulConfig(agentSoulConfig, draftAppFeatures)++ return (+ <AgentPreviewChat+ {...props}+ agentSoulConfig={previewAgentSoulConfig}+ />+ )+}++function useAgentConfigureData(agentId: string) {+ const agentQuery = useQuery(consoleQuery.agent.byAgentId.get.queryOptions({+ input: {+ params: {+ agent_id: agentId,+ },+ },+ }))+ const composerQuery = useQuery(consoleQuery.agent.byAgentId.composer.get.queryOptions({+ input: {+ params: {+ agent_id: agentId,+ },+ },+ }))+ const activeVersionId = composerQuery.data?.active_config_snapshot?.id+ const shouldLoadPublishedVersion = !composerQuery.data?.agent_soul+ const versionQuery = useQuery(consoleQuery.agent.byAgentId.versions.byVersionId.get.queryOptions({+ input: activeVersionId && shouldLoadPublishedVersion+ ? {+ params: {+ agent_id: agentId,+ version_id: activeVersionId,+ },+ }+ : skipToken,+ }))+ const versionDetail = versionQuery.data as AgentConfigSnapshotDetailResponse | undefined+ const activeConfigSnapshot = composerQuery.data?.active_config_snapshot ?? versionDetail+ const agentSoulConfig = composerQuery.data?.agent_soul ?? versionDetail?.config_snapshot++ return {+ agentQuery,+ composerQuery,+ versionQuery,+ shouldLoadPublishedVersion,+ activeVersionId,+ activeConfigSnapshot,+ agentSoulConfig,+ }+}++function useAgentConfigureModelOptions() {+ const [model, setModel] = useAtom(agentComposerModelAtom)+ const {+ data: defaultTextGenerationModel,+ } = useDefaultModel(ModelTypeEnum.textGeneration)+ const defaultModel = defaultTextGenerationModel+ ? {+ provider: defaultTextGenerationModel.provider.provider,+ model: defaultTextGenerationModel.model,+ }+ : undefined+ const currentModel = model ?? defaultModel+ const {+ textGenerationModelList,+ } = useTextGenerationCurrentProviderAndModelAndModelList(currentModel)++ return {+ currentModel,+ setConfigureModel: setModel,+ textGenerationModelList,+ }+}++function getPreviewAgentSoulConfig(+ agentSoulConfig: AgentSoulConfig | undefined,+ draftAppFeatures: AgentSoulConfig['app_features'] | undefined,+) {+ if (!agentSoulConfig || !draftAppFeatures)+ return agentSoulConfig++ return {+ ...agentSoulConfig,+ app_features: draftAppFeatures,+ }+}diff --git a/web/features/agent-v2/agent-detail/configure/use-agent-configure-sync.ts b/web/features/agent-v2/agent-detail/configure/use-agent-configure-sync.tsnew file mode 100644index 00000000000..ecb8a1b5f41--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/use-agent-configure-sync.ts@@ -0,0 +1,161 @@+'use client'++import type { AgentSoulConfig, ComposerSaveStrategy } from '@dify/contracts/api/console/agent/types.gen'+import type { DefaultModel } from '@/app/components/header/account-setting/model-provider-page/declarations'+import { useMutation, useQueryClient } from '@tanstack/react-query'+import { debounce } from 'es-toolkit/compat'+import { useSetAtom, useStore } from 'jotai'+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'+import { useSerialAsyncCallback } from '@/app/components/workflow/hooks/use-serial-async-callback'+import { agentSoulConfigToFormState, formStateToAgentSoulConfig } from '@/features/agent-v2/agent-composer/conversions'+import {+ agentComposerDraftAtom,+ agentComposerOriginalConfigAtom,+ agentComposerOriginalDraftAtom,+ agentComposerPublishedDraftAtom,+ isAgentComposerDirtyAtom,+} from '@/features/agent-v2/agent-composer/store'+import { consoleQuery } from '@/service/client'++const DRAFT_AUTOSAVE_WAIT = 5000++type AgentConfigurePublishPayload = {+ agent_id: string+ config_snapshot: AgentSoulConfig+}++export function useAgentConfigureSync({+ agentId,+ baseConfig,+ currentModel,+ enabled,+}: {+ agentId: string+ baseConfig?: AgentSoulConfig+ currentModel?: DefaultModel+ enabled: boolean+}) {+ const queryClient = useQueryClient()+ const store = useStore()+ const setOriginalConfig = useSetAtom(agentComposerOriginalConfigAtom)+ const setOriginalDraft = useSetAtom(agentComposerOriginalDraftAtom)+ const setPublishedDraft = useSetAtom(agentComposerPublishedDraftAtom)+ const [isPublishing, setIsPublishing] = useState(false)+ const [draftSavedAt, setDraftSavedAt] = useState<number | undefined>(undefined)+ const baseConfigRef = useRef(baseConfig)+ const currentModelRef = useRef(currentModel)+ const enabledRef = useRef(enabled)+ const lastAutosavedDraftKeyRef = useRef<string | undefined>(undefined)++ baseConfigRef.current = baseConfig+ currentModelRef.current = currentModel+ enabledRef.current = enabled++ const getAgentSoulDraft = useCallback(() => formStateToAgentSoulConfig({+ baseConfig: baseConfigRef.current,+ formState: store.get(agentComposerDraftAtom),+ currentModel: currentModelRef.current,+ }), [store])++ const saveComposerMutation = useMutation(+ consoleQuery.agent.byAgentId.composer.put.mutationOptions(),+ )++ const saveComposer = useSerialAsyncCallback(async (+ saveStrategy: ComposerSaveStrategy,+ configSnapshot: AgentSoulConfig,+ ) => {+ const savedDraftKey = JSON.stringify(configSnapshot)+ const composerState = await saveComposerMutation.mutateAsync({+ params: {+ agent_id: agentId,+ },+ body: {+ variant: 'agent_app',+ save_strategy: saveStrategy,+ agent_soul: configSnapshot,+ },+ })++ if (saveStrategy === 'save_to_current_version') {+ setOriginalDraft(agentSoulConfigToFormState(configSnapshot))+ setDraftSavedAt(Date.now())+ lastAutosavedDraftKeyRef.current = savedDraftKey+ return+ }++ queryClient.setQueryData(+ consoleQuery.agent.byAgentId.composer.get.queryKey({ input: { params: { agent_id: agentId } } }),+ composerState,+ )+ void queryClient.invalidateQueries({+ queryKey: consoleQuery.agent.byAgentId.versions.get.key(),+ })+ setOriginalConfig(composerState.agent_soul)+ const publishedDraft = agentSoulConfigToFormState(composerState.agent_soul)+ setOriginalDraft(publishedDraft)+ setPublishedDraft(publishedDraft)+ lastAutosavedDraftKeyRef.current = savedDraftKey+ })++ const latestDraftSaveRef = useRef<() => void>(() => undefined)+ latestDraftSaveRef.current = () => {+ void saveComposer('save_to_current_version', getAgentSoulDraft())+ }++ const debouncedSaveDraft = useMemo(() => debounce(() => {+ latestDraftSaveRef.current()+ }, DRAFT_AUTOSAVE_WAIT), [])++ const saveDraft = useCallback(async () => {+ if (!enabledRef.current)+ return++ debouncedSaveDraft.cancel?.()+ await saveComposer('save_to_current_version', getAgentSoulDraft())+ }, [debouncedSaveDraft, getAgentSoulDraft, saveComposer])++ useEffect(() => {+ return store.sub(agentComposerDraftAtom, () => {+ const agentSoulDraft = getAgentSoulDraft()+ const agentSoulDraftKey = JSON.stringify(agentSoulDraft)++ if (+ !enabledRef.current+ || !store.get(isAgentComposerDirtyAtom)+ || lastAutosavedDraftKeyRef.current === agentSoulDraftKey+ ) {+ return+ }++ debouncedSaveDraft()+ })+ }, [debouncedSaveDraft, getAgentSoulDraft, store])++ useEffect(() => {+ return () => {+ debouncedSaveDraft.flush?.()+ }+ }, [debouncedSaveDraft])++ const publishDraft = useCallback(async (payload: AgentConfigurePublishPayload) => {+ debouncedSaveDraft.cancel?.()+ setIsPublishing(true)+ try {+ await saveComposer('save_as_new_version', payload.config_snapshot)+ }+ catch {+ // Draft sync follows workflow autosave behavior: save failures are silent and keep the local draft intact.+ }+ finally {+ setIsPublishing(false)+ }+ }, [debouncedSaveDraft, saveComposer])++ return {+ draftSavedAt,+ isPublishing,+ publishDraft,+ saveDraft,+ }+}diff --git a/web/features/agent-v2/agent-detail/layout.tsx b/web/features/agent-v2/agent-detail/layout.tsxnew file mode 100644index 00000000000..863a30e24fb--- /dev/null+++ b/web/features/agent-v2/agent-detail/layout.tsx@@ -0,0 +1,36 @@+'use client'++import type { ReactNode } from 'react'+import { useQuery } from '@tanstack/react-query'+import { useTranslation } from 'react-i18next'+import useDocumentTitle from '@/hooks/use-document-title'+import { consoleQuery } from '@/service/client'++type AgentDetailLayoutProps = {+ agentId: string+ children: ReactNode+}++export function AgentDetailLayout({+ agentId,+ children,+}: AgentDetailLayoutProps) {+ const { t } = useTranslation('agentV2')+ const agentQuery = useQuery(consoleQuery.agent.byAgentId.get.queryOptions({+ input: {+ params: {+ agent_id: agentId,+ },+ },+ }))++ useDocumentTitle(agentQuery.data?.name ?? t('agentDetail.documentTitle'))++ return (+ <main className="relative flex h-full min-w-0 flex-col overflow-hidden">+ <div className="min-h-0 min-w-0 flex-1 overflow-auto">+ {children}+ </div>+ </main>+ )+}diff --git a/web/features/agent-v2/agent-detail/logs/mock-data.ts b/web/features/agent-v2/agent-detail/logs/mock-data.tsnew file mode 100644index 00000000000..b415a2d6c67--- /dev/null+++ b/web/features/agent-v2/agent-detail/logs/mock-data.ts@@ -0,0 +1,376 @@+import type { I18nKeysWithPrefix } from '@/types/i18n'++export type PeriodKey = 'last7days' | 'last30days' | 'allTime'+export type SourceKey = 'all' | 'webapp' | 'workflow'++export type FilterOption<T extends string> = {+ value: T+ labelKey: I18nKeysWithPrefix<'agentV2', 'agentDetail.logs.'>+}++type AgentLogRow = {+ id: string+ title: string+ endUser: string+ messageCount: number+ userRate: string+ operationRate: string+ updatedTime: string+ createdTime: string+ source: Exclude<SourceKey, 'all'>+ unread?: boolean+}++export const periodOptions: Array<FilterOption<PeriodKey>> = [+ { value: 'last7days', labelKey: 'agentDetail.logs.filters.period.last7days' },+ { value: 'last30days', labelKey: 'agentDetail.logs.filters.period.last30days' },+ { value: 'allTime', labelKey: 'agentDetail.logs.filters.period.allTime' },+]++export const sourceOptions: Array<FilterOption<SourceKey>> = [+ { value: 'all', labelKey: 'agentDetail.logs.filters.source.all' },+ { value: 'webapp', labelKey: 'agentDetail.logs.filters.source.webapp' },+ { value: 'workflow', labelKey: 'agentDetail.logs.filters.source.workflow' },+]++const LOG_ROW_COUNT = 5400+const LOG_INTERVAL_MINUTES = 2+const baseLogTime = new Date(2023, 2, 21, 10, 25)+const periodDays: Partial<Record<PeriodKey, number>> = {+ last7days: 7,+ last30days: 30,+}++const logTemplates: AgentLogRow[] = [+ {+ id: 'log_001',+ title: 'Asking about Dify agent orchestration best practices',+ endUser: '94924171-e6b0-4076-8f54-71d4370af8ef',+ messageCount: 2,+ userRate: 'N/A',+ operationRate: 'N/A',+ updatedTime: '2023-03-21 10:25',+ createdTime: '2023-03-21 10:25',+ source: 'webapp',+ unread: true,+ },+ {+ id: 'log_002',+ title: 'Alice, our user, talks about prompt orchestration techniques',+ endUser: 'N/A',+ messageCount: 3,+ userRate: 'N/A',+ operationRate: 'N/A',+ updatedTime: '2023-03-21 10:25',+ createdTime: '2023-03-21 10:25',+ source: 'workflow',+ unread: true,+ },+ {+ id: 'log_003',+ title: 'How to self-host a Dify chatbot for an internal team',+ endUser: '94924171-e6b0-4076-8f54-71d4370af8ef',+ messageCount: 5,+ userRate: 'N/A',+ operationRate: 'N/A',+ updatedTime: '2023-03-21 10:25',+ createdTime: '2023-03-21 10:25',+ source: 'webapp',+ unread: true,+ },+ {+ id: 'log_004',+ title: 'Requesting information about dataset retrieval settings',+ endUser: '94924171-e6b0-4076-8f54-71d4370af8ef',+ messageCount: 1,+ userRate: 'N/A',+ operationRate: 'N/A',+ updatedTime: '2023-03-21 10:25',+ createdTime: '2023-03-21 10:25',+ source: 'workflow',+ unread: true,+ },+ {+ id: 'log_005',+ title: 'Exploring options for connecting external knowledge bases',+ endUser: 'N/A',+ messageCount: 3,+ userRate: 'N/A',+ operationRate: 'N/A',+ updatedTime: '2023-03-21 10:25',+ createdTime: '2023-03-21 10:25',+ source: 'webapp',+ unread: true,+ },+ {+ id: 'log_006',+ title: 'What types of plugin tools can be used in workflows?',+ endUser: '94924171-e6b0-4076-8f54-71d4370af8ef',+ messageCount: 2,+ userRate: 'N/A',+ operationRate: 'N/A',+ updatedTime: '2023-03-21 10:25',+ createdTime: '2023-03-21 10:25',+ source: 'workflow',+ unread: true,+ },+ {+ id: 'log_007',+ title: 'Querying about Dify cloud deployment requirements',+ endUser: '94924171-e6b0-4076-8f54-71d4370af8ef',+ messageCount: 2,+ userRate: 'N/A',+ operationRate: 'N/A',+ updatedTime: '2023-03-21 10:25',+ createdTime: '2023-03-21 10:25',+ source: 'webapp',+ unread: true,+ },+ {+ id: 'log_008',+ title: 'Seeking assistance with YAML file setup',+ endUser: '94924171-e6b0-4076-8f54-71d4370af8ef',+ messageCount: 2,+ userRate: 'N/A',+ operationRate: 'N/A',+ updatedTime: '2023-03-21 10:25',+ createdTime: '2023-03-21 10:25',+ source: 'workflow',+ unread: true,+ },+ {+ id: 'log_009',+ title: 'Inquiring about compatibility with external APIs',+ endUser: '94924171-e6b0-4076-8f54-71d4370af8ef',+ messageCount: 5,+ userRate: 'N/A',+ operationRate: 'N/A',+ updatedTime: '2023-03-21 10:25',+ createdTime: '2023-03-21 10:25',+ source: 'webapp',+ unread: true,+ },+ {+ id: 'log_010',+ title: 'Can Dify integrate with my existing CRM?',+ endUser: '94924171-e6b0-4076-8f54-71d4370af8ef',+ messageCount: 2,+ userRate: 'N/A',+ operationRate: 'N/A',+ updatedTime: '2023-03-21 10:25',+ createdTime: '2023-03-21 10:25',+ source: 'workflow',+ unread: true,+ },+ {+ id: 'log_011',+ title: 'Exploring options for customizing chatbot responses',+ endUser: '94924171-e6b0-4076-8f54-71d4370af8ef',+ messageCount: 2,+ userRate: 'N/A',+ operationRate: 'N/A',+ updatedTime: '2023-03-21 10:25',+ createdTime: '2023-03-21 10:25',+ source: 'webapp',+ unread: true,+ },+ {+ id: 'log_012',+ title: 'Understanding data management and security in Dify',+ endUser: '94924171-e6b0-4076-8f54-71d4370af8ef',+ messageCount: 2,+ userRate: 'N/A',+ operationRate: 'N/A',+ updatedTime: '2023-03-21 10:25',+ createdTime: '2023-03-21 10:25',+ source: 'workflow',+ unread: true,+ },+ {+ id: 'log_013',+ title: 'Learning about available resources for getting started with Dify',+ endUser: '94924171-e6b0-4076-8f54-71d4370af8ef',+ messageCount: 2,+ userRate: 'N/A',+ operationRate: 'N/A',+ updatedTime: '2023-03-21 10:25',+ createdTime: '2023-03-21 10:25',+ source: 'webapp',+ unread: true,+ },+ {+ id: 'log_014',+ title: 'What are the best practices for optimizing prompts?',+ endUser: '94924171-e6b0-4076-8f54-71d4370af8ef',+ messageCount: 2,+ userRate: 'N/A',+ operationRate: 'N/A',+ updatedTime: '2023-03-21 10:25',+ createdTime: '2023-03-21 10:25',+ source: 'workflow',+ unread: true,+ },+ {+ id: 'log_015',+ title: 'How do I monitor the performance of my AI applications?',+ endUser: '94924171-e6b0-4076-8f54-71d4370af8ef',+ messageCount: 2,+ userRate: 'N/A',+ operationRate: 'N/A',+ updatedTime: '2023-03-21 10:25',+ createdTime: '2023-03-21 10:25',+ source: 'webapp',+ unread: true,+ },+ {+ id: 'log_016',+ title: 'Is there a free trial available for Dify?',+ endUser: '94924171-e6b0-4076-8f54-71d4370af8ef',+ messageCount: 2,+ userRate: 'N/A',+ operationRate: 'N/A',+ updatedTime: '2023-03-21 10:25',+ createdTime: '2023-03-21 10:25',+ source: 'workflow',+ unread: true,+ },+ {+ id: 'log_017',+ title: 'How can I improve user satisfaction metrics with Dify?',+ endUser: '94924171-e6b0-4076-8f54-71d4370af8ef',+ messageCount: 2,+ userRate: 'N/A',+ operationRate: 'N/A',+ updatedTime: '2023-03-21 10:25',+ createdTime: '2023-03-21 10:25',+ source: 'webapp',+ unread: true,+ },+ {+ id: 'log_018',+ title: 'Are there any upcoming features or improvements in Dify?',+ endUser: '94924171-e6b0-4076-8f54-71d4370af8ef',+ messageCount: 2,+ userRate: 'N/A',+ operationRate: 'N/A',+ updatedTime: '2023-03-21 10:25',+ createdTime: '2023-03-21 10:25',+ source: 'workflow',+ unread: true,+ },+ {+ id: 'log_019',+ title: 'What are the recommended steps to deploy a Dify chatbot?',+ endUser: '94924171-e6b0-4076-8f54-71d4370af8ef',+ messageCount: 2,+ userRate: 'N/A',+ operationRate: 'N/A',+ updatedTime: '2023-03-21 10:25',+ createdTime: '2023-03-21 10:25',+ source: 'webapp',+ unread: true,+ },+]++const formatDateTime = (date: Date) => {+ const year = date.getFullYear()+ const month = String(date.getMonth() + 1).padStart(2, '0')+ const day = String(date.getDate()).padStart(2, '0')+ const hour = String(date.getHours()).padStart(2, '0')+ const minute = String(date.getMinutes()).padStart(2, '0')++ return `${year}-${month}-${day} ${hour}:${minute}`+}++const formatLogTime = (index: number, offset: number) => {+ const logTime = new Date(baseLogTime)+ logTime.setMinutes(logTime.getMinutes() - index * LOG_INTERVAL_MINUTES - offset)++ return formatDateTime(logTime)+}++const getPeriodThreshold = (period: PeriodKey) => {+ const days = periodDays[period]++ if (!days)+ return undefined++ const threshold = new Date(baseLogTime)+ threshold.setDate(threshold.getDate() - days)++ return formatDateTime(threshold)+}++const logRows: AgentLogRow[] = Array.from({ length: LOG_ROW_COUNT }, (_, index) => {+ const template = logTemplates[index % logTemplates.length]!++ return {+ ...template,+ id: `${template.id}_${index + 1}`,+ messageCount: template.messageCount + (index % 4),+ updatedTime: formatLogTime(index, 0),+ createdTime: formatLogTime(index, 3),+ }+})++export function getOption<T extends string>(options: Array<FilterOption<T>>, value: T) {+ return options.find(option => option.value === value) ?? options[0]!+}++export function getSortParts(sortBy: string) {+ return {+ sortOrder: sortBy.startsWith('-') ? '-' : '',+ sortValue: sortBy.replace('-', '') || 'created_at',+ }+}++export function getAgentLogRowsView({+ period,+ source,+ keyword,+ sortBy,+ page,+ limit,+}: {+ period: PeriodKey+ source: SourceKey+ keyword: string+ sortBy: string+ page: number+ limit: number+}) {+ const normalizedKeyword = keyword.trim().toLowerCase()+ const periodThreshold = getPeriodThreshold(period)+ const filteredRows = logRows.filter((log) => {+ const matchesPeriod = !periodThreshold || log.createdTime >= periodThreshold+ const matchesSource = source === 'all' || log.source === source+ const matchesKeyword = !normalizedKeyword || [+ log.title,+ log.endUser,+ String(log.messageCount),+ log.updatedTime,+ log.createdTime,+ ].some(value => value.toLowerCase().includes(normalizedKeyword))++ return matchesPeriod && matchesSource && matchesKeyword+ })+ const { sortOrder, sortValue } = getSortParts(sortBy)+ const sortField = sortValue === 'updated_at' ? 'updatedTime' : 'createdTime'+ const sortDirection = sortOrder ? -1 : 1+ const sortedRows = [...filteredRows].sort((a, b) => {+ const timeSort = a[sortField].localeCompare(b[sortField]) * sortDirection++ if (timeSort !== 0)+ return timeSort++ return a.title.localeCompare(b.title) * sortDirection+ })+ const totalPages = Math.max(Math.ceil(sortedRows.length / limit), 1)+ const currentPage = Math.min(page, totalPages)++ return {+ currentPage,+ totalPages,+ rows: sortedRows.slice((currentPage - 1) * limit, currentPage * limit),+ }+}diff --git a/web/features/agent-v2/agent-detail/logs/page.tsx b/web/features/agent-v2/agent-detail/logs/page.tsxnew file mode 100644index 00000000000..15d4b5f750d--- /dev/null+++ b/web/features/agent-v2/agent-detail/logs/page.tsx@@ -0,0 +1,345 @@+'use client'++import type { TdHTMLAttributes, ThHTMLAttributes } from 'react'+import type {+ PeriodKey,+ SourceKey,+} from './mock-data'+import { cn } from '@langgenius/dify-ui/cn'+import { Pagination } from '@langgenius/dify-ui/pagination'+import {+ ScrollAreaContent,+ ScrollAreaRoot,+ ScrollAreaScrollbar,+ ScrollAreaThumb,+ ScrollAreaViewport,+} from '@langgenius/dify-ui/scroll-area'+import { Select, SelectContent, SelectItem, SelectItemIndicator, SelectItemText, SelectTrigger } from '@langgenius/dify-ui/select'+import { useState } from 'react'+import { useTranslation } from 'react-i18next'+import Chip from '@/app/components/base/chip'+import { SearchInput } from '@/app/components/base/search-input'+import Sort from '@/app/components/base/sort'+import { useDocLink } from '@/context/i18n'+import {+ getAgentLogRowsView,+ getOption,+ getSortParts,+ periodOptions,+ sourceOptions,+} from './mock-data'++export function AgentLogsPage() {+ const { t } = useTranslation('agentV2')+ const { t: tCommon } = useTranslation('common')+ const docLink = useDocLink()+ const [period, setPeriod] = useState<PeriodKey>('last7days')+ const [source, setSource] = useState<SourceKey>('all')+ const [keyword, setKeyword] = useState('')+ const [sortBy, setSortBy] = useState('-created_at')+ const [page, setPage] = useState(2)+ const [limit, setLimit] = useState(25)++ const selectedSource = getOption(sourceOptions, source)+ const { sortOrder, sortValue } = getSortParts(sortBy)+ const tableHeaderLabels = {+ unread: t('agentDetail.logs.table.unread'),+ title: t('agentDetail.logs.table.title'),+ endUser: t('agentDetail.logs.table.endUser'),+ messageCount: t('agentDetail.logs.table.messageCount'),+ userRate: t('agentDetail.logs.table.userRate'),+ operationRate: t('agentDetail.logs.table.operationRate'),+ updatedTime: t('agentDetail.logs.table.updatedTime'),+ createdTime: t('agentDetail.logs.table.createdTime'),+ }+ const periodItems = periodOptions.map(option => ({+ value: option.value,+ name: t(option.labelKey),+ }))+ const {+ currentPage,+ totalPages,+ rows,+ } = getAgentLogRowsView({+ period,+ source,+ keyword,+ sortBy,+ page,+ limit,+ })++ return (+ <section+ aria-label={t('agentDetail.sections.logs')}+ className="flex h-full min-w-0 flex-1 flex-col overflow-hidden bg-components-panel-bg-blur"+ >+ <header className="h-26.5 shrink-0 px-6 pt-3 pb-2">+ <div className="min-w-0">+ <h2 className="system-xl-semibold text-text-primary">+ {t('agentDetail.logs.title')}+ </h2>+ <p className="mt-1 flex min-w-0 flex-wrap items-center gap-x-0.5 system-xs-regular text-text-tertiary">+ <span>{t('agentDetail.logs.description')}</span>+ <a+ href={docLink('/use-dify/monitor/logs')}+ target="_blank"+ rel="noreferrer"+ className="inline-flex shrink-0 items-center gap-0.5 rounded-sm text-text-accent hover:underline focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"+ >+ {t('agentDetail.logs.learnMore')}+ <span aria-hidden className="i-ri-external-link-line size-3" />+ </a>+ </p>+ </div>++ <div className="mt-3 flex min-w-0 items-center justify-between gap-3">+ <div className="flex min-w-0 flex-1 items-center gap-2">+ <Chip+ value={period}+ items={periodItems}+ leftIcon={<span aria-hidden className="i-ri-calendar-line block size-4 text-text-secondary" />}+ className="min-w-32"+ onSelect={(item) => {+ setPage(1)+ setPeriod(item.value)+ }}+ onClear={() => {+ setPage(1)+ setPeriod('allTime')+ }}+ />++ <Select+ value={source}+ onValueChange={(nextValue) => {+ if (nextValue) {+ setPage(1)+ setSource(nextValue as SourceKey)+ }+ }}+ >+ <SelectTrigger+ aria-label={t('agentDetail.logs.filters.source.label')}+ className="mt-0 w-fit max-w-full min-w-22"+ >+ {t(selectedSource.labelKey)}+ </SelectTrigger>+ <SelectContent popupClassName="w-80">+ {sourceOptions.map(option => (+ <SelectItem key={option.value} value={option.value}>+ <SelectItemText>{t(option.labelKey)}</SelectItemText>+ <SelectItemIndicator />+ </SelectItem>+ ))}+ </SelectContent>+ </Select>++ <SearchInput+ aria-label={t('agentDetail.logs.filters.search.label')}+ value={keyword}+ placeholder={t('agentDetail.logs.filters.search.placeholder')}+ className="w-50 shrink-0"+ onValueChange={(nextKeyword) => {+ setPage(1)+ setKeyword(nextKeyword)+ }}+ />+ </div>++ <Sort+ order={sortOrder}+ value={sortValue}+ items={[+ { value: 'created_at', name: t('agentDetail.logs.filters.sort.lastCreatedTime') },+ { value: 'updated_at', name: t('agentDetail.logs.filters.sort.lastUpdatedTime') },+ ]}+ onSelect={(value) => {+ setPage(1)+ setSortBy(value)+ }}+ />+ </div>+ </header>++ <div className="min-h-0 flex-1 px-6 pt-2 pb-3">+ <div className="flex h-full min-w-0 flex-col overflow-x-auto">+ <div className="min-w-[1212px] shrink-0">+ <table aria-hidden="true" className="w-full table-fixed border-collapse">+ <LogsTableColGroup />+ <LogsTableHeader labels={tableHeaderLabels} />+ </table>+ </div>++ <ScrollAreaRoot className="relative min-h-0 min-w-[1212px] flex-1 overflow-hidden">+ <ScrollAreaViewport+ aria-label={t('agentDetail.logs.title')}+ role="region"+ tabIndex={-1}+ className="overscroll-contain"+ >+ <ScrollAreaContent>+ <table className="w-full table-fixed border-collapse">+ <LogsTableColGroup />+ <LogsTableHeader labels={tableHeaderLabels} rowClassName="sr-only" />+ <tbody className="system-sm-regular text-text-secondary">+ {rows.length > 0+ ? rows.map(log => (+ <tr+ key={log.id}+ className="h-10 border-b border-divider-subtle hover:bg-background-default-hover"+ >+ <td className="px-0">+ <span className={cn(+ 'mx-auto block size-1.5 rounded-full',+ log.unread ? 'bg-util-colors-blue-blue-500' : 'bg-transparent',+ )}+ />+ </td>+ <TableCell className="system-sm-medium text-text-secondary">+ {log.title}+ </TableCell>+ <TableCell translate="no">+ {log.endUser}+ </TableCell>+ <TableCell>+ {log.messageCount}+ </TableCell>+ <TableCell className="text-text-quaternary">+ {log.userRate}+ </TableCell>+ <TableCell className="text-text-quaternary">+ {log.operationRate}+ </TableCell>+ <TableCell>+ {log.updatedTime}+ </TableCell>+ <TableCell>+ {log.createdTime}+ </TableCell>+ </tr>+ ))+ : (+ <tr className="h-20 border-b border-divider-subtle">+ <td colSpan={8} className="px-3 text-center text-text-tertiary">+ {t('agentDetail.logs.empty')}+ </td>+ </tr>+ )}+ </tbody>+ </table>+ </ScrollAreaContent>+ </ScrollAreaViewport>+ <ScrollAreaScrollbar className="data-[orientation=vertical]:translate-x-1">+ <ScrollAreaThumb />+ </ScrollAreaScrollbar>+ </ScrollAreaRoot>+ </div>+ </div>++ <Pagination+ page={currentPage}+ totalPages={totalPages}+ onPageChange={setPage}+ className="h-14 shrink-0 px-6 py-3"+ labels={{+ previous: tCommon('pagination.previous'),+ next: tCommon('pagination.next'),+ editPageNumber: (page, totalPages) => tCommon('pagination.editPageNumber', { page, totalPages }),+ pageNumberInput: tCommon('pagination.pageNumber'),+ }}+ pageSize={{+ value: limit,+ options: [10, 25, 50],+ onValueChange: (nextLimit) => {+ setPage(1)+ setLimit(nextLimit)+ },+ label: tCommon('pagination.perPage'),+ ariaLabel: tCommon('pagination.perPage'),+ }}+ />+ </section>+ )+}++type LogsTableHeaderLabels = {+ unread: string+ title: string+ endUser: string+ messageCount: string+ userRate: string+ operationRate: string+ updatedTime: string+ createdTime: string+}++function LogsTableHeader({+ labels,+ rowClassName,+}: {+ labels: LogsTableHeaderLabels+ rowClassName?: string+}) {+ return (+ <thead>+ <tr className={cn('h-7 bg-background-section-burn text-left system-xs-medium-uppercase text-text-tertiary', rowClassName)}>+ <th scope="col" className="rounded-l-lg px-0">+ <span className="sr-only">{labels.unread}</span>+ </th>+ <TableHead>{labels.title}</TableHead>+ <TableHead>{labels.endUser}</TableHead>+ <TableHead>{labels.messageCount}</TableHead>+ <TableHead>{labels.userRate}</TableHead>+ <TableHead>{labels.operationRate}</TableHead>+ <TableHead>{labels.updatedTime}</TableHead>+ <TableHead className="rounded-r-lg">{labels.createdTime}</TableHead>+ </tr>+ </thead>+ )+}++function LogsTableColGroup() {+ return (+ <colgroup>+ <col className="w-5" />+ <col className="w-[42%]" />+ <col className="w-[14%]" />+ <col className="w-24" />+ <col className="w-20" />+ <col className="w-18" />+ <col className="w-34" />+ <col className="w-34" />+ </colgroup>+ )+}++function TableHead({+ className,+ ...props+}: ThHTMLAttributes<HTMLTableCellElement>) {+ return (+ <th+ scope="col"+ className={cn('px-3 text-left whitespace-nowrap', className)}+ {...props}+ />+ )+}++function TableCell({+ children,+ className,+ ...props+}: TdHTMLAttributes<HTMLTableCellElement>) {+ return (+ <td+ className={cn('min-w-0 px-3 whitespace-nowrap', className)}+ {...props}+ >+ <div className="truncate">+ {children}+ </div>+ </td>+ )+}diff --git a/web/features/agent-v2/agent-detail/monitoring/chart-utils.ts b/web/features/agent-v2/agent-detail/monitoring/chart-utils.tsnew file mode 100644index 00000000000..2e34d74dd80--- /dev/null+++ b/web/features/agent-v2/agent-detail/monitoring/chart-utils.ts@@ -0,0 +1,252 @@+import type { EChartsOption } from 'echarts'+import dayjs from 'dayjs'+import { formatNumber } from '@/utils/format'++export type AgentMonitoringChartType = 'conversations' | 'endUsers' | 'tokenUsage'++export type AgentMonitoringChartRow = {+ date: string+ total_price?: number | string+} & Record<string, number | string | undefined>++type ColorType = 'green' | 'orange' | 'blue'++const colorTypeMap: Record<ColorType, { lineColor: string, bgColor: [string, string] }> = {+ green: {+ lineColor: 'rgba(6, 148, 162, 1)',+ bgColor: ['rgba(6, 148, 162, 0.2)', 'rgba(67, 174, 185, 0.08)'],+ },+ orange: {+ lineColor: 'rgba(255, 138, 76, 1)',+ bgColor: ['rgba(254, 145, 87, 0.2)', 'rgba(255, 138, 76, 0.1)'],+ },+ blue: {+ lineColor: 'rgba(28, 100, 242, 1)',+ bgColor: ['rgba(28, 100, 242, 0.3)', 'rgba(28, 100, 242, 0.1)'],+ },+}++const chartTypeColorMap: Record<AgentMonitoringChartType, ColorType> = {+ conversations: 'blue',+ endUsers: 'blue',+ tokenUsage: 'blue',+}++const commonDateFormat = 'MMM D, YYYY'+const axisDateFormat = 'MMM'++const sumValues = (rows: AgentMonitoringChartRow[], field: string) => {+ return rows.reduce((sum, row) => sum + Number(row[field] ?? 0), 0)+}++const getChartColors = (chartType: AgentMonitoringChartType) => colorTypeMap[chartTypeColorMap[chartType]]++const getMarkLineSeedData = (statisticsLength: number) => {+ const markLineLength = statisticsLength >= 2 ? statisticsLength - 2 : statisticsLength+ return ['', ...Array.from({ length: markLineLength }, () => '1'), '']+}++const getTooltipContent = (+ chartType: AgentMonitoringChartType,+ yField: string,+ params: { name: string, data?: AgentMonitoringChartRow },+) => {+ const row = params.data ?? { date: params.name }+ const value = row[yField] ?? 0++ if (chartType !== 'tokenUsage')+ return `<div style='color:#6B7280;font-size:12px'>${params.name}</div><div style='font-size:14px;color:#1F2A37'>${value}</div>`++ return `<div style='color:#6B7280;font-size:12px'>${params.name}</div>+ <div style='font-size:14px;color:#1F2A37'>${value}+ <span style='font-size:12px'>+ <span style='margin-left:4px;color:#6B7280'>(</span>+ <span style='color:#FF8A4C'>~$${row.total_price ?? 0}</span>+ <span style='color:#6B7280'>)</span>+ </span>+ </div>`+}++export const getDefaultChartData = ({+ key = 'count',+}: {+ start: string+ end: string+ key?: string+}) => {+ const values = [180, 198, 188, 286, 423, 345]++ return values.map((value, index) => ({+ date: dayjs('2024-01-01').add(index, 'month').format(commonDateFormat),+ [key]: value,+ total_price: '0.0000',+ }))+}++export const getChartValueField = (+ rows: AgentMonitoringChartRow[],+ valueKey?: string,+) => {+ if (valueKey)+ return valueKey++ return Object.keys(rows[0] ?? {}).find(name => name.includes('count')) ?? 'count'+}++/**+ * @public+ */+// TODO: Remove this marker after summary values are wired to monitoring cards.+export const getSummaryValue = ({+ chartType,+ rows,+ valueKey,+ isAvg,+ unit = '',+}: {+ chartType: AgentMonitoringChartType+ rows: AgentMonitoringChartRow[]+ valueKey: string+ isAvg?: boolean+ unit?: string+}) => {+ const value = sumValues(rows, valueKey)+ const summary = isAvg ? value / (rows.length || 1) : value++ if (chartType === 'tokenUsage') {+ const formattedUsage = summary < 1000+ ? summary+ : `${formatNumber(Math.round(summary / 1000))}k`++ return `${formattedUsage}`+ }++ return `${summary.toLocaleString()} ${unit}`.trim()+}++export const getTokenSummary = (rows: AgentMonitoringChartRow[]) => {+ const totalPrice = rows.reduce((sum, row) => sum + Number.parseFloat(String(row.total_price ?? '0')), 0)++ return totalPrice.toLocaleString('en-US', {+ style: 'currency',+ currency: 'USD',+ minimumFractionDigits: 4,+ })+}++export const buildChartOptions = ({+ rows,+ chartType,+ valueKey,+ yMax,+}: {+ rows: AgentMonitoringChartRow[]+ chartType: AgentMonitoringChartType+ valueKey: string+ yMax?: number+}): EChartsOption => {+ const xData = rows.map(({ date }) => date)+ const chartColors = getChartColors(chartType)+ const markLineSeedData = getMarkLineSeedData(rows.length)++ return {+ dataset: {+ dimensions: ['date', valueKey],+ source: rows,+ },+ grid: { top: 8, right: 36, bottom: 10, left: 25, containLabel: true },+ tooltip: {+ trigger: 'item',+ position: 'top',+ borderWidth: 0,+ },+ xAxis: [{+ type: 'category',+ boundaryGap: false,+ axisLabel: {+ color: '#9CA3AF',+ hideOverlap: true,+ overflow: 'break',+ formatter(value) {+ return dayjs(value).format(axisDateFormat)+ },+ },+ axisLine: { show: false },+ axisTick: { show: false },+ splitLine: {+ show: true,+ lineStyle: {+ color: '#F3F4F6',+ width: 1,+ type: [10, 10],+ },+ interval(index) {+ return index === 0 || index === xData.length - 1+ },+ },+ }, {+ position: 'bottom',+ boundaryGap: false,+ data: markLineSeedData,+ axisLabel: { show: false },+ axisLine: { show: false },+ axisTick: { show: false },+ splitLine: {+ show: true,+ lineStyle: {+ color: '#E5E7EB',+ },+ interval(_index, value) {+ return !!value+ },+ },+ }],+ yAxis: {+ max: yMax ?? 'dataMax',+ type: 'value',+ axisLabel: { color: '#9CA3AF', hideOverlap: true },+ splitLine: {+ lineStyle: {+ color: '#F3F4F6',+ },+ },+ },+ series: [+ {+ type: 'line',+ showSymbol: true,+ symbolSize: 4,+ lineStyle: {+ color: chartColors.lineColor,+ width: 2,+ },+ itemStyle: {+ color: chartColors.lineColor,+ },+ areaStyle: {+ color: {+ type: 'linear',+ x: 0,+ y: 0,+ x2: 0,+ y2: 1,+ colorStops: [{+ offset: 0,+ color: chartColors.bgColor[0],+ }, {+ offset: 1,+ color: chartColors.bgColor[1],+ }],+ global: false,+ },+ },+ tooltip: {+ padding: [8, 12, 8, 12],+ formatter(params) {+ return getTooltipContent(chartType, valueKey, params as { name: string, data?: AgentMonitoringChartRow })+ },+ },+ },+ ],+ }+}diff --git a/web/features/agent-v2/agent-detail/monitoring/chart.tsx b/web/features/agent-v2/agent-detail/monitoring/chart.tsxnew file mode 100644index 00000000000..a7ca45bae91--- /dev/null+++ b/web/features/agent-v2/agent-detail/monitoring/chart.tsx@@ -0,0 +1,84 @@+'use client'++import type { AgentMonitoringChartRow, AgentMonitoringChartType } from './chart-utils'+import type { I18nKeysWithPrefix } from '@/types/i18n'+import ReactECharts from 'echarts-for-react'+import { useTranslation } from 'react-i18next'+import { Infotip } from '@/app/components/base/infotip'+import {+ buildChartOptions,+ getChartValueField,+ getTokenSummary,+} from './chart-utils'++type AgentMonitoringChartProps = {+ titleKey: I18nKeysWithPrefix<'agentV2', 'agentDetail.monitoring.'>+ explanationKey: I18nKeysWithPrefix<'agentV2', 'agentDetail.monitoring.'>+ summaryValue: string+ rows: AgentMonitoringChartRow[]+ chartType: AgentMonitoringChartType+ valueKey?: string+ unitKey?: I18nKeysWithPrefix<'agentV2', 'agentDetail.monitoring.'>+ yMax?: number+}++export function AgentMonitoringChart({+ titleKey,+ explanationKey,+ summaryValue,+ rows,+ chartType,+ valueKey,+ unitKey,+ yMax,+}: AgentMonitoringChartProps) {+ const { t } = useTranslation('agentV2')+ const yField = getChartValueField(rows, valueKey)+ const tokenSummary = getTokenSummary(rows)+ const options = buildChartOptions({+ rows,+ chartType,+ valueKey: yField,+ yMax,+ })+ const isEmptySummary = summaryValue === '0' || summaryValue.startsWith('0 ')++ return (+ <article className="flex min-h-79 w-full min-w-0 flex-col rounded-xl border border-components-panel-border bg-components-chart-bg px-6 pt-6 pb-4 shadow-xs">+ <div className="min-w-0">+ <div className="flex min-w-0 items-center gap-1">+ <h3 className="truncate system-xs-semibold-uppercase text-text-secondary">+ {t(titleKey)}+ </h3>+ <Infotip aria-label={t(explanationKey)}>+ {t(explanationKey)}+ </Infotip>+ </div>+ </div>++ <div className="mt-2 mb-4 flex min-w-0 items-baseline gap-1">+ <div className={`truncate text-2xl leading-8 font-semibold ${isEmptySummary ? 'text-text-quaternary' : 'text-text-primary'}`}>+ {summaryValue}+ </div>+ {chartType !== 'tokenUsage' && unitKey && (+ <div className="truncate system-sm-regular text-text-secondary">+ {t(unitKey)}+ </div>+ )}+ {chartType === 'tokenUsage' && (+ <div className="truncate system-sm-regular text-text-secondary">+ {t('agentDetail.monitoring.tokenUsageConsumed')}+ {' '}+ <span className="text-util-colors-orange-orange-600">+ (~+ {tokenSummary}+ )+ </span>+ </div>+ )}+ </div>++ <ReactECharts option={options} style={{ height: 240 }} />+ </article>+ )+}diff --git a/web/features/agent-v2/agent-detail/monitoring/mock-data.ts b/web/features/agent-v2/agent-detail/monitoring/mock-data.tsnew file mode 100644index 00000000000..78a566fd6bf--- /dev/null+++ b/web/features/agent-v2/agent-detail/monitoring/mock-data.ts@@ -0,0 +1,85 @@+import type { AgentMonitoringChartRow } from './chart-utils'+import type { I18nKeysWithPrefix } from '@/types/i18n'+import { getDefaultChartData } from './chart-utils'++type AgentMonitoringMetric = {+ id: string+ titleKey: I18nKeysWithPrefix<'agentV2', 'agentDetail.monitoring.'>+ explanationKey: I18nKeysWithPrefix<'agentV2', 'agentDetail.monitoring.'>+ chartType: 'conversations' | 'endUsers' | 'tokenUsage'+ rows: AgentMonitoringChartRow[]+ summaryValue: string+ valueKey?: string+ unitKey?: I18nKeysWithPrefix<'agentV2', 'agentDetail.monitoring.'>+ yMax: number+}++export const getAgentMonitoringMetrics = ({+ start,+ end,+}: {+ start: string+ end: string+}): AgentMonitoringMetric[] => [+ {+ id: 'total-messages',+ titleKey: 'agentDetail.monitoring.metrics.totalMessages.title',+ explanationKey: 'agentDetail.monitoring.metrics.totalMessages.explanation',+ chartType: 'conversations',+ rows: getDefaultChartData({ start, end, key: 'messages' }),+ summaryValue: '250k',+ valueKey: 'messages',+ yMax: 500,+ },+ {+ id: 'active-users',+ titleKey: 'agentDetail.monitoring.metrics.activeUsers.title',+ explanationKey: 'agentDetail.monitoring.metrics.activeUsers.explanation',+ chartType: 'endUsers',+ rows: getDefaultChartData({ start, end, key: 'users' }),+ summaryValue: '20k',+ valueKey: 'users',+ yMax: 500,+ },+ {+ id: 'avg-session-interactions',+ titleKey: 'agentDetail.monitoring.metrics.avgSessionInteractions.title',+ explanationKey: 'agentDetail.monitoring.metrics.avgSessionInteractions.explanation',+ chartType: 'conversations',+ rows: getDefaultChartData({ start, end, key: 'interactions' }),+ summaryValue: '20k',+ valueKey: 'interactions',+ yMax: 500,+ },+ {+ id: 'token-output-speed',+ titleKey: 'agentDetail.monitoring.metrics.tokenOutputSpeed.title',+ explanationKey: 'agentDetail.monitoring.metrics.tokenOutputSpeed.explanation',+ chartType: 'conversations',+ rows: getDefaultChartData({ start, end, key: 'tps' }),+ summaryValue: '1087',+ valueKey: 'tps',+ unitKey: 'agentDetail.monitoring.units.tokenPerSecond',+ yMax: 100,+ },+ {+ id: 'user-satisfaction-rate',+ titleKey: 'agentDetail.monitoring.metrics.userSatisfactionRate.title',+ explanationKey: 'agentDetail.monitoring.metrics.userSatisfactionRate.explanation',+ chartType: 'endUsers',+ rows: getDefaultChartData({ start, end, key: 'rate' }),+ summaryValue: '0',+ valueKey: 'rate',+ yMax: 1000,+ },+ {+ id: 'token-usage',+ titleKey: 'agentDetail.monitoring.metrics.tokenUsage.title',+ explanationKey: 'agentDetail.monitoring.metrics.tokenUsage.explanation',+ chartType: 'tokenUsage',+ rows: getDefaultChartData({ start, end, key: 'tokens' }),+ summaryValue: '1087',+ valueKey: 'tokens',+ yMax: 100,+ },+]diff --git a/web/features/agent-v2/agent-detail/monitoring/page.tsx b/web/features/agent-v2/agent-detail/monitoring/page.tsxnew file mode 100644index 00000000000..6dedc0de4bc--- /dev/null+++ b/web/features/agent-v2/agent-detail/monitoring/page.tsx@@ -0,0 +1,142 @@+'use client'++import type { AgentAccessSource } from '../access/access-sources'+import { ScrollArea } from '@langgenius/dify-ui/scroll-area'+import { useQuery } from '@tanstack/react-query'+import dayjs from 'dayjs'+import { useState } from 'react'+import { useTranslation } from 'react-i18next'+import Chip from '@/app/components/base/chip'+import { useDocLink } from '@/context/i18n'+import { consoleQuery } from '@/service/client'+import { getAgentAccessSources } from '../access/access-sources'+import { AgentMonitoringChart } from './chart'+import { getAgentMonitoringMetrics } from './mock-data'+import { AgentMonitoringTimeRangePicker } from './time-range-picker'++type SourceFilterValue = 'all' | AgentAccessSource['id']+type AgentMonitoringPageProps = {+ agentId: string+}++const queryDateFormat = 'YYYY-MM-DD HH:mm'++const getDefaultPeriodQuery = () => {+ const start = dayjs().startOf('day')+ const end = dayjs().endOf('day')++ return {+ start: start.format(queryDateFormat),+ end: end.format(queryDateFormat),+ }+}++const getSourceValue = (source: AgentAccessSource): SourceFilterValue => source.id++export function AgentMonitoringPage({+ agentId,+}: AgentMonitoringPageProps) {+ const { t } = useTranslation('agentV2')+ const docLink = useDocLink()+ const [period, setPeriod] = useState(() => ({+ name: t('agentDetail.monitoring.timeRanges.today'),+ query: getDefaultPeriodQuery(),+ }))+ const [sourceFilter, setSourceFilter] = useState<SourceFilterValue>('all')+ const agentQuery = useQuery(consoleQuery.agent.byAgentId.get.queryOptions({+ input: {+ params: {+ agent_id: agentId,+ },+ },+ }))+ const accessSources = getAgentAccessSources(agentQuery.data)+ const sourceItems = [+ {+ value: 'all' as const,+ name: t('agentDetail.monitoring.sources.all'),+ triggerName: t('agentDetail.monitoring.sourceTrigger', {+ name: t('agentDetail.monitoring.sources.all'),+ }),+ },+ ...accessSources.map(source => ({+ value: getSourceValue(source),+ name: t(source.nameKey),+ triggerName: t('agentDetail.monitoring.sourceTrigger', {+ name: t(source.nameKey),+ }),+ })),+ ]+ const metrics = getAgentMonitoringMetrics(period.query)++ return (+ <section+ aria-label={t('agentDetail.sections.monitoring')}+ className="flex h-full min-w-0 flex-1 flex-col overflow-hidden bg-components-panel-bg-blur"+ >+ <header className="h-26.5 shrink-0 px-6 pt-3 pb-2">+ <div className="min-w-0">+ <h2 className="system-xl-semibold text-text-primary">+ {t('agentDetail.monitoring.title')}+ </h2>+ <p className="mt-1 flex min-w-0 flex-wrap items-center gap-x-0.5 system-xs-regular text-text-tertiary">+ <span>{t('agentDetail.monitoring.description')}</span>+ <a+ href={docLink('/use-dify/monitor/logs')}+ target="_blank"+ rel="noreferrer"+ className="inline-flex shrink-0 items-center gap-0.5 rounded-sm text-text-accent hover:underline focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"+ >+ {t('agentDetail.monitoring.learnMore')}+ <span aria-hidden className="i-ri-external-link-line size-3" />+ </a>+ </p>+ </div>++ <div className="mt-3 flex min-w-0 flex-wrap items-center gap-2">+ <AgentMonitoringTimeRangePicker+ value={period}+ onChange={setPeriod}+ />++ <Chip+ showLeftIcon={false}+ className="min-w-53"+ panelClassName="w-61"+ value={sourceFilter}+ items={sourceItems}+ onSelect={(item) => {+ setSourceFilter(item.value)+ }}+ onClear={() => {+ setSourceFilter('all')+ }}+ />+ </div>+ </header>++ <ScrollArea+ className="min-h-0 flex-1 overflow-hidden"+ slotClassNames={{+ content: 'px-6 pt-2 pb-3',+ }}+ >+ <div className="grid w-full grid-cols-1 gap-3 xl:grid-cols-2">+ {metrics.map(metric => (+ <AgentMonitoringChart+ key={metric.id}+ titleKey={metric.titleKey}+ explanationKey={metric.explanationKey}+ summaryValue={metric.summaryValue}+ rows={metric.rows}+ chartType={metric.chartType}+ valueKey={metric.valueKey}+ unitKey={metric.unitKey}+ yMax={metric.yMax}+ />+ ))}+ </div>+ </ScrollArea>+ </section>+ )+}diff --git a/web/features/agent-v2/agent-detail/monitoring/time-range-picker.tsx b/web/features/agent-v2/agent-detail/monitoring/time-range-picker.tsxnew file mode 100644index 00000000000..9f23663ac5d--- /dev/null+++ b/web/features/agent-v2/agent-detail/monitoring/time-range-picker.tsx@@ -0,0 +1,228 @@+'use client'++import type { Dayjs } from 'dayjs'+import type { TriggerProps } from '@/app/components/base/date-and-time-picker/types'+import type { I18nKeysWithPrefix } from '@/types/i18n'+import { cn } from '@langgenius/dify-ui/cn'+import { Select, SelectContent, SelectItem, SelectItemIndicator, SelectItemText, SelectTrigger } from '@langgenius/dify-ui/select'+import dayjs from 'dayjs'+import { noop } from 'es-toolkit/function'+import { useState } from 'react'+import { useTranslation } from 'react-i18next'+import DatePicker from '@/app/components/base/date-and-time-picker/date-picker'+import { useLocale } from '@/context/i18n'+import { formatToLocalTime } from '@/utils/format'++export type AgentMonitoringPeriod = {+ name: string+ query: {+ start: string+ end: string+ }+}++type TimeRangeKey = 'today' | 'last7days' | 'last30days'++type TimeRangeOption = {+ value: TimeRangeKey+ days: number+ nameKey: I18nKeysWithPrefix<'agentV2', 'agentDetail.monitoring.timeRanges.'>+}++type AgentMonitoringTimeRangePickerProps = {+ value: AgentMonitoringPeriod+ onChange: (period: AgentMonitoringPeriod) => void+}++const today = dayjs()+const queryDateFormat = 'YYYY-MM-DD HH:mm'++const timeRangeOptions: TimeRangeOption[] = [+ { value: 'today', days: 0, nameKey: 'agentDetail.monitoring.timeRanges.today' },+ { value: 'last7days', days: 7, nameKey: 'agentDetail.monitoring.timeRanges.last7days' },+ { value: 'last30days', days: 30, nameKey: 'agentDetail.monitoring.timeRanges.last30days' },+]++const getRangePeriod = (option: TimeRangeOption): AgentMonitoringPeriod => {+ const end = today.endOf('day')+ const start = option.days === 0+ ? today.startOf('day')+ : today.subtract(option.days, 'day').startOf('day')++ return {+ name: option.value,+ query: {+ start: start.format(queryDateFormat),+ end: end.format(queryDateFormat),+ },+ }+}++function DateRangePart({+ start,+ end,+ onStartChange,+ onEndChange,+}: {+ start: Dayjs+ end: Dayjs+ onStartChange: (date?: Dayjs) => void+ onEndChange: (date?: Dayjs) => void+}) {+ const locale = useLocale()++ const renderDate = ({ value, handleClickTrigger, isOpen }: TriggerProps) => (+ <div+ role="button"+ tabIndex={0}+ data-open={isOpen ? 'true' : undefined}+ className={cn(+ 'flex h-7 cursor-pointer items-center rounded-lg px-1 system-sm-regular text-components-input-text-filled hover:bg-state-base-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden data-[open=true]:bg-state-base-hover',+ )}+ onClick={handleClickTrigger}+ onKeyDown={(event) => {+ if (event.key !== 'Enter' && event.key !== ' ')+ return++ event.preventDefault()+ event.currentTarget.click()+ }}+ >+ {value ? formatToLocalTime(value, locale, 'MMM D') : ''}+ </div>+ )++ const availableStartDate = end.subtract(30, 'day')+ const isStartDateDisabled = (date: Dayjs) => {+ if (date.isAfter(today, 'date'))+ return true++ return !((date.isAfter(availableStartDate, 'date') || date.isSame(availableStartDate, 'date')) && (date.isBefore(end, 'date') || date.isSame(end, 'date')))+ }++ const availableEndDate = start.add(30, 'day')+ const isEndDateDisabled = (date: Dayjs) => {+ if (date.isAfter(today, 'date'))+ return true++ return !((date.isAfter(start, 'date') || date.isSame(start, 'date')) && (date.isBefore(availableEndDate, 'date') || date.isSame(availableEndDate, 'date')))+ }++ return (+ <div className="flex h-8 items-center space-x-0.5 rounded-lg bg-components-input-bg-normal px-2">+ <span aria-hidden className="i-ri-calendar-line size-3.5 text-text-tertiary" />+ <DatePicker+ value={start}+ onChange={onStartChange}+ renderTrigger={renderDate}+ needTimePicker={false}+ onClear={noop}+ noConfirm+ getIsDateDisabled={isStartDateDisabled}+ />+ <span className="system-sm-regular text-text-tertiary">-</span>+ <DatePicker+ value={end}+ onChange={onEndChange}+ renderTrigger={renderDate}+ needTimePicker={false}+ onClear={noop}+ noConfirm+ getIsDateDisabled={isEndDateDisabled}+ />+ </div>+ )+}++export function AgentMonitoringTimeRangePicker({+ value,+ onChange,+}: AgentMonitoringTimeRangePickerProps) {+ const { t } = useTranslation('agentV2')+ const locale = useLocale()+ const [selectedRange, setSelectedRange] = useState<TimeRangeKey | 'custom'>('today')+ const [start, setStart] = useState(() => dayjs(value.query.start))+ const [end, setEnd] = useState(() => dayjs(value.query.end))++ const selectedOption = timeRangeOptions.find(option => option.value === selectedRange)++ const handleRangeChange = (nextValue: string | null) => {+ if (!nextValue)+ return++ const option = timeRangeOptions.find(item => item.value === nextValue)+ if (!option)+ return++ const nextPeriod = getRangePeriod(option)+ setSelectedRange(option.value)+ setStart(dayjs(nextPeriod.query.start))+ setEnd(dayjs(nextPeriod.query.end))+ onChange({+ ...nextPeriod,+ name: t(option.nameKey),+ })+ }++ const handleDateChange = (type: 'start' | 'end') => (date?: Dayjs) => {+ if (!date)+ return++ if (type === 'start' && date.isSame(start))+ return++ if (type === 'end' && date.isSame(end))+ return++ const nextStart = type === 'start' ? date : start+ const nextEnd = type === 'end' ? date : end+ const nextName = `${formatToLocalTime(nextStart, locale, 'MMM D')} - ${formatToLocalTime(nextEnd, locale, 'MMM D')}`++ setSelectedRange('custom')+ setStart(nextStart)+ setEnd(nextEnd)+ onChange({+ name: nextName,+ query: {+ start: nextStart.format(queryDateFormat),+ end: nextEnd.format(queryDateFormat),+ },+ })+ }++ return (+ <div className="flex min-w-0 items-center">+ <Select+ value={selectedRange === 'custom' ? null : selectedRange}+ onValueChange={handleRangeChange}+ >+ <SelectTrigger+ aria-label={t('agentDetail.monitoring.timeRangeLabel')}+ className="mt-0 h-auto w-20 shrink-0 border-0 bg-transparent p-0 hover:bg-transparent focus-visible:bg-transparent [&>*:last-child]:hidden"+ >+ <div className="flex h-8 w-full cursor-pointer items-center justify-between rounded-lg bg-components-input-bg-normal pr-2 pl-3 group-data-popup-open:bg-state-base-hover-alt">+ <div className="system-sm-regular text-components-input-text-filled">+ {selectedRange === 'custom' ? t('agentDetail.monitoring.timeRanges.custom') : selectedOption ? t(selectedOption.nameKey) : value.name}+ </div>+ <span aria-hidden className="i-ri-arrow-down-s-line size-4 text-text-quaternary group-data-popup-open:text-text-secondary" />+ </div>+ </SelectTrigger>+ <SelectContent className="translate-x-[-24px]" popupClassName="w-50" listClassName="p-1">+ {timeRangeOptions.map(option => (+ <SelectItem key={option.value} value={option.value} className="h-8 py-0 pr-2 pl-7 system-md-regular">+ <SelectItemText className="px-0">{t(option.nameKey)}</SelectItemText>+ <SelectItemIndicator className="absolute top-2 left-2 ml-0" />+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <span aria-hidden className="i-custom-vender-other-hourglass-shape h-3.5 w-2 text-components-input-bg-normal" />+ <DateRangePart+ start={start}+ end={end}+ onStartChange={handleDateChange('start')}+ onEndChange={handleDateChange('end')}+ />+ </div>+ )+}diff --git a/web/features/agent-v2/agent-detail/navigation.tsx b/web/features/agent-v2/agent-detail/navigation.tsxnew file mode 100644index 00000000000..44295e2ff31--- /dev/null+++ b/web/features/agent-v2/agent-detail/navigation.tsx@@ -0,0 +1,263 @@+'use client'++import type { AgentIconType } from '@dify/contracts/api/console/agent/types.gen'+import type { ComponentProps } from 'react'+import type { AgentDetailSectionKey } from './section'+import type { NavIcon } from '@/app/components/app-sidebar/nav-link'+import { cn } from '@langgenius/dify-ui/cn'+import { Kbd, KbdGroup } from '@langgenius/dify-ui/kbd'+import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'+import { formatForDisplay } from '@tanstack/react-hotkeys'+import { skipToken, useQuery } from '@tanstack/react-query'+import { useTranslation } from 'react-i18next'+import NavLink from '@/app/components/app-sidebar/nav-link'+import ToggleButton from '@/app/components/app-sidebar/toggle-button'+import AppIcon from '@/app/components/base/app-icon'+import Divider from '@/app/components/base/divider'+import SidebarLeftArrowIcon from '@/app/components/base/icons/src/vender/SidebarLeftArrowIcon'+import { useSetGotoAnythingOpen } from '@/app/components/goto-anything/atoms'+import Link from '@/next/link'+import { usePathname, useRouter } from '@/next/navigation'+import { consoleQuery } from '@/service/client'+import { getAgentDetailPath, getAgentIdFromPathname } from './routes'++type AgentDetailTopProps = {+ expand?: boolean+ onToggle?: () => void+}++type AgentDetailSectionProps = {+ expand?: boolean+}++type AgentDetailNavItem = {+ labelKey: `agentDetail.sections.${AgentDetailSectionKey}`+ href: string+ icon: NavIcon+ activeIcon: NavIcon+}++const SEARCH_SHORTCUT = ['Mod', 'K']++const createAgentNavIcon = (iconClassName: string) => {+ function AgentNavIcon({ className }: ComponentProps<'svg'>) {+ return <span aria-hidden className={cn(iconClassName, className)} />+ }++ return AgentNavIcon+}++const terminalWindowLineIcon = createAgentNavIcon('i-ri-terminal-window-line')+const terminalWindowFillIcon = createAgentNavIcon('i-ri-terminal-window-fill')+const accessPointIcon = createAgentNavIcon('i-custom-vender-agent-v2-access-point')+const fileListLineIcon = createAgentNavIcon('i-ri-file-list-3-line')+const fileListFillIcon = createAgentNavIcon('i-ri-file-list-3-fill')+const dashboardLineIcon = createAgentNavIcon('i-ri-dashboard-2-line')+const dashboardFillIcon = createAgentNavIcon('i-ri-dashboard-2-fill')++const getAgentDetailNavigation = (agentId: string): AgentDetailNavItem[] => [+ {+ labelKey: 'agentDetail.sections.configure',+ href: getAgentDetailPath(agentId, 'configure'),+ icon: terminalWindowLineIcon,+ activeIcon: terminalWindowFillIcon,+ },+ {+ labelKey: 'agentDetail.sections.access',+ href: getAgentDetailPath(agentId, 'access'),+ icon: accessPointIcon,+ activeIcon: accessPointIcon,+ },+ {+ labelKey: 'agentDetail.sections.logs',+ href: getAgentDetailPath(agentId, 'logs'),+ icon: fileListLineIcon,+ activeIcon: fileListFillIcon,+ },+ {+ labelKey: 'agentDetail.sections.monitoring',+ href: getAgentDetailPath(agentId, 'monitoring'),+ icon: dashboardLineIcon,+ activeIcon: dashboardFillIcon,+ },+]++export function AgentDetailTop({+ expand = true,+ onToggle,+}: AgentDetailTopProps) {+ const { t: tApp } = useTranslation('app')+ const { t: tCommon } = useTranslation('common')+ const router = useRouter()+ const setGotoAnythingOpen = useSetGotoAnythingOpen()++ if (!expand) {+ return (+ <div className="flex w-full items-center justify-center px-3 pt-2 pb-1">+ {onToggle && (+ <ToggleButton+ expand={expand}+ handleToggle={onToggle}+ icon={<SidebarLeftArrowIcon aria-hidden className="size-4" />}+ className="size-8 rounded-[10px] border-0 bg-transparent px-0 text-text-tertiary shadow-none hover:border-0 hover:bg-state-base-hover hover:text-text-secondary"+ />+ )}+ </div>+ )+ }++ return (+ <div className="flex items-center py-2 pr-2 pl-1">+ <div className="flex min-w-0 flex-1 items-center gap-px">+ <div className="flex shrink-0 items-center rounded-lg py-2 pr-1.5 pl-0.5 transition-colors hover:bg-background-default-hover">+ <button+ type="button"+ aria-label={tCommon('operation.back')}+ className="flex size-4 items-center justify-center text-text-tertiary hover:text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"+ onClick={() => router.back()}+ >+ <span aria-hidden className="i-ri-arrow-left-s-line size-4" />+ </button>+ <Link+ href="/"+ aria-label={tCommon('mainNav.home')}+ className="flex size-4 items-center justify-center text-text-tertiary hover:text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"+ >+ <span aria-hidden className="i-custom-vender-main-nav-app-home size-4" />+ </Link>+ </div>+ <span className="shrink-0 system-md-regular text-text-quaternary">+ /+ </span>+ <Link href="/roster" className="shrink-0 truncate rounded-lg px-1.5 py-2 system-sm-semibold-uppercase text-text-secondary transition-colors hover:bg-background-default-hover hover:text-text-primary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden">+ {tCommon('menus.roster')}+ </Link>+ </div>+ <Tooltip>+ <TooltipTrigger+ render={(+ <button+ type="button"+ aria-label={tApp('gotoAnything.searchTitle')}+ className="flex size-8 shrink-0 items-center justify-center overflow-hidden rounded-[10px] text-text-tertiary transition-colors hover:bg-state-base-hover hover:text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"+ onClick={() => setGotoAnythingOpen(true)}+ >+ <span aria-hidden className="i-custom-vender-main-nav-quick-search size-4" />+ </button>+ )}+ />+ <TooltipContent placement="bottom" className="flex items-center gap-1 rounded-lg border-[0.5px] border-components-panel-border bg-components-tooltip-bg p-1.5 system-xs-medium text-text-secondary shadow-lg backdrop-blur-[5px]">+ <span className="px-0.5">{tApp('gotoAnything.quickAction')}</span>+ <KbdGroup>+ {SEARCH_SHORTCUT.map(key => (+ <Kbd key={key}>{formatForDisplay(key)}</Kbd>+ ))}+ </KbdGroup>+ </TooltipContent>+ </Tooltip>+ {onToggle && (+ <ToggleButton+ expand={expand}+ handleToggle={onToggle}+ icon={<SidebarLeftArrowIcon aria-hidden className="size-4" />}+ className="size-8 rounded-[10px] border-0 bg-transparent px-0 text-text-tertiary shadow-none hover:border-0 hover:bg-state-base-hover hover:text-text-secondary"+ />+ )}+ </div>+ )+}++export function AgentDetailSection({+ expand = true,+}: AgentDetailSectionProps) {+ const { t } = useTranslation('agentV2')+ const pathname = usePathname()+ const agentId = getAgentIdFromPathname(pathname)+ const agentQuery = useQuery(consoleQuery.agent.byAgentId.get.queryOptions({+ input: agentId+ ? {+ params: {+ agent_id: agentId,+ },+ }+ : skipToken,+ }))++ if (!agentId)+ return null++ const navigation = getAgentDetailNavigation(agentId)+ const agent = agentQuery.data+ const imageUrl = (agent?.icon_type === 'image' || agent?.icon_type === 'link') ? agent.icon : undefined+ const iconType = (imageUrl ? 'image' : agent?.icon_type) as AgentIconType | null | undefined++ return (+ <div className={cn('flex min-h-0 flex-1 flex-col', expand ? 'px-2 pb-2' : 'pb-2')}>+ {!expand && (+ <div className="flex w-full shrink-0 justify-center px-3.5 pt-0.5 pb-[3px]">+ <Divider+ type="horizontal"+ bgStyle="solid"+ className="my-0 h-px w-[27px] bg-divider-subtle"+ />+ </div>+ )}+ <div className={cn('py-2', expand && '-mx-1')}>+ <div className={cn(+ 'flex h-13 items-center rounded-xl py-1.5 pr-2 pl-1.5',+ !expand && 'justify-center',+ )}+ >+ <div className={cn(+ 'shrink-0',+ expand && 'mr-2',+ )}+ >+ <span aria-hidden>+ <AppIcon+ size="large"+ rounded+ iconType={iconType}+ icon={agent?.icon ?? undefined}+ background={agent?.icon_background}+ imageUrl={imageUrl}+ />+ </span>+ </div>+ <div className={cn('flex h-10 min-w-0 flex-1 flex-col justify-center', !expand && 'hidden')}>+ <div className="truncate system-md-semibold text-text-secondary">+ {agent?.name ?? t('agentDetail.title')}+ </div>+ <div className="truncate system-2xs-medium-uppercase text-text-tertiary">+ {agent?.role ?? t('agentDetail.type')}+ </div>+ </div>+ </div>+ </div>+ <div className={cn(expand ? 'px-3 py-0.5' : 'px-1 py-0.5')}>+ <Divider+ type="horizontal"+ bgStyle={expand ? 'gradient' : 'solid'}+ className={cn(+ 'my-0 h-px',+ expand+ ? 'bg-linear-to-r from-divider-subtle to-background-gradient-mask-transparent'+ : 'bg-divider-subtle',+ )}+ />+ </div>+ <nav className={cn('flex flex-col gap-y-0.5 py-2', expand ? 'px-1' : 'px-3')} aria-label={t('agentDetail.navigationLabel')}>+ {navigation.map(item => (+ <NavLink+ key={item.href}+ mode={expand ? 'expand' : 'collapse'}+ iconMap={{ selected: item.activeIcon, normal: item.icon }}+ name={t(item.labelKey)}+ href={item.href}+ pathname={pathname}+ />+ ))}+ </nav>+ </div>+ )+}diff --git a/web/features/agent-v2/agent-detail/page.tsx b/web/features/agent-v2/agent-detail/page.tsxnew file mode 100644index 00000000000..7b23ece3869--- /dev/null+++ b/web/features/agent-v2/agent-detail/page.tsx@@ -0,0 +1,31 @@+'use client'++import type { AgentDetailSectionKey } from './section'+import { AgentAccessPage } from './access/page'+import { AgentConfigurePage } from './configure/page'+import { AgentLogsPage } from './logs/page'+import { AgentMonitoringPage } from './monitoring/page'++type AgentDetailPageProps = {+ agentId: string+ section: AgentDetailSectionKey+}++export function AgentDetailPage({+ agentId,+ section,+}: AgentDetailPageProps) {+ if (section === 'monitoring')+ return <AgentMonitoringPage agentId={agentId} />++ if (section === 'logs')+ return <AgentLogsPage />++ if (section === 'access')+ return <AgentAccessPage agentId={agentId} />++ if (section === 'configure')+ return <AgentConfigurePage agentId={agentId} />++ return null+}diff --git a/web/features/agent-v2/agent-detail/routes.ts b/web/features/agent-v2/agent-detail/routes.tsnew file mode 100644index 00000000000..313562f5c60--- /dev/null+++ b/web/features/agent-v2/agent-detail/routes.ts@@ -0,0 +1,15 @@+import type { AgentDetailSectionKey } from './section'++export const getAgentDetailPath = (+ agentId: string,+ section: AgentDetailSectionKey,+) => `/roster/agent/${agentId}/${section}`++export const getAgentIdFromPathname = (pathname: string) => {+ const [section, type, agentId] = pathname.split('/').filter(Boolean)++ if (section !== 'roster' || type !== 'agent')+ return undefined++ return agentId+}diff --git a/web/features/agent-v2/agent-detail/section.ts b/web/features/agent-v2/agent-detail/section.tsnew file mode 100644index 00000000000..9e242c01372--- /dev/null+++ b/web/features/agent-v2/agent-detail/section.ts@@ -0,0 +1 @@+export type AgentDetailSectionKey = 'configure' | 'access' | 'logs' | 'monitoring'diff --git a/web/features/agent-v2/feature-flag.ts b/web/features/agent-v2/feature-flag.tsnew file mode 100644index 00000000000..3b7e5589dc1--- /dev/null+++ b/web/features/agent-v2/feature-flag.ts@@ -0,0 +1,3 @@+import { env } from '@/env'++export const isAgentV2Enabled = () => env.NEXT_PUBLIC_ENABLE_AGENT_V2diff --git a/web/features/agent-v2/roster/components/__tests__/agent-roster-list.spec.tsx b/web/features/agent-v2/roster/components/__tests__/agent-roster-list.spec.tsxnew file mode 100644index 00000000000..85e0f0a9d79--- /dev/null+++ b/web/features/agent-v2/roster/components/__tests__/agent-roster-list.spec.tsx@@ -0,0 +1,140 @@+import type { ComponentProps } from 'react'+import type { AgentRosterListItem } from '../agent-roster-list'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { render, screen } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { AgentRosterList } from '../agent-roster-list'++vi.mock('@/hooks/use-timestamp', () => ({+ default: () => ({+ formatTime: () => '06/12/2026 12:00:00 PM',+ }),+}))++const createAgent = (overrides: Partial<AgentRosterListItem> = {}): AgentRosterListItem => ({+ active_config_is_published: false,+ description: 'Find and summarize market materials.',+ id: 'agent-1',+ icon_url: null,+ mode: 'agent',+ name: 'Research Agent',+ published_reference_count: 0,+ published_references: [],+ role: 'Research Assistant',+ ...overrides,+})++const renderList = (+ agents: AgentRosterListItem[],+ overrides: Partial<ComponentProps<typeof AgentRosterList>> = {},+) => {+ const queryClient = new QueryClient()++ return render(+ <QueryClientProvider client={queryClient}>+ <AgentRosterList+ agents={agents}+ hasMore={false}+ isEmptySearch={false}+ isError={false}+ isFetching={false}+ isFetchingNextPage={false}+ isPending={false}+ label="Agent roster list"+ onLoadMore={vi.fn()}+ {...overrides}+ />+ </QueryClientProvider>,+ )+}++describe('AgentRosterList', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ it('renders role under the card title instead of the agent mode', () => {+ renderList([createAgent()])++ expect(screen.getByText('Research Assistant')).toBeInTheDocument()+ expect(screen.queryByText('agent')).not.toBeInTheDocument()+ })++ it('uses the Figma-aligned card title and role typography', () => {+ renderList([createAgent()])++ expect(screen.getByRole('heading', { name: 'Research Agent' })).toHaveClass('system-md-semibold')+ expect(screen.getByText('Research Assistant')).toHaveClass('system-xs-regular')+ expect(screen.getByText('agentV2.roster.usageStatus.draft')).toHaveClass('system-2xs-medium-uppercase')+ })++ it('only renders the draft badge for unpublished agents', () => {+ renderList([+ createAgent({+ active_config_is_published: true,+ id: 'agent-published',+ name: 'Published Agent',+ published_reference_count: 1,+ }),+ createAgent({+ id: 'agent-draft',+ name: 'Draft Agent',+ published_reference_count: 0,+ }),+ ])++ expect(screen.getByText('agentV2.roster.usageStatus.draft')).toBeInTheDocument()+ expect(screen.getByRole('heading', { name: 'Published Agent' })).toBeInTheDocument()+ expect(screen.queryByText('agentV2.roster.usageStatus.inUse')).not.toBeInTheDocument()+ expect(screen.queryByText('agentV2.roster.status.active')).not.toBeInTheDocument()+ })++ it('renders the Figma-aligned empty roster overlay', () => {+ const { container } = renderList([])++ expect(screen.getByRole('heading', { name: 'agentV2.roster.empty' })).toHaveClass('system-sm-regular', 'text-text-tertiary')+ expect(container.querySelectorAll('.bg-background-default-lighter')).toHaveLength(16)+ expect(container.querySelector('.bg-linear-to-b')).toBeInTheDocument()+ expect(container.querySelector('.i-ri-robot-2-line')).toHaveClass('size-6', 'text-text-tertiary')+ })++ it('uses the same overlay treatment for empty search results', () => {+ const { container } = renderList([], { isEmptySearch: true })++ expect(screen.getByRole('heading', { name: 'agentV2.roster.emptySearch' })).toBeInTheDocument()+ expect(container.querySelectorAll('.bg-background-default-lighter')).toHaveLength(16)+ expect(screen.queryByText('agentV2.roster.emptySearchDescription')).not.toBeInTheDocument()+ })++ it('uses the same overlay treatment for loading errors', () => {+ const { container } = renderList([], { isError: true })++ expect(screen.getByRole('heading', { name: 'agentV2.roster.loadingError' })).toHaveClass('system-sm-regular', 'text-text-tertiary')+ expect(container.querySelectorAll('.bg-background-default-lighter')).toHaveLength(16)+ expect(container.querySelector('.bg-linear-to-b')).toBeInTheDocument()+ })++ it('opens published workflow references from the card reference trigger', async () => {+ const user = userEvent.setup()+ renderList([+ createAgent({+ published_reference_count: 1,+ published_references: [+ {+ app_id: 'workflow-app-id',+ app_icon: '🐍',+ app_icon_background: '#E9F8D8',+ app_icon_type: 'emoji',+ app_name: 'RFP Review Flow',+ },+ ],+ }),+ ])++ await user.click(screen.getByRole('button', { name: /agentV2\.roster\.references\.trigger/ }))++ const workflowLink = screen.getByRole('menuitem', { name: /RFP Review Flow/ })+ expect(workflowLink).toHaveAttribute('href', '/app/workflow-app-id/workflow')+ expect(screen.getByText(/agentV2\.roster\.references\.label/)).toBeInTheDocument()+ })+})diff --git a/web/features/agent-v2/roster/components/__tests__/create-agent-dialog.spec.tsx b/web/features/agent-v2/roster/components/__tests__/create-agent-dialog.spec.tsxnew file mode 100644index 00000000000..e340936678a--- /dev/null+++ b/web/features/agent-v2/roster/components/__tests__/create-agent-dialog.spec.tsx@@ -0,0 +1,114 @@+import { render, screen, within } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { CreateAgentDialog } from '../create-agent-dialog'++const mutationMock = vi.hoisted(() => ({+ isPending: false,+ mutate: vi.fn(),+}))++const toastMock = vi.hoisted(() => ({+ error: vi.fn(),+ success: vi.fn(),+}))++vi.mock('@tanstack/react-query', () => ({+ useMutation: () => ({+ isPending: mutationMock.isPending,+ mutate: mutationMock.mutate,+ }),+}))++vi.mock('@langgenius/dify-ui/toast', () => ({+ toast: toastMock,+}))++vi.mock('@/service/client', () => ({+ consoleQuery: {+ agent: {+ post: {+ mutationOptions: vi.fn(() => ({})),+ },+ },+ },+}))++describe('CreateAgentDialog', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mutationMock.isPending = false+ })++ it('submits agent app fields and default icon fields when creating an agent', async () => {+ const user = userEvent.setup()+ render(<CreateAgentDialog />)++ await user.click(screen.getByRole('button', { name: /agentV2\.roster\.createAgent/ }))++ const dialog = await screen.findByRole('dialog', { name: 'agentV2.roster.createDialog.title' })+ await user.type(within(dialog).getByRole('textbox', { name: 'agentV2.roster.createForm.nameLabel' }), ' Research Agent ')+ await user.type(within(dialog).getByRole('textbox', { name: 'agentV2.roster.createForm.roleLabel' }), ' Research Assistant ')+ await user.type(within(dialog).getByPlaceholderText('agentV2.roster.createForm.descriptionPlaceholder'), ' Find and summarize market materials. ')+ await user.click(within(dialog).getByRole('button', { name: 'common.operation.create' }))++ expect(mutationMock.mutate).toHaveBeenCalledWith({+ body: {+ name: 'Research Agent',+ description: 'Find and summarize market materials.',+ role: 'Research Assistant',+ icon_type: 'emoji',+ icon: '🧸',+ icon_background: '#F5F3FF',+ },+ }, expect.objectContaining({+ onError: expect.any(Function),+ onSuccess: expect.any(Function),+ }))+ })++ it('shows a field error when creating with an empty name', async () => {+ const user = userEvent.setup()+ render(<CreateAgentDialog />)++ await user.click(screen.getByRole('button', { name: /agentV2\.roster\.createAgent/ }))++ const dialog = await screen.findByRole('dialog', { name: 'agentV2.roster.createDialog.title' })+ await user.type(within(dialog).getByRole('textbox', { name: 'agentV2.roster.createForm.roleLabel' }), 'Research Assistant')+ await user.click(within(dialog).getByRole('button', { name: 'common.operation.create' }))++ expect(await within(dialog).findByText('agentV2.roster.createForm.nameRequired')).toBeInTheDocument()+ expect(toastMock.error).not.toHaveBeenCalled()+ expect(mutationMock.mutate).not.toHaveBeenCalled()+ })++ it('shows a field error when creating with an empty role', async () => {+ const user = userEvent.setup()+ render(<CreateAgentDialog />)++ await user.click(screen.getByRole('button', { name: /agentV2\.roster\.createAgent/ }))++ const dialog = await screen.findByRole('dialog', { name: 'agentV2.roster.createDialog.title' })+ await user.type(within(dialog).getByRole('textbox', { name: 'agentV2.roster.createForm.nameLabel' }), 'Research Agent')+ await user.click(within(dialog).getByRole('button', { name: 'common.operation.create' }))++ expect(await within(dialog).findByText('agentV2.roster.createForm.roleRequired')).toBeInTheDocument()+ expect(toastMock.error).not.toHaveBeenCalled()+ expect(mutationMock.mutate).not.toHaveBeenCalled()+ })++ it('shows a field error when creating with a blank role', async () => {+ const user = userEvent.setup()+ render(<CreateAgentDialog />)++ await user.click(screen.getByRole('button', { name: /agentV2\.roster\.createAgent/ }))++ const dialog = await screen.findByRole('dialog', { name: 'agentV2.roster.createDialog.title' })+ await user.type(within(dialog).getByRole('textbox', { name: 'agentV2.roster.createForm.nameLabel' }), 'Research Agent')+ await user.type(within(dialog).getByRole('textbox', { name: 'agentV2.roster.createForm.roleLabel' }), ' ')+ await user.click(within(dialog).getByRole('button', { name: 'common.operation.create' }))++ expect(await within(dialog).findByText('agentV2.roster.createForm.roleRequired')).toBeInTheDocument()+ expect(toastMock.error).not.toHaveBeenCalled()+ expect(mutationMock.mutate).not.toHaveBeenCalled()+ })+})diff --git a/web/features/agent-v2/roster/components/__tests__/edit-agent-dialog.spec.tsx b/web/features/agent-v2/roster/components/__tests__/edit-agent-dialog.spec.tsxnew file mode 100644index 00000000000..cc69c2d1b13--- /dev/null+++ b/web/features/agent-v2/roster/components/__tests__/edit-agent-dialog.spec.tsx@@ -0,0 +1,221 @@+import type { AgentAppPartial } from '@dify/contracts/api/console/agent/types.gen'+import { render, screen, within } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { EditAgentDialog } from '../edit-agent-dialog'++const mutationMock = vi.hoisted(() => ({+ isPending: false,+ mutate: vi.fn(),+}))++const toastMock = vi.hoisted(() => ({+ error: vi.fn(),+ success: vi.fn(),+}))++vi.mock('@tanstack/react-query', () => ({+ useMutation: () => ({+ isPending: mutationMock.isPending,+ mutate: mutationMock.mutate,+ }),+}))++vi.mock('@langgenius/dify-ui/toast', () => ({+ toast: toastMock,+}))++vi.mock('@/app/components/base/app-icon-picker', () => ({+ __esModule: true,+ default: ({+ onSelect,+ open,+ }: {+ onSelect: (payload: { type: 'emoji', icon: string, background: string }) => void+ open: boolean+ }) => open+ ? (+ <button+ type="button"+ onClick={() => onSelect({ type: 'emoji', icon: '🧠', background: '#E0F2FE' })}+ >+ Select brain icon+ </button>+ )+ : null,+}))++vi.mock('@/service/client', () => ({+ consoleQuery: {+ agent: {+ byAgentId: {+ put: {+ mutationOptions: vi.fn(() => ({})),+ },+ },+ },+ },+}))++const createAgent = (overrides: Partial<AgentAppPartial> = {}): AgentAppPartial => ({+ description: 'Find and summarize market materials.',+ icon: '🧸',+ icon_background: '#F5F3FF',+ icon_type: 'emoji',+ id: 'agent-1',+ icon_url: null,+ mode: 'agent',+ name: 'Research Agent',+ role: 'Research Assistant',+ ...overrides,+})++const renderDialog = (agent = createAgent()) => {+ const onOpenChange = vi.fn()++ render(+ <EditAgentDialog+ agent={agent}+ open+ onOpenChange={onOpenChange}+ />,+ )++ return { onOpenChange }+}++describe('EditAgentDialog', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mutationMock.isPending = false+ })++ it('submits the full agent payload when only the name changes', async () => {+ const user = userEvent.setup()+ renderDialog()++ const dialog = screen.getByRole('dialog', { name: 'agentV2.roster.editDialog.title' })+ await user.clear(within(dialog).getByRole('textbox', { name: 'agentV2.roster.createForm.nameLabel' }))+ await user.type(within(dialog).getByRole('textbox', { name: 'agentV2.roster.createForm.nameLabel' }), ' Market Agent ')+ await user.click(within(dialog).getByRole('button', { name: 'common.operation.save' }))++ expect(mutationMock.mutate).toHaveBeenCalledWith({+ params: {+ agent_id: 'agent-1',+ },+ body: {+ name: 'Market Agent',+ description: 'Find and summarize market materials.',+ role: 'Research Assistant',+ icon_type: 'emoji',+ icon: '🧸',+ icon_background: '#F5F3FF',+ },+ }, expect.objectContaining({+ onError: expect.any(Function),+ onSuccess: expect.any(Function),+ }))+ })++ it('submits the full agent payload when only the role changes', async () => {+ const user = userEvent.setup()+ renderDialog()++ const dialog = screen.getByRole('dialog', { name: 'agentV2.roster.editDialog.title' })+ await user.clear(within(dialog).getByRole('textbox', { name: 'agentV2.roster.createForm.roleLabel' }))+ await user.type(within(dialog).getByRole('textbox', { name: 'agentV2.roster.createForm.roleLabel' }), ' Market Analyst ')+ await user.click(within(dialog).getByRole('button', { name: 'common.operation.save' }))++ expect(mutationMock.mutate).toHaveBeenCalledWith({+ params: {+ agent_id: 'agent-1',+ },+ body: {+ name: 'Research Agent',+ description: 'Find and summarize market materials.',+ role: 'Market Analyst',+ icon_type: 'emoji',+ icon: '🧸',+ icon_background: '#F5F3FF',+ },+ }, expect.objectContaining({+ onError: expect.any(Function),+ onSuccess: expect.any(Function),+ }))+ })++ it('submits selected icon fields when the roster icon changes', async () => {+ const user = userEvent.setup()+ renderDialog()++ const dialog = screen.getByRole('dialog', { name: 'agentV2.roster.editDialog.title' })+ await user.click(within(dialog).getByRole('button', { name: /agentV2\.roster\.editAgent/ }))+ await user.click(screen.getByRole('button', { hidden: true, name: 'Select brain icon' }))+ await user.click(within(dialog).getByRole('button', { name: 'common.operation.save' }))++ expect(mutationMock.mutate).toHaveBeenCalledWith({+ params: {+ agent_id: 'agent-1',+ },+ body: {+ name: 'Research Agent',+ description: 'Find and summarize market materials.',+ role: 'Research Assistant',+ icon_type: 'emoji',+ icon: '🧠',+ icon_background: '#E0F2FE',+ },+ }, expect.objectContaining({+ onError: expect.any(Function),+ onSuccess: expect.any(Function),+ }))+ })++ it('shows a field error when saving with an empty name', async () => {+ const user = userEvent.setup()+ renderDialog()++ const dialog = screen.getByRole('dialog', { name: 'agentV2.roster.editDialog.title' })+ await user.clear(within(dialog).getByRole('textbox', { name: 'agentV2.roster.createForm.nameLabel' }))++ const saveButton = within(dialog).getByRole('button', { name: 'common.operation.save' })+ expect(saveButton).not.toBeDisabled()+ await user.click(saveButton)++ expect(await within(dialog).findByText('agentV2.roster.createForm.nameRequired')).toBeInTheDocument()+ expect(toastMock.error).not.toHaveBeenCalled()+ expect(mutationMock.mutate).not.toHaveBeenCalled()+ })++ it('shows a field error when saving with an empty role', async () => {+ const user = userEvent.setup()+ renderDialog()++ const dialog = screen.getByRole('dialog', { name: 'agentV2.roster.editDialog.title' })+ await user.clear(within(dialog).getByRole('textbox', { name: 'agentV2.roster.createForm.roleLabel' }))++ const saveButton = within(dialog).getByRole('button', { name: 'common.operation.save' })+ expect(saveButton).not.toBeDisabled()+ await user.click(saveButton)++ expect(await within(dialog).findByText('agentV2.roster.createForm.roleRequired')).toBeInTheDocument()+ expect(toastMock.error).not.toHaveBeenCalled()+ expect(mutationMock.mutate).not.toHaveBeenCalled()+ })++ it('shows a field error when saving with a blank role', async () => {+ const user = userEvent.setup()+ renderDialog()++ const dialog = screen.getByRole('dialog', { name: 'agentV2.roster.editDialog.title' })+ await user.clear(within(dialog).getByRole('textbox', { name: 'agentV2.roster.createForm.roleLabel' }))+ await user.type(within(dialog).getByRole('textbox', { name: 'agentV2.roster.createForm.roleLabel' }), ' ')++ const saveButton = within(dialog).getByRole('button', { name: 'common.operation.save' })+ expect(saveButton).not.toBeDisabled()+ await user.click(saveButton)++ expect(await within(dialog).findByText('agentV2.roster.createForm.roleRequired')).toBeInTheDocument()+ expect(toastMock.error).not.toHaveBeenCalled()+ expect(mutationMock.mutate).not.toHaveBeenCalled()+ })+})diff --git a/web/features/agent-v2/roster/components/__tests__/roster-toolbar.spec.tsx b/web/features/agent-v2/roster/components/__tests__/roster-toolbar.spec.tsxnew file mode 100644index 00000000000..6b215aa1b3c--- /dev/null+++ b/web/features/agent-v2/roster/components/__tests__/roster-toolbar.spec.tsx@@ -0,0 +1,63 @@+import type { RosterFilterValue } from '../roster-filter'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { render, screen } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { RosterToolbar } from '../roster-toolbar'++const renderToolbar = ({+ filter = 'all',+ onFilterChange = vi.fn(),+}: {+ filter?: RosterFilterValue+ onFilterChange?: (value: RosterFilterValue) => void+} = {}) => {+ const queryClient = new QueryClient()++ render(+ <QueryClientProvider client={queryClient}>+ <RosterToolbar+ draftAgents={2}+ filter={filter}+ keyword=""+ onFilterChange={onFilterChange}+ onKeywordChange={vi.fn()}+ publishedAgents={1}+ />+ </QueryClientProvider>,+ )++ return { onFilterChange }+}++describe('RosterToolbar', () => {+ it('enables roster filters and emits the selected filter', async () => {+ const user = userEvent.setup()+ const { onFilterChange } = renderToolbar()++ const publishedFilter = screen.getByRole('button', { name: /agentV2\.roster\.filters\.published/ })+ const draftsFilter = screen.getByRole('button', { name: /agentV2\.roster\.filters\.drafts/ })++ expect(publishedFilter).toBeEnabled()+ expect(draftsFilter).toBeEnabled()++ await user.click(publishedFilter)++ expect(onFilterChange).toHaveBeenCalledWith('published')+ })++ it('renders stable filter count badges and omits the all count', () => {+ renderToolbar()++ expect(screen.getByRole('button', { name: /agentV2\.roster\.filters\.all/ })).not.toHaveTextContent('3')++ expect(screen.getByText('1').parentElement).toHaveClass(+ 'min-w-4',+ 'shrink-0',+ 'border-divider-deep',+ 'py-0.5',+ 'system-2xs-medium-uppercase',+ 'tabular-nums',+ )+ expect(screen.getByText('1')).toHaveClass('min-w-px', 'flex-1', 'text-center')+ })+})diff --git a/web/features/agent-v2/roster/components/agent-roster-list.tsx b/web/features/agent-v2/roster/components/agent-roster-list.tsxnew file mode 100644index 00000000000..9a1c473228c--- /dev/null+++ b/web/features/agent-v2/roster/components/agent-roster-list.tsx@@ -0,0 +1,259 @@+'use client'++import type { AgentAppPartial, AgentIconType } from '@dify/contracts/api/console/agent/types.gen'+import { Button } from '@langgenius/dify-ui/button'+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from '@langgenius/dify-ui/dropdown-menu'+import { useId, useState } from 'react'+import { useTranslation } from 'react-i18next'+import AppIcon from '@/app/components/base/app-icon'+import { SkeletonRectangle } from '@/app/components/base/skeleton'+import useTimestamp from '@/hooks/use-timestamp'+import Link from '@/next/link'+import { AgentWorkflowReferencesDropdown } from './agent-workflow-references-dropdown'+import { DeleteAgentDialog } from './delete-agent-dialog'+import { EditAgentDialog } from './edit-agent-dialog'++type AgentRosterListProps = {+ agents: AgentRosterListItem[]+ hasMore: boolean+ isEmptySearch: boolean+ isError: boolean+ isFetching: boolean+ isFetchingNextPage: boolean+ isPending: boolean+ label: string+ onLoadMore: () => void+}++export type AgentRosterListItem = AgentAppPartial++const skeletonRows = ['primary', 'secondary', 'tertiary'] as const+const emptyPlaceholderCardIds = Array.from({ length: 16 }, (_, index) => `agent-roster-placeholder-card-${index}`)++function AgentRosterSkeleton() {+ return (+ <>+ {skeletonRows.map(row => (+ <div key={row} className="relative h-36.5 rounded-xl border-[0.5px] border-components-card-border bg-components-card-bg shadow-xs shadow-shadow-shadow-3">+ <div className="flex items-center gap-3 pt-3.5 pr-4 pb-2 pl-3.5">+ <SkeletonRectangle className="my-0 size-12 shrink-0 animate-pulse rounded-full" />+ <div className="min-w-0 flex-1 space-y-2.5 py-px">+ <SkeletonRectangle className="my-0 h-4 w-36 max-w-full animate-pulse rounded-md" />+ <SkeletonRectangle className="my-0 h-3 w-20 max-w-full animate-pulse rounded-md" />+ </div>+ </div>+ <div className="px-4 py-1">+ <SkeletonRectangle className="my-0 h-3 w-full animate-pulse rounded-md" />+ <SkeletonRectangle className="mt-2 mb-0 h-3 w-3/4 animate-pulse rounded-md" />+ </div>+ <div className="flex items-center pt-2 pr-3 pb-3 pl-4">+ <SkeletonRectangle className="my-0 h-4 w-6 animate-pulse rounded-md" />+ <SkeletonRectangle className="my-0 ml-2.5 h-4 w-28 animate-pulse rounded-md" />+ </div>+ </div>+ ))}+ </>+ )+}++function AgentRosterPlaceholderState({ title }: { title: string }) {+ return (+ <section+ aria-labelledby="agent-roster-placeholder-title"+ className="relative col-span-full min-h-[calc(100vh-142px)] overflow-hidden"+ >+ <div className="pointer-events-none absolute inset-0 grid grid-cols-1 grid-rows-4 gap-3 sm:grid-cols-2 xl:grid-cols-4">+ {emptyPlaceholderCardIds.map(id => (+ <div key={id} className="rounded-xl bg-background-default-lighter opacity-75" />+ ))}+ </div>+ <div className="pointer-events-none absolute inset-0 bg-linear-to-b from-background-body/0 to-background-body" />+ <div className="absolute inset-0 flex items-center justify-center overflow-hidden p-2">+ <div className="flex flex-col items-center gap-3">+ <div className="flex size-14 items-center justify-center rounded-[10px]">+ <div className="flex size-full min-w-px items-center justify-center overflow-hidden rounded-xl border border-dashed border-divider-regular bg-components-card-bg p-1 backdrop-blur-md">+ <span aria-hidden className="i-ri-robot-2-line size-6 text-text-tertiary" />+ </div>+ </div>+ <h2 id="agent-roster-placeholder-title" className="system-sm-regular whitespace-nowrap text-text-tertiary">+ {title}+ </h2>+ </div>+ </div>+ </section>+ )+}++function AgentRosterItem({+ agent,+}: {+ agent: AgentRosterListItem+}) {+ const { t } = useTranslation('agentV2')+ const { t: tCommon } = useTranslation('common')+ const { formatTime } = useTimestamp()+ const nameId = useId()+ const descriptionId = useId()+ const [isEditOpen, setIsEditOpen] = useState(false)+ const [isDeleteOpen, setIsDeleteOpen] = useState(false)+ const updatedAt = agent.updated_at != null+ ? formatTime(agent.updated_at, t('roster.dateTimeFormat'))+ : null+ const referenceCount = agent.published_reference_count ?? 0+ const publishedReferences = agent.published_references ?? []+ const hasPublishedReferences = publishedReferences.length > 0+ const isDraft = agent.active_config_is_published !== true+ const imageUrl = (agent.icon_type === 'image' || agent.icon_type === 'link') ? agent.icon : undefined+ const iconType = (imageUrl ? 'image' : agent.icon_type) as AgentIconType | null | undefined++ return (+ <article className="group relative col-span-1 h-36.5 min-w-0 overflow-hidden rounded-xl border-[0.5px] border-solid border-components-card-border bg-components-card-bg shadow-xs shadow-shadow-shadow-3 transition-shadow duration-200 ease-in-out hover:shadow-lg">+ <div className="flex h-full min-w-0 flex-col">+ <Link+ href={`/roster/agent/${agent.id}/configure`}+ aria-labelledby={nameId}+ aria-describedby={agent.description ? descriptionId : undefined}+ className="block shrink-0 cursor-pointer touch-manipulation rounded-xl outline-hidden focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:ring-inset"+ >+ <div className="flex items-center gap-3 pt-3.5 pr-4 pb-2 pl-3.5">+ <span aria-hidden className="shrink-0">+ <AppIcon+ size="xl"+ rounded+ iconType={iconType}+ icon={agent.icon ?? undefined}+ background={agent.icon_background}+ imageUrl={imageUrl}+ />+ </span>+ <div className="flex min-w-0 flex-1 flex-col gap-0.5 py-px">+ <h2 id={nameId} className="truncate system-md-semibold text-text-secondary">+ {agent.name}+ </h2>+ <p className="truncate system-xs-regular text-text-tertiary">+ {agent.role}+ </p>+ </div>+ </div>+ <div className="px-4 py-1 system-xs-regular text-text-tertiary">+ <div id={descriptionId} className="line-clamp-2 min-h-8">+ {agent.description}+ </div>+ </div>+ </Link>+ <div className="flex min-w-0 shrink-0 items-center pt-2 pr-3 pb-3 pl-4 system-xs-regular text-text-tertiary">+ <div className="flex min-w-0 flex-1 items-center gap-1.5">+ {hasPublishedReferences+ ? (+ <AgentWorkflowReferencesDropdown+ agentName={agent.name}+ publishedReferences={publishedReferences}+ referenceCount={referenceCount}+ />+ )+ : (+ <div className="flex shrink-0 items-center gap-1">+ <span aria-hidden className="i-custom-vender-agent-v2-plan size-3 shrink-0 text-text-tertiary" />+ <span className="system-xs-regular text-text-tertiary">{referenceCount}</span>+ </div>+ )}+ {updatedAt && (+ <>+ <span aria-hidden className="shrink-0 text-text-quaternary">·</span>+ <span className="min-w-0 truncate">{updatedAt}</span>+ </>+ )}+ </div>+ </div>+ </div>+ {isDraft && (+ <div className="absolute top-0 right-0 flex h-5 items-start overflow-hidden">+ <div className="h-5 w-3 bg-background-section-burn [clip-path:polygon(0_0,100%_0,100%_100%)]" />+ <div className="flex h-5 items-center bg-background-section-burn pr-2 pl-0.5 system-2xs-medium-uppercase text-text-tertiary">+ {t('roster.usageStatus.draft')}+ </div>+ </div>+ )}+ <div+ className="pointer-events-none absolute top-2 right-2 z-20 flex items-center overflow-hidden rounded-[10px] border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 opacity-0 shadow-lg backdrop-blur-xs transition-opacity group-focus-within:pointer-events-auto group-focus-within:opacity-100 group-hover:pointer-events-auto group-hover:opacity-100 has-data-popup-open:pointer-events-auto has-data-popup-open:opacity-100"+ >+ <DropdownMenu modal={false}>+ <DropdownMenuTrigger+ aria-label={t('roster.moreActions', { name: agent.name })}+ className="flex size-8 cursor-pointer items-center justify-center rounded-lg p-1.5 hover:bg-state-base-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden data-popup-open:bg-state-base-hover"+ >+ <span className="sr-only">{t('roster.moreActions', { name: agent.name })}</span>+ <span aria-hidden className="i-ri-more-fill size-4.5 text-text-tertiary" />+ </DropdownMenuTrigger>+ <DropdownMenuContent placement="bottom-end" sideOffset={4} popupClassName="w-40">+ <DropdownMenuItem className="gap-2" onClick={() => setIsEditOpen(true)}>+ <span aria-hidden className="i-ri-edit-line size-4 shrink-0 text-text-tertiary" />+ <span>{t('roster.editInfo')}</span>+ </DropdownMenuItem>+ <DropdownMenuItem disabled className="gap-2">+ <span aria-hidden className="i-ri-file-copy-line size-4 shrink-0 text-text-tertiary" />+ <span>{tCommon('operation.duplicate')}</span>+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ variant="destructive"+ className="gap-2"+ onClick={() => setIsDeleteOpen(true)}+ >+ <span aria-hidden className="i-ri-delete-bin-line size-4 shrink-0" />+ <span>{tCommon('operation.delete')}</span>+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ <EditAgentDialog agent={agent} open={isEditOpen} onOpenChange={setIsEditOpen} />+ <DeleteAgentDialog agentId={agent.id} agentName={agent.name} open={isDeleteOpen} onOpenChange={setIsDeleteOpen} />+ </article>+ )+}++export function AgentRosterList({+ agents,+ hasMore,+ isEmptySearch,+ isError,+ isFetching,+ isFetchingNextPage,+ isPending,+ label,+ onLoadMore,+}: AgentRosterListProps) {+ const { t } = useTranslation('agentV2')++ return (+ <section aria-label={label} className="grid grid-cols-[repeat(auto-fill,minmax(min(100%,294px),1fr))] gap-2.5" aria-busy={isFetching || undefined}>+ {isPending && <AgentRosterSkeleton />}+ {!isPending && isError && (+ <AgentRosterPlaceholderState title={t('roster.loadingError')} />+ )}+ {!isPending && !isError && agents.length === 0 && (+ <AgentRosterPlaceholderState title={isEmptySearch ? t('roster.emptySearch') : t('roster.empty')} />+ )}+ {!isPending && !isError && agents.map(agent => (+ <AgentRosterItem key={agent.id} agent={agent} />+ ))}+ {!isPending && !isError && hasMore && (+ <div className="col-span-full flex justify-center pt-1">+ <Button+ loading={isFetchingNextPage}+ disabled={isFetchingNextPage}+ onClick={onLoadMore}+ >+ {t('roster.loadMore')}+ </Button>+ </div>+ )}+ </section>+ )+}diff --git a/web/features/agent-v2/roster/components/agent-workflow-references-dropdown.tsx b/web/features/agent-v2/roster/components/agent-workflow-references-dropdown.tsxnew file mode 100644index 00000000000..9974a30468c--- /dev/null+++ b/web/features/agent-v2/roster/components/agent-workflow-references-dropdown.tsx@@ -0,0 +1,79 @@+'use client'++import type { AgentAppPublishedReferenceResponse, AgentIconType } from '@dify/contracts/api/console/agent/types.gen'+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuLinkItem,+ DropdownMenuTrigger,+} from '@langgenius/dify-ui/dropdown-menu'+import { useTranslation } from 'react-i18next'+import AppIcon from '@/app/components/base/app-icon'+import Link from '@/next/link'++const getWorkflowReferenceHref = (reference: AgentAppPublishedReferenceResponse) => `/app/${reference.app_id}/workflow`++const getWorkflowReferenceIconType = (reference: AgentAppPublishedReferenceResponse): AgentIconType | undefined => {+ if (reference.app_icon_type === 'image' || reference.app_icon_type === 'link')+ return 'image'++ if (reference.app_icon_type === 'emoji')+ return 'emoji'++ return undefined+}++const getWorkflowReferenceImageUrl = (reference: AgentAppPublishedReferenceResponse) => {+ if (reference.app_icon_type === 'image' || reference.app_icon_type === 'link')+ return reference.app_icon++ return undefined+}++export function AgentWorkflowReferencesDropdown({+ agentName,+ publishedReferences,+ referenceCount,+}: {+ agentName: string+ publishedReferences: AgentAppPublishedReferenceResponse[]+ referenceCount: number+}) {+ const { t } = useTranslation('agentV2')++ return (+ <DropdownMenu modal={false}>+ <DropdownMenuTrigger+ aria-label={t('roster.references.trigger', { name: agentName, count: referenceCount })}+ className="-ml-1 flex shrink-0 cursor-pointer items-center gap-1 rounded-md px-1 py-0.5 outline-hidden hover:bg-state-base-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid data-popup-open:bg-state-base-hover"+ >+ <span aria-hidden className="i-custom-vender-agent-v2-plan size-3 shrink-0 text-text-tertiary" />+ <span className="system-xs-regular text-text-tertiary">{referenceCount}</span>+ </DropdownMenuTrigger>+ <DropdownMenuContent placement="bottom-start" sideOffset={4} popupClassName="w-[264px] p-1">+ <div className="flex h-7.5 items-center px-2 system-xs-medium text-text-tertiary">+ {t('roster.references.label', { name: agentName })}+ </div>+ {publishedReferences.map(reference => (+ <DropdownMenuLinkItem+ key={reference.app_id}+ render={<Link href={getWorkflowReferenceHref(reference)} />}+ className="mx-0 h-8 gap-2 px-2 py-1 pr-2.5 system-md-regular text-text-secondary"+ >+ <span aria-hidden className="shrink-0">+ <AppIcon+ size="tiny"+ iconType={getWorkflowReferenceIconType(reference)}+ icon={reference.app_icon ?? undefined}+ background={reference.app_icon_background}+ imageUrl={getWorkflowReferenceImageUrl(reference)}+ />+ </span>+ <span className="min-w-0 flex-1 truncate">{reference.app_name}</span>+ <span aria-hidden className="i-ri-external-link-line size-3 shrink-0 text-text-tertiary" />+ </DropdownMenuLinkItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ )+}diff --git a/web/features/agent-v2/roster/components/create-agent-dialog.tsx b/web/features/agent-v2/roster/components/create-agent-dialog.tsxnew file mode 100644index 00000000000..de6b5f24ff2--- /dev/null+++ b/web/features/agent-v2/roster/components/create-agent-dialog.tsx@@ -0,0 +1,219 @@+'use client'++import type { AgentAppCreatePayload } from '@dify/contracts/api/console/agent/types.gen'+import type { AppIconSelection } from '@/app/components/base/app-icon-picker'+import { Button } from '@langgenius/dify-ui/button'+import { Dialog, DialogCloseButton, DialogContent, DialogDescription, DialogTitle, DialogTrigger } from '@langgenius/dify-ui/dialog'+import { FieldControl, FieldError, FieldLabel, FieldRoot } from '@langgenius/dify-ui/field'+import { Form } from '@langgenius/dify-ui/form'+import { Textarea } from '@langgenius/dify-ui/textarea'+import { toast } from '@langgenius/dify-ui/toast'+import { useMutation } from '@tanstack/react-query'+import { useState } from 'react'+import { useTranslation } from 'react-i18next'+import AppIcon from '@/app/components/base/app-icon'+import AppIconPicker from '@/app/components/base/app-icon-picker'+import { consoleQuery } from '@/service/client'++type AgentFormValues = {+ description?: string+ name?: string+ role?: string+}++const defaultAgentIcon = {+ type: 'emoji',+ icon: '🧸',+ background: '#F5F3FF',+} satisfies AppIconSelection++export function CreateAgentDialog() {+ const { t } = useTranslation('agentV2')+ const { t: tCommon } = useTranslation('common')+ const [open, setOpen] = useState(false)+ const [formKey, setFormKey] = useState(0)+ const [iconPickerOpen, setIconPickerOpen] = useState(false)+ const [agentIcon, setAgentIcon] = useState<AppIconSelection>(defaultAgentIcon)+ const createAgentMutation = useMutation(consoleQuery.agent.post.mutationOptions())++ const resetForm = () => {+ setFormKey(key => key + 1)+ setAgentIcon(defaultAgentIcon)+ setIconPickerOpen(false)+ }++ const handleOpenChange = (nextOpen: boolean) => {+ setOpen(nextOpen)+ if (!nextOpen)+ resetForm()+ }++ const handleSubmit = (formValues: AgentFormValues) => {+ const trimmedName = formValues.name?.trim() ?? ''+ const trimmedRole = formValues.role?.trim() ?? ''+ if (createAgentMutation.isPending)+ return++ const body = {+ name: trimmedName,+ description: formValues.description?.trim() ?? '',+ role: trimmedRole,+ icon_type: agentIcon.type,+ icon: agentIcon.type === 'image' ? agentIcon.fileId : agentIcon.icon,+ icon_background: agentIcon.type === 'emoji' ? agentIcon.background : undefined,+ } satisfies AgentAppCreatePayload++ createAgentMutation.mutate({+ body,+ }, {+ onSuccess: () => {+ toast.success(t('roster.createSuccess'))+ handleOpenChange(false)+ },+ onError: () => {+ toast.error(t('roster.createFailed'))+ },+ })+ }++ return (+ <>+ <Dialog open={open} onOpenChange={handleOpenChange}>+ <DialogTrigger+ render={(+ <Button+ variant="primary"+ className="h-8 gap-0.5 px-3"+ />+ )}+ >+ <span aria-hidden className="i-ri-add-line size-4" />+ <span className="px-0.5 system-sm-medium">{t('roster.createAgent')}</span>+ </DialogTrigger>+ <DialogContent className="flex max-h-[calc(100dvh-2rem)] w-[520px] flex-col overflow-hidden! p-0!">+ <DialogCloseButton className="top-5 right-5 size-8 rounded-lg" />+ <div className="shrink-0 pt-6 pr-14 pb-3 pl-6">+ <DialogTitle className="title-2xl-semi-bold text-text-primary">+ {t('roster.createDialog.title')}+ </DialogTitle>+ <DialogDescription className="sr-only">+ {t('roster.createDialog.description')}+ </DialogDescription>+ </div>+ <Form<AgentFormValues>+ key={formKey}+ className="min-h-0 flex-1"+ onFormSubmit={handleSubmit}+ >+ <div className="space-y-5 px-6 py-3">+ <div className="flex items-end gap-4 pb-2">+ <button+ type="button"+ aria-label={t('roster.createForm.changeIcon')}+ className="shrink-0 rounded-full outline-hidden focus-visible:ring-2 focus-visible:ring-state-accent-solid"+ onClick={() => setIconPickerOpen(true)}+ >+ <AppIcon+ size="xxl"+ rounded+ className="size-16 cursor-pointer"+ iconType={agentIcon.type}+ icon={agentIcon.type === 'image' ? agentIcon.fileId : agentIcon.icon}+ background={agentIcon.type === 'emoji' ? agentIcon.background : undefined}+ imageUrl={agentIcon.type === 'image' ? agentIcon.url : undefined}+ />+ </button>+ <div className="flex min-w-0 flex-1 gap-3 pb-1">+ <FieldRoot+ name="name"+ className="relative min-w-0 flex-1"+ validate={(value) => {+ if (typeof value === 'string' && value.length > 0 && !value.trim())+ return t('roster.createForm.nameRequired')++ return null+ }}+ >+ <FieldLabel>+ {t('roster.createForm.nameLabel')}+ </FieldLabel>+ <FieldControl+ autoComplete="off"+ // eslint-disable-next-line jsx-a11y/no-autofocus -- The create dialog opens from an explicit command, and the next expected action is naming the agent.+ autoFocus+ maxLength={255}+ placeholder={t('roster.createForm.namePlaceholder')}+ required+ />+ <div className="absolute top-full left-0 mt-1">+ <FieldError match="valueMissing">{t('roster.createForm.nameRequired')}</FieldError>+ <FieldError match="customError" />+ </div>+ </FieldRoot>+ <FieldRoot+ name="role"+ className="relative min-w-0 flex-1"+ validate={(value) => {+ if (typeof value === 'string' && value.length > 0 && !value.trim())+ return t('roster.createForm.roleRequired')++ return null+ }}+ >+ <FieldLabel>+ {t('roster.createForm.roleLabel')}+ </FieldLabel>+ <FieldControl+ autoComplete="off"+ maxLength={255}+ placeholder={t('roster.createForm.rolePlaceholder')}+ required+ />+ <div className="absolute top-full left-0 mt-1">+ <FieldError match="valueMissing">{t('roster.createForm.roleRequired')}</FieldError>+ <FieldError match="customError" />+ </div>+ </FieldRoot>+ </div>+ </div>+ <FieldRoot name="description">+ <FieldLabel>+ {t('roster.createForm.descriptionLabel')}+ <span className="ml-1 system-xs-regular text-text-tertiary">+ {t('roster.createForm.descriptionOptional')}+ </span>+ </FieldLabel>+ <Textarea+ autoComplete="off"+ className="h-20 resize-none"+ placeholder={t('roster.createForm.descriptionPlaceholder')}+ />+ </FieldRoot>+ </div>+ <div className="flex shrink-0 justify-end gap-2 px-6 pt-5 pb-6">+ <Button type="button" className="min-w-18" onClick={() => handleOpenChange(false)} disabled={createAgentMutation.isPending}>+ {tCommon('operation.cancel')}+ </Button>+ <Button+ type="submit"+ variant="primary"+ className="min-w-18"+ loading={createAgentMutation.isPending}+ >+ {tCommon('operation.create')}+ </Button>+ </div>+ </Form>+ </DialogContent>+ </Dialog>+ <AppIconPicker+ open={iconPickerOpen}+ initialEmoji={agentIcon.type === 'emoji'+ ? { icon: agentIcon.icon, background: agentIcon.background }+ : undefined}+ onOpenChange={setIconPickerOpen}+ onSelect={setAgentIcon}+ />+ </>+ )+}diff --git a/web/features/agent-v2/roster/components/delete-agent-dialog.tsx b/web/features/agent-v2/roster/components/delete-agent-dialog.tsxnew file mode 100644index 00000000000..e463cc76fb1--- /dev/null+++ b/web/features/agent-v2/roster/components/delete-agent-dialog.tsx@@ -0,0 +1,77 @@+'use client'++import {+ AlertDialog,+ AlertDialogActions,+ AlertDialogCancelButton,+ AlertDialogConfirmButton,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogTitle,+} from '@langgenius/dify-ui/alert-dialog'+import { toast } from '@langgenius/dify-ui/toast'+import { useMutation } from '@tanstack/react-query'+import { useTranslation } from 'react-i18next'+import { consoleQuery } from '@/service/client'++type DeleteAgentDialogProps = {+ agentId: string+ agentName: string+ open: boolean+ onOpenChange: (open: boolean) => void+}++export function DeleteAgentDialog({+ agentId,+ agentName,+ open,+ onOpenChange,+}: DeleteAgentDialogProps) {+ const { t } = useTranslation('agentV2')+ const { t: tCommon } = useTranslation('common')+ const deleteAgentMutation = useMutation(consoleQuery.agent.byAgentId.delete.mutationOptions())++ const handleDelete = () => {+ if (deleteAgentMutation.isPending)+ return++ deleteAgentMutation.mutate({+ params: {+ agent_id: agentId,+ },+ }, {+ onSuccess: () => {+ toast.success(t('roster.deleteSuccess'))+ onOpenChange(false)+ },+ onError: () => {+ toast.error(t('roster.deleteFailed'))+ },+ })+ }++ return (+ <AlertDialog open={open} onOpenChange={onOpenChange}>+ <AlertDialogContent className="p-6">+ <AlertDialogTitle className="truncate title-2xl-semi-bold text-text-primary">+ {t('roster.deleteDialog.title', { name: agentName })}+ </AlertDialogTitle>+ <AlertDialogDescription className="mt-2 system-md-regular wrap-break-word whitespace-pre-wrap text-text-tertiary">+ {t('roster.deleteDialog.description')}+ </AlertDialogDescription>+ <AlertDialogActions className="p-0 pt-6">+ <AlertDialogCancelButton disabled={deleteAgentMutation.isPending}>+ {tCommon('operation.cancel')}+ </AlertDialogCancelButton>+ <AlertDialogConfirmButton+ tone="destructive"+ loading={deleteAgentMutation.isPending}+ onClick={handleDelete}+ >+ {tCommon('operation.delete')}+ </AlertDialogConfirmButton>+ </AlertDialogActions>+ </AlertDialogContent>+ </AlertDialog>+ )+}diff --git a/web/features/agent-v2/roster/components/edit-agent-dialog.tsx b/web/features/agent-v2/roster/components/edit-agent-dialog.tsxnew file mode 100644index 00000000000..cdcfe0c6d3f--- /dev/null+++ b/web/features/agent-v2/roster/components/edit-agent-dialog.tsx@@ -0,0 +1,302 @@+'use client'++import type { AgentAppPartial, AgentAppUpdatePayload } from '@dify/contracts/api/console/agent/types.gen'+import type { AppIconSelection } from '@/app/components/base/app-icon-picker'+import { Button } from '@langgenius/dify-ui/button'+import { Dialog, DialogCloseButton, DialogContent, DialogDescription, DialogTitle } from '@langgenius/dify-ui/dialog'+import { FieldControl, FieldError, FieldLabel, FieldRoot } from '@langgenius/dify-ui/field'+import { Form } from '@langgenius/dify-ui/form'+import { Textarea } from '@langgenius/dify-ui/textarea'+import { toast } from '@langgenius/dify-ui/toast'+import { useMutation } from '@tanstack/react-query'+import { useState } from 'react'+import { useTranslation } from 'react-i18next'+import AppIcon from '@/app/components/base/app-icon'+import AppIconPicker from '@/app/components/base/app-icon-picker'+import { consoleQuery } from '@/service/client'++type EditAgentDialogProps = {+ agent: AgentAppPartial+ open: boolean+ onOpenChange: (open: boolean) => void+}++type AgentFormValues = {+ description?: string+ name?: string+ role?: string+}++type AgentIconSelection = AppIconSelection | {+ type: 'link'+ icon: string+ url: string+}++const defaultAgentIcon = {+ type: 'emoji',+ icon: '🧸',+ background: '#F5F3FF',+} satisfies AppIconSelection++const createAgentIconSelection = (agent: AgentAppPartial): AgentIconSelection => {+ if (agent.icon_type === 'image' && agent.icon) {+ return {+ type: 'image',+ fileId: agent.icon,+ url: agent.icon,+ }+ }++ if (agent.icon_type === 'link' && agent.icon) {+ return {+ type: 'link',+ icon: agent.icon,+ url: agent.icon,+ }+ }++ return {+ type: 'emoji',+ icon: agent.icon || defaultAgentIcon.icon,+ background: agent.icon_background || defaultAgentIcon.background,+ }+}++const getAgentIconKey = (icon: AgentIconSelection) => {+ if (icon.type === 'emoji')+ return `${icon.type}:${icon.icon}:${icon.background}`++ if (icon.type === 'image')+ return `${icon.type}:${icon.fileId}`++ return `${icon.type}:${icon.icon}`+}++const applyIconPayload = (body: AgentAppUpdatePayload, icon: AgentIconSelection) => {+ if (icon.type === 'emoji') {+ body.icon_type = icon.type+ body.icon = icon.icon+ body.icon_background = icon.background+ return+ }++ body.icon_type = icon.type+ body.icon = icon.type === 'image' ? icon.fileId : icon.icon+ body.icon_background = undefined+}++export function EditAgentDialog({+ agent,+ open,+ onOpenChange,+}: EditAgentDialogProps) {+ const { t } = useTranslation('agentV2')+ const { t: tCommon } = useTranslation('common')+ const [name, setName] = useState(agent.name)+ const [description, setDescription] = useState(agent.description ?? '')+ const [role, setRole] = useState(agent.role ?? '')+ const [iconPickerOpen, setIconPickerOpen] = useState(false)+ const [agentIcon, setAgentIcon] = useState<AgentIconSelection>(() => createAgentIconSelection(agent))+ const updateAgentMutation = useMutation(consoleQuery.agent.byAgentId.put.mutationOptions())++ const handleSubmit = (formValues: AgentFormValues) => {+ const trimmedName = formValues.name?.trim() ?? ''+ const trimmedDescription = formValues.description?.trim() ?? ''+ const trimmedRole = formValues.role?.trim() ?? ''+ const hasIconChanges = getAgentIconKey(agentIcon) !== getAgentIconKey(createAgentIconSelection(agent))+ const hasFormChanges = trimmedName !== agent.name.trim()+ || trimmedDescription !== (agent.description?.trim() ?? '')+ || trimmedRole !== (agent.role?.trim() ?? '')+ || hasIconChanges++ if (updateAgentMutation.isPending)+ return++ if (!hasFormChanges)+ return++ const body: AgentAppUpdatePayload = {+ name: trimmedName,+ description: trimmedDescription,+ // Keep sending the trimmed role even when empty: omitting the field+ // preserves the current backing-agent role, while "" intentionally clears it.+ role: trimmedRole,+ }++ applyIconPayload(body, agentIcon)++ updateAgentMutation.mutate({+ params: {+ agent_id: agent.id,+ },+ body,+ }, {+ onSuccess: () => {+ toast.success(t('roster.updateSuccess'))+ onOpenChange(false)+ },+ onError: () => {+ toast.error(t('roster.updateFailed'))+ },+ })+ }++ const handleOpenChange = (nextOpen: boolean) => {+ if (nextOpen) {+ setName(agent.name)+ setDescription(agent.description ?? '')+ setRole(agent.role ?? '')+ setAgentIcon(createAgentIconSelection(agent))+ }+ else {+ setIconPickerOpen(false)+ }+ onOpenChange(nextOpen)+ }++ const trimmedName = name.trim()+ const trimmedDescription = description.trim()+ const trimmedRole = role.trim()+ const hasIconChanges = getAgentIconKey(agentIcon) !== getAgentIconKey(createAgentIconSelection(agent))+ const hasChanges = trimmedName !== agent.name.trim()+ || trimmedDescription !== (agent.description?.trim() ?? '')+ || trimmedRole !== (agent.role?.trim() ?? '')+ || hasIconChanges++ return (+ <>+ <Dialog open={open} onOpenChange={handleOpenChange}>+ <DialogContent className="flex max-h-[calc(100dvh-2rem)] w-[520px] flex-col overflow-hidden! p-0!">+ <DialogCloseButton className="top-5 right-5 size-8 rounded-lg" />+ <div className="shrink-0 pt-6 pr-14 pb-3 pl-6">+ <DialogTitle className="title-2xl-semi-bold text-text-primary">+ {t('roster.editDialog.title')}+ </DialogTitle>+ <DialogDescription className="sr-only">+ {t('roster.editDialog.description')}+ </DialogDescription>+ </div>+ <Form<AgentFormValues>+ className="min-h-0 flex-1"+ onFormSubmit={handleSubmit}+ >+ <div className="space-y-5 px-6 py-3">+ <div className="flex items-end gap-4 pb-2">+ <button+ type="button"+ aria-label={t('roster.editAgent', { name: agent.name })}+ className="shrink-0 rounded-full outline-hidden focus-visible:ring-2 focus-visible:ring-state-accent-solid"+ onClick={() => setIconPickerOpen(true)}+ >+ <AppIcon+ size="xxl"+ rounded+ className="size-16 cursor-pointer"+ iconType={agentIcon.type === 'link' ? 'image' : agentIcon.type}+ icon={agentIcon.type === 'emoji' ? agentIcon.icon : undefined}+ background={agentIcon.type === 'emoji' ? agentIcon.background : undefined}+ imageUrl={agentIcon.type === 'emoji' ? undefined : agentIcon.url}+ />+ </button>+ <div className="flex min-w-0 flex-1 gap-3 pb-1">+ <FieldRoot+ name="name"+ className="relative min-w-0 flex-1"+ validate={(value) => {+ if (typeof value === 'string' && value.length > 0 && !value.trim())+ return t('roster.createForm.nameRequired')++ return null+ }}+ >+ <FieldLabel>+ {t('roster.createForm.nameLabel')}+ </FieldLabel>+ <FieldControl+ autoComplete="off"+ // eslint-disable-next-line jsx-a11y/no-autofocus -- The edit dialog opens from an explicit command, and the name field is the primary editable control.+ autoFocus+ maxLength={255}+ onValueChange={setName}+ placeholder={t('roster.createForm.namePlaceholder')}+ required+ value={name}+ />+ <div className="absolute top-full left-0 mt-1">+ <FieldError match="valueMissing">{t('roster.createForm.nameRequired')}</FieldError>+ <FieldError match="customError" />+ </div>+ </FieldRoot>+ <FieldRoot+ name="role"+ className="relative min-w-0 flex-1"+ validate={(value) => {+ if (typeof value === 'string' && value.length > 0 && !value.trim())+ return t('roster.createForm.roleRequired')++ return null+ }}+ >+ <FieldLabel>+ {t('roster.createForm.roleLabel')}+ </FieldLabel>+ <FieldControl+ autoComplete="off"+ maxLength={255}+ onValueChange={setRole}+ placeholder={t('roster.createForm.rolePlaceholder')}+ required+ value={role}+ />+ <div className="absolute top-full left-0 mt-1">+ <FieldError match="valueMissing">{t('roster.createForm.roleRequired')}</FieldError>+ <FieldError match="customError" />+ </div>+ </FieldRoot>+ </div>+ </div>+ <FieldRoot name="description">+ <FieldLabel>+ {t('roster.createForm.descriptionLabel')}+ <span className="ml-1 system-xs-regular text-text-tertiary">+ {t('roster.createForm.descriptionOptional')}+ </span>+ </FieldLabel>+ <Textarea+ autoComplete="off"+ className="h-20 resize-none"+ onValueChange={setDescription}+ placeholder={t('roster.createForm.descriptionPlaceholder')}+ value={description}+ />+ </FieldRoot>+ </div>+ <div className="flex shrink-0 justify-end gap-2 px-6 pt-5 pb-6">+ <Button type="button" className="min-w-18" onClick={() => onOpenChange(false)} disabled={updateAgentMutation.isPending}>+ {tCommon('operation.cancel')}+ </Button>+ <Button+ type="submit"+ variant="primary"+ className="min-w-18"+ disabled={!hasChanges}+ loading={updateAgentMutation.isPending}+ >+ {tCommon('operation.save')}+ </Button>+ </div>+ </Form>+ </DialogContent>+ </Dialog>+ <AppIconPicker+ open={iconPickerOpen}+ initialEmoji={agentIcon.type === 'emoji'+ ? { icon: agentIcon.icon, background: agentIcon.background }+ : undefined}+ onOpenChange={setIconPickerOpen}+ onSelect={setAgentIcon}+ />+ </>+ )+}diff --git a/web/features/agent-v2/roster/components/roster-filter.ts b/web/features/agent-v2/roster/components/roster-filter.tsnew file mode 100644index 00000000000..a80025d6f65--- /dev/null+++ b/web/features/agent-v2/roster/components/roster-filter.ts@@ -0,0 +1,2 @@+export const ROSTER_FILTER_VALUES = ['all', 'published', 'drafts'] as const+export type RosterFilterValue = typeof ROSTER_FILTER_VALUES[number]diff --git a/web/features/agent-v2/roster/components/roster-toolbar.tsx b/web/features/agent-v2/roster/components/roster-toolbar.tsxnew file mode 100644index 00000000000..690d3373c30--- /dev/null+++ b/web/features/agent-v2/roster/components/roster-toolbar.tsx@@ -0,0 +1,95 @@+'use client'++import type { RosterFilterValue } from './roster-filter'+import { SegmentedControl, SegmentedControlItem } from '@langgenius/dify-ui/segmented-control'+import { useTranslation } from 'react-i18next'+import { SearchInput } from '@/app/components/base/search-input'+import { CreateAgentDialog } from './create-agent-dialog'++type RosterToolbarProps = {+ draftAgents: number+ filter: RosterFilterValue+ keyword: string+ onFilterChange: (value: RosterFilterValue) => void+ onKeywordChange: (value: string) => void+ publishedAgents: number+}++type RosterFilterItemProps = {+ count?: number+ label: string+ value: RosterFilterValue+}++function RosterFilterItem({+ count,+ label,+ value,+}: RosterFilterItemProps) {+ return (+ <SegmentedControlItem+ value={value}+ className="gap-1 data-pressed:text-text-secondary"+ >+ <span>{label}</span>+ {count !== undefined && (+ <span className="flex min-w-4 shrink-0 items-center justify-center rounded-[5px] border border-divider-deep bg-components-badge-bg-dimm px-1 py-0.5 system-2xs-medium-uppercase text-text-tertiary tabular-nums">+ <span className="min-w-px flex-1 text-center">+ {count}+ </span>+ </span>+ )}+ </SegmentedControlItem>+ )+}++export function RosterToolbar({+ draftAgents,+ filter,+ keyword,+ onFilterChange,+ onKeywordChange,+ publishedAgents,+}: RosterToolbarProps) {+ const { t } = useTranslation('agentV2')++ return (+ <div className="flex min-w-0 flex-wrap items-center gap-2">+ <SegmentedControl+ aria-label={t('roster.filters.label')}+ value={[filter]}+ onValueChange={(value) => {+ const nextFilter = value[0]++ if (nextFilter)+ onFilterChange(nextFilter)+ }}+ >+ <RosterFilterItem+ value="all"+ label={t('roster.filters.all')}+ />+ <RosterFilterItem+ value="published"+ label={t('roster.filters.published')}+ count={publishedAgents}+ />+ <RosterFilterItem+ value="drafts"+ label={t('roster.filters.drafts')}+ count={draftAgents}+ />+ </SegmentedControl>+ <SearchInput+ aria-label={t('roster.searchLabel')}+ className="h-8 w-50 max-w-full"+ placeholder={t('roster.searchPlaceholder')}+ value={keyword}+ onValueChange={onKeywordChange}+ />+ <div className="ml-auto flex min-w-0 items-center gap-2">+ <CreateAgentDialog />+ </div>+ </div>+ )+}diff --git a/web/features/agent-v2/roster/page.tsx b/web/features/agent-v2/roster/page.tsxnew file mode 100644index 00000000000..c4f75470df6--- /dev/null+++ b/web/features/agent-v2/roster/page.tsx@@ -0,0 +1,150 @@+'use client'++import type { AgentRosterListItem } from './components/agent-roster-list'+import type { RosterFilterValue } from './components/roster-filter'+import {+ ScrollAreaContent,+ ScrollAreaRoot,+ ScrollAreaScrollbar,+ ScrollAreaThumb,+ ScrollAreaViewport,+} from '@langgenius/dify-ui/scroll-area'+import { Tabs, TabsList, TabsPanel, TabsTab } from '@langgenius/dify-ui/tabs'+import { keepPreviousData, useInfiniteQuery } from '@tanstack/react-query'+import { useDebounce } from 'ahooks'+import { debounce, parseAsString, parseAsStringLiteral, useQueryState } from 'nuqs'+import { useTranslation } from 'react-i18next'+import useDocumentTitle from '@/hooks/use-document-title'+import { consoleQuery } from '@/service/client'+import { AgentRosterList } from './components/agent-roster-list'+import { ROSTER_FILTER_VALUES } from './components/roster-filter'+import { RosterToolbar } from './components/roster-toolbar'++const ROSTER_PAGE_SIZE = 30+const isAgentPublished = (agent: AgentRosterListItem) => agent.active_config_is_published === true+const rosterTabClassName = 'pt-0 pb-2 system-xl-semibold data-active:border-util-colors-blue-brand-blue-brand-500 data-disabled:opacity-100'++const getFilteredRosterItems = (+ agents: AgentRosterListItem[],+ filter: RosterFilterValue,+) => {+ if (filter === 'published')+ return agents.filter(isAgentPublished)++ if (filter === 'drafts')+ return agents.filter(agent => !isAgentPublished(agent))++ return agents+}++export default function RosterPage() {+ const { t } = useTranslation('agentV2')+ const { t: tCommon } = useTranslation('common')+ const [keyword, setKeyword] = useQueryState('keyword', parseAsString.withDefault('').withOptions({+ limitUrlUpdates: debounce(300),+ }))+ const [rosterFilter, setRosterFilter] = useQueryState(+ 'filter',+ parseAsStringLiteral(ROSTER_FILTER_VALUES).withDefault('all'),+ )+ const debouncedKeyword = useDebounce(keyword.trim(), { wait: 300 })++ const rosterQueryInput = {+ limit: ROSTER_PAGE_SIZE,+ ...(debouncedKeyword ? { name: debouncedKeyword } : {}),+ }++ const {+ data: rosterPages,+ isPending,+ isFetching,+ isFetchingNextPage,+ fetchNextPage,+ hasNextPage,+ error,+ } = useInfiniteQuery({+ ...consoleQuery.agent.get.infiniteOptions({+ input: pageParam => ({+ query: {+ ...rosterQueryInput,+ page: Number(pageParam),+ },+ }),+ getNextPageParam: lastPage => lastPage.has_more ? lastPage.page + 1 : undefined,+ initialPageParam: 1,+ placeholderData: keepPreviousData,+ }),+ })++ const rosterItems: AgentRosterListItem[] = rosterPages?.pages.flatMap(page => page.data) ?? []+ const publishedAgents = rosterItems.filter(isAgentPublished).length+ const draftAgents = Math.max(rosterItems.length - publishedAgents, 0)+ const filteredRosterItems = getFilteredRosterItems(rosterItems, rosterFilter)++ useDocumentTitle(tCommon('menus.roster'))++ return (+ <main className="flex h-0 min-w-0 grow flex-col overflow-hidden bg-background-body">+ <Tabs defaultValue="agent" className="flex min-h-0 flex-1 flex-col">+ <div className="h-25.5 shrink-0 bg-background-body px-8 pt-4 pb-4">+ <div className="flex min-w-0 items-center justify-between gap-4">+ <TabsList aria-label={t('roster.tabsLabel')}>+ <TabsTab value="agent" className={rosterTabClassName}>+ {t('roster.tabs.agent')}+ </TabsTab>+ <TabsTab value="human" disabled className={rosterTabClassName}>+ {t('roster.tabs.human')}+ </TabsTab>+ </TabsList>+ <a+ href="https://docs.dify.ai/"+ target="_blank"+ rel="noreferrer"+ className="hidden shrink-0 items-center gap-0.5 rounded-md system-xs-regular text-text-tertiary hover:text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden sm:inline-flex"+ >+ {t('roster.learnMore')}+ <span aria-hidden className="i-ri-external-link-line size-3" />+ </a>+ </div>+ <div className="mt-3.5">+ <RosterToolbar+ draftAgents={draftAgents}+ filter={rosterFilter}+ keyword={keyword}+ onFilterChange={(value) => {+ void setRosterFilter(value)+ }}+ onKeywordChange={(value) => {+ void setKeyword(value)+ }}+ publishedAgents={publishedAgents}+ />+ </div>+ </div>++ <TabsPanel value="agent" tabIndex={-1} className="min-h-0 flex-1">+ <ScrollAreaRoot className="relative h-full min-h-0 min-w-0 overflow-hidden">+ <ScrollAreaViewport tabIndex={-1} className="overscroll-contain">+ <ScrollAreaContent className="min-h-full px-8 pt-2 pb-8">+ <AgentRosterList+ agents={filteredRosterItems}+ hasMore={!!hasNextPage}+ isEmptySearch={!!debouncedKeyword || rosterFilter !== 'all'}+ isError={!!error}+ isFetching={isFetching}+ isFetchingNextPage={isFetchingNextPage}+ isPending={isPending}+ label={t('roster.listLabel')}+ onLoadMore={() => fetchNextPage()}+ />+ </ScrollAreaContent>+ </ScrollAreaViewport>+ <ScrollAreaScrollbar className="data-[orientation=vertical]:my-1 data-[orientation=vertical]:me-1">+ <ScrollAreaThumb />+ </ScrollAreaScrollbar>+ </ScrollAreaRoot>+ </TabsPanel>+ </Tabs>+ </main>+ )+}diff --git a/web/i18n-config/resources.ts b/web/i18n-config/resources.tsindex d2d0f76be75..4a3fa9a4eac 100644--- a/web/i18n-config/resources.ts+++ b/web/i18n-config/resources.ts@@ -1,3 +1,4 @@+import type agentV2 from '../i18n/en-US/agent-v-2.json'import type appAnnotation from '../i18n/en-US/app-annotation.json'import type appApi from '../i18n/en-US/app-api.json'import type appDebug from '../i18n/en-US/app-debug.json'@@ -39,6 +40,7 @@ export type Resources = {appDebug: typeof appDebugappLog: typeof appLogappOverview: typeof appOverview+ agentV2: typeof agentV2billing: typeof billingcommon: typeof commoncustom: typeof custom@@ -74,6 +76,7 @@ export const namespaces = ['appDebug','appLog','appOverview',+ 'agentV2','billing','common','custom',diff --git a/web/i18n/ar-TN/common.json b/web/i18n/ar-TN/common.jsonindex 47f9a91ba71..50ad6b445ff 100644--- a/web/i18n/ar-TN/common.json+++ b/web/i18n/ar-TN/common.json@@ -318,6 +318,7 @@"menus.newDataset": "إنشاء معرفة","menus.plugins": "الإضافات","menus.pluginsTips": "ادمج الإضافات الخارجية أو أنشئ إضافات AI متوافقة مع ChatGPT.",+ "menus.roster": "قائمة الوكلاء","menus.status": "بيتا","menus.tools": "الأدوات","model.addMoreModel": "انتقل إلى الإعدادات لإضافة المزيد من النماذج",diff --git a/web/i18n/ar-TN/workflow.json b/web/i18n/ar-TN/workflow.jsonindex bd525a065ac..5668fb84f8b 100644--- a/web/i18n/ar-TN/workflow.json+++ b/web/i18n/ar-TN/workflow.json@@ -1,5 +1,6 @@{- "blocks.agent": "وكيل",+ "blocks.agent": "Agent",+ "blocks.agent-v2": "Agent","blocks.answer": "إجابة","blocks.assigner": "معين المتغيرات","blocks.code": "كود",@@ -33,6 +34,7 @@"blocks.variable-aggregator": "مجمع المتغيرات","blocks.variable-assigner": "مجمع المتغيرات","blocksAbout.agent": "استدعاء نماذج اللغة الكبيرة للإجابة على الأسئلة أو معالجة اللغة الطبيعية",+ "blocksAbout.agent-v2": "استدعاء نماذج اللغة الكبيرة للإجابة على الأسئلة أو معالجة اللغة الطبيعية","blocksAbout.answer": "تحديد محتوى الرد لمحادثة الدردشة","blocksAbout.assigner": "تُستخدم عقدة تعيين المتغير لتعيين قيم للمتغيرات القابلة للكتابة (مثل متغيرات المحادثة).","blocksAbout.code": "تنفيذ قطعة من كود Python أو NodeJS لتنفيذ منطق مخصص",@@ -414,6 +416,7 @@"nodes.agent.pluginNotFoundDesc": "تم تثبيت هذا الملحق من GitHub. يرجى الانتقال إلى الملحقات لإعادة التثبيت","nodes.agent.pluginNotInstalled": "هذا الملحق غير مثبت","nodes.agent.pluginNotInstalledDesc": "تم تثبيت هذا الملحق من GitHub. يرجى الانتقال إلى الملحقات لإعادة التثبيت",+ "nodes.agent.roster.label": "وكيل","nodes.agent.strategy.configureTip": "يرجى تكوين استراتيجية الوكيل.","nodes.agent.strategy.configureTipDesc": "بعد تكوين استراتيجية الوكيل، ستقوم هذه العقدة تلقائيًا بتحميل التكوينات المتبقية. ستؤثر الاستراتيجية على آلية التفكير في الأدوات متعددة الخطوات. ","nodes.agent.strategy.label": "استراتيجية الوكيل",diff --git a/web/i18n/de-DE/common.json b/web/i18n/de-DE/common.jsonindex 008ff6e8270..ad337a46eb2 100644--- a/web/i18n/de-DE/common.json+++ b/web/i18n/de-DE/common.json@@ -318,6 +318,7 @@"menus.newDataset": "Wissen erstellen","menus.plugins": "Integrationen","menus.pluginsTips": "Integrieren Sie Integrationen von Drittanbietern oder erstellen Sie ChatGPT-kompatible KI-Integrationen.",+ "menus.roster": "Agent-Verzeichnis","menus.status": "Beta","menus.tools": "Werkzeuge","model.addMoreModel": "Gehen Sie zu den Einstellungen, um mehr Modelle hinzuzufügen",diff --git a/web/i18n/de-DE/workflow.json b/web/i18n/de-DE/workflow.jsonindex 75478d61c4d..167451e7145 100644--- a/web/i18n/de-DE/workflow.json+++ b/web/i18n/de-DE/workflow.json@@ -1,5 +1,6 @@{"blocks.agent": "Agent",+ "blocks.agent-v2": "Agent","blocks.answer": "Antwort","blocks.assigner": "Variablenzuweiser","blocks.code": "Code",@@ -33,6 +34,7 @@"blocks.variable-aggregator": "Variablen-Aggregator","blocks.variable-assigner": "Variablen-Zuweiser","blocksAbout.agent": "Aufruf großer Sprachmodelle zur Beantwortung von Fragen oder zur Verarbeitung natürlicher Sprache",+ "blocksAbout.agent-v2": "Aufruf großer Sprachmodelle zur Beantwortung von Fragen oder zur Verarbeitung natürlicher Sprache","blocksAbout.answer": "Definieren Sie den Antwortinhalt einer Chat-Konversation","blocksAbout.assigner": "Der Variablenzuweisungsknoten wird verwendet, um beschreibbaren Variablen (wie Gesprächsvariablen) Werte zuzuweisen.","blocksAbout.code": "Ein Stück Python- oder NodeJS-Code ausführen, um benutzerdefinierte Logik zu implementieren",@@ -414,6 +416,7 @@"nodes.agent.pluginNotFoundDesc": "Dieses Integration wird von GitHub installiert. Bitte gehen Sie zu Integrationen, um sie neu zu installieren","nodes.agent.pluginNotInstalled": "Dieses Integration ist nicht installiert","nodes.agent.pluginNotInstalledDesc": "Dieses Integration wird von GitHub installiert. Bitte gehen Sie zu Integrationen, um sie neu zu installieren",+ "nodes.agent.roster.label": "Agent","nodes.agent.strategy.configureTip": "Bitte konfigurieren Sie die Agentenstrategie.","nodes.agent.strategy.configureTipDesc": "Nach der Konfiguration der agentischen Strategie lädt dieser Knoten automatisch die verbleibenden Konfigurationen. Die Strategie wirkt sich auf den Mechanismus des mehrstufigen Tool-Reasoning aus.","nodes.agent.strategy.label": "Agentische Strategie",diff --git a/web/i18n/en-US/agent-v-2.json b/web/i18n/en-US/agent-v-2.jsonnew file mode 100644index 00000000000..f94d9197ad7--- /dev/null+++ b/web/i18n/en-US/agent-v-2.json@@ -0,0 +1,382 @@+{+ "agentDetail.access.actionUnavailable": "This action is not available yet.",+ "agentDetail.access.actions.monitoring": "Monitoring",+ "agentDetail.access.copyAccessUrl": "Copy access URL",+ "agentDetail.access.copyFailed": "Failed to copy reference.",+ "agentDetail.access.copyReference": "Copy reference for {{name}}",+ "agentDetail.access.copyServiceEndpoint": "Copy service API endpoint",+ "agentDetail.access.description": "Every surface this agent is reachable from.",+ "agentDetail.access.empty": "No linked access points",+ "agentDetail.access.emptyDescription": "This roster agent has no app or workflow references yet.",+ "agentDetail.access.entries.agentApp.description": "Agent app linked to this roster agent.",+ "agentDetail.access.entries.agentApp.name": "Agent app",+ "agentDetail.access.entries.workflow.description": "Workflow and node reference linked to this roster agent.",+ "agentDetail.access.entries.workflow.name": "Workflow node",+ "agentDetail.access.entryCount_one": "{{count}} entry",+ "agentDetail.access.entryCount_other": "{{count}} entries",+ "agentDetail.access.groups.references.heading": "References",+ "agentDetail.access.groups.references.label": "Linked references",+ "agentDetail.access.learnMore": "Learn more",+ "agentDetail.access.moreActions": "More actions for {{name}}",+ "agentDetail.access.serviceApi.actions.apiKey": "API Key",+ "agentDetail.access.serviceApi.actions.apiReference": "API Reference",+ "agentDetail.access.serviceApi.endpoint": "Service API Endpoint",+ "agentDetail.access.serviceApi.title": "Backend service API",+ "agentDetail.access.status.disabled": "Disabled",+ "agentDetail.access.status.enabled": "Enabled",+ "agentDetail.access.status.inService": "In service",+ "agentDetail.access.status.outOfService": "Out of service",+ "agentDetail.access.title": "Access Point",+ "agentDetail.access.toggleSurface": "Toggle {{name}} access",+ "agentDetail.access.webApp.accessUrl": "Access URL",+ "agentDetail.access.webApp.actions.customize": "Customize",+ "agentDetail.access.webApp.actions.embedded": "Embedded",+ "agentDetail.access.webApp.actions.launch": "Launch",+ "agentDetail.access.webApp.actions.settings": "Settings",+ "agentDetail.access.webApp.refreshUrl": "Refresh access URL",+ "agentDetail.access.webApp.showQrCode": "Show QR code",+ "agentDetail.access.webApp.ssoEnabled": "SSO Enabled",+ "agentDetail.access.webApp.title": "Web app",+ "agentDetail.access.workflow.description": "Used as a node inside the workflow",+ "agentDetail.access.workflow.empty": "No workflow references yet.",+ "agentDetail.access.workflow.loadFailed": "Failed to load workflow references.",+ "agentDetail.access.workflow.loading": "Loading workflow references…",+ "agentDetail.access.workflow.nodeCount_one": "{{count}} node",+ "agentDetail.access.workflow.nodeCount_other": "{{count}} nodes",+ "agentDetail.access.workflow.notAvailable": "N/A",+ "agentDetail.access.workflow.openInStudio": "Open in Studio",+ "agentDetail.access.workflow.openInStudioFor": "Open {{name}} in Studio",+ "agentDetail.access.workflow.table.actions": "Actions",+ "agentDetail.access.workflow.table.lastUpdated": "Last updated",+ "agentDetail.access.workflow.table.name": "Name",+ "agentDetail.access.workflow.table.nodes": "Nodes",+ "agentDetail.access.workflow.table.version": "Version",+ "agentDetail.access.workflow.title": "Workflow access",+ "agentDetail.configure.advancedSettings.description": "For power users. Env vars, sandbox & memory.",+ "agentDetail.configure.advancedSettings.envEditor.add": "Add environment variable",+ "agentDetail.configure.advancedSettings.envEditor.deleteVariable": "Delete {{key}}",+ "agentDetail.configure.advancedSettings.envEditor.hideValue": "Hide {{key}} value",+ "agentDetail.configure.advancedSettings.envEditor.importEnv": "Import .env",+ "agentDetail.configure.advancedSettings.envEditor.importEnvTip.mac": "To show hidden .env files, press Command + Shift + . in the file picker.",+ "agentDetail.configure.advancedSettings.envEditor.importEnvTip.other": "If your .env file is hidden, enable hidden files in your system file picker.",+ "agentDetail.configure.advancedSettings.envEditor.importEnvTip.windows": "To show hidden .env files, enable Hidden items in File Explorer.",+ "agentDetail.configure.advancedSettings.envEditor.keyColumn": "Key",+ "agentDetail.configure.advancedSettings.envEditor.keyPlaceholder": "Key",+ "agentDetail.configure.advancedSettings.envEditor.label": "Env Editor",+ "agentDetail.configure.advancedSettings.envEditor.revealValue": "Reveal {{key}} value",+ "agentDetail.configure.advancedSettings.envEditor.scopeColumn": "Scope",+ "agentDetail.configure.advancedSettings.envEditor.scopePlain": "Plain",+ "agentDetail.configure.advancedSettings.envEditor.scopeSecret": "Secret",+ "agentDetail.configure.advancedSettings.envEditor.scopeSelector": "Select environment variable scope",+ "agentDetail.configure.advancedSettings.envEditor.tip": "Environment variables available to this agent at runtime.",+ "agentDetail.configure.advancedSettings.envEditor.toggle": "Toggle env editor",+ "agentDetail.configure.advancedSettings.envEditor.valueColumn": "Value",+ "agentDetail.configure.advancedSettings.envEditor.valuePlaceholder": "Value",+ "agentDetail.configure.advancedSettings.label": "Advanced Settings",+ "agentDetail.configure.advancedSettings.toggle": "Toggle advanced settings",+ "agentDetail.configure.chatFeatures.description": "Shape the end-user chat experience on your web app and chat surfaces.",+ "agentDetail.configure.chatFeatures.title": "Chat Features",+ "agentDetail.configure.files.add": "Add file",+ "agentDetail.configure.files.empty.description": "Upload docs the agent can read, like specs, templates, or guidelines",+ "agentDetail.configure.files.empty.title": "No files yet",+ "agentDetail.configure.files.label": "Files",+ "agentDetail.configure.files.preview.empty": "No preview content.",+ "agentDetail.configure.files.preview.failed": "Failed to load preview.",+ "agentDetail.configure.files.remove": "Remove {{name}}",+ "agentDetail.configure.files.tip": "Files this agent can use while orchestrating tasks.",+ "agentDetail.configure.files.toggle": "Toggle files",+ "agentDetail.configure.files.treeLabel": "Agent files",+ "agentDetail.configure.files.upload.action": "Upload",+ "agentDetail.configure.files.upload.browse": "browse",+ "agentDetail.configure.files.upload.description": "Upload a file for this agent.",+ "agentDetail.configure.files.upload.dropzone": "Drop a file here, or",+ "agentDetail.configure.files.upload.failed": "Failed to upload file.",+ "agentDetail.configure.files.upload.fileType": "FILE",+ "agentDetail.configure.files.upload.invalidFile": "Upload one file.",+ "agentDetail.configure.files.upload.success": "File uploaded.",+ "agentDetail.configure.files.upload.title": "Upload file",+ "agentDetail.configure.knowledgeRetrieval.add": "Add knowledge retrieval",+ "agentDetail.configure.knowledgeRetrieval.defaultName": "Retrieval {{index}}",+ "agentDetail.configure.knowledgeRetrieval.dialog.knowledge.add": "Add knowledge",+ "agentDetail.configure.knowledgeRetrieval.dialog.knowledge.empty": "Click the “+” button to add knowledge",+ "agentDetail.configure.knowledgeRetrieval.dialog.knowledge.label": "Knowledge",+ "agentDetail.configure.knowledgeRetrieval.dialog.knowledge.retrievalSetting": "Retrieval Setting",+ "agentDetail.configure.knowledgeRetrieval.dialog.learnMore": "Learn more about Knowledge retrieval",+ "agentDetail.configure.knowledgeRetrieval.dialog.metadata.automatic": "Automatic",+ "agentDetail.configure.knowledgeRetrieval.dialog.metadata.conditions": "Conditions",+ "agentDetail.configure.knowledgeRetrieval.dialog.metadata.disabled": "Disabled",+ "agentDetail.configure.knowledgeRetrieval.dialog.metadata.label": "Metadata Filtering",+ "agentDetail.configure.knowledgeRetrieval.dialog.metadata.manual": "Manual",+ "agentDetail.configure.knowledgeRetrieval.dialog.metadata.modeLabel": "Select metadata filtering mode",+ "agentDetail.configure.knowledgeRetrieval.dialog.nameLabel": "Knowledge retrieval name",+ "agentDetail.configure.knowledgeRetrieval.dialog.query.agent": "Agent decide",+ "agentDetail.configure.knowledgeRetrieval.dialog.query.agentDescription": "The agent writes its own query from the prompt and available context. Nothing to set up here.",+ "agentDetail.configure.knowledgeRetrieval.dialog.query.custom": "Custom query",+ "agentDetail.configure.knowledgeRetrieval.dialog.query.customDescription": "Write a fixed query for this retrieval source.",+ "agentDetail.configure.knowledgeRetrieval.dialog.query.customInputLabel": "Custom query text",+ "agentDetail.configure.knowledgeRetrieval.dialog.query.customPlaceholder": "Type a search query",+ "agentDetail.configure.knowledgeRetrieval.dialog.query.label": "Query",+ "agentDetail.configure.knowledgeRetrieval.dialog.title": "Knowledge Retrieval · Agent decide",+ "agentDetail.configure.knowledgeRetrieval.edit": "Edit {{name}}",+ "agentDetail.configure.knowledgeRetrieval.empty.description": "Connect a knowledge base the agent can search while answering",+ "agentDetail.configure.knowledgeRetrieval.empty.title": "No knowledge yet",+ "agentDetail.configure.knowledgeRetrieval.label": "Knowledge Retrieval",+ "agentDetail.configure.knowledgeRetrieval.remove": "Remove {{name}}",+ "agentDetail.configure.knowledgeRetrieval.retrievalOne": "Retrieval 1",+ "agentDetail.configure.knowledgeRetrieval.retrievalTwo": "Retrieval 2",+ "agentDetail.configure.knowledgeRetrieval.tip": "Knowledge retrieval sources this agent can use while orchestrating tasks.",+ "agentDetail.configure.knowledgeRetrieval.toggle": "Toggle knowledge retrieval",+ "agentDetail.configure.model.label": "Model",+ "agentDetail.configure.orchestrate": "Orchestrate",+ "agentDetail.configure.preview.chatFeatures": "Chat Features",+ "agentDetail.configure.preview.empty.defaultAgentName": "Agent",+ "agentDetail.configure.preview.empty.description": "Send a message to test the current draft.",+ "agentDetail.configure.preview.empty.noInstructionsDescription": "No instructions yet, so replies come from the plain model.",+ "agentDetail.configure.preview.endUserAuth": "End-user authentication",+ "agentDetail.configure.preview.restart": "Restart preview",+ "agentDetail.configure.preview.title": "Preview",+ "agentDetail.configure.prompt.copied": "Prompt copied",+ "agentDetail.configure.prompt.copy": "Copy prompt",+ "agentDetail.configure.prompt.copyFailed": "Failed to copy prompt.",+ "agentDetail.configure.prompt.insert.label": "Insert",+ "agentDetail.configure.prompt.insert.question": "Start question",+ "agentDetail.configure.prompt.insert.reportFile": "Output report file",+ "agentDetail.configure.prompt.insert.tenders": "Start tenders",+ "agentDetail.configure.prompt.label": "Prompt",+ "agentDetail.configure.prompt.mention.davidHayes": "David Hayes",+ "agentDetail.configure.prompt.mention.label": "Mention",+ "agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",+ "agentDetail.configure.prompt.placeholder": "Write instructions here,",+ "agentDetail.configure.prompt.tip": "Define how this agent should interpret inputs, call tools, and produce outputs.",+ "agentDetail.configure.publishBar.draft": "Draft",+ "agentDetail.configure.publishBar.publishUpdate": "Publish update",+ "agentDetail.configure.publishBar.published": "Published",+ "agentDetail.configure.publishBar.publishedAt": "Published {{time}}",+ "agentDetail.configure.publishBar.publishing": "Publishing…",+ "agentDetail.configure.publishBar.saved": "Saved 5 min ago",+ "agentDetail.configure.publishBar.savedAt": "Saved {{time}}",+ "agentDetail.configure.publishBar.unpublishedChanges": "Unpublished changes",+ "agentDetail.configure.publishBar.upToDate": "Up to date",+ "agentDetail.configure.publishBar.versionHistory": "Open version history",+ "agentDetail.configure.publishImpact.affectedWorkflows": "Affected Workflows",+ "agentDetail.configure.publishImpact.cancel": "Cancel",+ "agentDetail.configure.publishImpact.descriptionPrefix": "Your agent appears in",+ "agentDetail.configure.publishImpact.descriptionSuffix": ". Changes will impact them.",+ "agentDetail.configure.publishImpact.fallbackAgentName": "this agent",+ "agentDetail.configure.publishImpact.title": "{{action}} to {{name}}",+ "agentDetail.configure.publishImpact.workflowCount_one": "{{count}} workflow",+ "agentDetail.configure.publishImpact.workflowCount_other": "{{count}} workflows",+ "agentDetail.configure.skills.add": "Add skill",+ "agentDetail.configure.skills.detail.contentRegion": "Skill detail content",+ "agentDetail.configure.skills.detail.fileCount": "{{count}} FILES",+ "agentDetail.configure.skills.detail.fileTreeLabel": "Skill files",+ "agentDetail.configure.skills.detail.files": "Files",+ "agentDetail.configure.skills.empty.description": "Skills give the agent reusable expertise it can call while working",+ "agentDetail.configure.skills.empty.title": "No skills yet",+ "agentDetail.configure.skills.itemType": "Skill",+ "agentDetail.configure.skills.label": "Skills",+ "agentDetail.configure.skills.remove": "Remove {{name}}",+ "agentDetail.configure.skills.tip": "Skills this agent can use while orchestrating tasks.",+ "agentDetail.configure.skills.toggle": "Toggle skills",+ "agentDetail.configure.skills.upload.action": "Upload",+ "agentDetail.configure.skills.upload.browse": "browse",+ "agentDetail.configure.skills.upload.description": "Upload a .zip or .skill package for this agent.",+ "agentDetail.configure.skills.upload.dropzone": "Drop a skill package here, or",+ "agentDetail.configure.skills.upload.failed": "Failed to upload skill.",+ "agentDetail.configure.skills.upload.fileType": "ZIP / SKILL",+ "agentDetail.configure.skills.upload.invalidFile": "Upload a .zip or .skill file.",+ "agentDetail.configure.skills.upload.success": "Skill uploaded.",+ "agentDetail.configure.skills.upload.title": "Upload skill",+ "agentDetail.configure.tools.add": "Add tool",+ "agentDetail.configure.tools.addMenu.cliTool.badge": "For developers",+ "agentDetail.configure.tools.addMenu.cliTool.description": "Install a command line program the agent runs in its sandbox. Needs install and usually API keys.",+ "agentDetail.configure.tools.addMenu.cliTool.label": "CLI tool",+ "agentDetail.configure.tools.addMenu.tool.description": "Pick a tool already in this workspace, like web search or integrations.",+ "agentDetail.configure.tools.addMenu.tool.label": "Tool",+ "agentDetail.configure.tools.cliDialog.description": "Install a CLI tool from any package registry. The agent gains shell access to the binary it provides.",+ "agentDetail.configure.tools.cliDialog.editTitle": "Edit CLI Tool",+ "agentDetail.configure.tools.cliDialog.env.description": "Store API keys, tokens, or secrets that this CLI tool needs. Values are encrypted at rest and injected as environment variables when the agent invokes the tool.",+ "agentDetail.configure.tools.cliDialog.env.label": "Environment Variables",+ "agentDetail.configure.tools.cliDialog.env.optional": "(optional)",+ "agentDetail.configure.tools.cliDialog.installCommand.description": "Sandboxed · runs once on first invocation",+ "agentDetail.configure.tools.cliDialog.installCommand.label": "Install Command",+ "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "Paste your install command here, e.g. npm install -g @lark/cli · brew install jq",+ "agentDetail.configure.tools.cliDialog.installCommand.required": "Install command is required.",+ "agentDetail.configure.tools.cliDialog.learnMore": "Learn more about CLI Tool",+ "agentDetail.configure.tools.cliDialog.name.label": "CLI Tool Name",+ "agentDetail.configure.tools.cliDialog.name.placeholder": "Name your CLI tool",+ "agentDetail.configure.tools.cliDialog.name.required": "CLI tool name is required.",+ "agentDetail.configure.tools.cliDialog.securityTip": "Never visible to agent prompt; injected only as $VAR at runtime",+ "agentDetail.configure.tools.cliDialog.title": "Add a CLI Tool",+ "agentDetail.configure.tools.cliTool": "CLI Tool",+ "agentDetail.configure.tools.credential.authOne": "Auth 1",+ "agentDetail.configure.tools.credential.endUserOAuth": "End-user · OAuth",+ "agentDetail.configure.tools.editAction": "Edit {{name}}",+ "agentDetail.configure.tools.empty.description": "Tools let the agent act, like searching the web or calling your apps",+ "agentDetail.configure.tools.empty.title": "No tools yet",+ "agentDetail.configure.tools.label": "Tools",+ "agentDetail.configure.tools.moreActions": "More actions for {{name}}",+ "agentDetail.configure.tools.pluginType": "Plugin",+ "agentDetail.configure.tools.preAuthorize": "Pre-authorize",+ "agentDetail.configure.tools.removeAction": "Remove {{name}}",+ "agentDetail.configure.tools.removeProvider": "Remove all tools",+ "agentDetail.configure.tools.tip": "Tools this agent can call while orchestrating tasks.",+ "agentDetail.configure.tools.toggle": "Toggle tools",+ "agentDetail.configure.tools.toolTabs.all": "All",+ "agentDetail.configure.tools.toolTabs.cli": "CLI",+ "agentDetail.configure.tools.toolTabs.custom": "Custom",+ "agentDetail.configure.tools.toolTabs.mcp": "MCP",+ "agentDetail.configure.tools.toolTabs.plugins": "Plugins",+ "agentDetail.configure.tools.toolTabs.workflow": "Workflow",+ "agentDetail.documentTitle": "Agent",+ "agentDetail.history": "History",+ "agentDetail.logs.description": "Full logs record the running status of the application, including user inputs, agent replies, planning and tool uses.",+ "agentDetail.logs.empty": "No logs found",+ "agentDetail.logs.filters.period.allTime": "All time",+ "agentDetail.logs.filters.period.label": "Log period",+ "agentDetail.logs.filters.period.last30days": "Last 30 days",+ "agentDetail.logs.filters.period.last7days": "Last 7 days",+ "agentDetail.logs.filters.search.label": "Search logs",+ "agentDetail.logs.filters.search.placeholder": "Search",+ "agentDetail.logs.filters.sort.lastCreatedTime": "Last Created time",+ "agentDetail.logs.filters.sort.lastUpdatedTime": "Last Updated time",+ "agentDetail.logs.filters.source.all": "Source",+ "agentDetail.logs.filters.source.label": "Log source",+ "agentDetail.logs.filters.source.webapp": "Webapp",+ "agentDetail.logs.filters.source.workflow": "Workflow",+ "agentDetail.logs.learnMore": "Learn more",+ "agentDetail.logs.table.createdTime": "Created Time",+ "agentDetail.logs.table.endUser": "End-user",+ "agentDetail.logs.table.messageCount": "Msg. Count",+ "agentDetail.logs.table.operationRate": "Op. Rate",+ "agentDetail.logs.table.title": "Title",+ "agentDetail.logs.table.unread": "Unread",+ "agentDetail.logs.table.updatedTime": "Updated Time",+ "agentDetail.logs.table.userRate": "User Rate",+ "agentDetail.logs.title": "Logs",+ "agentDetail.memorySettings.budgetLabel": "Memory Budget",+ "agentDetail.memorySettings.description": "Memory settings from the active configuration snapshot.",+ "agentDetail.memorySettings.export.description": "Memory export is planned for a later release.",+ "agentDetail.memorySettings.export.download": "Download",+ "agentDetail.memorySettings.export.soon": "Soon",+ "agentDetail.memorySettings.export.title": "Export current memory",+ "agentDetail.memorySettings.notConfigured": "Not configured",+ "agentDetail.memorySettings.scopeLabel": "Memory Scope",+ "agentDetail.memorySettings.title": "Memory",+ "agentDetail.metadata.activeVersionLabel": "Active Version",+ "agentDetail.metadata.appIdLabel": "App ID",+ "agentDetail.metadata.description": "Read-only roster fields returned by the agent backend.",+ "agentDetail.metadata.emptyValue": "Not available",+ "agentDetail.metadata.scopeLabel": "Scope",+ "agentDetail.metadata.scopes.roster": "Roster",+ "agentDetail.metadata.scopes.workflow_only": "Workflow only",+ "agentDetail.metadata.sourceLabel": "Source",+ "agentDetail.metadata.statusLabel": "Status",+ "agentDetail.metadata.title": "Metadata",+ "agentDetail.metadata.updatedAtLabel": "Updated At",+ "agentDetail.metadata.workflowIdLabel": "Workflow ID",+ "agentDetail.metadata.workflowNodeIdLabel": "Workflow Node ID",+ "agentDetail.monitoring.change": "{{value}} from previous period",+ "agentDetail.monitoring.dateRangeLabel": "Date range",+ "agentDetail.monitoring.description": "Track the reusable agent activity, cost, and interaction quality across workflows.",+ "agentDetail.monitoring.learnMore": "Learn more",+ "agentDetail.monitoring.metrics.activeUsers.explanation": "Unique end users who triggered workflows using this agent.",+ "agentDetail.monitoring.metrics.activeUsers.title": "Active Users",+ "agentDetail.monitoring.metrics.avgSessionInteractions.explanation": "Continuous user-agent communication count for this access point.",+ "agentDetail.monitoring.metrics.avgSessionInteractions.title": "Avg. Session Interactions",+ "agentDetail.monitoring.metrics.tokenOutputSpeed.explanation": "Average output speed from the beginning of the request to completion.",+ "agentDetail.monitoring.metrics.tokenOutputSpeed.title": "Token Output Speed",+ "agentDetail.monitoring.metrics.tokenUsage.explanation": "Estimated token cost produced by this agent across workflow runs.",+ "agentDetail.monitoring.metrics.tokenUsage.title": "Token Usage",+ "agentDetail.monitoring.metrics.totalConversations.explanation": "Daily AI conversations that reached this agent through the selected access point.",+ "agentDetail.monitoring.metrics.totalConversations.title": "Total Conversations",+ "agentDetail.monitoring.metrics.totalMessages.explanation": "Daily agent interaction count.",+ "agentDetail.monitoring.metrics.totalMessages.title": "Total Messages",+ "agentDetail.monitoring.metrics.userSatisfactionRate.explanation": "The number of likes per 1,000 messages for this agent.",+ "agentDetail.monitoring.metrics.userSatisfactionRate.title": "User Satisfaction Rate",+ "agentDetail.monitoring.pickSource": "Pick an app",+ "agentDetail.monitoring.sourceLabel": "App",+ "agentDetail.monitoring.sourceTrigger": "Source {{name}}",+ "agentDetail.monitoring.sources.all": "All",+ "agentDetail.monitoring.timeRangeLabel": "Time range",+ "agentDetail.monitoring.timeRanges.custom": "Custom",+ "agentDetail.monitoring.timeRanges.last30days": "Last 30 days",+ "agentDetail.monitoring.timeRanges.last7days": "Last 7 days",+ "agentDetail.monitoring.timeRanges.today": "Today",+ "agentDetail.monitoring.title": "Monitoring",+ "agentDetail.monitoring.tokenUsageConsumed": "Consumed tokens",+ "agentDetail.monitoring.units.tokenPerSecond": "Token/s",+ "agentDetail.navigationLabel": "Agent navigation",+ "agentDetail.publish": "Publish",+ "agentDetail.publishSoon": "Soon",+ "agentDetail.sections.access": "Access Point",+ "agentDetail.sections.configure": "Orchestrate",+ "agentDetail.sections.logs": "Logs",+ "agentDetail.sections.monitoring": "Monitoring",+ "agentDetail.subtitle": "Agent ID: {{agentId}}",+ "agentDetail.title": "Agent",+ "agentDetail.type": "AGENT",+ "agentDetail.versionHistory.active": "Active",+ "agentDetail.versionHistory.empty": "No versions yet",+ "agentDetail.versionHistory.filter": "Filter versions",+ "agentDetail.versionHistory.versionName": "Version {{version}}",+ "roster.createAgent": "Create agent",+ "roster.createAgentOptions": "Create agent options",+ "roster.createDialog.description": "Create a reusable agent in this workspace roster.",+ "roster.createDialog.title": "Create agent",+ "roster.createFailed": "Failed to create agent.",+ "roster.createForm.changeIcon": "Change agent icon",+ "roster.createForm.descriptionLabel": "Description",+ "roster.createForm.descriptionOptional": "(optional)",+ "roster.createForm.descriptionPlaceholder": "e.g. Gathers sources on a topic and summarizes the key findings",+ "roster.createForm.nameLabel": "Name",+ "roster.createForm.namePlaceholder": "e.g. Max",+ "roster.createForm.nameRequired": "Name is required.",+ "roster.createForm.roleLabel": "Role",+ "roster.createForm.rolePlaceholder": "e.g. Research Assistant",+ "roster.createForm.roleRequired": "Role is required.",+ "roster.createSuccess": "Agent created.",+ "roster.dateTimeFormat": "MM/DD/YYYY hh:mm:ss A",+ "roster.deleteDialog.description": "This agent will be removed from the active roster list.",+ "roster.deleteDialog.title": "Delete {{name}}?",+ "roster.deleteFailed": "Failed to delete agent.",+ "roster.deleteSuccess": "Agent deleted.",+ "roster.editAgent": "Edit {{name}}",+ "roster.editDialog.description": "Update the roster name, description, and role for this agent.",+ "roster.editDialog.title": "Edit agent",+ "roster.editInfo": "Edit Info",+ "roster.empty": "No agent yet",+ "roster.emptyDescription": "Agents saved to this workspace will appear here.",+ "roster.emptySearch": "No matching agents",+ "roster.emptySearchDescription": "Try another agent name.",+ "roster.filters.all": "All",+ "roster.filters.drafts": "Drafts",+ "roster.filters.label": "Agent filters",+ "roster.filters.published": "Published",+ "roster.learnMore": "Learn more about Agent Roster",+ "roster.listLabel": "Agent roster list",+ "roster.loadMore": "Load more",+ "roster.loadingError": "Failed to load agents. Refresh and try again.",+ "roster.moreActions": "More actions for {{name}}",+ "roster.nodeSelector.createInlineFailed": "Failed to create inline agent. Refresh and try again.",+ "roster.nodeSelector.dialogLabel": "Select an agent",+ "roster.nodeSelector.manageInAgentConsole": "Manage in Agent Console",+ "roster.nodeSelector.searchPlaceholder": "Search…",+ "roster.nodeSelector.startFromScratch": "Start from Scratch",+ "roster.references.label": "Workflows using {{name}}",+ "roster.references.trigger": "Workflows using {{name}}",+ "roster.searchLabel": "Search agents",+ "roster.searchPlaceholder": "Search agents by name…",+ "roster.sources.agent_app": "Agent app",+ "roster.sources.imported": "Imported",+ "roster.sources.system": "System",+ "roster.sources.workflow": "Workflow",+ "roster.status.active": "Active",+ "roster.status.archived": "Archived",+ "roster.tabs.agent": "Agent",+ "roster.tabs.human": "Human",+ "roster.tabsLabel": "Roster type",+ "roster.updateFailed": "Failed to update agent. Check the fields and try again.",+ "roster.updateSuccess": "Agent updated.",+ "roster.usageStatus.draft": "Draft"+}diff --git a/web/i18n/en-US/common.json b/web/i18n/en-US/common.jsonindex 63c94d0e298..429565887c6 100644--- a/web/i18n/en-US/common.json+++ b/web/i18n/en-US/common.json@@ -318,6 +318,7 @@"menus.newDataset": "Create Knowledge","menus.plugins": "Integrations","menus.pluginsTips": "Integrate third-party services or create ChatGPT-compatible AI integrations.",+ "menus.roster": "Roster","menus.status": "beta","menus.tools": "Tools","model.addMoreModel": "Go to settings to add more models",diff --git a/web/i18n/en-US/workflow.json b/web/i18n/en-US/workflow.jsonindex a983c24e7cc..ea7845f63a2 100644--- a/web/i18n/en-US/workflow.json+++ b/web/i18n/en-US/workflow.json@@ -1,5 +1,6 @@{"blocks.agent": "Agent",+ "blocks.agent-v2": "Agent","blocks.answer": "Answer","blocks.assigner": "Variable Assigner","blocks.code": "Code",@@ -33,6 +34,7 @@"blocks.variable-aggregator": "Variable Aggregator","blocks.variable-assigner": "Variable Aggregator","blocksAbout.agent": "Invoking large language models to answer questions or process natural language",+ "blocksAbout.agent-v2": "Invoking large language models to answer questions or process natural language","blocksAbout.answer": "Define the reply content of a chat conversation","blocksAbout.assigner": "The variable assignment node is used for assigning values to writable variables(like conversation variables).","blocksAbout.code": "Execute a piece of Python or NodeJS code to implement custom logic",@@ -378,6 +380,7 @@"globalVar.fieldsDescription.workflowId": "Workflow ID","globalVar.fieldsDescription.workflowRunId": "Workflow run ID","globalVar.title": "System Variables",+ "nodes.agent.advancedSetting": "Advanced Settings","nodes.agent.checkList.strategyNotSelected": "Strategy not selected","nodes.agent.clickToViewParameterSchema": "Click to view parameter schema","nodes.agent.configureModel": "Configure Model",@@ -400,13 +403,34 @@"nodes.agent.modelNotSupport.title": "Unsupported Model","nodes.agent.modelSelectorTooltips.deprecated": "This model is deprecated","nodes.agent.notAuthorized": "Not Authorized",+ "nodes.agent.outputVars.confirm": "Confirm",+ "nodes.agent.outputVars.defaultValueArrayInvalid": "Enter a JSON array.",+ "nodes.agent.outputVars.defaultValueBooleanInvalid": "Enter true or false.",+ "nodes.agent.outputVars.defaultValueFileUnsupported": "File defaults are not configurable here yet.",+ "nodes.agent.outputVars.defaultValueLabel": "Default",+ "nodes.agent.outputVars.defaultValueNumberInvalid": "Enter a valid number.",+ "nodes.agent.outputVars.defaultValueObjectInvalid": "Enter a JSON object.",+ "nodes.agent.outputVars.defaultValuePlaceholder": "Default value",+ "nodes.agent.outputVars.delete": "Delete {{name}}",+ "nodes.agent.outputVars.descriptionLabel": "Description",+ "nodes.agent.outputVars.descriptionPlaceholder": "Add description",+ "nodes.agent.outputVars.edit": "Edit {{name}}",+ "nodes.agent.outputVars.editorLabel": "Output variable editor","nodes.agent.outputVars.files.title": "agent generated files","nodes.agent.outputVars.files.transfer_method": "Transfer method.Value is remote_url or local_file","nodes.agent.outputVars.files.type": "Support type. Now only support image","nodes.agent.outputVars.files.upload_file_id": "Upload file id","nodes.agent.outputVars.files.url": "Image url","nodes.agent.outputVars.json": "agent generated json",+ "nodes.agent.outputVars.nameDuplicate": "Output name already exists",+ "nodes.agent.outputVars.nameInvalid": "Use letters, numbers, and underscores. Start with a letter or underscore.",+ "nodes.agent.outputVars.nameLabel": "Field name",+ "nodes.agent.outputVars.namePlaceholder": "Field Name",+ "nodes.agent.outputVars.newOutput": "New output",+ "nodes.agent.outputVars.requiredLabel": "Required",+ "nodes.agent.outputVars.showAdvancedOptions": "Show advanced options","nodes.agent.outputVars.text": "agent generated content",+ "nodes.agent.outputVars.typeLabel": "Output type","nodes.agent.outputVars.usage": "Model Usage Information","nodes.agent.parameterSchema": "Parameter Schema","nodes.agent.pluginInstaller.install": "Install",@@ -414,6 +438,17 @@"nodes.agent.pluginNotFoundDesc": "This integration is installed from GitHub. Please go to Integrations to reinstall","nodes.agent.pluginNotInstalled": "This integration is not installed","nodes.agent.pluginNotInstalledDesc": "This integration is installed from GitHub. Please go to Integrations to reinstall",+ "nodes.agent.roster.change": "Change",+ "nodes.agent.roster.editInConsole": "Edit in Agent Console",+ "nodes.agent.roster.inlineSetup.description": "A one-off setup that lives only in this node",+ "nodes.agent.roster.inlineSetup.name": "Inline setup",+ "nodes.agent.roster.inlineSetup.title": "Agent setup",+ "nodes.agent.roster.inlineSetup.type": "Only in this node",+ "nodes.agent.roster.label": "Agent",+ "nodes.agent.roster.makeCopy": "Make a copy",+ "nodes.agent.roster.more": "More agent actions",+ "nodes.agent.roster.openPanel": "Open {{name}} details",+ "nodes.agent.roster.panelLabel": "{{name}} details","nodes.agent.strategy.configureTip": "Please configure agentic strategy.","nodes.agent.strategy.configureTipDesc": "After configuring the agentic strategy, this node will automatically load the remaining configurations. The strategy will affect the mechanism of multi-step tool reasoning. ","nodes.agent.strategy.label": "Agentic Strategy",@@ -425,6 +460,11 @@"nodes.agent.strategyNotFoundDescAndSwitchVersion": "The installed integration version does not provide this strategy. Click to switch version.","nodes.agent.strategyNotInstallTooltip": "{{strategy}} is not installed","nodes.agent.strategyNotSet": "Agentic strategy Not Set",+ "nodes.agent.task.insert": "Insert",+ "nodes.agent.task.label": "Agent task",+ "nodes.agent.task.mention": "Mention",+ "nodes.agent.task.placeholder": "Describe what this agent should do...",+ "nodes.agent.task.tooltip": "Define the task instructions this agent should follow in this workflow.","nodes.agent.toolNotAuthorizedTooltip": "{{tool}} Not Authorized","nodes.agent.toolNotInstallTooltip": "{{tool}} is not installed","nodes.agent.toolbox": "toolbox",@@ -1210,7 +1250,7 @@"tabs.pluginByAuthor": "By {{author}}","tabs.question-understand": "Question Understand","tabs.requestToCommunity": "Requests to the community",- "tabs.searchBlock": "Search node",+ "tabs.searchBlock": "Search nodes, agent, human, Knowledge","tabs.searchDataSource": "Search Data Source","tabs.searchSnippets": "Search snippets...","tabs.searchTool": "Search integration",diff --git a/web/i18n/es-ES/common.json b/web/i18n/es-ES/common.jsonindex 3672515b88c..7d7fb80bfc2 100644--- a/web/i18n/es-ES/common.json+++ b/web/i18n/es-ES/common.json@@ -318,6 +318,7 @@"menus.newDataset": "Crear Conocimiento","menus.plugins": "Integraciones","menus.pluginsTips": "Integrar integraciones de terceros o crear Integraciones AI compatibles con ChatGPT.",+ "menus.roster": "Directorio de agentes","menus.status": "beta","menus.tools": "Herramientas","model.addMoreModel": "Ir a configuraciones para agregar más modelos",diff --git a/web/i18n/es-ES/workflow.json b/web/i18n/es-ES/workflow.jsonindex ecd36f6f574..8a1e55de077 100644--- a/web/i18n/es-ES/workflow.json+++ b/web/i18n/es-ES/workflow.json@@ -1,5 +1,6 @@{- "blocks.agent": "Agente",+ "blocks.agent": "Agent",+ "blocks.agent-v2": "Agent","blocks.answer": "Respuesta","blocks.assigner": "Asignador de Variables","blocks.code": "Código",@@ -33,6 +34,7 @@"blocks.variable-aggregator": "Agregador de variables","blocks.variable-assigner": "Asignador de variables","blocksAbout.agent": "Invocar modelos de lenguaje de gran tamaño para responder preguntas o procesar el lenguaje natural",+ "blocksAbout.agent-v2": "Invocar modelos de lenguaje de gran tamaño para responder preguntas o procesar el lenguaje natural","blocksAbout.answer": "Define el contenido de respuesta de una conversación de chat","blocksAbout.assigner": "El nodo de asignación de variables se utiliza para asignar valores a variables escribibles (como variables de conversación).","blocksAbout.code": "Ejecuta un fragmento de código Python o NodeJS para implementar lógica personalizada",@@ -414,6 +416,7 @@"nodes.agent.pluginNotFoundDesc": "Este integración se instala desde GitHub. Por favor, vaya a Integraciones para reinstalar","nodes.agent.pluginNotInstalled": "Este integración no está instalado","nodes.agent.pluginNotInstalledDesc": "Este integración se instala desde GitHub. Por favor, vaya a Integraciones para reinstalar",+ "nodes.agent.roster.label": "Agente","nodes.agent.strategy.configureTip": "Configure la estrategia de agentes.","nodes.agent.strategy.configureTipDesc": "Después de configurar la estrategia agentica, este nodo cargará automáticamente las configuraciones restantes. La estrategia afectará el mecanismo de razonamiento de herramientas de varios pasos.","nodes.agent.strategy.label": "Estrategia Agentica",diff --git a/web/i18n/fa-IR/common.json b/web/i18n/fa-IR/common.jsonindex 3e7bc10046e..e461067627a 100644--- a/web/i18n/fa-IR/common.json+++ b/web/i18n/fa-IR/common.json@@ -318,6 +318,7 @@"menus.newDataset": "ایجاد دانش","menus.plugins": "یکپارچهسازیها","menus.pluginsTips": "یکپارچهسازیهای شخص ثالث را ادغام کنید یا یکپارچهسازیهای هوش مصنوعی سازگار با ChatGPT ایجاد کنید.",+ "menus.roster": "فهرست عاملها","menus.status": "بتا","menus.tools": "ابزارها","model.addMoreModel": "برای افزودن مدلهای بیشتر به تنظیمات بروید",diff --git a/web/i18n/fa-IR/workflow.json b/web/i18n/fa-IR/workflow.jsonindex 43c479c3ffd..84ed7b640c8 100644--- a/web/i18n/fa-IR/workflow.json+++ b/web/i18n/fa-IR/workflow.json@@ -1,5 +1,6 @@{- "blocks.agent": "عامل",+ "blocks.agent": "Agent",+ "blocks.agent-v2": "Agent","blocks.answer": "پاسخ","blocks.assigner": "تخصیصدهنده متغیر","blocks.code": "کد",@@ -33,6 +34,7 @@"blocks.variable-aggregator": "تجمیعکننده متغیر","blocks.variable-assigner": "تخصیصدهنده متغیر","blocksAbout.agent": "فراخوانی مدلهای زبانی بزرگ برای پاسخ به سؤالات یا پردازش زبان طبیعی",+ "blocksAbout.agent-v2": "فراخوانی مدلهای زبانی بزرگ برای پاسخ به سؤالات یا پردازش زبان طبیعی","blocksAbout.answer": "تعریف محتوای پاسخ در مکالمه چت","blocksAbout.assigner": "گره تخصیص متغیر برای مقداردهی به متغیرهای قابلنوشتن (مانند متغیرهای مکالمه) استفاده میشود.","blocksAbout.code": "اجرای کد Python یا NodeJS برای پیادهسازی منطق سفارشی",@@ -414,6 +416,7 @@"nodes.agent.pluginNotFoundDesc": "این یکپارچهسازی از GitHub نصب شده. برای نصب مجدد به بخش یکپارچهسازیها بروید.","nodes.agent.pluginNotInstalled": "این یکپارچهسازی نصب نشده است","nodes.agent.pluginNotInstalledDesc": "این یکپارچهسازی از GitHub نصب شده. برای نصب مجدد به بخش یکپارچهسازیها بروید.",+ "nodes.agent.roster.label": "عامل","nodes.agent.strategy.configureTip": "لطفاً استراتژی عامل را پیکربندی کنید.","nodes.agent.strategy.configureTipDesc": "پس از انتخاب استراتژی عامل، تنظیمات مربوطه بهطور خودکار بارگذاری میشوند. این استراتژی بر مکانیسم استدلال چندمرحلهای ابزار تأثیر میگذارد.","nodes.agent.strategy.label": "استراتژی عامل",diff --git a/web/i18n/fr-FR/common.json b/web/i18n/fr-FR/common.jsonindex 95d90f056c7..7de464807c2 100644--- a/web/i18n/fr-FR/common.json+++ b/web/i18n/fr-FR/common.json@@ -318,6 +318,7 @@"menus.newDataset": "Créer des Connaissances","menus.plugins": "Intégrations","menus.pluginsTips": "Intégrez des intégrations tiers ou créez des AI-Intégrations compatibles avec ChatGPT.",+ "menus.roster": "Répertoire des agents","menus.status": "bêta","menus.tools": "Outils","model.addMoreModel": "Allez dans les paramètres pour ajouter plus de modèles",diff --git a/web/i18n/fr-FR/workflow.json b/web/i18n/fr-FR/workflow.jsonindex 6820df36460..abcbe4feb9d 100644--- a/web/i18n/fr-FR/workflow.json+++ b/web/i18n/fr-FR/workflow.json@@ -1,5 +1,6 @@{"blocks.agent": "Agent",+ "blocks.agent-v2": "Agent","blocks.answer": "Réponse","blocks.assigner": "Assignateur de Variables","blocks.code": "Code",@@ -33,6 +34,7 @@"blocks.variable-aggregator": "Agrégateur de variables","blocks.variable-assigner": "Assigneur de variables","blocksAbout.agent": "Appel de grands modèles de langage pour répondre à des questions ou traiter le langage naturel",+ "blocksAbout.agent-v2": "Appel de grands modèles de langage pour répondre à des questions ou traiter le langage naturel","blocksAbout.answer": "Définir le contenu de la réponse d'une conversation","blocksAbout.assigner": "Le nœud d'assignation de variables est utilisé pour attribuer des valeurs aux variables modifiables (comme les variables de conversation).","blocksAbout.code": "Exécuter un morceau de code Python ou NodeJS pour implémenter une logique personnalisée",@@ -414,6 +416,7 @@"nodes.agent.pluginNotFoundDesc": "Ce intégration est installé à partir de GitHub. Veuillez aller dans Intégrations pour réinstaller","nodes.agent.pluginNotInstalled": "Ce intégration n’est pas installé","nodes.agent.pluginNotInstalledDesc": "Ce intégration est installé à partir de GitHub. Veuillez aller dans Intégrations pour réinstaller",+ "nodes.agent.roster.label": "Agent","nodes.agent.strategy.configureTip": "Veuillez configurer la stratégie agentique.","nodes.agent.strategy.configureTipDesc": "Après avoir configuré la stratégie agentique, ce nœud chargera automatiquement les configurations restantes. La stratégie affectera le mécanisme du raisonnement à l’outil en plusieurs étapes.","nodes.agent.strategy.label": "Stratégie agentique",diff --git a/web/i18n/hi-IN/common.json b/web/i18n/hi-IN/common.jsonindex 26094b5db98..c678fefa2a6 100644--- a/web/i18n/hi-IN/common.json+++ b/web/i18n/hi-IN/common.json@@ -318,6 +318,7 @@"menus.newDataset": "ज्ञान बनाएं","menus.plugins": "एकीकरण","menus.pluginsTips": "थर्ड-पार्टी एकीकरण को एकीकृत करें या ChatGPT-संगत AI-Integrations बनाएं।",+ "menus.roster": "एजेंट सूची","menus.status": "बीटा","menus.tools": "उपकरण","model.addMoreModel": "अधिक मॉडल जोड़ने के लिए सेटिंग्स पर जाएं",diff --git a/web/i18n/hi-IN/workflow.json b/web/i18n/hi-IN/workflow.jsonindex 8e89f0bd212..b6a6cb473b5 100644--- a/web/i18n/hi-IN/workflow.json+++ b/web/i18n/hi-IN/workflow.json@@ -1,5 +1,6 @@{- "blocks.agent": "एजेंट",+ "blocks.agent": "Agent",+ "blocks.agent-v2": "Agent","blocks.answer": "उत्तर","blocks.assigner": "चर असाइनर","blocks.code": "कोड",@@ -33,6 +34,7 @@"blocks.variable-aggregator": "वेरिएबल एग्रीगेटर","blocks.variable-assigner": "वेरिएबल एग्रीगेटर","blocksAbout.agent": "प्रश्नों का उत्तर देने या प्राकृतिक भाषा को संसाधित करने के लिए बड़े भाषा मॉडलों को आमंत्रित करना",+ "blocksAbout.agent-v2": "प्रश्नों का उत्तर देने या प्राकृतिक भाषा को संसाधित करने के लिए बड़े भाषा मॉडलों को आमंत्रित करना","blocksAbout.answer": "चैट संवाद के उत्तर सामग्री को परिभाषित करें","blocksAbout.assigner": "चर असाइनमेंट नोड का उपयोग लिखने योग्य चर (जैसे वार्तालाप चर) को मान असाइन करने के लिए किया जाता है।","blocksAbout.code": "कस्टम लॉजिक को लागू करने के लिए एक टुकड़ा Python या NodeJS कोड निष्पादित करें",@@ -414,6 +416,7 @@"nodes.agent.pluginNotFoundDesc": "यह एकीकरण गिटहब से स्थापित किया गया है। कृपया पुनः स्थापित करने के लिए एकीकरण पर जाएं।","nodes.agent.pluginNotInstalled": "यह एकीकरण स्थापित नहीं है","nodes.agent.pluginNotInstalledDesc": "यह एकीकरण गिटहब से स्थापित किया गया है। कृपया पुनः स्थापित करने के लिए एकीकरण पर जाएं।",+ "nodes.agent.roster.label": "एजेंट","nodes.agent.strategy.configureTip": "कृपया एजेंटिक रणनीति को कॉन्फ़िगर करें।","nodes.agent.strategy.configureTipDesc": "एजेंटिक रणनीति को कॉन्फ़िगर करने के बाद, यह नोड स्वचालित रूप से शेष कॉन्फ़िगरेशन लोड करेगा। यह रणनीति बहु-चरण उपकरण तर्क के तंत्र को प्रभावित करेगी।","nodes.agent.strategy.label": "एजेंटिक रणनीति",diff --git a/web/i18n/id-ID/common.json b/web/i18n/id-ID/common.jsonindex 45125b73fde..6a44ac1d148 100644--- a/web/i18n/id-ID/common.json+++ b/web/i18n/id-ID/common.json@@ -318,6 +318,7 @@"menus.newDataset": "Ciptakan Pengetahuan","menus.plugins": "Integrasi","menus.pluginsTips": "Integrasikan integrasi pihak ketiga atau buat AI-Integrasi yang kompatibel dengan ChatGPT.",+ "menus.roster": "Daftar Agen","menus.status": "beta","menus.tools": "Perkakas","model.addMoreModel": "Buka pengaturan untuk menambahkan lebih banyak model",diff --git a/web/i18n/id-ID/workflow.json b/web/i18n/id-ID/workflow.jsonindex 87202bf6698..ffd4bc7ee8c 100644--- a/web/i18n/id-ID/workflow.json+++ b/web/i18n/id-ID/workflow.json@@ -1,5 +1,6 @@{- "blocks.agent": "Agen",+ "blocks.agent": "Agent",+ "blocks.agent-v2": "Agent","blocks.answer": "Jawaban","blocks.assigner": "Penerima Variabel","blocks.code": "Kode",@@ -33,6 +34,7 @@"blocks.variable-aggregator": "Agregator Variabel","blocks.variable-assigner": "Agregator Variabel","blocksAbout.agent": "Memanggil model bahasa besar untuk menjawab pertanyaan atau memproses bahasa alami",+ "blocksAbout.agent-v2": "Memanggil model bahasa besar untuk menjawab pertanyaan atau memproses bahasa alami","blocksAbout.answer": "Menentukan konten balasan percakapan obrolan","blocksAbout.assigner": "Simpul penetapan variabel digunakan untuk menetapkan nilai ke variabel yang dapat ditulis (seperti variabel percakapan).","blocksAbout.code": "Eksekusi sepotong kode Python atau NodeJS untuk mengimplementasikan logika kustom",@@ -414,6 +416,7 @@"nodes.agent.pluginNotFoundDesc": "Integrasi ini diinstal dari GitHub. Silakan buka Integrasis untuk menginstal ulang","nodes.agent.pluginNotInstalled": "Integrasi ini tidak diinstal","nodes.agent.pluginNotInstalledDesc": "Integrasi ini diinstal dari GitHub. Silakan buka Integrasis untuk menginstal ulang",+ "nodes.agent.roster.label": "Agen","nodes.agent.strategy.configureTip": "Silakan konfigurasikan strategi agen.","nodes.agent.strategy.configureTipDesc": "Setelah mengonfigurasi strategi agen, node ini akan secara otomatis memuat konfigurasi yang tersisa. Strategi tersebut akan mempengaruhi mekanisme penalaran alat multi-langkah.","nodes.agent.strategy.label": "Strategi Agen",diff --git a/web/i18n/it-IT/common.json b/web/i18n/it-IT/common.jsonindex 860c63ec3be..aa71b3df53e 100644--- a/web/i18n/it-IT/common.json+++ b/web/i18n/it-IT/common.json@@ -318,6 +318,7 @@"menus.newDataset": "Crea Conoscenza","menus.plugins": "Integrazione","menus.pluginsTips": "Integra integrazione di terze parti o crea integrazione AI compatibili con ChatGPT.",+ "menus.roster": "Elenco agenti","menus.status": "beta","menus.tools": "Strumenti","model.addMoreModel": "Vai alle impostazioni per aggiungere altri modelli",diff --git a/web/i18n/it-IT/workflow.json b/web/i18n/it-IT/workflow.jsonindex 052025b82e4..b6859ebcabd 100644--- a/web/i18n/it-IT/workflow.json+++ b/web/i18n/it-IT/workflow.json@@ -1,5 +1,6 @@{- "blocks.agent": "Agente",+ "blocks.agent": "Agent",+ "blocks.agent-v2": "Agent","blocks.answer": "Risposta","blocks.assigner": "Assegnatore di Variabili","blocks.code": "Codice",@@ -33,6 +34,7 @@"blocks.variable-aggregator": "Aggregatore Variabili","blocks.variable-assigner": "Assegnatore Variabili","blocksAbout.agent": "Richiamo di modelli linguistici di grandi dimensioni per rispondere a domande o elaborare il linguaggio naturale",+ "blocksAbout.agent-v2": "Richiamo di modelli linguistici di grandi dimensioni per rispondere a domande o elaborare il linguaggio naturale","blocksAbout.answer": "Definisci il contenuto della risposta di una conversazione chat","blocksAbout.assigner": "Il nodo di assegnazione delle variabili è utilizzato per assegnare valori a variabili scrivibili (come le variabili di conversazione).","blocksAbout.code": "Esegui un pezzo di codice Python o NodeJS per implementare la logica personalizzata",@@ -414,6 +416,7 @@"nodes.agent.pluginNotFoundDesc": "Questo integrazione viene installato da GitHub. Vai su Integrazione per reinstallare","nodes.agent.pluginNotInstalled": "Questo integrazione non è installato","nodes.agent.pluginNotInstalledDesc": "Questo integrazione viene installato da GitHub. Vai su Integrazione per reinstallare",+ "nodes.agent.roster.label": "Agente","nodes.agent.strategy.configureTip": "Configurare la strategia agentic.","nodes.agent.strategy.configureTipDesc": "Dopo aver configurato la strategia agentic, questo nodo caricherà automaticamente le configurazioni rimanenti. La strategia influenzerà il meccanismo del ragionamento con strumenti a più fasi.","nodes.agent.strategy.label": "Strategia agentica",diff --git a/web/i18n/ja-JP/common.json b/web/i18n/ja-JP/common.jsonindex c85ba6c8acf..b20b17e27a0 100644--- a/web/i18n/ja-JP/common.json+++ b/web/i18n/ja-JP/common.json@@ -318,6 +318,7 @@"menus.newDataset": "ナレッジの作成","menus.plugins": "インテグレーション","menus.pluginsTips": "サードパーティのインテグレーションを統合するか、ChatGPT 互換の AI インテグレーションを作成します。",+ "menus.roster": "エージェント名簿","menus.status": "ベータ版","menus.tools": "ツール","model.addMoreModel": "設定画面から他のモデルを追加してください",diff --git a/web/i18n/ja-JP/workflow.json b/web/i18n/ja-JP/workflow.jsonindex 0ef5f9af860..607bfe4de07 100644--- a/web/i18n/ja-JP/workflow.json+++ b/web/i18n/ja-JP/workflow.json@@ -1,5 +1,6 @@{- "blocks.agent": "エージェント",+ "blocks.agent": "Agent",+ "blocks.agent-v2": "Agent","blocks.answer": "回答","blocks.assigner": "変数代入","blocks.code": "コード実行",@@ -33,6 +34,7 @@"blocks.variable-aggregator": "変数集約器","blocks.variable-assigner": "変数代入器","blocksAbout.agent": "大規模言語モデルを活用した質問応答や自然言語処理を実行します。",+ "blocksAbout.agent-v2": "大規模言語モデルを活用した質問応答や自然言語処理を実行します。","blocksAbout.answer": "チャットダイアログの返答内容を定義します。","blocksAbout.assigner": "書き込み可能な変数(例:会話変数)への値の割り当てを行います。","blocksAbout.code": "Python/NodeJS コードを実行してカスタムロジックを実装します。",@@ -414,6 +416,7 @@"nodes.agent.pluginNotFoundDesc": "このインテグレーションは GitHub からインストールされています。再インストールするにはインテグレーションに移動してください。","nodes.agent.pluginNotInstalled": "このインテグレーションはインストールされていません","nodes.agent.pluginNotInstalledDesc": "このインテグレーションは GitHub からインストールされています。再インストールするにはインテグレーションに移動してください。",+ "nodes.agent.roster.label": "エージェント","nodes.agent.strategy.configureTip": "エージェンティック戦略を設定してください。","nodes.agent.strategy.configureTipDesc": "エージェント戦略を設定した後、このノードは残りの設定を自動的に読み込みます。この戦略は、マルチステップツール推論のメカニズムに影響を与えます。","nodes.agent.strategy.label": "エージェンティック戦略",diff --git a/web/i18n/ko-KR/common.json b/web/i18n/ko-KR/common.jsonindex da818bfb09b..79e93c93541 100644--- a/web/i18n/ko-KR/common.json+++ b/web/i18n/ko-KR/common.json@@ -318,6 +318,7 @@"menus.newDataset": "지식 만들기","menus.plugins": "통합","menus.pluginsTips": "타사 통합을 통합하거나 ChatGPT 호환 AI 통합을 작성합니다.",+ "menus.roster": "에이전트 명단","menus.status": "베타 버전","menus.tools": "도구","model.addMoreModel": "설정에서 다른 모델을 추가하세요",diff --git a/web/i18n/ko-KR/workflow.json b/web/i18n/ko-KR/workflow.jsonindex 1b139234d39..14acb9e0059 100644--- a/web/i18n/ko-KR/workflow.json+++ b/web/i18n/ko-KR/workflow.json@@ -1,5 +1,6 @@{- "blocks.agent": "에이전트",+ "blocks.agent": "Agent",+ "blocks.agent-v2": "Agent","blocks.answer": "답변","blocks.assigner": "변수 할당자","blocks.code": "코드",@@ -33,6 +34,7 @@"blocks.variable-aggregator": "변수 집계자","blocks.variable-assigner": "변수 할당자","blocksAbout.agent": "질문에 답하거나 자연어를 처리하기 위해 대규모 언어 모델을 호출하는 경우",+ "blocksAbout.agent-v2": "질문에 답하거나 자연어를 처리하기 위해 대규모 언어 모델을 호출하는 경우","blocksAbout.answer": "대화의 답변 내용을 정의합니다","blocksAbout.assigner": "변수 할당 노드는 쓰기 가능한 변수 (대화 변수 등) 에 값을 할당하는 데 사용됩니다.","blocksAbout.code": "사용자 정의 논리를 구현하기 위해 Python 또는 NodeJS 코드를 실행합니다",@@ -414,6 +416,7 @@"nodes.agent.pluginNotFoundDesc": "이 통합은 GitHub 에서 설치됩니다. 통합으로 이동하여 다시 설치하십시오.","nodes.agent.pluginNotInstalled": "이 통합은 설치되어 있지 않습니다.","nodes.agent.pluginNotInstalledDesc": "이 통합은 GitHub 에서 설치됩니다. 통합으로 이동하여 다시 설치하십시오.",+ "nodes.agent.roster.label": "에이전트","nodes.agent.strategy.configureTip": "에이전트 전략을 구성하세요.","nodes.agent.strategy.configureTipDesc": "에이전트 전략을 구성한 후 이 노드는 나머지 구성을 자동으로 로드합니다. 이 전략은 다단계 도구 추론의 메커니즘에 영향을 미칩니다.","nodes.agent.strategy.label": "에이전트 전략",diff --git a/web/i18n/nl-NL/common.json b/web/i18n/nl-NL/common.jsonindex 10d08708a4e..56a4b69d322 100644--- a/web/i18n/nl-NL/common.json+++ b/web/i18n/nl-NL/common.json@@ -318,6 +318,7 @@"menus.newDataset": "Create Knowledge","menus.plugins": "Integraties","menus.pluginsTips": "Integrate third-party integraties or create ChatGPT-compatible AI-Integraties.",+ "menus.roster": "Agentenoverzicht","menus.status": "beta","menus.tools": "Tools","model.addMoreModel": "Go to settings to add more models",diff --git a/web/i18n/nl-NL/workflow.json b/web/i18n/nl-NL/workflow.jsonindex 08b8e69c463..69138d7eb05 100644--- a/web/i18n/nl-NL/workflow.json+++ b/web/i18n/nl-NL/workflow.json@@ -1,5 +1,6 @@{"blocks.agent": "Agent",+ "blocks.agent-v2": "Agent","blocks.answer": "Answer","blocks.assigner": "Variable Assigner","blocks.code": "Code",@@ -33,6 +34,7 @@"blocks.variable-aggregator": "Variable Aggregator","blocks.variable-assigner": "Variable Aggregator","blocksAbout.agent": "Invoking large language models to answer questions or process natural language",+ "blocksAbout.agent-v2": "Invoking large language models to answer questions or process natural language","blocksAbout.answer": "Define the reply content of a chat conversation","blocksAbout.assigner": "The variable assignment node is used for assigning values to writable variables(like conversation variables).","blocksAbout.code": "Execute a piece of Python or NodeJS code to implement custom logic",@@ -414,6 +416,7 @@"nodes.agent.pluginNotFoundDesc": "This integratie is installed from GitHub. Please go to Integraties to reinstall","nodes.agent.pluginNotInstalled": "This integratie is not installed","nodes.agent.pluginNotInstalledDesc": "This integratie is installed from GitHub. Please go to Integraties to reinstall",+ "nodes.agent.roster.label": "Agent","nodes.agent.strategy.configureTip": "Please configure agentic strategy.","nodes.agent.strategy.configureTipDesc": "After configuring the agentic strategy, this node will automatically load the remaining configurations. The strategy will affect the mechanism of multi-step tool reasoning. ","nodes.agent.strategy.label": "Agentic Strategy",diff --git a/web/i18n/pl-PL/common.json b/web/i18n/pl-PL/common.jsonindex 2f6d2726c7a..1626af3964b 100644--- a/web/i18n/pl-PL/common.json+++ b/web/i18n/pl-PL/common.json@@ -318,6 +318,7 @@"menus.newDataset": "Utwórz Wiedzę","menus.plugins": "Integracjay","menus.pluginsTips": "Integruj integracjay stron trzecich lub twórz integracjay AI kompatybilne z ChatGPT.",+ "menus.roster": "Lista agentów","menus.status": "beta","menus.tools": "Narzędzia","model.addMoreModel": "Przejdź do ustawień, aby dodać więcej modeli",diff --git a/web/i18n/pl-PL/workflow.json b/web/i18n/pl-PL/workflow.jsonindex 63759d2b567..dfedde1f7e1 100644--- a/web/i18n/pl-PL/workflow.json+++ b/web/i18n/pl-PL/workflow.json@@ -1,5 +1,6 @@{"blocks.agent": "Agent",+ "blocks.agent-v2": "Agent","blocks.answer": "Odpowiedź","blocks.assigner": "Przypisywacz Zmiennych","blocks.code": "Kod",@@ -33,6 +34,7 @@"blocks.variable-aggregator": "Agregator zmiennych","blocks.variable-assigner": "Agregator zmiennych","blocksAbout.agent": "Wywoływanie dużych modeli językowych w celu odpowiadania na pytania lub przetwarzania języka naturalnego",+ "blocksAbout.agent-v2": "Wywoływanie dużych modeli językowych w celu odpowiadania na pytania lub przetwarzania języka naturalnego","blocksAbout.answer": "Zdefiniuj treść odpowiedzi w rozmowie","blocksAbout.assigner": "Węzeł przypisania zmiennych służy do przypisywania wartości do zmiennych zapisywalnych (takich jak zmienne konwersacji).","blocksAbout.code": "Wykonaj fragment kodu Python lub NodeJS, aby wdrożyć niestandardową logikę",@@ -414,6 +416,7 @@"nodes.agent.pluginNotFoundDesc": "Ta integracja jest instalowana z GitHub. Przejdź do Integracje, aby ponownie zainstalować","nodes.agent.pluginNotInstalled": "Ta integracja nie jest zainstalowana","nodes.agent.pluginNotInstalledDesc": "Ta integracja jest instalowana z GitHub. Przejdź do Integracje, aby ponownie zainstalować",+ "nodes.agent.roster.label": "Agent","nodes.agent.strategy.configureTip": "Skonfiguruj strategię agentyczną.","nodes.agent.strategy.configureTipDesc": "Po skonfigurowaniu strategii agentycznej ten węzeł automatycznie załaduje pozostałe konfiguracje. Strategia będzie miała wpływ na mechanizm wieloetapowego rozumowania narzędziowego.","nodes.agent.strategy.label": "Strategia agentyczna",diff --git a/web/i18n/pt-BR/common.json b/web/i18n/pt-BR/common.jsonindex 1da739881b9..3b6890c26c9 100644--- a/web/i18n/pt-BR/common.json+++ b/web/i18n/pt-BR/common.json@@ -318,6 +318,7 @@"menus.newDataset": "Criar Conhecimento","menus.plugins": "Integrações","menus.pluginsTips": "Integre integrações de terceiros ou crie integrações de IA compatíveis com o ChatGPT.",+ "menus.roster": "Lista de agentes","menus.status": "beta","menus.tools": "Ferramentas","model.addMoreModel": "Vá para configurações para adicionar mais modelos",diff --git a/web/i18n/pt-BR/workflow.json b/web/i18n/pt-BR/workflow.jsonindex a4a12926612..848ec2774d4 100644--- a/web/i18n/pt-BR/workflow.json+++ b/web/i18n/pt-BR/workflow.json@@ -1,5 +1,6 @@{- "blocks.agent": "Agente",+ "blocks.agent": "Agent",+ "blocks.agent-v2": "Agent","blocks.answer": "Resposta","blocks.assigner": "Atribuidor de Variáveis","blocks.code": "Código",@@ -33,6 +34,7 @@"blocks.variable-aggregator": "Agregador de variáveis","blocks.variable-assigner": "Atribuidor de variáveis","blocksAbout.agent": "Invocar grandes modelos de linguagem para responder a perguntas ou processar linguagem natural",+ "blocksAbout.agent-v2": "Invocar grandes modelos de linguagem para responder a perguntas ou processar linguagem natural","blocksAbout.answer": "Definir o conteúdo da resposta de uma conversa","blocksAbout.assigner": "O nó de atribuição de variáveis é usado para atribuir valores a variáveis graváveis (como variáveis de conversação).","blocksAbout.code": "Executar um pedaço de código Python ou NodeJS para implementar lógica personalizada",@@ -414,6 +416,7 @@"nodes.agent.pluginNotFoundDesc": "Este integração é instalado a partir do GitHub. Por favor, vá para Integrações para reinstalar","nodes.agent.pluginNotInstalled": "Este integração não está instalado","nodes.agent.pluginNotInstalledDesc": "Este integração é instalado a partir do GitHub. Por favor, vá para Integrações para reinstalar",+ "nodes.agent.roster.label": "Agente","nodes.agent.strategy.configureTip": "Configure a estratégia agente.","nodes.agent.strategy.configureTipDesc": "Depois de configurar a estratégia agêntica, esse nó carregará automaticamente as configurações restantes. A estratégia afetará o mecanismo de raciocínio da ferramenta de várias etapas.","nodes.agent.strategy.label": "Estratégia Agêntica",diff --git a/web/i18n/ro-RO/common.json b/web/i18n/ro-RO/common.jsonindex cd367a8f02f..22357b143d3 100644--- a/web/i18n/ro-RO/common.json+++ b/web/i18n/ro-RO/common.json@@ -318,6 +318,7 @@"menus.newDataset": "Creează Cunoștințe","menus.plugins": "Integrare-uri","menus.pluginsTips": "Integrați integrare-uri terțe părți sau creați AI-Integrare-uri compatibile cu ChatGPT.",+ "menus.roster": "Listă agenți","menus.status": "beta","menus.tools": "Instrumente","model.addMoreModel": "Mergeți la setări pentru a adăuga mai multe modele",diff --git a/web/i18n/ro-RO/workflow.json b/web/i18n/ro-RO/workflow.jsonindex 5fd41b86b39..4d778174a41 100644--- a/web/i18n/ro-RO/workflow.json+++ b/web/i18n/ro-RO/workflow.json@@ -1,5 +1,6 @@{"blocks.agent": "Agent",+ "blocks.agent-v2": "Agent","blocks.answer": "Răspuns","blocks.assigner": "Asignator de Variabile","blocks.code": "Cod",@@ -33,6 +34,7 @@"blocks.variable-aggregator": "Agregator de variabile","blocks.variable-assigner": "Asignator de variabile","blocksAbout.agent": "Invocarea modelelor lingvistice mari pentru a răspunde la întrebări sau pentru a procesa limbajul natural",+ "blocksAbout.agent-v2": "Invocarea modelelor lingvistice mari pentru a răspunde la întrebări sau pentru a procesa limbajul natural","blocksAbout.answer": "Definiți conținutul răspunsului unei conversații","blocksAbout.assigner": "Nodul de atribuire a variabilelor este utilizat pentru a atribui valori variabilelor inscriptibile (precum variabilele de conversație).","blocksAbout.code": "Executați un fragment de cod Python sau NodeJS pentru a implementa logică personalizată",@@ -414,6 +416,7 @@"nodes.agent.pluginNotFoundDesc": "Acest integrare este instalat de pe GitHub. Vă rugăm să accesați Integrări pentru a reinstala","nodes.agent.pluginNotInstalled": "Acest integrare nu este instalat","nodes.agent.pluginNotInstalledDesc": "Acest integrare este instalat de pe GitHub. Vă rugăm să accesați Integrări pentru a reinstala",+ "nodes.agent.roster.label": "Agent","nodes.agent.strategy.configureTip": "Vă rugăm să configurați strategia agentică.","nodes.agent.strategy.configureTipDesc": "După configurarea strategiei agentice, acest nod va încărca automat configurațiile rămase. Strategia va afecta mecanismul raționamentului instrumentelor în mai mulți pași.","nodes.agent.strategy.label": "Strategia agentică",diff --git a/web/i18n/ru-RU/common.json b/web/i18n/ru-RU/common.jsonindex fbaa91d60b1..ff084881dba 100644--- a/web/i18n/ru-RU/common.json+++ b/web/i18n/ru-RU/common.json@@ -318,6 +318,7 @@"menus.newDataset": "Создать знания","menus.plugins": "Интеграции","menus.pluginsTips": "Интегрируйте сторонние интеграции или создавайте совместимые с ChatGPT AI-интеграции.",+ "menus.roster": "Список агентов","menus.status": "бета","menus.tools": "Инструменты","model.addMoreModel": "Перейдите в настройки, чтобы добавить больше моделей",diff --git a/web/i18n/ru-RU/workflow.json b/web/i18n/ru-RU/workflow.jsonindex fb878c2a729..1da91682c4c 100644--- a/web/i18n/ru-RU/workflow.json+++ b/web/i18n/ru-RU/workflow.json@@ -1,5 +1,6 @@{- "blocks.agent": "Агент",+ "blocks.agent": "Agent",+ "blocks.agent-v2": "Agent","blocks.answer": "Ответ","blocks.assigner": "Назначение переменных","blocks.code": "Код",@@ -33,6 +34,7 @@"blocks.variable-aggregator": "Агрегатор переменных","blocks.variable-assigner": "Назначение переменных","blocksAbout.agent": "Вызов больших языковых моделей для ответа на вопросы или обработки естественного языка",+ "blocksAbout.agent-v2": "Вызов больших языковых моделей для ответа на вопросы или обработки естественного языка","blocksAbout.answer": "Определите содержимое ответа в чате","blocksAbout.assigner": "Узел назначения переменной используется для назначения значений записываемым переменным (например, переменным разговора).","blocksAbout.code": "Выполните фрагмент кода Python или NodeJS для реализации пользовательской логики",@@ -414,6 +416,7 @@"nodes.agent.pluginNotFoundDesc": "Этот интеграция устанавливается с GitHub. Пожалуйста, перейдите в раздел Интеграции для переустановки","nodes.agent.pluginNotInstalled": "Этот интеграция не установлен","nodes.agent.pluginNotInstalledDesc": "Этот интеграция устанавливается с GitHub. Пожалуйста, перейдите в раздел Интеграции для переустановки",+ "nodes.agent.roster.label": "Агент","nodes.agent.strategy.configureTip": "Пожалуйста, настройте агентскую стратегию.","nodes.agent.strategy.configureTipDesc": "После настройки агентской стратегии этот узел автоматически загрузит оставшиеся конфигурации. Стратегия будет влиять на механизм многоступенчатого мышления инструмента.","nodes.agent.strategy.label": "Агентная стратегия",diff --git a/web/i18n/sl-SI/common.json b/web/i18n/sl-SI/common.jsonindex eb20a4f51ef..f317bcb96db 100644--- a/web/i18n/sl-SI/common.json+++ b/web/i18n/sl-SI/common.json@@ -318,6 +318,7 @@"menus.newDataset": "Ustvari znanje","menus.plugins": "Integracije","menus.pluginsTips": "Integrirajte integracijae tretjih oseb ali ustvarite integracijae, združljive s ChatGPT.",+ "menus.roster": "Seznam agentov","menus.status": "beta","menus.tools": "Orodja","model.addMoreModel": "Pojdite v nastavitve, da dodate več modelov",diff --git a/web/i18n/sl-SI/workflow.json b/web/i18n/sl-SI/workflow.jsonindex 6a22dd642ea..9761b0743b9 100644--- a/web/i18n/sl-SI/workflow.json+++ b/web/i18n/sl-SI/workflow.json@@ -1,5 +1,6 @@{"blocks.agent": "Agent",+ "blocks.agent-v2": "Agent","blocks.answer": "Odgovor","blocks.assigner": "Dodeljevalec spremenljivk","blocks.code": "Koda",@@ -33,6 +34,7 @@"blocks.variable-aggregator": "Spremenljivka agregator","blocks.variable-assigner": "Spremenljivka agregator","blocksAbout.agent": "Uporaba velikih jezikovnih modelov za odgovarjanje na vprašanja ali obdelavo naravnega jezika",+ "blocksAbout.agent-v2": "Uporaba velikih jezikovnih modelov za odgovarjanje na vprašanja ali obdelavo naravnega jezika","blocksAbout.answer": "Določi vsebino odgovora v pogovoru.","blocksAbout.assigner": "Vožnji vozlišča za dodelitev spremenljivk se uporablja za dodeljevanje vrednosti spremenljivkam, ki jih je mogoče zapisati (kot so spremenljivke za pogovor).","blocksAbout.code": "Izvedite kos Python ali NodeJS kode za izvajanje prilagojene logike.",@@ -414,6 +416,7 @@"nodes.agent.pluginNotFoundDesc": "Ta integracija je nameščen iz GitHuba. Prosimo, da greste v integracijae in ga ponovo namestite.","nodes.agent.pluginNotInstalled": "Ta integracija ni nameščen","nodes.agent.pluginNotInstalledDesc": "Ta integracija je nameščen iz GitHuba. Prosimo, da greste v integracijae in ga ponovo namestite.",+ "nodes.agent.roster.label": "Agent","nodes.agent.strategy.configureTip": "Prosimo, konfigurirajte agentno strategijo.","nodes.agent.strategy.configureTipDesc": "Po nastavitvi agentne strategije bo ta vozlišče samodejno naložilo preostale nastavitve. Strategija bo vplivala na mehanizem večstopenjskega razmišljanja o orodju.","nodes.agent.strategy.label": "Agentična strategija",diff --git a/web/i18n/th-TH/common.json b/web/i18n/th-TH/common.jsonindex 31e712a5298..8a1184c0fe1 100644--- a/web/i18n/th-TH/common.json+++ b/web/i18n/th-TH/common.json@@ -318,6 +318,7 @@"menus.newDataset": "สร้างความรู้","menus.plugins": "การผสานรวม","menus.pluginsTips": "รวมการผสานรวมของบุคคลที่สามหรือสร้างการผสานรวม AI ที่เข้ากันได้กับ ChatGPT",+ "menus.roster": "รายชื่อตัวแทน","menus.status": "Beta","menus.tools": "เครื่อง มือ","model.addMoreModel": "ไปที่การตั้งค่าเพื่อเพิ่มรุ่นเพิ่มเติม",diff --git a/web/i18n/th-TH/workflow.json b/web/i18n/th-TH/workflow.jsonindex bc9593ade00..5f758d714b5 100644--- a/web/i18n/th-TH/workflow.json+++ b/web/i18n/th-TH/workflow.json@@ -1,5 +1,6 @@{- "blocks.agent": "ตัวแทน",+ "blocks.agent": "Agent",+ "blocks.agent-v2": "Agent","blocks.answer": "ตอบ","blocks.assigner": "ตัวกําหนดตัวแปร","blocks.code": "รหัส",@@ -33,6 +34,7 @@"blocks.variable-aggregator": "ตัวรวบรวมตัวแปร","blocks.variable-assigner": "ตัวรวบรวมตัวแปร","blocksAbout.agent": "การเรียกใช้โมเดลภาษาขนาดใหญ่เพื่อตอบคําถามหรือประมวลผลภาษาธรรมชาติ",+ "blocksAbout.agent-v2": "การเรียกใช้โมเดลภาษาขนาดใหญ่เพื่อตอบคําถามหรือประมวลผลภาษาธรรมชาติ","blocksAbout.answer": "กําหนดเนื้อหาการตอบกลับของการสนทนาแชท","blocksAbout.assigner": "โหนดการกําหนดตัวแปรใช้สําหรับกําหนดค่าให้กับตัวแปรที่เขียนได้ (เช่นตัวแปรการสนทนา)","blocksAbout.code": "เรียกใช้โค้ด Python หรือ NodeJS เพื่อใช้ตรรกะที่กําหนดเอง",@@ -414,6 +416,7 @@"nodes.agent.pluginNotFoundDesc": "การผสานรวมนี้ติดตั้งจาก GitHub โปรดไปที่การผสานรวมเพื่อติดตั้งใหม่","nodes.agent.pluginNotInstalled": "ไม่ได้ติดตั้งการผสานรวมนี้","nodes.agent.pluginNotInstalledDesc": "การผสานรวมนี้ติดตั้งจาก GitHub โปรดไปที่การผสานรวมเพื่อติดตั้งใหม่",+ "nodes.agent.roster.label": "ตัวแทน","nodes.agent.strategy.configureTip": "โปรดกําหนดค่ากลยุทธ์เอเจนต์","nodes.agent.strategy.configureTipDesc": "หลังจากกําหนดค่ากลยุทธ์ตัวแทนโหนดนี้จะโหลดการกําหนดค่าที่เหลือโดยอัตโนมัติ กลยุทธ์จะส่งผลต่อกลไกการให้เหตุผลของเครื่องมือหลายขั้นตอน","nodes.agent.strategy.label": "กลยุทธ์ตัวแทน",diff --git a/web/i18n/tr-TR/common.json b/web/i18n/tr-TR/common.jsonindex 8e3091963bc..7d8e7096feb 100644--- a/web/i18n/tr-TR/common.json+++ b/web/i18n/tr-TR/common.json@@ -318,6 +318,7 @@"menus.newDataset": "Bilgi Oluştur","menus.plugins": "Entegrasyonlar","menus.pluginsTips": "Üçüncü taraf entegrasyonlari entegre edin veya ChatGPT uyumlu AI-Entegrasyonlari oluşturun.",+ "menus.roster": "Ajan listesi","menus.status": "beta","menus.tools": "Araçlar","model.addMoreModel": "Daha fazla model eklemek için ayarlara gidin",diff --git a/web/i18n/tr-TR/workflow.json b/web/i18n/tr-TR/workflow.jsonindex 8fb401c1c89..cc1bcfd9197 100644--- a/web/i18n/tr-TR/workflow.json+++ b/web/i18n/tr-TR/workflow.json@@ -1,5 +1,6 @@{- "blocks.agent": "Aracı",+ "blocks.agent": "Agent",+ "blocks.agent-v2": "Agent","blocks.answer": "Yanıt","blocks.assigner": "Değişken Atayıcı","blocks.code": "Kod",@@ -33,6 +34,7 @@"blocks.variable-aggregator": "Değişken Toplayıcı","blocks.variable-assigner": "Değişken Ata","blocksAbout.agent": "Soruları yanıtlamak veya doğal dili işlemek için büyük dil modellerini çağırma",+ "blocksAbout.agent-v2": "Soruları yanıtlamak veya doğal dili işlemek için büyük dil modellerini çağırma","blocksAbout.answer": "Bir sohbet konuşmasının yanıt içeriğini tanımlayın","blocksAbout.assigner": "Değişken atama düğümü, yazılabilir değişkenlere (konuşma değişkenleri gibi) değer atamak için kullanılır.","blocksAbout.code": "Özel mantığı uygulamak için bir Python veya NodeJS kod parçası yürütün",@@ -414,6 +416,7 @@"nodes.agent.pluginNotFoundDesc": "Bu entegrasyon GitHub'dan yüklenmiştir. Lütfen şuraya gidin: Entegrasyonlar yeniden yüklemek için","nodes.agent.pluginNotInstalled": "Bu entegrasyon yüklü değil","nodes.agent.pluginNotInstalledDesc": "Bu entegrasyon GitHub'dan yüklenmiştir. Lütfen şuraya gidin: Entegrasyonlar yeniden yüklemek için",+ "nodes.agent.roster.label": "Ajan","nodes.agent.strategy.configureTip": "Lütfen ajan stratejisini yapılandırın.","nodes.agent.strategy.configureTipDesc": "Aracı stratejiyi yapılandırdıktan sonra, bu düğüm kalan yapılandırmaları otomatik olarak yükleyecektir. Strateji, çok adımlı araç akıl yürütme mekanizmasını etkileyecektir.","nodes.agent.strategy.label": "Ajan Stratejisi",diff --git a/web/i18n/uk-UA/common.json b/web/i18n/uk-UA/common.jsonindex 4ac12aeb081..995d6ef0318 100644--- a/web/i18n/uk-UA/common.json+++ b/web/i18n/uk-UA/common.json@@ -318,6 +318,7 @@"menus.newDataset": "Створити знання","menus.plugins": "Інтеграції","menus.pluginsTips": "Інтегруйте сторонні інтеграції або створіть AI-сумісні інтеграції.",+ "menus.roster": "Список агентів","menus.status": "бета","menus.tools": "Інструменти","model.addMoreModel": "Перейдіть до налаштувань, щоб додати більше моделей",diff --git a/web/i18n/uk-UA/workflow.json b/web/i18n/uk-UA/workflow.jsonindex 50f56e584d0..c3a43bf48ae 100644--- a/web/i18n/uk-UA/workflow.json+++ b/web/i18n/uk-UA/workflow.json@@ -1,5 +1,6 @@{- "blocks.agent": "Агент",+ "blocks.agent": "Agent",+ "blocks.agent-v2": "Agent","blocks.answer": "Відповідь","blocks.assigner": "Призначувач змінних","blocks.code": "Код",@@ -33,6 +34,7 @@"blocks.variable-aggregator": "Агрегатор змінних","blocks.variable-assigner": "Присвоювач змінних","blocksAbout.agent": "Виклик великих мовних моделей для відповідей на запитання або обробки природної мови",+ "blocksAbout.agent-v2": "Виклик великих мовних моделей для відповідей на запитання або обробки природної мови","blocksAbout.answer": "Визначте зміст відповіді у чаті","blocksAbout.assigner": "Вузол призначення змінних використовується для присвоєння значень записуваним змінним (таким як змінні розмови).","blocksAbout.code": "Виконайте фрагмент коду Python або NodeJS для реалізації користувацької логіки",@@ -414,6 +416,7 @@"nodes.agent.pluginNotFoundDesc": "Цей інтеграція встановлюється з GitHub. Будь ласка, перейдіть до Інтеграції для перевстановлення","nodes.agent.pluginNotInstalled": "Цей інтеграція не встановлено","nodes.agent.pluginNotInstalledDesc": "Цей інтеграція встановлюється з GitHub. Будь ласка, перейдіть до Інтеграції для перевстановлення",+ "nodes.agent.roster.label": "Агент","nodes.agent.strategy.configureTip": "Будь ласка, налаштуйте агентичну стратегію.","nodes.agent.strategy.configureTipDesc": "Після налаштування агентної стратегії цей вузол автоматично завантажить решту конфігурацій. Стратегія вплине на механізм багатоступінчастого інструментального міркування.","nodes.agent.strategy.label": "Агентична стратегія",diff --git a/web/i18n/vi-VN/common.json b/web/i18n/vi-VN/common.jsonindex 68566ea7e11..2fb270d7260 100644--- a/web/i18n/vi-VN/common.json+++ b/web/i18n/vi-VN/common.json@@ -318,6 +318,7 @@"menus.newDataset": "Tạo Kiến thức","menus.plugins": "Tích hợp","menus.pluginsTips": "Tích hợp các tích hợp bên thứ ba hoặc tạo ra các AI-Tích hợp tương thích với ChatGPT.",+ "menus.roster": "Danh sách tác nhân","menus.status": "beta","menus.tools": "Công cụ","model.addMoreModel": "Điều chỉnh cài đặt để thêm mô hình",diff --git a/web/i18n/vi-VN/workflow.json b/web/i18n/vi-VN/workflow.jsonindex 7eb0ed55282..c37ac7e8cd1 100644--- a/web/i18n/vi-VN/workflow.json+++ b/web/i18n/vi-VN/workflow.json@@ -1,5 +1,6 @@{- "blocks.agent": "Người đại lý",+ "blocks.agent": "Agent",+ "blocks.agent-v2": "Agent","blocks.answer": "Trả lời","blocks.assigner": "Trình gán biến","blocks.code": "Mã",@@ -33,6 +34,7 @@"blocks.variable-aggregator": "Trình tổng hợp biến","blocks.variable-assigner": "Trình gán biến","blocksAbout.agent": "Gọi các mô hình ngôn ngữ lớn để trả lời câu hỏi hoặc xử lý ngôn ngữ tự nhiên",+ "blocksAbout.agent-v2": "Gọi các mô hình ngôn ngữ lớn để trả lời câu hỏi hoặc xử lý ngôn ngữ tự nhiên","blocksAbout.answer": "Định nghĩa nội dung trả lời của cuộc trò chuyện","blocksAbout.assigner": "Nút gán biến được sử dụng để gán giá trị cho các biến có thể ghi (như các biến hội thoại).","blocksAbout.code": "Thực thi một đoạn mã Python hoặc NodeJS để thực hiện logic tùy chỉnh",@@ -414,6 +416,7 @@"nodes.agent.pluginNotFoundDesc": "Tích hợp này được cài đặt từ GitHub. Vui lòng vào Tích hợp để cài đặt lại","nodes.agent.pluginNotInstalled": "Tích hợp này chưa được cài đặt","nodes.agent.pluginNotInstalledDesc": "Tích hợp này được cài đặt từ GitHub. Vui lòng vào Tích hợp để cài đặt lại",+ "nodes.agent.roster.label": "Tác nhân","nodes.agent.strategy.configureTip": "Vui lòng định cấu hình chiến lược tác nhân.","nodes.agent.strategy.configureTipDesc": "Sau khi cấu hình chiến lược tác nhân, nút này sẽ tự động tải các cấu hình còn lại. Chiến lược sẽ ảnh hưởng đến cơ chế suy luận công cụ nhiều bước.","nodes.agent.strategy.label": "Chiến lược đại lý",diff --git a/web/i18n/zh-Hans/agent-v-2.json b/web/i18n/zh-Hans/agent-v-2.jsonnew file mode 100644index 00000000000..27f30d27199--- /dev/null+++ b/web/i18n/zh-Hans/agent-v-2.json@@ -0,0 +1,382 @@+{+ "agentDetail.access.actionUnavailable": "此操作暂不可用。",+ "agentDetail.access.actions.monitoring": "监控",+ "agentDetail.access.copyAccessUrl": "复制访问 URL",+ "agentDetail.access.copyFailed": "引用复制失败。",+ "agentDetail.access.copyReference": "复制 {{name}} 的引用",+ "agentDetail.access.copyServiceEndpoint": "复制服务 API 端点",+ "agentDetail.access.description": "此智能体可被触达的所有入口。",+ "agentDetail.access.empty": "暂无关联访问入口",+ "agentDetail.access.emptyDescription": "当前 Roster 智能体还没有应用或工作流引用。",+ "agentDetail.access.entries.agentApp.description": "关联到此 Roster 智能体的智能体应用。",+ "agentDetail.access.entries.agentApp.name": "智能体应用",+ "agentDetail.access.entries.workflow.description": "关联到此 Roster 智能体的工作流与节点引用。",+ "agentDetail.access.entries.workflow.name": "工作流节点",+ "agentDetail.access.entryCount_one": "{{count}} 个条目",+ "agentDetail.access.entryCount_other": "{{count}} 个条目",+ "agentDetail.access.groups.references.heading": "引用",+ "agentDetail.access.groups.references.label": "关联引用",+ "agentDetail.access.learnMore": "了解更多",+ "agentDetail.access.moreActions": "{{name}} 的更多操作",+ "agentDetail.access.serviceApi.actions.apiKey": "API Key",+ "agentDetail.access.serviceApi.actions.apiReference": "API Reference",+ "agentDetail.access.serviceApi.endpoint": "服务 API 端点",+ "agentDetail.access.serviceApi.title": "后端服务 API",+ "agentDetail.access.status.disabled": "已禁用",+ "agentDetail.access.status.enabled": "已启用",+ "agentDetail.access.status.inService": "服务中",+ "agentDetail.access.status.outOfService": "已停用",+ "agentDetail.access.title": "访问点",+ "agentDetail.access.toggleSurface": "切换 {{name}} 访问状态",+ "agentDetail.access.webApp.accessUrl": "访问 URL",+ "agentDetail.access.webApp.actions.customize": "自定义",+ "agentDetail.access.webApp.actions.embedded": "嵌入",+ "agentDetail.access.webApp.actions.launch": "启动",+ "agentDetail.access.webApp.actions.settings": "设置",+ "agentDetail.access.webApp.refreshUrl": "刷新访问 URL",+ "agentDetail.access.webApp.showQrCode": "显示二维码",+ "agentDetail.access.webApp.ssoEnabled": "已启用 SSO",+ "agentDetail.access.webApp.title": "Web app",+ "agentDetail.access.workflow.description": "作为工作流内的节点使用",+ "agentDetail.access.workflow.empty": "暂无工作流引用。",+ "agentDetail.access.workflow.loadFailed": "工作流引用加载失败。",+ "agentDetail.access.workflow.loading": "正在加载工作流引用…",+ "agentDetail.access.workflow.nodeCount_one": "{{count}} 个节点",+ "agentDetail.access.workflow.nodeCount_other": "{{count}} 个节点",+ "agentDetail.access.workflow.notAvailable": "N/A",+ "agentDetail.access.workflow.openInStudio": "在 Studio 中打开",+ "agentDetail.access.workflow.openInStudioFor": "在 Studio 中打开 {{name}}",+ "agentDetail.access.workflow.table.actions": "操作",+ "agentDetail.access.workflow.table.lastUpdated": "最后更新",+ "agentDetail.access.workflow.table.name": "名称",+ "agentDetail.access.workflow.table.nodes": "节点",+ "agentDetail.access.workflow.table.version": "版本",+ "agentDetail.access.workflow.title": "工作流访问",+ "agentDetail.configure.advancedSettings.description": "面向高级用户。环境变量、沙箱与记忆。",+ "agentDetail.configure.advancedSettings.envEditor.add": "添加环境变量",+ "agentDetail.configure.advancedSettings.envEditor.deleteVariable": "删除 {{key}}",+ "agentDetail.configure.advancedSettings.envEditor.hideValue": "隐藏 {{key}} 的值",+ "agentDetail.configure.advancedSettings.envEditor.importEnv": "导入 .env",+ "agentDetail.configure.advancedSettings.envEditor.importEnvTip.mac": "如需显示隐藏的 .env 文件,请在文件选择器中按 Command + Shift + .。",+ "agentDetail.configure.advancedSettings.envEditor.importEnvTip.other": "如果 .env 文件被隐藏,请在系统文件选择器中开启隐藏文件显示。",+ "agentDetail.configure.advancedSettings.envEditor.importEnvTip.windows": "如需显示隐藏的 .env 文件,请在文件资源管理器中开启“隐藏的项目”。",+ "agentDetail.configure.advancedSettings.envEditor.keyColumn": "Key",+ "agentDetail.configure.advancedSettings.envEditor.keyPlaceholder": "Key",+ "agentDetail.configure.advancedSettings.envEditor.label": "Env Editor",+ "agentDetail.configure.advancedSettings.envEditor.revealValue": "显示 {{key}} 的值",+ "agentDetail.configure.advancedSettings.envEditor.scopeColumn": "Scope",+ "agentDetail.configure.advancedSettings.envEditor.scopePlain": "Plain",+ "agentDetail.configure.advancedSettings.envEditor.scopeSecret": "Secret",+ "agentDetail.configure.advancedSettings.envEditor.scopeSelector": "选择环境变量作用域",+ "agentDetail.configure.advancedSettings.envEditor.tip": "此智能体运行时可使用的环境变量。",+ "agentDetail.configure.advancedSettings.envEditor.toggle": "展开或收起 Env Editor",+ "agentDetail.configure.advancedSettings.envEditor.valueColumn": "Value",+ "agentDetail.configure.advancedSettings.envEditor.valuePlaceholder": "Value",+ "agentDetail.configure.advancedSettings.label": "高级设置",+ "agentDetail.configure.advancedSettings.toggle": "展开或收起高级设置",+ "agentDetail.configure.chatFeatures.description": "配置 Web app 和聊天界面的终端用户聊天体验。",+ "agentDetail.configure.chatFeatures.title": "Chat 功能",+ "agentDetail.configure.files.add": "添加文件",+ "agentDetail.configure.files.empty.description": "上传智能体可读取的文档,例如规格、模板或指南",+ "agentDetail.configure.files.empty.title": "暂无文件",+ "agentDetail.configure.files.label": "文件",+ "agentDetail.configure.files.preview.empty": "暂无预览内容。",+ "agentDetail.configure.files.preview.failed": "预览加载失败。",+ "agentDetail.configure.files.remove": "移除 {{name}}",+ "agentDetail.configure.files.tip": "此智能体在编排任务时可使用的文件。",+ "agentDetail.configure.files.toggle": "展开或收起文件",+ "agentDetail.configure.files.treeLabel": "智能体文件",+ "agentDetail.configure.files.upload.action": "上传",+ "agentDetail.configure.files.upload.browse": "选择",+ "agentDetail.configure.files.upload.description": "为此智能体上传文件。",+ "agentDetail.configure.files.upload.dropzone": "拖入文件,或",+ "agentDetail.configure.files.upload.failed": "文件上传失败。",+ "agentDetail.configure.files.upload.fileType": "文件",+ "agentDetail.configure.files.upload.invalidFile": "请上传一个文件。",+ "agentDetail.configure.files.upload.success": "文件已上传。",+ "agentDetail.configure.files.upload.title": "上传文件",+ "agentDetail.configure.knowledgeRetrieval.add": "添加知识检索",+ "agentDetail.configure.knowledgeRetrieval.defaultName": "Retrieval {{index}}",+ "agentDetail.configure.knowledgeRetrieval.dialog.knowledge.add": "添加知识",+ "agentDetail.configure.knowledgeRetrieval.dialog.knowledge.empty": "点击“+”按钮添加知识",+ "agentDetail.configure.knowledgeRetrieval.dialog.knowledge.label": "知识",+ "agentDetail.configure.knowledgeRetrieval.dialog.knowledge.retrievalSetting": "检索设置",+ "agentDetail.configure.knowledgeRetrieval.dialog.learnMore": "了解更多关于知识检索",+ "agentDetail.configure.knowledgeRetrieval.dialog.metadata.automatic": "自动",+ "agentDetail.configure.knowledgeRetrieval.dialog.metadata.conditions": "条件",+ "agentDetail.configure.knowledgeRetrieval.dialog.metadata.disabled": "禁用",+ "agentDetail.configure.knowledgeRetrieval.dialog.metadata.label": "元数据过滤",+ "agentDetail.configure.knowledgeRetrieval.dialog.metadata.manual": "手动",+ "agentDetail.configure.knowledgeRetrieval.dialog.metadata.modeLabel": "选择元数据过滤模式",+ "agentDetail.configure.knowledgeRetrieval.dialog.nameLabel": "知识检索名称",+ "agentDetail.configure.knowledgeRetrieval.dialog.query.agent": "智能体决定",+ "agentDetail.configure.knowledgeRetrieval.dialog.query.agentDescription": "智能体会根据提示词和可用上下文自行编写查询。无需在此设置。",+ "agentDetail.configure.knowledgeRetrieval.dialog.query.custom": "自定义查询",+ "agentDetail.configure.knowledgeRetrieval.dialog.query.customDescription": "为此检索来源编写固定查询。",+ "agentDetail.configure.knowledgeRetrieval.dialog.query.customInputLabel": "自定义查询文本",+ "agentDetail.configure.knowledgeRetrieval.dialog.query.customPlaceholder": "输入搜索查询",+ "agentDetail.configure.knowledgeRetrieval.dialog.query.label": "查询",+ "agentDetail.configure.knowledgeRetrieval.dialog.title": "知识检索 · 智能体决定",+ "agentDetail.configure.knowledgeRetrieval.edit": "编辑 {{name}}",+ "agentDetail.configure.knowledgeRetrieval.empty.description": "连接智能体回答时可搜索的知识库",+ "agentDetail.configure.knowledgeRetrieval.empty.title": "暂无知识",+ "agentDetail.configure.knowledgeRetrieval.label": "知识检索",+ "agentDetail.configure.knowledgeRetrieval.remove": "删除 {{name}}",+ "agentDetail.configure.knowledgeRetrieval.retrievalOne": "Retrieval 1",+ "agentDetail.configure.knowledgeRetrieval.retrievalTwo": "Retrieval 2",+ "agentDetail.configure.knowledgeRetrieval.tip": "此智能体在编排任务时可使用的知识检索来源。",+ "agentDetail.configure.knowledgeRetrieval.toggle": "展开或收起知识检索",+ "agentDetail.configure.model.label": "模型",+ "agentDetail.configure.orchestrate": "编排",+ "agentDetail.configure.preview.chatFeatures": "Chat 功能",+ "agentDetail.configure.preview.empty.defaultAgentName": "智能体",+ "agentDetail.configure.preview.empty.description": "发送一条消息来测试当前草稿。",+ "agentDetail.configure.preview.empty.noInstructionsDescription": "尚未设置指令,回复将来自基础模型。",+ "agentDetail.configure.preview.endUserAuth": "终端用户认证",+ "agentDetail.configure.preview.restart": "重新开始预览",+ "agentDetail.configure.preview.title": "预览",+ "agentDetail.configure.prompt.copied": "提示词已复制",+ "agentDetail.configure.prompt.copy": "复制提示词",+ "agentDetail.configure.prompt.copyFailed": "提示词复制失败。",+ "agentDetail.configure.prompt.insert.label": "插入",+ "agentDetail.configure.prompt.insert.question": "开始问题",+ "agentDetail.configure.prompt.insert.reportFile": "输出报告文件",+ "agentDetail.configure.prompt.insert.tenders": "开始招标列表",+ "agentDetail.configure.prompt.label": "提示词",+ "agentDetail.configure.prompt.mention.davidHayes": "David Hayes",+ "agentDetail.configure.prompt.mention.label": "提及",+ "agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",+ "agentDetail.configure.prompt.placeholder": "在此编写指令,",+ "agentDetail.configure.prompt.tip": "定义这个智能体如何理解输入、调用工具并生成输出。",+ "agentDetail.configure.publishBar.draft": "草稿",+ "agentDetail.configure.publishBar.publishUpdate": "发布更新",+ "agentDetail.configure.publishBar.published": "已发布",+ "agentDetail.configure.publishBar.publishedAt": "{{time}}发布",+ "agentDetail.configure.publishBar.publishing": "发布中…",+ "agentDetail.configure.publishBar.saved": "5 分钟前已保存",+ "agentDetail.configure.publishBar.savedAt": "{{time}}已保存",+ "agentDetail.configure.publishBar.unpublishedChanges": "有未发布的更改",+ "agentDetail.configure.publishBar.upToDate": "已是最新",+ "agentDetail.configure.publishBar.versionHistory": "打开版本历史",+ "agentDetail.configure.publishImpact.affectedWorkflows": "受影响的工作流",+ "agentDetail.configure.publishImpact.cancel": "取消",+ "agentDetail.configure.publishImpact.descriptionPrefix": "你的智能体出现在",+ "agentDetail.configure.publishImpact.descriptionSuffix": "中。更改会影响它们。",+ "agentDetail.configure.publishImpact.fallbackAgentName": "此智能体",+ "agentDetail.configure.publishImpact.title": "{{action}}到 {{name}}",+ "agentDetail.configure.publishImpact.workflowCount_one": "{{count}} 个工作流",+ "agentDetail.configure.publishImpact.workflowCount_other": "{{count}} 个工作流",+ "agentDetail.configure.skills.add": "添加技能",+ "agentDetail.configure.skills.detail.contentRegion": "技能详情内容",+ "agentDetail.configure.skills.detail.fileCount": "{{count}} 个文件",+ "agentDetail.configure.skills.detail.fileTreeLabel": "技能文件",+ "agentDetail.configure.skills.detail.files": "文件",+ "agentDetail.configure.skills.empty.description": "技能为智能体提供工作时可调用的可复用专业能力",+ "agentDetail.configure.skills.empty.title": "暂无技能",+ "agentDetail.configure.skills.itemType": "技能",+ "agentDetail.configure.skills.label": "技能",+ "agentDetail.configure.skills.remove": "移除 {{name}}",+ "agentDetail.configure.skills.tip": "此智能体在编排任务时可使用的技能。",+ "agentDetail.configure.skills.toggle": "展开或收起技能",+ "agentDetail.configure.skills.upload.action": "上传",+ "agentDetail.configure.skills.upload.browse": "选择",+ "agentDetail.configure.skills.upload.description": "为此智能体上传 .zip 或 .skill 技能包。",+ "agentDetail.configure.skills.upload.dropzone": "拖入技能包,或",+ "agentDetail.configure.skills.upload.failed": "技能上传失败。",+ "agentDetail.configure.skills.upload.fileType": "ZIP / SKILL",+ "agentDetail.configure.skills.upload.invalidFile": "请上传 .zip 或 .skill 文件。",+ "agentDetail.configure.skills.upload.success": "技能已上传。",+ "agentDetail.configure.skills.upload.title": "上传技能",+ "agentDetail.configure.tools.add": "添加工具",+ "agentDetail.configure.tools.addMenu.cliTool.badge": "开发者适用",+ "agentDetail.configure.tools.addMenu.cliTool.description": "安装智能体可在沙箱中运行的命令行程序。需要安装命令,通常还需要 API Key。",+ "agentDetail.configure.tools.addMenu.cliTool.label": "CLI 工具",+ "agentDetail.configure.tools.addMenu.tool.description": "选择工作区中已有的工具,例如 Web 搜索或集成。",+ "agentDetail.configure.tools.addMenu.tool.label": "工具",+ "agentDetail.configure.tools.cliDialog.description": "从任意包注册表安装 CLI 工具。智能体会获得运行该二进制文件的 shell 访问能力。",+ "agentDetail.configure.tools.cliDialog.editTitle": "编辑 CLI 工具",+ "agentDetail.configure.tools.cliDialog.env.description": "存储此 CLI 工具所需的 API Key、Token 或密钥。值会静态加密,并在智能体调用工具时作为环境变量注入。",+ "agentDetail.configure.tools.cliDialog.env.label": "环境变量",+ "agentDetail.configure.tools.cliDialog.env.optional": "(可选)",+ "agentDetail.configure.tools.cliDialog.installCommand.description": "沙箱中执行 · 首次调用时运行一次",+ "agentDetail.configure.tools.cliDialog.installCommand.label": "安装命令",+ "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "粘贴安装命令,例如 npm install -g @lark/cli · brew install jq",+ "agentDetail.configure.tools.cliDialog.installCommand.required": "请输入安装命令。",+ "agentDetail.configure.tools.cliDialog.learnMore": "了解 CLI 工具",+ "agentDetail.configure.tools.cliDialog.name.label": "CLI 工具名称",+ "agentDetail.configure.tools.cliDialog.name.placeholder": "为 CLI 工具命名",+ "agentDetail.configure.tools.cliDialog.name.required": "请输入 CLI 工具名称。",+ "agentDetail.configure.tools.cliDialog.securityTip": "不会出现在智能体提示词中;仅在运行时作为 $VAR 注入",+ "agentDetail.configure.tools.cliDialog.title": "添加 CLI 工具",+ "agentDetail.configure.tools.cliTool": "CLI 工具",+ "agentDetail.configure.tools.credential.authOne": "Auth 1",+ "agentDetail.configure.tools.credential.endUserOAuth": "终端用户 · OAuth",+ "agentDetail.configure.tools.editAction": "编辑 {{name}}",+ "agentDetail.configure.tools.empty.description": "工具让智能体可以执行操作,例如搜索网页或调用你的应用",+ "agentDetail.configure.tools.empty.title": "暂无工具",+ "agentDetail.configure.tools.label": "工具",+ "agentDetail.configure.tools.moreActions": "{{name}} 的更多操作",+ "agentDetail.configure.tools.pluginType": "插件",+ "agentDetail.configure.tools.preAuthorize": "预授权",+ "agentDetail.configure.tools.removeAction": "移除 {{name}}",+ "agentDetail.configure.tools.removeProvider": "移除所有工具",+ "agentDetail.configure.tools.tip": "此智能体在编排任务时可调用的工具。",+ "agentDetail.configure.tools.toggle": "展开或收起工具",+ "agentDetail.configure.tools.toolTabs.all": "全部",+ "agentDetail.configure.tools.toolTabs.cli": "CLI",+ "agentDetail.configure.tools.toolTabs.custom": "自定义",+ "agentDetail.configure.tools.toolTabs.mcp": "MCP",+ "agentDetail.configure.tools.toolTabs.plugins": "插件",+ "agentDetail.configure.tools.toolTabs.workflow": "Workflow",+ "agentDetail.documentTitle": "智能体",+ "agentDetail.history": "历史记录",+ "agentDetail.logs.description": "完整日志记录应用运行状态,包括用户输入、智能体回复、规划和工具使用。",+ "agentDetail.logs.empty": "暂无日志",+ "agentDetail.logs.filters.period.allTime": "全部时间",+ "agentDetail.logs.filters.period.label": "日志时间范围",+ "agentDetail.logs.filters.period.last30days": "最近 30 天",+ "agentDetail.logs.filters.period.last7days": "最近 7 天",+ "agentDetail.logs.filters.search.label": "搜索日志",+ "agentDetail.logs.filters.search.placeholder": "搜索",+ "agentDetail.logs.filters.sort.lastCreatedTime": "最近创建时间",+ "agentDetail.logs.filters.sort.lastUpdatedTime": "最近更新时间",+ "agentDetail.logs.filters.source.all": "来源",+ "agentDetail.logs.filters.source.label": "日志来源",+ "agentDetail.logs.filters.source.webapp": "Webapp",+ "agentDetail.logs.filters.source.workflow": "工作流",+ "agentDetail.logs.learnMore": "了解更多",+ "agentDetail.logs.table.createdTime": "创建时间",+ "agentDetail.logs.table.endUser": "终端用户",+ "agentDetail.logs.table.messageCount": "消息数",+ "agentDetail.logs.table.operationRate": "操作率",+ "agentDetail.logs.table.title": "标题",+ "agentDetail.logs.table.unread": "未读",+ "agentDetail.logs.table.updatedTime": "更新时间",+ "agentDetail.logs.table.userRate": "用户评分",+ "agentDetail.logs.title": "日志",+ "agentDetail.memorySettings.budgetLabel": "记忆预算",+ "agentDetail.memorySettings.description": "当前活跃配置快照中的记忆设置。",+ "agentDetail.memorySettings.export.description": "记忆导出将在后续版本开放。",+ "agentDetail.memorySettings.export.download": "下载",+ "agentDetail.memorySettings.export.soon": "后续推出",+ "agentDetail.memorySettings.export.title": "导出当前记忆",+ "agentDetail.memorySettings.notConfigured": "未配置",+ "agentDetail.memorySettings.scopeLabel": "记忆范围",+ "agentDetail.memorySettings.title": "记忆",+ "agentDetail.metadata.activeVersionLabel": "活跃版本",+ "agentDetail.metadata.appIdLabel": "应用 ID",+ "agentDetail.metadata.description": "智能体后端返回的只读 Roster 字段。",+ "agentDetail.metadata.emptyValue": "暂无",+ "agentDetail.metadata.scopeLabel": "范围",+ "agentDetail.metadata.scopes.roster": "Roster",+ "agentDetail.metadata.scopes.workflow_only": "仅工作流",+ "agentDetail.metadata.sourceLabel": "来源",+ "agentDetail.metadata.statusLabel": "状态",+ "agentDetail.metadata.title": "元数据",+ "agentDetail.metadata.updatedAtLabel": "更新时间",+ "agentDetail.metadata.workflowIdLabel": "工作流 ID",+ "agentDetail.metadata.workflowNodeIdLabel": "工作流节点 ID",+ "agentDetail.monitoring.change": "较上一周期 {{value}}",+ "agentDetail.monitoring.dateRangeLabel": "日期范围",+ "agentDetail.monitoring.description": "跟踪可复用智能体在工作流中的活跃度、成本和交互质量。",+ "agentDetail.monitoring.learnMore": "了解更多",+ "agentDetail.monitoring.metrics.activeUsers.explanation": "触发过使用此智能体的工作流的独立终端用户数。",+ "agentDetail.monitoring.metrics.activeUsers.title": "活跃用户",+ "agentDetail.monitoring.metrics.avgSessionInteractions.explanation": "此访问入口下用户与智能体的连续沟通次数。",+ "agentDetail.monitoring.metrics.avgSessionInteractions.title": "平均会话互动数",+ "agentDetail.monitoring.metrics.tokenOutputSpeed.explanation": "从请求开始到输出完成期间的平均输出速度。",+ "agentDetail.monitoring.metrics.tokenOutputSpeed.title": "Token 输出速度",+ "agentDetail.monitoring.metrics.tokenUsage.explanation": "此智能体在工作流运行中产生的预估 token 成本。",+ "agentDetail.monitoring.metrics.tokenUsage.title": "Token 用量",+ "agentDetail.monitoring.metrics.totalConversations.explanation": "通过所选访问入口触达此智能体的每日 AI 会话数。",+ "agentDetail.monitoring.metrics.totalConversations.title": "全部会话数",+ "agentDetail.monitoring.metrics.totalMessages.explanation": "每日智能体互动总次数。",+ "agentDetail.monitoring.metrics.totalMessages.title": "全部消息数",+ "agentDetail.monitoring.metrics.userSatisfactionRate.explanation": "每 1000 条消息的点赞数,反映用户满意度。",+ "agentDetail.monitoring.metrics.userSatisfactionRate.title": "用户满意度",+ "agentDetail.monitoring.pickSource": "选择应用",+ "agentDetail.monitoring.sourceLabel": "应用",+ "agentDetail.monitoring.sourceTrigger": "来源 {{name}}",+ "agentDetail.monitoring.sources.all": "全部",+ "agentDetail.monitoring.timeRangeLabel": "时间范围",+ "agentDetail.monitoring.timeRanges.custom": "自定义",+ "agentDetail.monitoring.timeRanges.last30days": "最近 30 天",+ "agentDetail.monitoring.timeRanges.last7days": "最近 7 天",+ "agentDetail.monitoring.timeRanges.today": "今天",+ "agentDetail.monitoring.title": "监控",+ "agentDetail.monitoring.tokenUsageConsumed": "耗费 Tokens",+ "agentDetail.monitoring.units.tokenPerSecond": "Token/秒",+ "agentDetail.navigationLabel": "智能体导航",+ "agentDetail.publish": "发布",+ "agentDetail.publishSoon": "后续推出",+ "agentDetail.sections.access": "访问点",+ "agentDetail.sections.configure": "编排",+ "agentDetail.sections.logs": "日志",+ "agentDetail.sections.monitoring": "监控",+ "agentDetail.subtitle": "智能体 ID:{{agentId}}",+ "agentDetail.title": "智能体",+ "agentDetail.type": "智能体",+ "agentDetail.versionHistory.active": "当前",+ "agentDetail.versionHistory.empty": "暂无版本",+ "agentDetail.versionHistory.filter": "筛选版本",+ "agentDetail.versionHistory.versionName": "版本 {{version}}",+ "roster.createAgent": "创建智能体",+ "roster.createAgentOptions": "创建智能体选项",+ "roster.createDialog.description": "在当前工作区 Roster 中创建一个可复用智能体。",+ "roster.createDialog.title": "创建智能体",+ "roster.createFailed": "智能体创建失败。",+ "roster.createForm.changeIcon": "更换智能体图标",+ "roster.createForm.descriptionLabel": "描述",+ "roster.createForm.descriptionOptional": "(可选)",+ "roster.createForm.descriptionPlaceholder": "例如:收集某个主题的来源资料并总结关键发现",+ "roster.createForm.nameLabel": "名称",+ "roster.createForm.namePlaceholder": "例如:Max",+ "roster.createForm.nameRequired": "请输入名称。",+ "roster.createForm.roleLabel": "角色",+ "roster.createForm.rolePlaceholder": "例如:研究助理",+ "roster.createForm.roleRequired": "请输入角色。",+ "roster.createSuccess": "智能体已创建。",+ "roster.dateTimeFormat": "YYYY-MM-DD HH:mm:ss",+ "roster.deleteDialog.description": "此智能体将从当前活跃 Roster 列表中移除。",+ "roster.deleteDialog.title": "删除 {{name}}?",+ "roster.deleteFailed": "智能体删除失败。",+ "roster.deleteSuccess": "智能体已删除。",+ "roster.editAgent": "编辑 {{name}}",+ "roster.editDialog.description": "更新此智能体在 Roster 中的名称、描述和角色。",+ "roster.editDialog.title": "编辑智能体",+ "roster.editInfo": "编辑信息",+ "roster.empty": "暂无智能体",+ "roster.emptyDescription": "保存在此工作区的智能体会显示在这里。",+ "roster.emptySearch": "没有匹配的智能体",+ "roster.emptySearchDescription": "请尝试其他智能体名称。",+ "roster.filters.all": "全部",+ "roster.filters.drafts": "草稿",+ "roster.filters.label": "智能体筛选",+ "roster.filters.published": "已发布",+ "roster.learnMore": "了解 Agent Roster",+ "roster.listLabel": "智能体 Roster 列表",+ "roster.loadMore": "加载更多",+ "roster.loadingError": "智能体加载失败。请刷新后重试。",+ "roster.moreActions": "{{name}} 的更多操作",+ "roster.nodeSelector.createInlineFailed": "Inline 智能体创建失败。请刷新后重试。",+ "roster.nodeSelector.dialogLabel": "选择智能体",+ "roster.nodeSelector.manageInAgentConsole": "在智能体控制台管理",+ "roster.nodeSelector.searchPlaceholder": "搜索…",+ "roster.nodeSelector.startFromScratch": "从空白开始",+ "roster.references.label": "使用 {{name}} 的工作流",+ "roster.references.trigger": "使用 {{name}} 的工作流",+ "roster.searchLabel": "搜索智能体",+ "roster.searchPlaceholder": "按名称搜索智能体…",+ "roster.sources.agent_app": "智能体应用",+ "roster.sources.imported": "导入",+ "roster.sources.system": "系统",+ "roster.sources.workflow": "工作流",+ "roster.status.active": "活跃",+ "roster.status.archived": "已归档",+ "roster.tabs.agent": "智能体",+ "roster.tabs.human": "人工成员",+ "roster.tabsLabel": "Roster 类型",+ "roster.updateFailed": "智能体更新失败。请检查字段后重试。",+ "roster.updateSuccess": "智能体已更新。",+ "roster.usageStatus.draft": "草稿"+}diff --git a/web/i18n/zh-Hans/common.json b/web/i18n/zh-Hans/common.jsonindex d0fbf61e154..0245ca738b9 100644--- a/web/i18n/zh-Hans/common.json+++ b/web/i18n/zh-Hans/common.json@@ -318,6 +318,7 @@"menus.newDataset": "创建知识库","menus.plugins": "集成","menus.pluginsTips": "集成第三方服务或创建与 ChatGPT 兼容的 AI 集成。",+ "menus.roster": "智能体名册","menus.status": "beta","menus.tools": "工具","model.addMoreModel": "添加更多模型",diff --git a/web/i18n/zh-Hans/workflow.json b/web/i18n/zh-Hans/workflow.jsonindex 0bb422169d6..004b1d3b6bd 100644--- a/web/i18n/zh-Hans/workflow.json+++ b/web/i18n/zh-Hans/workflow.json@@ -1,5 +1,6 @@{"blocks.agent": "Agent",+ "blocks.agent-v2": "Agent","blocks.answer": "直接回复","blocks.assigner": "变量赋值","blocks.code": "代码执行",@@ -33,6 +34,7 @@"blocks.variable-aggregator": "变量聚合器","blocks.variable-assigner": "变量赋值器","blocksAbout.agent": "调用大型语言模型回答问题或处理自然语言",+ "blocksAbout.agent-v2": "调用大型语言模型回答问题或处理自然语言","blocksAbout.answer": "定义一个聊天对话的回复内容","blocksAbout.assigner": "变量赋值节点用于向可写入变量(例如会话变量)进行变量赋值。","blocksAbout.code": "执行一段 Python 或 NodeJS 代码实现自定义逻辑",@@ -378,6 +380,7 @@"globalVar.fieldsDescription.workflowId": "工作流 ID","globalVar.fieldsDescription.workflowRunId": "工作流运行 ID","globalVar.title": "系统变量",+ "nodes.agent.advancedSetting": "高级设置","nodes.agent.checkList.strategyNotSelected": "未选择策略","nodes.agent.clickToViewParameterSchema": "点击查看参数 schema","nodes.agent.configureModel": "配置模型",@@ -400,13 +403,34 @@"nodes.agent.modelNotSupport.title": "不支持的模型","nodes.agent.modelSelectorTooltips.deprecated": "此模型已弃用","nodes.agent.notAuthorized": "未授权",+ "nodes.agent.outputVars.confirm": "确认",+ "nodes.agent.outputVars.defaultValueArrayInvalid": "请输入 JSON 数组。",+ "nodes.agent.outputVars.defaultValueBooleanInvalid": "请输入 true 或 false。",+ "nodes.agent.outputVars.defaultValueFileUnsupported": "这里暂不支持配置文件默认值。",+ "nodes.agent.outputVars.defaultValueLabel": "默认值",+ "nodes.agent.outputVars.defaultValueNumberInvalid": "请输入有效数字。",+ "nodes.agent.outputVars.defaultValueObjectInvalid": "请输入 JSON 对象。",+ "nodes.agent.outputVars.defaultValuePlaceholder": "默认值",+ "nodes.agent.outputVars.delete": "删除 {{name}}",+ "nodes.agent.outputVars.descriptionLabel": "描述",+ "nodes.agent.outputVars.descriptionPlaceholder": "添加描述",+ "nodes.agent.outputVars.edit": "编辑 {{name}}",+ "nodes.agent.outputVars.editorLabel": "输出变量编辑器","nodes.agent.outputVars.files.title": "agent 生成的文件","nodes.agent.outputVars.files.transfer_method": "传输方式。值为 remote_url 或 local_file","nodes.agent.outputVars.files.type": "支持类型。现在只支持图片","nodes.agent.outputVars.files.upload_file_id": "上传文件 ID","nodes.agent.outputVars.files.url": "图片链接","nodes.agent.outputVars.json": "agent 生成的 json",+ "nodes.agent.outputVars.nameDuplicate": "输出变量名称已存在",+ "nodes.agent.outputVars.nameInvalid": "请使用字母、数字和下划线,并以字母或下划线开头。",+ "nodes.agent.outputVars.nameLabel": "字段名称",+ "nodes.agent.outputVars.namePlaceholder": "字段名称",+ "nodes.agent.outputVars.newOutput": "新建输出",+ "nodes.agent.outputVars.requiredLabel": "必填",+ "nodes.agent.outputVars.showAdvancedOptions": "显示高级选项","nodes.agent.outputVars.text": "agent 生成的内容",+ "nodes.agent.outputVars.typeLabel": "输出类型","nodes.agent.outputVars.usage": "模型用量信息","nodes.agent.parameterSchema": "参数 Schema","nodes.agent.pluginInstaller.install": "安装",@@ -414,6 +438,17 @@"nodes.agent.pluginNotFoundDesc": "此集成安装自 GitHub。请前往集成重新安装","nodes.agent.pluginNotInstalled": "此集成未安装","nodes.agent.pluginNotInstalledDesc": "此集成安装自 GitHub。请前往集成重新安装",+ "nodes.agent.roster.change": "更换",+ "nodes.agent.roster.editInConsole": "在 Agent Console 中编辑",+ "nodes.agent.roster.inlineSetup.description": "仅存在于此节点的一次性设置",+ "nodes.agent.roster.inlineSetup.name": "内联配置",+ "nodes.agent.roster.inlineSetup.title": "Agent 设置",+ "nodes.agent.roster.inlineSetup.type": "仅在此节点中",+ "nodes.agent.roster.label": "Agent",+ "nodes.agent.roster.makeCopy": "创建副本",+ "nodes.agent.roster.more": "更多 Agent 操作",+ "nodes.agent.roster.openPanel": "打开 {{name}} 详情",+ "nodes.agent.roster.panelLabel": "{{name}} 详情","nodes.agent.strategy.configureTip": "请配置 Agent 策略。","nodes.agent.strategy.configureTipDesc": "配置完成后,此节点将自动加载剩余配置。策略将影响多步工具推理的机制。","nodes.agent.strategy.label": "Agent 策略",@@ -425,6 +460,11 @@"nodes.agent.strategyNotFoundDescAndSwitchVersion": "已安装的集成版本不提供此策略。点击切换版本。","nodes.agent.strategyNotInstallTooltip": "{{strategy}} 未安装","nodes.agent.strategyNotSet": "代理策略未设置",+ "nodes.agent.task.insert": "插入",+ "nodes.agent.task.label": "Agent 任务",+ "nodes.agent.task.mention": "提及",+ "nodes.agent.task.placeholder": "描述这个 Agent 要完成的任务...",+ "nodes.agent.task.tooltip": "定义该 Agent 在当前工作流中需要遵循的任务指令。","nodes.agent.toolNotAuthorizedTooltip": "{{tool}} 未授权","nodes.agent.toolNotInstallTooltip": "{{tool}} 未安装","nodes.agent.toolbox": "工具箱",@@ -1210,7 +1250,7 @@"tabs.pluginByAuthor": "来自 {{author}}","tabs.question-understand": "问题理解","tabs.requestToCommunity": "向社区反馈",- "tabs.searchBlock": "搜索节点",+ "tabs.searchBlock": "搜索节点、Agent、人工、知识库","tabs.searchDataSource": "搜索数据源","tabs.searchSnippets": "搜索 snippets...","tabs.searchTool": "搜索集成",diff --git a/web/i18n/zh-Hant/common.json b/web/i18n/zh-Hant/common.jsonindex e32c6846d80..8e586d5640e 100644--- a/web/i18n/zh-Hant/common.json+++ b/web/i18n/zh-Hant/common.json@@ -318,6 +318,7 @@"menus.newDataset": "建立知識庫","menus.plugins": "集成","menus.pluginsTips": "集成第三方服務或建立與 ChatGPT 相容的 AI 集成。",+ "menus.roster": "智能體名冊","menus.status": "beta","menus.tools": "工具","model.addMoreModel": "新增更多模型",diff --git a/web/i18n/zh-Hant/workflow.json b/web/i18n/zh-Hant/workflow.jsonindex d0f0f804031..f1da5b4096d 100644--- a/web/i18n/zh-Hant/workflow.json+++ b/web/i18n/zh-Hant/workflow.json@@ -1,5 +1,6 @@{- "blocks.agent": "代理",+ "blocks.agent": "Agent",+ "blocks.agent-v2": "Agent","blocks.answer": "直接回覆","blocks.assigner": "變數分配器","blocks.code": "程式碼執行",@@ -33,6 +34,7 @@"blocks.variable-aggregator": "變數聚合器","blocks.variable-assigner": "變數聚合器","blocksAbout.agent": "調用大型語言模型來回答問題或處理自然語言",+ "blocksAbout.agent-v2": "調用大型語言模型來回答問題或處理自然語言","blocksAbout.answer": "定義一個聊天對話的回覆內容","blocksAbout.assigner": "變數分配節點用於為可寫入的變數(如對話變數)分配值。","blocksAbout.code": "執行一段 Python 或 NodeJS 程式碼實現自定義邏輯",@@ -414,6 +416,7 @@"nodes.agent.pluginNotFoundDesc": "此集成安裝自 GitHub。請前往集成重新安裝","nodes.agent.pluginNotInstalled": "此集成未安裝","nodes.agent.pluginNotInstalledDesc": "此集成安裝自 GitHub。請前往集成重新安裝",+ "nodes.agent.roster.label": "智能體","nodes.agent.strategy.configureTip": "請配置 agentic 策略。","nodes.agent.strategy.configureTipDesc": "配置代理策略后,該節點將自動載入剩餘的配置。該策略將影響多步驟工具推理的機制。","nodes.agent.strategy.label": "代理策略",diff --git a/web/knip.config.ts b/web/knip.config.tsindex dfd9adf79a1..419bf825299 100644--- a/web/knip.config.ts+++ b/web/knip.config.ts@@ -13,6 +13,10 @@ const config: KnipConfig = {ignore: ['public/**',],+ ignoreFiles: [+ 'features/agent-v2/agent-detail/configure/components/orchestrate/memory.tsx',+ 'features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/option-menu.tsx',+ ],ignoreBinaries: ['only-allow','pbcopy',diff --git a/web/service/client.spec.ts b/web/service/client.spec.tsindex de48850c86e..f38769992e1 100644--- a/web/service/client.spec.ts+++ b/web/service/client.spec.ts@@ -1,5 +1,6 @@import type { ApiBasedExtensionResponse } from '@dify/contracts/api/console/api-based-extension/types.gen'import type { MutationFunctionContext } from '@tanstack/react-query'+import type { consoleQuery as ConsoleQuery } from './client'import type { Tag } from '@/contract/console/tags'import { QueryClient } from '@tanstack/react-query'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'@@ -43,6 +44,43 @@ const createApiBasedExtension = (overrides: Partial<ApiBasedExtensionResponse> =...overrides,})+type AgentMutationResponse = Parameters<NonNullable<ReturnType<typeof ConsoleQuery.agent.post.mutationOptions>['onSuccess']>>[0]+type AgentComposerMutationResponse = Parameters<NonNullable<ReturnType<typeof ConsoleQuery.agent.byAgentId.composer.put.mutationOptions>['onSuccess']>>[0]++const createAgent = (overrides: Partial<AgentMutationResponse> = {}): AgentMutationResponse => ({+ ...overrides,+ active_config_is_published: overrides.active_config_is_published ?? false,+ enable_api: overrides.enable_api ?? true,+ enable_site: overrides.enable_site ?? true,+ description: overrides.description ?? 'Agent description',+ id: overrides.id ?? 'agent-1',+ icon_url: overrides.icon_url ?? null,+ mode: overrides.mode ?? 'agent',+ name: overrides.name ?? 'Agent',+ role: overrides.role ?? 'Assistant',+})++const createComposerState = (overrides: Partial<AgentComposerMutationResponse> = {}): AgentComposerMutationResponse => ({+ active_config_snapshot: {+ id: 'snapshot-1',+ version: 1,+ },+ agent: {+ active_config_snapshot_id: 'snapshot-1',+ description: 'Agent description',+ id: 'agent-1',+ name: 'Agent',+ scope: 'roster',+ status: 'active',+ },+ agent_soul: {+ schema_version: 1,+ },+ save_options: ['save_to_current_version', 'save_as_new_version'],+ variant: 'agent_app',+ ...overrides,+})+// Scenario: base URL selection and warnings.describe('getBaseURL', () => {beforeEach(() => {@@ -112,6 +150,212 @@ describe('getBaseURL', () => {})})+// Scenario: oRPC mutation defaults own shared Agent roster cache behavior.+describe('consoleQuery agent mutation defaults', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ afterEach(() => {+ vi.restoreAllMocks()+ })++ it('should invalidate roster and invite option lists after creating an agent', async () => {+ const consoleQuery = await loadConsoleQuery()+ const queryClient = new QueryClient()+ const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')+ const createdAgent = createAgent()++ const mutationOptions = consoleQuery.agent.post.mutationOptions()+ await mutationOptions.onSuccess?.(+ createdAgent,+ {+ body: {+ name: createdAgent.name,+ description: createdAgent.description,+ role: createdAgent.role ?? 'Assistant',+ },+ },+ undefined,+ createMutationContext(queryClient),+ )++ expect(invalidateQueries).toHaveBeenCalledWith({+ queryKey: consoleQuery.agent.get.key(),+ })+ expect(invalidateQueries).toHaveBeenCalledWith({+ queryKey: consoleQuery.agent.inviteOptions.get.key(),+ })+ })++ it('should invalidate invite option lists after updating an agent', async () => {+ const consoleQuery = await loadConsoleQuery()+ const queryClient = new QueryClient()+ const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')+ const updatedAgent = createAgent({ name: 'Updated Agent' })++ const mutationOptions = consoleQuery.agent.byAgentId.put.mutationOptions()+ await mutationOptions.onSuccess?.(+ updatedAgent,+ {+ params: {+ agent_id: updatedAgent.id,+ },+ body: {+ name: updatedAgent.name,+ role: updatedAgent.role ?? 'Assistant',+ },+ },+ undefined,+ createMutationContext(queryClient),+ )++ expect(invalidateQueries).toHaveBeenCalledWith({+ queryKey: consoleQuery.agent.inviteOptions.get.key(),+ })+ })++ it('should invalidate roster and invite option lists after publishing an agent config', async () => {+ const consoleQuery = await loadConsoleQuery()+ const queryClient = new QueryClient()+ const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')+ const removeQueries = vi.spyOn(queryClient, 'removeQueries')+ const inviteOptionsQueryKey = consoleQuery.agent.inviteOptions.get.queryKey({+ input: {+ query: {+ app_id: 'app-1',+ limit: 8,+ page: 1,+ },+ },+ })+ queryClient.setQueryData(inviteOptionsQueryKey, {+ data: [+ {+ active_config_is_published: true,+ active_config_snapshot: null,+ active_config_snapshot_id: 'snapshot-1',+ agent_kind: 'dify_agent',+ app_id: null,+ archived_at: null,+ archived_by: null,+ created_at: 1,+ created_by: null,+ description: 'Agent description',+ existing_node_ids: [],+ icon: null,+ icon_background: null,+ icon_type: null,+ id: 'agent-1',+ in_current_workflow_count: 0,+ is_in_current_workflow: false,+ name: 'Agent',+ published_node_reference_count: 0,+ published_reference_count: 0,+ published_references: [],+ role: '',+ scope: 'roster',+ source: 'workflow',+ status: 'active',+ updated_at: 1,+ updated_by: null,+ workflow_id: null,+ workflow_node_id: null,+ },+ ],+ has_more: false,+ limit: 8,+ page: 1,+ total: 1,+ })++ const mutationOptions = consoleQuery.agent.byAgentId.composer.put.mutationOptions()+ await mutationOptions.onSuccess?.(+ createComposerState(),+ {+ params: {+ agent_id: 'agent-1',+ },+ body: {+ variant: 'agent_app',+ save_strategy: 'save_as_new_version',+ agent_soul: {+ schema_version: 1,+ },+ },+ },+ undefined,+ createMutationContext(queryClient),+ )++ expect(invalidateQueries).toHaveBeenCalledWith({+ queryKey: consoleQuery.agent.get.key(),+ })+ expect(invalidateQueries).toHaveBeenCalledWith({+ queryKey: consoleQuery.agent.inviteOptions.get.key(),+ })+ expect(removeQueries).toHaveBeenCalledWith({+ queryKey: consoleQuery.agent.inviteOptions.get.key(),+ })+ expect(queryClient.getQueryData(inviteOptionsQueryKey)).toBeUndefined()+ })++ it('should keep roster and invite option lists stable after saving an agent draft', async () => {+ const consoleQuery = await loadConsoleQuery()+ const queryClient = new QueryClient()+ const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')++ const mutationOptions = consoleQuery.agent.byAgentId.composer.put.mutationOptions()+ await mutationOptions.onSuccess?.(+ createComposerState(),+ {+ params: {+ agent_id: 'agent-1',+ },+ body: {+ variant: 'agent_app',+ save_strategy: 'save_to_current_version',+ agent_soul: {+ schema_version: 1,+ },+ },+ },+ undefined,+ createMutationContext(queryClient),+ )++ expect(invalidateQueries).not.toHaveBeenCalledWith({+ queryKey: consoleQuery.agent.get.key(),+ })+ expect(invalidateQueries).not.toHaveBeenCalledWith({+ queryKey: consoleQuery.agent.inviteOptions.get.key(),+ })+ })++ it('should invalidate invite option lists after deleting an agent', async () => {+ const consoleQuery = await loadConsoleQuery()+ const queryClient = new QueryClient()+ const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')+ const deletedAgent = createAgent()++ const mutationOptions = consoleQuery.agent.byAgentId.delete.mutationOptions()+ await mutationOptions.onSuccess?.(+ {},+ {+ params: {+ agent_id: deletedAgent.id,+ },+ },+ undefined,+ createMutationContext(queryClient),+ )++ expect(invalidateQueries).toHaveBeenCalledWith({+ queryKey: consoleQuery.agent.inviteOptions.get.key(),+ })+ })+})+// Scenario: oRPC mutation defaults own shared tag cache behavior.describe('consoleQuery tag mutation defaults', () => {beforeEach(() => {diff --git a/web/service/client.ts b/web/service/client.tsindex 3a26185a9b3..0e0ecaf6ed3 100644--- a/web/service/client.ts+++ b/web/service/client.ts@@ -1,3 +1,4 @@+import type { AgentAppPagination } from '@dify/contracts/api/console/agent/types.gen'import type { ApiBasedExtensionResponse } from '@dify/contracts/api/console/api-based-extension/types.gen'import type {GetReleaseResponse,@@ -7,7 +8,7 @@ import type {import type { ContractRouterClient } from '@orpc/contract'import type { JsonifiedClient } from '@orpc/openapi-client'import type { RouterUtils } from '@orpc/tanstack-query'-import type { QueryClient, QueryKey } from '@tanstack/react-query'+import type { InfiniteData, QueryClient, QueryKey } from '@tanstack/react-query'import type { Tag } from '@/contract/console/tags'import { createORPCClient, onError } from '@orpc/client'import { OpenAPILink } from '@orpc/openapi-client/fetch'@@ -23,6 +24,7 @@ import {marketplaceRouterContract,} from '@/contract/router'import { isClient } from '@/utils/client'+// eslint-disable-next-line no-restricted-importsimport { request } from './base'function getMarketplaceHeaders() {@@ -345,6 +347,142 @@ export const consoleClient: JsonifiedClient<ContractRouterClient<typeof consoleRexport const consoleQuery: RouterUtils<typeof consoleClient> = createTanstackQueryUtils(consoleClient, {path: ['console'],experimental_defaults: {+ agent: {+ post: {+ mutationOptions: {+ onSuccess: (_createdAgent, _variables, _onMutateResult, context) => {+ context.client.invalidateQueries({+ queryKey: consoleQuery.agent.get.key(),+ })+ context.client.invalidateQueries({+ queryKey: consoleQuery.agent.inviteOptions.get.key(),+ })+ },+ },+ },+ byAgentId: {+ put: {+ mutationOptions: {+ onSuccess: (updatedAgent, variables, _onMutateResult, context) => {+ context.client.setQueriesData(+ {+ queryKey: consoleQuery.agent.get.key({ type: 'query' }),+ },+ (oldList: AgentAppPagination | undefined) => {+ if (!oldList?.data.some(item => item.id === updatedAgent.id))+ return oldList++ return {+ ...oldList,+ data: oldList.data.map(item => item.id === updatedAgent.id ? updatedAgent : item),+ }+ },+ )+ context.client.setQueriesData(+ {+ queryKey: consoleQuery.agent.get.key({ type: 'infinite' }),+ },+ (oldList: InfiniteData<AgentAppPagination, unknown> | undefined) => {+ if (!oldList?.pages.some(page => page.data.some(item => item.id === updatedAgent.id)))+ return oldList++ return {+ ...oldList,+ pages: oldList.pages.map(page => ({+ ...page,+ data: page.data.map(item => item.id === updatedAgent.id ? updatedAgent : item),+ })),+ }+ },+ )+ context.client.setQueryData(+ consoleQuery.agent.byAgentId.get.queryKey({+ input: {+ params: {+ agent_id: variables.params.agent_id,+ },+ },+ }),+ updatedAgent,+ )+ context.client.invalidateQueries({+ queryKey: consoleQuery.agent.inviteOptions.get.key(),+ })+ },+ },+ },+ composer: {+ put: {+ mutationOptions: {+ onSuccess: (_composerState, variables, _onMutateResult, context) => {+ if (variables.body.save_strategy !== 'save_as_new_version')+ return++ context.client.invalidateQueries({+ queryKey: consoleQuery.agent.get.key(),+ })+ context.client.invalidateQueries({+ queryKey: consoleQuery.agent.inviteOptions.get.key(),+ })+ context.client.removeQueries({+ queryKey: consoleQuery.agent.inviteOptions.get.key(),+ })+ },+ },+ },+ },+ delete: {+ mutationOptions: {+ onSuccess: (_data, variables, _onMutateResult, context) => {+ context.client.setQueriesData(+ {+ queryKey: consoleQuery.agent.get.key({ type: 'query' }),+ },+ (oldList: AgentAppPagination | undefined) => {+ if (!oldList?.data.some(item => item.id === variables.params.agent_id))+ return oldList++ return {+ ...oldList,+ data: oldList.data.filter(item => item.id !== variables.params.agent_id),+ total: Math.max(0, oldList.total - 1),+ }+ },+ )+ context.client.setQueriesData(+ {+ queryKey: consoleQuery.agent.get.key({ type: 'infinite' }),+ },+ (oldList: InfiniteData<AgentAppPagination, unknown> | undefined) => {+ if (!oldList?.pages.some(page => page.data.some(item => item.id === variables.params.agent_id)))+ return oldList++ return {+ ...oldList,+ pages: oldList.pages.map((page) => {+ const total = Math.max(0, page.total - 1)++ return {+ ...page,+ data: page.data.filter(item => item.id !== variables.params.agent_id),+ has_more: page.page * page.limit < total,+ total,+ }+ }),+ }+ },+ )+ context.client.invalidateQueries({+ queryKey: consoleQuery.agent.get.key(),+ })+ context.client.invalidateQueries({+ queryKey: consoleQuery.agent.inviteOptions.get.key(),+ })+ },+ },+ },+ },+ },explore: {updateAppAccessMode: {mutationOptions: {