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 (2026-06-22) (#37651)
盐粒 Yanlif4fdbeba7614
diff --git a/.github/workflows/build-push.yml b/.github/workflows/build-push.ymlindex 0134ea850d0..63ce63cad42 100644--- a/.github/workflows/build-push.yml+++ b/.github/workflows/build-push.yml@@ -21,6 +21,7 @@ env:DIFY_WEB_IMAGE_NAME: ${{ vars.DIFY_WEB_IMAGE_NAME || 'langgenius/dify-web' }}DIFY_API_IMAGE_NAME: ${{ vars.DIFY_API_IMAGE_NAME || 'langgenius/dify-api' }}DIFY_AGENT_IMAGE_NAME: ${{ vars.DIFY_AGENT_IMAGE_NAME || 'langgenius/dify-agent-backend' }}+ DIFY_AGENT_LOCAL_SANDBOX_IMAGE_NAME: ${{ vars.DIFY_AGENT_LOCAL_SANDBOX_IMAGE_NAME || 'langgenius/dify-agent-local-sandbox' }}jobs:build:@@ -74,6 +75,20 @@ jobs:file: "dify-agent/Dockerfile"platform: linux/arm64runs_on: depot-ubuntu-24.04-4+ - service_name: "build-agent-local-sandbox-amd64"+ image_name_env: "DIFY_AGENT_LOCAL_SANDBOX_IMAGE_NAME"+ artifact_context: "local-sandbox"+ build_context: "{{defaultContext}}:dify-agent"+ file: "docker/local-sandbox/Dockerfile"+ platform: linux/amd64+ runs_on: depot-ubuntu-24.04-4+ - service_name: "build-agent-local-sandbox-arm64"+ image_name_env: "DIFY_AGENT_LOCAL_SANDBOX_IMAGE_NAME"+ artifact_context: "local-sandbox"+ build_context: "{{defaultContext}}:dify-agent"+ file: "docker/local-sandbox/Dockerfile"+ platform: linux/arm64+ runs_on: depot-ubuntu-24.04-4steps:- name: Prepare@@ -139,6 +154,9 @@ jobs:- service_name: "validate-agent-amd64"build_context: "{{defaultContext}}"file: "dify-agent/Dockerfile"+ - service_name: "validate-agent-local-sandbox-amd64"+ build_context: "{{defaultContext}}:dify-agent"+ file: "docker/local-sandbox/Dockerfile"steps:- name: Set up Docker Buildxuses: docker/setup-buildx-action@d7f5e7f509e45cec5c76c4d5afdd7de93d0b3df5 # v4.1.0@@ -167,6 +185,9 @@ jobs:- service_name: "merge-agent-images"image_name_env: "DIFY_AGENT_IMAGE_NAME"context: "agent"+ - service_name: "merge-agent-local-sandbox-images"+ image_name_env: "DIFY_AGENT_LOCAL_SANDBOX_IMAGE_NAME"+ context: "local-sandbox"steps:- name: Download digestsuses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1diff --git a/api/clients/agent_backend/request_builder.py b/api/clients/agent_backend/request_builder.pyindex c245a09e970..6eadd4ce3d8 100644--- a/api/clients/agent_backend/request_builder.py+++ b/api/clients/agent_backend/request_builder.py@@ -78,6 +78,13 @@ def _filter_snapshot_to_specs(return CompositorSessionSnapshot(schema_version=snapshot.schema_version, layers=filtered_layers)+def _shell_layer_deps(*, include_drive: bool) -> dict[str, str]:+ deps = {"execution_context": DIFY_EXECUTION_CONTEXT_LAYER_ID}+ if include_drive:+ deps["drive"] = DIFY_DRIVE_LAYER_ID+ return deps++class AgentBackendModelConfig(BaseModel):"""API-side model/plugin selection before it is converted to Dify Agent layers."""@@ -263,6 +270,7 @@ class AgentBackendRunRequestBuilder:RunLayerSpec(name=DIFY_DRIVE_LAYER_ID,type=DIFY_DRIVE_LAYER_TYPE_ID,+ deps={"execution_context": DIFY_EXECUTION_CONTEXT_LAYER_ID},metadata=run_input.metadata,config=run_input.drive_config,)@@ -329,14 +337,15 @@ class AgentBackendRunRequestBuilder:)if run_input.include_shell:- # Sandboxed bash workspace (dify.shell). Depends on execution_context so- # the agent server can mint per-command Agent Stub env (back proxy);+ # Sandboxed bash workspace (dify.shell). Depends on execution_context+ # so the agent server can mint per-command Agent Stub env, and on+ # drive when present so that env points at /mnt/drive/<drive_ref>.# shellctl connection itself is server-injected.layers.append(RunLayerSpec(name=DIFY_SHELL_LAYER_ID,type=DIFY_SHELL_LAYER_TYPE_ID,- deps={"execution_context": DIFY_EXECUTION_CONTEXT_LAYER_ID},+ deps=_shell_layer_deps(include_drive=run_input.drive_config is not None),metadata=run_input.metadata,config=run_input.shell_config or DifyShellLayerConfig(),)@@ -460,6 +469,7 @@ class AgentBackendRunRequestBuilder:RunLayerSpec(name=DIFY_DRIVE_LAYER_ID,type=DIFY_DRIVE_LAYER_TYPE_ID,+ deps={"execution_context": DIFY_EXECUTION_CONTEXT_LAYER_ID},metadata=run_input.metadata,config=run_input.drive_config,)@@ -528,14 +538,15 @@ class AgentBackendRunRequestBuilder:)if run_input.include_shell:- # Sandboxed bash workspace (dify.shell). Depends on execution_context so- # the agent server can mint per-command Agent Stub env (back proxy);+ # Sandboxed bash workspace (dify.shell). Depends on execution_context+ # so the agent server can mint per-command Agent Stub env, and on+ # drive when present so that env points at /mnt/drive/<drive_ref>.# shellctl connection itself is server-injected.layers.append(RunLayerSpec(name=DIFY_SHELL_LAYER_ID,type=DIFY_SHELL_LAYER_TYPE_ID,- deps={"execution_context": DIFY_EXECUTION_CONTEXT_LAYER_ID},+ deps=_shell_layer_deps(include_drive=run_input.drive_config is not None),metadata=run_input.metadata,config=run_input.shell_config or DifyShellLayerConfig(),)diff --git a/api/controllers/console/app/agent.py b/api/controllers/console/app/agent.pyindex a53a174da42..86a3c473547 100644--- a/api/controllers/console/app/agent.py+++ b/api/controllers/console/app/agent.py@@ -1,4 +1,3 @@-import loggingfrom typing import Anyfrom uuid import UUID@@ -30,7 +29,6 @@ from fields.base import ResponseModelfrom libs.helper import uuid_valuefrom libs.login import login_requiredfrom models import Account-from models.agent_config_entities import AgentFileRefConfig, AgentSkillRefConfigfrom models.model import App, AppMode, UploadFilefrom services.agent.composer_service import AgentComposerServicefrom services.agent.skill_package_service import SkillManifest, SkillPackageError@@ -49,8 +47,6 @@ from services.agent_drive_service import ()from services.agent_service import AgentService-logger = logging.getLogger(__name__)-_WORKFLOW_AGENT_DRIVE_APP_MODES = [AppMode.WORKFLOW, AppMode.ADVANCED_CHAT]_AGENT_SKILL_UPLOAD_PARAMS = {"file": {@@ -130,8 +126,16 @@ class AgentLogResponse(ResponseModel):files: list[Any] = Field(default_factory=list)+class AgentUploadedSkillResponse(ResponseModel):+ name: str+ description: str+ path: str+ skill_md_key: str+ archive_key: str | None = None++class AgentSkillUploadResponse(ResponseModel):- skill: AgentSkillRefConfig+ skill: AgentUploadedSkillResponsemanifest: SkillManifest@@ -145,13 +149,11 @@ class AgentDriveFileResponse(ResponseModel):class AgentDriveFileCommitResponse(ResponseModel):file: AgentDriveFileResponse- config_version_id: str | None = Noneclass AgentDriveDeleteResponse(ResponseModel):result: strremoved_keys: list[str] = Field(default_factory=list)- config_version_id: str | None = Noneregister_schema_models(console_ns, AgentLogQuery, AgentDriveFilePayload, AgentDriveDeleteFileByAgentQuery)@@ -161,6 +163,7 @@ register_response_schema_models(AgentDriveFileCommitResponse,AgentDriveFileResponse,AgentLogResponse,+ AgentUploadedSkillResponse,AgentSkillUploadResponse,SkillToolInferenceResult,)@@ -242,24 +245,6 @@ def _commit_drive_file_for_app(*, current_user: Account, app_model: App, allow_nreturn {"code": exc.code, "message": exc.message}, exc.status_coderow = committed[0]- file_ref = AgentFileRefConfig.model_validate(- {- "id": row["key"],- "name": upload_file.name,- "file_id": upload_file.id,- "drive_key": row["key"],- "type": row.get("mime_type"),- "size": row.get("size"),- }- )- config_version_id = AgentComposerService.add_drive_file_ref(- tenant_id=app_model.tenant_id,- agent_id=agent_id,- account_id=current_user.id,- file_ref=file_ref,- app_id=app_model.id,- node_id=node_id,- )return {"file": {"name": upload_file.name,@@ -268,7 +253,6 @@ def _commit_drive_file_for_app(*, current_user: Account, app_model: App, allow_n"size": row.get("size"),"mime_type": row.get("mime_type"),},- "config_version_id": config_version_id,}, 201@@ -283,24 +267,17 @@ def _delete_drive_file_for_app(*, current_user: Account, app_model: App, allow_nexcept AgentDriveError as exc:return {"code": exc.code, "message": exc.message}, exc.status_code- config_version_id = AgentComposerService.remove_drive_refs(- tenant_id=app_model.tenant_id,- agent_id=agent_id,- account_id=current_user.id,- file_key=key,- app_id=app_model.id,- node_id=node_id,- )- removed_keys: list[str] = []try:- removed_keys = AgentDriveService().delete(tenant_id=app_model.tenant_id, agent_id=agent_id, key=key)+ result = AgentDriveService().commit(+ tenant_id=app_model.tenant_id,+ user_id=current_user.id,+ agent_id=agent_id,+ items=[DriveCommitItem(key=key, file_ref=None)],+ )except AgentDriveError as exc:return {"code": exc.code, "message": exc.message}, exc.status_code- except Exception:- # Soul-first ordering: the ref is already gone; orphan KV rows are- # harmless and an idempotent DELETE retry cleans them.- logger.exception("agent drive delete failed for key %s (soul already updated)", key)- return {"result": "success", "removed_keys": removed_keys, "config_version_id": config_version_id}+ removed_keys = [item["key"] for item in result if item.get("removed")]+ return {"result": "success", "removed_keys": removed_keys}def _delete_skill_for_app(*, current_user: Account, app_model: App, slug: str, allow_node_id: bool = True):@@ -312,22 +289,20 @@ def _delete_skill_for_app(*, current_user: Account, app_model: App, slug: str, aif "/" in slug or not slug.strip():return {"code": "drive_key_invalid", "message": "skill slug must be a single path segment"}, 400- config_version_id = AgentComposerService.remove_drive_refs(- tenant_id=app_model.tenant_id,- agent_id=agent_id,- account_id=current_user.id,- skill_slug=slug,- app_id=app_model.id,- node_id=node_id,- )- removed_keys: list[str] = []try:- removed_keys = AgentDriveService().delete(tenant_id=app_model.tenant_id, agent_id=agent_id, prefix=f"{slug}/")+ result = AgentDriveService().commit(+ tenant_id=app_model.tenant_id,+ user_id=current_user.id,+ agent_id=agent_id,+ items=[+ DriveCommitItem(key=f"{slug}/SKILL.md", file_ref=None),+ DriveCommitItem(key=f"{slug}/.DIFY-SKILL-FULL.zip", file_ref=None),+ ],+ )except AgentDriveError as exc:return {"code": exc.code, "message": exc.message}, exc.status_code- except Exception:- logger.exception("agent drive delete failed for skill %s (soul already updated)", slug)- return {"result": "success", "removed_keys": removed_keys, "config_version_id": config_version_id}+ removed_keys = [item["key"] for item in result if item.get("removed")]+ return {"result": "success", "removed_keys": removed_keys}def _infer_skill_tools_for_app(*, app_model: App, slug: str):@@ -455,7 +430,7 @@ class AgentDriveFilesApi(Resource):return _commit_drive_file_for_app(current_user=current_user, app_model=app_model)@console_ns.doc("delete_agent_drive_file")- @console_ns.doc(description="Delete one drive file by key; soul ref first, then the KV row (ENG-625 D5)")+ @console_ns.doc(description="Delete one drive file by key via drive commit-null semantics")@console_ns.doc(params={"app_id": "Application ID", **query_params_from_model(AgentDriveDeleteFileQuery)})@console_ns.response(200, "File removed", console_ns.models[AgentDriveDeleteResponse.__name__])@setup_required@@ -486,9 +461,7 @@ class AgentSkillByAgentApi(Resource):@console_ns.route("/apps/<uuid:app_id>/agent/skills/<string:slug>")class AgentSkillApi(Resource):@console_ns.doc("delete_agent_skill")- @console_ns.doc(- description="Delete a standardized skill: soul ref first, then the <slug>/ drive prefix (ENG-625 D5)"- )+ @console_ns.doc(description="Delete a standardized skill by removing its known drive keys via commit-null")@console_ns.doc(params={"app_id": "Application ID",diff --git a/api/controllers/inner_api/knowledge/retrieval.py b/api/controllers/inner_api/knowledge/retrieval.pyindex ef33fbda518..1c1320fde42 100644--- a/api/controllers/inner_api/knowledge/retrieval.py+++ b/api/controllers/inner_api/knowledge/retrieval.py@@ -1,9 +1,10 @@-"""Inner API endpoint for tenant-scoped knowledge retrieval.+"""Plugin inner API endpoint for tenant-scoped knowledge retrieval.This controller is a thin HTTP wrapper around``services.knowledge_retrieval_inner_service.InnerKnowledgeRetrievalService``.-It intentionally keeps authorization simple: shared inner API key plus-tenant-scoped app/dataset validation in the service layer.+It uses the plugin inner API key because dify-agent calls this endpoint through+the same trusted Dify API bridge as other agent/plugin inner calls; tenant-scoped+app/dataset validation remains in the service layer."""from flask_restx import Resource@@ -11,7 +12,7 @@ from pydantic import ValidationErrorfrom controllers.common.schema import register_response_schema_models, register_schema_modelsfrom controllers.inner_api import inner_api_ns-from controllers.inner_api.wraps import inner_api_only+from controllers.inner_api.wraps import plugin_inner_api_onlyfrom core.workflow.nodes.knowledge_retrieval import exc as retrieval_excfrom libs.exception import BaseHTTPExceptionfrom services.entities.knowledge_retrieval_inner import InnerKnowledgeRetrieveRequest, InnerKnowledgeRetrieveResponse@@ -48,7 +49,7 @@ register_response_schema_models(inner_api_ns, InnerKnowledgeRetrieveResponse)class InnerKnowledgeRetrieveApi(Resource):"""Retrieve knowledge from one or more datasets within the caller tenant."""- @inner_api_only+ @plugin_inner_api_only@inner_api_ns.doc("inner_knowledge_retrieve")@inner_api_ns.doc(description="Retrieve knowledge for trusted internal callers")@inner_api_ns.expect(inner_api_ns.models[InnerKnowledgeRetrieveRequest.__name__])@@ -60,9 +61,8 @@ class InnerKnowledgeRetrieveApi(Resource):@inner_api_ns.doc(responses={400: "Invalid request body",- 401: "Unauthorized - invalid inner API key",403: "Caller tenant does not own the requested resource",- 404: "App or dataset not found",+ 404: "Invalid plugin inner API key, app not found, or dataset not found",422: "Invalid retrieval configuration",429: "Knowledge retrieval rate limited",502: "External knowledge retrieval failed",diff --git a/api/controllers/inner_api/plugin/agent_drive.py b/api/controllers/inner_api/plugin/agent_drive.pyindex a80caea3c55..0cdb9dab35f 100644--- a/api/controllers/inner_api/plugin/agent_drive.py+++ b/api/controllers/inner_api/plugin/agent_drive.py@@ -1,10 +1,12 @@-"""Inner API for the agent drive (agent 网盘) control plane — ENG-591.+"""Inner API for the agent drive (agent 网盘) control plane.-Two endpoints, called by the dify-agent server (not the sandbox) with the inner-API key. The drive ref is the URL segment ``agent-<agent_id>``; the path-like-file key travels in the query/body, never as a URL path segment (so its ``/``-characters do not collide with routing). Drive-owned semantics: tenant scoped,-no user-level FileAccessScope.+These endpoints are called by the dify-agent server (not the sandbox) with the+inner API key. The drive ref is the URL segment ``agent-<agent_id>``; the+path-like file key travels in the query/body, never as a URL path segment (so+its ``/`` characters do not collide with routing). Drive-owned semantics:+tenant scoped, no user-level FileAccessScope. Commit still canonicalizes the+trusted execution-context user through the same EndUser lookup as plugin file+upload before validating ToolFile ownership."""from flask import request@@ -13,6 +15,7 @@ from pydantic import BaseModel, ValidationErrorfrom controllers.console.wraps import setup_requiredfrom controllers.inner_api import inner_api_ns+from controllers.inner_api.plugin.wraps import get_userfrom controllers.inner_api.wraps import plugin_inner_api_onlyfrom services.agent_drive_service import (AgentDriveError,@@ -56,6 +59,24 @@ class AgentDriveManifestApi(Resource):return {"items": items}+@inner_api_ns.route("/drive/<string:drive_ref>/skills")+class AgentDriveSkillsApi(Resource):+ @setup_required+ @plugin_inner_api_only+ @inner_api_ns.doc("agent_drive_skills")+ @inner_api_ns.doc(description="List the skill catalog of an agent drive")+ def get(self, drive_ref: str):+ try:+ agent_id = parse_agent_drive_ref(drive_ref)+ tenant_id = (request.args.get("tenant_id") or "").strip()+ if not tenant_id:+ raise AgentDriveError("missing_tenant_id", "tenant_id is required", status_code=400)+ items = AgentDriveService().list_skills(tenant_id=tenant_id, agent_id=agent_id)+ except AgentDriveError as exc:+ return _error_response(exc)+ return {"items": items}++@inner_api_ns.route("/drive/<string:drive_ref>/commit")class AgentDriveCommitApi(Resource):@setup_required@@ -69,9 +90,10 @@ class AgentDriveCommitApi(Resource):body = _CommitRequest.model_validate(request.get_json(silent=True) or {})except ValidationError as exc:raise AgentDriveError("invalid_request", str(exc), status_code=400) from exc+ user = get_user(body.tenant_id, body.user_id)items = AgentDriveService().commit(tenant_id=body.tenant_id,- user_id=body.user_id,+ user_id=user.id,agent_id=agent_id,items=body.items,)diff --git a/api/core/app/apps/agent_app/runtime_request_builder.py b/api/core/app/apps/agent_app/runtime_request_builder.pyindex 01206b12db6..fc1fcb0b168 100644--- a/api/core/app/apps/agent_app/runtime_request_builder.py+++ b/api/core/app/apps/agent_app/runtime_request_builder.py@@ -37,6 +37,7 @@ from core.workflow.nodes.agent_v2.plugin_tools_builder import (from core.workflow.nodes.agent_v2.runtime_request_builder import (append_runtime_warnings,build_ask_human_layer_config,+ build_drive_aware_soul_mention_resolver,build_drive_layer_config,build_knowledge_layer_config,build_shell_layer_config,@@ -123,9 +124,19 @@ class AgentAppRuntimeRequestBuilder:}drive_config = None+ soul_prompt_resolver = build_soul_mention_resolver(agent_soul)if dify_config.AGENT_DRIVE_MANIFEST_ENABLED:- drive_config, drive_warnings = build_drive_layer_config(agent_soul, agent_id=context.agent_id)+ drive_config, drive_warnings = build_drive_layer_config(+ agent_soul,+ tenant_id=context.dify_context.tenant_id,+ agent_id=context.agent_id,+ )append_runtime_warnings(metadata, drive_warnings)+ soul_prompt_resolver = build_drive_aware_soul_mention_resolver(+ agent_soul,+ tenant_id=context.dify_context.tenant_id,+ agent_id=context.agent_id,+ )knowledge_config = build_knowledge_layer_config(agent_soul)request = self._request_builder.build_for_agent_app(@@ -154,9 +165,7 @@ class AgentAppRuntimeRequestBuilder:),# ENG-616: expand slash-menu mention tokens to canonical names so# no frontend-internal {{#…#}} marker ever reaches the model.- agent_soul_prompt=expand_prompt_mentions(- agent_soul.prompt.system_prompt, build_soul_mention_resolver(agent_soul)- ).strip()+ agent_soul_prompt=expand_prompt_mentions(agent_soul.prompt.system_prompt, soul_prompt_resolver).strip()or None,user_prompt=context.user_query,tools=tools_layer,diff --git a/api/core/workflow/nodes/agent_v2/runtime_feature_manifest.py b/api/core/workflow/nodes/agent_v2/runtime_feature_manifest.pyindex 65c5d42e916..fa7b28cbb0a 100644--- a/api/core/workflow/nodes/agent_v2/runtime_feature_manifest.py+++ b/api/core/workflow/nodes/agent_v2/runtime_feature_manifest.py@@ -16,9 +16,6 @@ SUPPORTED_AGENT_BACKEND_FEATURES = frozenset("knowledge","env","sandbox",- # ENG-623: exposed at runtime as the dify.drive declaration layer- # (an index the agent pulls through the back proxy).- "skills_files",# ENG-635: human involvement is exposed at runtime as the dify.ask_human# deferred tool; a call pauses via the existing HITL form mechanism."human",@@ -32,11 +29,7 @@ RESERVED_AGENT_BACKEND_FEATURES = frozenset()-def build_runtime_feature_manifest(- agent_soul: AgentSoulConfig,- *,- drive_manifest_enabled: bool = False,-) -> dict[str, Any]:+def build_runtime_feature_manifest(agent_soul: AgentSoulConfig) -> dict[str, Any]:"""Describe PRD capabilities supported by or still reserved from Agent backend runtime."""warnings: list[dict[str, str]] = []soul_dump = agent_soul.model_dump(mode="json", exclude_none=True, exclude_defaults=True)@@ -54,38 +47,10 @@ def build_runtime_feature_manifest(})- has_skills_files = bool(agent_soul.skills_files.skills or agent_soul.skills_files.files)- if has_skills_files and not drive_manifest_enabled:- warnings.append(- {- "section": "agent_soul.skills_files",- "code": "drive_manifest_disabled",- "message": (- "skills_files is configured but AGENT_DRIVE_MANIFEST_ENABLED is off; "- "the drive declaration layer is not injected into this run."- ),- }- )- for skill in agent_soul.skills_files.skills:- if not skill.skill_md_key:- warnings.append(- {- "section": "agent_soul.skills_files",- "code": "skill_ref_dangling",- "message": (- f"skill_ref_dangling: skill '{skill.name or skill.id or 'unknown'}' has no drive key; "- "re-standardize it to expose it at runtime."- ),- }- )-reserved_status = dict.fromkeys(sorted(RESERVED_AGENT_BACKEND_FEATURES), "reserved_not_executed")reserved_status["knowledge"] = ("supported_by_knowledge_layer" if list_configured_knowledge_dataset_ids(agent_soul) else "not_configured")- reserved_status["skills_files"] = (- "supported_by_drive_manifest" if drive_manifest_enabled else "drive_manifest_disabled"- )reserved_status["tools.dify_tools"] = "supported_when_config_valid"reserved_status["tools.cli_tools"] = "supported_by_shell_bootstrap"reserved_status["env"] = "supported_by_shell_bootstrap"diff --git a/api/core/workflow/nodes/agent_v2/runtime_request_builder.py b/api/core/workflow/nodes/agent_v2/runtime_request_builder.pyindex 8aaa4fcc1d3..e3c2dcee839 100644--- a/api/core/workflow/nodes/agent_v2/runtime_request_builder.py+++ b/api/core/workflow/nodes/agent_v2/runtime_request_builder.py@@ -7,7 +7,6 @@ from typing import Any, Literal, Protocol, assert_never, castfrom agenton.compositor import CompositorSessionSnapshotfrom dify_agent.layers.ask_human import DifyAskHumanLayerConfigfrom dify_agent.layers.drive import (- DifyDriveFileConfig,DifyDriveLayerConfig,DifyDriveSkillConfig,)@@ -55,10 +54,13 @@ from models.agent_config_entities import ()from models.provider_ids import ModelProviderIDfrom services.agent.prompt_mentions import (+ MentionKind,build_node_job_mention_resolver,build_soul_mention_resolver,expand_prompt_mentions,+ parse_prompt_mentions,)+from services.agent_drive_service import AgentDriveService, decode_drive_mention_reffrom .output_failure_orchestrator import retry_idempotency_keyfrom .plugin_tools_builder import WorkflowAgentPluginToolsBuilder, WorkflowAgentPluginToolsBuildError@@ -153,9 +155,6 @@ class WorkflowAgentRuntimeRequestBuilder:expand_prompt_mentions(node_job.workflow_prompt, build_node_job_mention_resolver(node_job)).strip()or "Run this workflow Agent Node for the current run.")- soul_prompt = expand_prompt_mentions(- agent_soul.prompt.system_prompt, build_soul_mention_resolver(agent_soul)- ).strip()user_prompt = workflow_context_prompt.strip() or "Use the current workflow context."credentials = self._credentials_provider.fetch(agent_soul.model.model_provider, agent_soul.model.model)try:@@ -182,9 +181,20 @@ class WorkflowAgentRuntimeRequestBuilder:}drive_config: DifyDriveLayerConfig | None = None+ soul_prompt_resolver = build_soul_mention_resolver(agent_soul)if dify_config.AGENT_DRIVE_MANIFEST_ENABLED:- drive_config, drive_warnings = build_drive_layer_config(agent_soul, agent_id=context.agent.id)+ drive_config, drive_warnings = build_drive_layer_config(+ agent_soul,+ tenant_id=context.dify_context.tenant_id,+ agent_id=context.agent.id,+ )append_runtime_warnings(metadata, drive_warnings)+ soul_prompt_resolver = build_drive_aware_soul_mention_resolver(+ agent_soul,+ tenant_id=context.dify_context.tenant_id,+ agent_id=context.agent.id,+ )+ soul_prompt = expand_prompt_mentions(agent_soul.prompt.system_prompt, soul_prompt_resolver).strip()knowledge_config = build_knowledge_layer_config(agent_soul)request = self._request_builder.build_for_workflow_node(@@ -292,10 +302,7 @@ class WorkflowAgentRuntimeRequestBuilder:"agent_config_snapshot_id": context.snapshot.id,"binding_id": context.binding.id,"workflow_node_job_mode": node_job.mode.value,- "runtime_support": build_runtime_feature_manifest(- agent_soul,- drive_manifest_enabled=dify_config.AGENT_DRIVE_MANIFEST_ENABLED,- ),+ "runtime_support": build_runtime_feature_manifest(agent_soul),}def _build_workflow_context_prompt(@@ -603,76 +610,107 @@ def append_runtime_warnings(metadata: dict[str, Any], warnings: list[dict[str, sexisting.extend(warnings)+def build_drive_aware_soul_mention_resolver(+ agent_soul: AgentSoulConfig,+ *,+ tenant_id: str,+ agent_id: str,+):+ """Resolve skill/file mentions against the agent drive and everything else via Agent Soul."""++ base_resolver = build_soul_mention_resolver(agent_soul)+ drive_service = AgentDriveService()+ skill_catalog = drive_service.list_skills(tenant_id=tenant_id, agent_id=agent_id)+ skill_names_by_key = {skill["skill_md_key"]: skill["name"] for skill in skill_catalog}+ drive_keys = {item["key"] for item in drive_service.manifest(tenant_id=tenant_id, agent_id=agent_id)}++ def _resolve(mention: object) -> str | None:+ if not hasattr(mention, "kind") or not hasattr(mention, "ref_id"):+ return None+ kind = cast(MentionKind, mention.kind)+ ref_id = cast(str, mention.ref_id)+ label = cast(str | None, getattr(mention, "label", None))+ if kind == MentionKind.SKILL:+ decoded_key = decode_drive_mention_ref(ref_id)+ return skill_names_by_key.get(decoded_key) or label or decoded_key+ if kind == MentionKind.FILE:+ decoded_key = decode_drive_mention_ref(ref_id)+ if decoded_key in drive_keys:+ return decoded_key.rsplit("/", 1)[-1]+ return label or decoded_key+ return base_resolver(cast(Any, mention))++ return _resolve++def build_drive_layer_config(agent_soul: AgentSoulConfig,*,+ tenant_id: str,agent_id: str | None,) -> tuple[DifyDriveLayerConfig | None, list[dict[str, str]]]:- """Catalog the soul's drive-backed Skills & Files into the dify.drive declaration.-- Returns ``(config, warnings)`` — ``config is None`` means nothing to inject- (no skills/files configured, or no agent identity to address the drive by).- Refs that predate standardization (no drive key) are skipped with a warning- instead of failing the run, so historic souls keep running.- """- skill_refs = agent_soul.skills_files.skills- file_refs = agent_soul.skills_files.files- if not skill_refs and not file_refs:- return None, []+ """Derive drive runtime catalog + prompt-mentioned eager-pull keys from the drive."""- warnings: list[dict[str, str]] = []+ mentioned_drive_refs = [+ decode_drive_mention_ref(mention.ref_id)+ for mention in parse_prompt_mentions(agent_soul.prompt.system_prompt)+ if mention.kind in {MentionKind.SKILL, MentionKind.FILE}+ ]+ ordered_mentions = list(dict.fromkeys(ref for ref in mentioned_drive_refs if ref))if not agent_id:- warnings.append(+ if not ordered_mentions:+ return None, []+ return None, [{- "section": "agent_soul.skills_files",- "code": "skill_ref_dangling",- "message": "skills_files is configured but the run has no bound agent to address a drive by.",+ "section": "agent_soul.prompt.system_prompt",+ "code": "drive_ref_dangling",+ "message": "drive mentions are configured but the run has no bound agent to address a drive by.",}- )- return None, warnings+ ]- skills: list[DifyDriveSkillConfig] = []- for skill in skill_refs:- if not skill.skill_md_key:- warnings.append(- {- "section": "agent_soul.skills_files",- "code": "skill_ref_dangling",- "message": (- f"skill_ref_dangling: skill '{skill.name or skill.id or 'unknown'}' has no drive key; "- "re-standardize it to expose it at runtime."- ),- }- )+ drive_service = AgentDriveService()+ skills_catalog = drive_service.list_skills(tenant_id=tenant_id, agent_id=agent_id)+ manifest_items = drive_service.manifest(tenant_id=tenant_id, agent_id=agent_id)+ manifest_by_key = {item["key"]: item for item in manifest_items}+ skill_keys = {skill["skill_md_key"] for skill in skills_catalog}+ warnings: list[dict[str, str]] = []+ mentioned_skill_keys: list[str] = []+ mentioned_file_keys: list[str] = []+ for drive_key in ordered_mentions:+ if drive_key in skill_keys:+ mentioned_skill_keys.append(drive_key)continue- skills.append(- DifyDriveSkillConfig(- name=skill.name or skill.skill_md_key.split("/", 1)[0],- description=skill.description or "",- skill_md_key=skill.skill_md_key,- archive_key=skill.full_archive_key,- )+ if drive_key in manifest_by_key:+ mentioned_file_keys.append(drive_key)+ continue+ warnings.append(+ {+ "section": "agent_soul.prompt.system_prompt",+ "code": "mention_target_missing",+ "message": f"drive mention '{drive_key}' has no matching drive entry.",+ })- files: list[DifyDriveFileConfig] = []- for file in file_refs:- if not file.drive_key:- # Plain upload references (pre-ENG-625) are not drive-backed; they are- # simply invisible to the manifest rather than a defect worth warning on.- continue- size = file.get("size")- files.append(- DifyDriveFileConfig(- name=file.name or file.drive_key.rsplit("/", 1)[-1],- key=file.drive_key,- size=size if isinstance(size, int) else None,- mime_type=file.type,- )+ skills = [+ DifyDriveSkillConfig(+ path=skill["path"],+ name=skill["name"],+ description=skill["description"],+ skill_md_key=skill["skill_md_key"],+ archive_key=skill["archive_key"],)+ for skill in skills_catalog+ ]- if not skills and not files:- return None, warnings- return DifyDriveLayerConfig(drive_ref=f"agent-{agent_id}", skills=skills, files=files), warnings+ return (+ DifyDriveLayerConfig(+ drive_ref=f"agent-{agent_id}",+ skills=skills,+ mentioned_skill_keys=mentioned_skill_keys,+ mentioned_file_keys=mentioned_file_keys,+ ),+ warnings,+ )def _cli_tool_enabled(item: object) -> bool:diff --git a/api/core/workflow/nodes/agent_v2/validators.py b/api/core/workflow/nodes/agent_v2/validators.pyindex ca3adb5b0d1..2eabac10dd6 100644--- a/api/core/workflow/nodes/agent_v2/validators.py+++ b/api/core/workflow/nodes/agent_v2/validators.py@@ -35,7 +35,6 @@ class WorkflowAgentNodeValidator:"soul","prompt","system_prompt",- "skills_files","skills","files","tools",diff --git a/api/fields/agent_fields.py b/api/fields/agent_fields.pyindex 07bcbad26e3..e60a6b01426 100644--- a/api/fields/agent_fields.py+++ b/api/fields/agent_fields.py@@ -1,5 +1,5 @@from datetime import datetime-from typing import Annotated, Literal+from typing import Literalfrom pydantic import Field, field_validator@@ -16,10 +16,8 @@ from models.agent import ()from models.agent_config_entities import (AgentCliToolConfig,- AgentFileRefConfig,AgentHumanContactConfig,AgentKnowledgeDatasetConfig,- AgentSkillRefConfig,AgentSoulConfig,DeclaredOutputConfig,DeclaredOutputType,@@ -396,20 +394,6 @@ class AgentComposerDifyToolCandidateResponse(ResponseModel):tools_count: int | None = None-class AgentComposerSkillCandidateResponse(AgentSkillRefConfig):- kind: Literal["skill"] = "skill"---class AgentComposerFileCandidateResponse(AgentFileRefConfig):- kind: Literal["file"] = "file"---AgentComposerSkillFileCandidateResponse = Annotated[- AgentComposerSkillCandidateResponse | AgentComposerFileCandidateResponse,- Field(discriminator="kind"),-]--class AgentComposerNodeJobCandidatesResponse(ResponseModel):previous_node_outputs: list[WorkflowPreviousNodeOutputRef] = Field(default_factory=list)declare_output_types: list[DeclaredOutputType] = Field(default_factory=list)@@ -417,7 +401,6 @@ class AgentComposerNodeJobCandidatesResponse(ResponseModel):class AgentComposerSoulCandidatesResponse(ResponseModel):- skills_files: list[AgentComposerSkillFileCandidateResponse] = Field(default_factory=list)dify_tools: list[AgentComposerDifyToolCandidateResponse] = Field(default_factory=list)cli_tools: list[AgentCliToolConfig] = Field(default_factory=list)knowledge_datasets: list[AgentKnowledgeDatasetConfig] = Field(default_factory=list)diff --git a/api/migrations/versions/2026_06_15_1100-b7c2d9e8a1f4_add_tenant_last_opened_at.py b/api/migrations/versions/2026_06_15_1100-b7c2d9e8a1f4_add_tenant_last_opened_at.pyindex ce2fd2b79ca..066a2ba8ca8 100644--- a/api/migrations/versions/2026_06_15_1100-b7c2d9e8a1f4_add_tenant_last_opened_at.py+++ b/api/migrations/versions/2026_06_15_1100-b7c2d9e8a1f4_add_tenant_last_opened_at.py@@ -7,7 +7,7 @@ Create Date: 2026-06-05 11:00:00.000000"""import sqlalchemy as sa-from alembic import op+from alembic import context, op# revision identifiers, used by Alembic.revision = "b7c2d9e8a1f4"@@ -17,10 +17,23 @@ depends_on = Nonedef upgrade():+ if _has_last_opened_at_column():+ returnwith op.batch_alter_table("tenant_account_joins", schema=None) as batch_op:batch_op.add_column(sa.Column("last_opened_at", sa.DateTime(), nullable=True))def downgrade():+ if not _has_last_opened_at_column():+ returnwith op.batch_alter_table("tenant_account_joins", schema=None) as batch_op:batch_op.drop_column("last_opened_at")+++def _has_last_opened_at_column() -> bool:+ if context.is_offline_mode():+ # Offline SQL generation cannot inspect the target schema. Assume the+ # linear migration path so generated SQL stays explicit.+ return False+ inspector = sa.inspect(op.get_bind())+ return "last_opened_at" in {column["name"] for column in inspector.get_columns("tenant_account_joins")}diff --git a/api/migrations/versions/2026_06_18_2300-b2515f9d4c2a_agent_drive_skill_metadata_refactor.py b/api/migrations/versions/2026_06_18_2300-b2515f9d4c2a_agent_drive_skill_metadata_refactor.pyindex 9dc85d2a89b..3398c2eb018 100644--- a/api/migrations/versions/2026_06_18_2300-b2515f9d4c2a_agent_drive_skill_metadata_refactor.py+++ b/api/migrations/versions/2026_06_18_2300-b2515f9d4c2a_agent_drive_skill_metadata_refactor.py@@ -6,9 +6,15 @@ Create Date: 2026-06-18 23:00:00.000000"""-import sqlalchemy as sa+from __future__ import annotations++import json+from typing import Any+from alembic import op+import sqlalchemy as safrom sqlalchemy.dialects import mysql+from sqlalchemy.engine.mock import MockConnection# revision identifiers, used by Alembic.revision = "b2515f9d4c2a"@@ -31,9 +37,46 @@ def upgrade() -> None:"agent_drive_files",["tenant_id", "agent_id", "is_skill", "key"],)+ _remove_skills_files_from_snapshots()def downgrade() -> None:op.drop_index("agent_drive_files_tenant_agent_is_skill_key_idx", table_name="agent_drive_files")op.drop_column("agent_drive_files", "skill_metadata")op.drop_column("agent_drive_files", "is_skill")+++def _remove_skills_files_from_snapshots() -> None:+ connection = op.get_bind()+ if connection is None or isinstance(connection, MockConnection):+ return+ snapshots = sa.table(+ "agent_config_snapshots",+ sa.column("id", sa.String()),+ sa.column("config_snapshot", sa.Text()),+ )+ rows = connection.execute(sa.select(snapshots.c.id, snapshots.c.config_snapshot)).fetchall()+ for row in rows:+ cleaned = _strip_skills_files(row.config_snapshot)+ if cleaned is None:+ continue+ connection.execute(+ snapshots.update()+ .where(snapshots.c.id == row.id)+ .values(config_snapshot=json.dumps(cleaned, separators=(",", ":"), sort_keys=True))+ )+++def _strip_skills_files(raw_snapshot: Any) -> dict[str, Any] | None:+ if raw_snapshot is None:+ return None+ if isinstance(raw_snapshot, str):+ snapshot = json.loads(raw_snapshot)+ elif isinstance(raw_snapshot, dict):+ snapshot = dict(raw_snapshot)+ else:+ snapshot = dict(raw_snapshot)+ if not isinstance(snapshot, dict) or "skills_files" not in snapshot:+ return None+ snapshot.pop("skills_files", None)+ return snapshotdiff --git a/api/models/agent_config_entities.py b/api/models/agent_config_entities.pyindex 76108f271d4..2503ba66f06 100644--- a/api/models/agent_config_entities.py+++ b/api/models/agent_config_entities.py@@ -361,11 +361,6 @@ class AgentSoulPromptConfig(BaseModel):system_prompt: str = ""-class AgentSoulSkillsFilesConfig(BaseModel):- files: list[AgentFileRefConfig] = Field(default_factory=list)- skills: list[AgentSkillRefConfig] = Field(default_factory=list)--class AgentSoulDifyToolCredentialRef(BaseModel):"""Reference to a stored Dify Plugin Tool credential.@@ -514,7 +509,6 @@ class AgentSoulConfig(BaseModel):schema_version: int = 1prompt: AgentSoulPromptConfig = Field(default_factory=AgentSoulPromptConfig)- skills_files: AgentSoulSkillsFilesConfig = Field(default_factory=AgentSoulSkillsFilesConfig)tools: AgentSoulToolsConfig = Field(default_factory=AgentSoulToolsConfig)knowledge: AgentSoulKnowledgeConfig = Field(default_factory=AgentSoulKnowledgeConfig)human: AgentSoulHumanConfig = Field(default_factory=AgentSoulHumanConfig)diff --git a/api/openapi/markdown/console-openapi.md b/api/openapi/markdown/console-openapi.mdindex 881e83061cc..c600984c089 100644--- a/api/openapi/markdown/console-openapi.md+++ b/api/openapi/markdown/console-openapi.md@@ -1622,7 +1622,7 @@ Inspect one drive-backed skill for slash-menu hover/detail UI| 200 | Drive skill inspect view | **application/json**: [AgentDriveSkillInspectResponse](#agentdriveskillinspectresponse)<br> |### [DELETE] /apps/{app_id}/agent/files-Delete one drive file by key; soul ref first, then the KV row (ENG-625 D5)+Delete one drive file by key via drive commit-null semantics#### Parameters@@ -1708,7 +1708,7 @@ Upload + standardize a Skill into the agent drive| 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)+Delete a standardized skill by removing its known drive keys via commit-null#### Parameters@@ -12417,23 +12417,6 @@ Risk marker for CLI tool bootstrap commands.| provider_id | string | | No || tools_count | integer | | No |-#### AgentComposerFileCandidateResponse--| Name | Type | Description | Required |-| ---- | ---- | ----------- | -------- |-| drive_key | string | | No |-| file_id | string | | No |-| id | string | | No |-| kind | string, <br>**Default:** file | | No |-| name | string | | No |-| reference | string | | No |-| remote_url | string | | No |-| tenant_id | string | | No |-| transfer_method | string | | No |-| type | string | | No |-| upload_file_id | string | | No |-| url | string | | No |-#### AgentComposerImpactBindingResponse| Name | Type | Description | Required |@@ -12458,22 +12441,6 @@ Risk marker for CLI tool bootstrap commands.| human_contacts | [ [AgentHumanContactConfig](#agenthumancontactconfig) ] | | No || previous_node_outputs | [ [WorkflowPreviousNodeOutputRef](#workflowpreviousnodeoutputref) ] | | No |-#### AgentComposerSkillCandidateResponse--| Name | Type | Description | Required |-| ---- | ---- | ----------- | -------- |-| description | string | | No |-| file_id | string | | No |-| full_archive_file_id | string | | No |-| full_archive_key | string | | No |-| id | string | | No |-| kind | string, <br>**Default:** skill | | No |-| manifest_files | [ string ] | | No |-| name | string | | No |-| path | string | | No |-| skill_md_file_id | string | | No |-| skill_md_key | string | | No |-#### AgentComposerSoulCandidatesResponse| Name | Type | Description | Required |@@ -12482,7 +12449,6 @@ Risk marker for CLI tool bootstrap commands.| dify_tools | [ [AgentComposerDifyToolCandidateResponse](#agentcomposerdifytoolcandidateresponse) ] | | No || human_contacts | [ [AgentHumanContactConfig](#agenthumancontactconfig) ] | | No || knowledge_datasets | [ [AgentKnowledgeDatasetConfig](#agentknowledgedatasetconfig) ] | | No |-| skills_files | [ ] | | No |#### AgentComposerSoulLockResponse@@ -12603,7 +12569,6 @@ Audit operation recorded for Agent Soul version/revision changes.| Name | Type | Description | Required || ---- | ---- | ----------- | -------- |-| config_version_id | string | | No || removed_keys | [ string ] | | No || result | string | | Yes |@@ -12617,7 +12582,6 @@ Audit operation recorded for Agent Soul version/revision changes.| Name | Type | Description | Required || ---- | ---- | ----------- | -------- |-| config_version_id | string | | No || file | [AgentDriveFileResponse](#agentdrivefileresponse) | | Yes |#### AgentDriveFilePayload@@ -13203,27 +13167,12 @@ Visibility and lifecycle scope of an Agent record.| enabled | boolean | | No || type | string | | No |-#### AgentSkillRefConfig--| Name | Type | Description | Required |-| ---- | ---- | ----------- | -------- |-| description | string | | No |-| file_id | string | | No |-| full_archive_file_id | string | | No |-| full_archive_key | string | | No |-| id | string | | No |-| manifest_files | [ string ] | | No |-| name | string | | No |-| path | string | | No |-| skill_md_file_id | string | | No |-| skill_md_key | string | | No |-#### AgentSkillUploadResponse| Name | Type | Description | Required || ---- | ---- | ----------- | -------- || manifest | [SkillManifest](#skillmanifest) | | Yes |-| skill | [AgentSkillRefConfig](#agentskillrefconfig) | | Yes |+| skill | [AgentUploadedSkillResponse](#agentuploadedskillresponse) | | Yes |#### AgentSoulAppFeaturesConfig@@ -13252,7 +13201,6 @@ Visibility and lifecycle scope of an Agent record.| prompt | [AgentSoulPromptConfig](#agentsoulpromptconfig) | | No || sandbox | [AgentSoulSandboxConfig](#agentsoulsandboxconfig) | | No || schema_version | integer, <br>**Default:** 1 | | No |-| skills_files | [AgentSoulSkillsFilesConfig](#agentsoulskillsfilesconfig) | | No || tools | [AgentSoulToolsConfig](#agentsoultoolsconfig) | | No |#### AgentSoulDifyToolConfig@@ -13369,13 +13317,6 @@ Reference to model credentials resolved only at runtime.| config | [AgentSandboxProviderConfig](#agentsandboxproviderconfig) | | No || provider | string | | No |-#### AgentSoulSkillsFilesConfig--| Name | Type | Description | Required |-| ---- | ---- | ----------- | -------- |-| files | [ [AgentFileRefConfig](#agentfilerefconfig) ] | | No |-| skills | [ [AgentSkillRefConfig](#agentskillrefconfig) ] | | No |-#### AgentSoulToolsConfig| Name | Type | Description | Required |@@ -13507,6 +13448,16 @@ Soft lifecycle state for Agent records.| tool_output | object | | Yes || tool_parameters | object | | Yes |+#### AgentUploadedSkillResponse++| Name | Type | Description | Required |+| ---- | ---- | ----------- | -------- |+| archive_key | string | | No |+| description | string | | Yes |+| name | string | | Yes |+| path | string | | Yes |+| skill_md_key | string | | Yes |+#### AgentUserSatisfactionRateStatisticResponse| Name | Type | Description | Required |diff --git a/api/services/agent/composer_candidates.py b/api/services/agent/composer_candidates.pyindex 0a1419be399..7868f2a2f63 100644--- a/api/services/agent/composer_candidates.py+++ b/api/services/agent/composer_candidates.py@@ -137,9 +137,6 @@ def soul_candidates(soul = agent_soul or AgentSoulConfig()truncated = False- skills_files = [{"kind": "skill", **skill.model_dump(exclude_none=True)} for skill in soul.skills_files.skills]- skills_files += [{"kind": "file", **file.model_dump(exclude_none=True)} for file in soul.skills_files.files]-cli_tools = [tool.model_dump(exclude_none=True) for tool in soul.tools.cli_tools if tool.enabled]dataset_ids = [dataset.id for dataset in soul.knowledge.datasets if dataset.id]@@ -162,7 +159,6 @@ def soul_candidates(dify_tools = workspace_tools_loader()lists = {- "skills_files": skills_files,"dify_tools": dify_tools,"cli_tools": cli_tools,"knowledge_datasets": knowledge_datasets,diff --git a/api/services/agent/composer_service.py b/api/services/agent/composer_service.pyindex af6be0abfa6..815fdcc4420 100644--- a/api/services/agent/composer_service.py+++ b/api/services/agent/composer_service.py@@ -21,7 +21,6 @@ from models.agent import (WorkflowAgentNodeBinding,)from models.agent_config_entities import (- AgentFileRefConfig,DeclaredOutputConfig,)from models.agent_config_entities import (@@ -34,7 +33,6 @@ from services.agent.errors import (AgentNameConflictError,AgentNotFoundError,AgentVersionNotFoundError,- InvalidComposerConfigError,)from services.entities.agent_entities import (AgentSoulConfig,@@ -106,29 +104,6 @@ class AgentComposerService:workflow = cls._get_draft_workflow(tenant_id=tenant_id, app_id=app_id)binding = cls._get_workflow_binding(tenant_id=tenant_id, workflow_id=workflow.id, node_id=node_id)- # ENG-623 §4.4: drive-backed refs must point at real drive rows before the- # soul is persisted. Only strategies that write the soul onto an *existing*- # agent are checked — new-agent strategies create a fresh (empty) drive, so- # any carried drive key would be flagged on the next save instead.- if (- payload.agent_soul is not None- and binding is not None- and binding.agent_id- and payload.save_strategy- in (- ComposerSaveStrategy.NODE_JOB_ONLY,- ComposerSaveStrategy.SAVE_TO_CURRENT_VERSION,- ComposerSaveStrategy.SAVE_AS_NEW_VERSION,- )- and (- payload.save_strategy != ComposerSaveStrategy.NODE_JOB_ONLY- or binding.binding_type == WorkflowAgentBindingType.INLINE_AGENT- )- ):- cls._require_drive_refs_resolved(- tenant_id=tenant_id, agent_id=binding.agent_id, agent_soul=payload.agent_soul- )-match payload.save_strategy:case ComposerSaveStrategy.NODE_JOB_ONLY:binding = cls._save_node_job_only(@@ -176,7 +151,11 @@ class AgentComposerService:version_id=version_id,)state = cls._serialize_workflow_state(binding=binding, agent=agent, version=version)- state["validation"] = cls.collect_validation_findings(tenant_id=tenant_id, payload=payload)+ state["validation"] = cls.collect_validation_findings(+ tenant_id=tenant_id,+ payload=payload,+ agent_id=binding.agent_id,+ )return state@classmethod@@ -250,9 +229,6 @@ class AgentComposerService:db.session.rollback()raise AgentNameConflictError() from exc- # ENG-623 §4.4: dangling drive-backed refs are rejected before persisting.- cls._require_drive_refs_resolved(tenant_id=tenant_id, agent_id=agent.id, agent_soul=payload.agent_soul)-if payload.save_strategy == ComposerSaveStrategy.SAVE_AS_NEW_VERSION or not agent.active_config_snapshot_id:version = cls._create_config_version(tenant_id=tenant_id,@@ -281,7 +257,11 @@ class AgentComposerService:db.session.commit()state = cls.load_agent_app_composer(tenant_id=tenant_id, app_id=app_id)- state["validation"] = cls.collect_validation_findings(tenant_id=tenant_id, payload=payload)+ state["validation"] = cls.collect_validation_findings(+ tenant_id=tenant_id,+ payload=payload,+ agent_id=agent.id,+ )return state@classmethod@@ -292,11 +272,7 @@ class AgentComposerService:payload: ComposerSavePayload,agent_id: str | None = None,) -> dict[str, Any]:- """ENG-617 soft findings, with DB-backed dataset existence for placeholders.-- With ``agent_id`` the drive-backed skill/file refs are also checked against- the agent drive (ENG-623 §4.4) and dangling ones surface as warnings.- """+ """ENG-617 soft findings, with DB-backed dataset and drive mention checks."""from services.agent.prompt_mentions import MentionKind, parse_prompt_mentionsmentioned_ids: set[str] = set()@@ -312,136 +288,14 @@ class AgentComposerService:findings = ComposerConfigValidator.collect_soft_findings(payload, existing_dataset_ids=existing_dataset_ids)if agent_id and payload.agent_soul is not None:findings["warnings"].extend(- cls._drive_ref_findings(tenant_id=tenant_id, agent_id=agent_id, agent_soul=payload.agent_soul)+ cls._drive_mention_findings(+ tenant_id=tenant_id,+ agent_id=agent_id,+ prompt=payload.agent_soul.prompt.system_prompt,+ ))return findings- @classmethod- def remove_drive_refs(- cls,- *,- tenant_id: str,- agent_id: str,- account_id: str,- skill_slug: str | None = None,- file_key: str | None = None,- app_id: str | None = None,- node_id: str | None = None,- ) -> str | None:- """Drop the soul refs backed by a drive skill/file before the drive rows go.-- Soul-first ordering (ENG-625 D5): a mid-failure leaves harmless orphan KV- rows that an idempotent DELETE retry cleans, instead of a soul ref that- keeps failing dangling-ref validation. Returns the new config version id,- or ``None`` when the soul held no matching ref (idempotent re-delete).- """- if (skill_slug is None) == (file_key is None):- raise ValueError("remove_drive_refs requires exactly one of skill_slug or file_key")- agent = db.session.scalar(select(Agent).where(Agent.tenant_id == tenant_id, Agent.id == agent_id).limit(1))- if agent is None or not agent.active_config_snapshot_id:- return None- current_snapshot = cls._require_version(- tenant_id=tenant_id, agent_id=agent.id, version_id=agent.active_config_snapshot_id- )- agent_soul = AgentSoulConfig.model_validate(current_snapshot.config_snapshot_dict)-- removed_display: str | None = None- if skill_slug is not None:- kept_skills = []- for skill in agent_soul.skills_files.skills:- slug = (skill.skill_md_key or "").split("/", 1)[0] or (skill.path or "").strip("/")- if slug == skill_slug:- removed_display = skill.name or skill.id or skill_slug- continue- kept_skills.append(skill)- if removed_display is None:- return None- agent_soul.skills_files.skills = kept_skills- note = f"Removed skill '{removed_display}' from the drive."- else:- kept_files = []- for file in agent_soul.skills_files.files:- if file.drive_key == file_key:- removed_display = file.name or file.drive_key- continue- kept_files.append(file)- if removed_display is None:- return None- agent_soul.skills_files.files = kept_files- note = f"Removed file '{removed_display}' from the drive."-- version = cls._update_current_version(- current_snapshot=current_snapshot,- account_id=account_id,- agent_soul=agent_soul,- operation=AgentConfigRevisionOperation.SAVE_CURRENT_VERSION,- version_note=note,- )- agent.active_config_snapshot_id = version.id- agent.updated_by = account_id- cls._sync_draft_binding_snapshot(- tenant_id=tenant_id,- app_id=app_id,- node_id=node_id,- agent_id=agent_id,- snapshot_id=version.id,- account_id=account_id,- )- db.session.commit()- return version.id-- @classmethod- def add_drive_file_ref(- cls,- *,- tenant_id: str,- agent_id: str,- account_id: str,- file_ref: AgentFileRefConfig,- app_id: str | None = None,- node_id: str | None = None,- ) -> str | None:- """Add or replace one drive-backed file ref in the active Agent Soul.-- ``POST /agent/files`` is an ADD FILE user action, not just a low-level- drive commit. The committed file must be present in ``skills_files.files``- because runtime ``dify.drive`` is built from the active Agent Soul.- """- if not file_ref.drive_key:- raise ValueError("file_ref.drive_key is required")- agent = db.session.scalar(select(Agent).where(Agent.tenant_id == tenant_id, Agent.id == agent_id).limit(1))- if agent is None or not agent.active_config_snapshot_id:- return None- current_snapshot = cls._require_version(- tenant_id=tenant_id, agent_id=agent.id, version_id=agent.active_config_snapshot_id- )- agent_soul = AgentSoulConfig.model_validate(current_snapshot.config_snapshot_dict)- kept_files = [item for item in agent_soul.skills_files.files if item.drive_key != file_ref.drive_key]- kept_files.append(file_ref)- agent_soul.skills_files.files = kept_files-- display = file_ref.name or file_ref.drive_key- version = cls._update_current_version(- current_snapshot=current_snapshot,- account_id=account_id,- agent_soul=agent_soul,- operation=AgentConfigRevisionOperation.SAVE_CURRENT_VERSION,- version_note=f"Added file '{display}' to the drive.",- )- agent.active_config_snapshot_id = version.id- agent.active_config_has_model = agent_soul_has_model(agent_soul)- agent.updated_by = account_id- cls._sync_draft_binding_snapshot(- tenant_id=tenant_id,- app_id=app_id,- node_id=node_id,- agent_id=agent_id,- snapshot_id=version.id,- account_id=account_id,- )- db.session.commit()- return version.id-@classmethoddef resolve_bound_agent_id(cls, *, tenant_id: str, app_id: str) -> str | None:"""The Agent App's bound roster agent id, if any (validate-endpoint context)."""@@ -468,49 +322,25 @@ class AgentComposerService:return binding.agent_id if binding else None@classmethod- def _sync_draft_binding_snapshot(+ def _drive_mention_findings(cls,*,tenant_id: str,- app_id: str | None,- node_id: str | None,agent_id: str,- snapshot_id: str,- account_id: str,- ) -> None:- """Keep workflow node bindings on the new active snapshot after direct drive edits."""- if not app_id or not node_id:- return- try:- workflow = cls._get_draft_workflow(tenant_id=tenant_id, app_id=app_id)- except ValueError:- return- binding = cls._get_workflow_binding(tenant_id=tenant_id, workflow_id=workflow.id, node_id=node_id)- if binding is None or binding.agent_id != agent_id:- return- binding.current_snapshot_id = snapshot_id- binding.updated_by = account_id-- @classmethod- def _drive_ref_findings(- cls,- *,- tenant_id: str,- agent_id: str,- agent_soul: AgentSoulConfig,+ prompt: str,) -> list[dict[str, str | None]]:- """Drive-backed refs whose keys have no row in the agent drive (ENG-623 §4.4).+ """Soft warnings for missing drive-backed prompt mentions."""+ from services.agent.prompt_mentions import MentionKind, parse_prompt_mentions+ from services.agent_drive_service import decode_drive_mention_ref- Each finding message starts with its stable code token- (``skill_ref_dangling`` / ``file_ref_dangling``) in the ENG-616/617 style.- """wanted_keys: dict[str, tuple[str, str]] = {}- for skill in agent_soul.skills_files.skills:- if skill.skill_md_key:- wanted_keys[skill.skill_md_key] = ("skill_ref_dangling", skill.name or skill.id or "unknown")- for file in agent_soul.skills_files.files:- if file.drive_key:- wanted_keys[file.drive_key] = ("file_ref_dangling", file.name or file.id or "unknown")+ for mention in parse_prompt_mentions(prompt):+ if mention.kind not in {MentionKind.SKILL, MentionKind.FILE}:+ continue+ decoded_key = decode_drive_mention_ref(mention.ref_id)+ if not decoded_key:+ continue+ wanted_keys[decoded_key] = (mention.kind.value, mention.label or decoded_key)if not wanted_keys:return []@@ -524,28 +354,20 @@ class AgentComposerService:))findings: list[dict[str, str | None]] = []- for key, (code, display) in wanted_keys.items():+ for key, (kind, display) in wanted_keys.items():if key in existing_keys:continue- kind = "skill" if code == "skill_ref_dangling" else "file"findings.append({- "code": code,+ "code": "mention_target_missing","surface": "agent_soul","kind": kind,"id": key,- "message": f"{code}: {kind} '{display}' has no drive entry for key '{key}'.",+ "message": f"{kind} '{display}' has no drive entry for key '{key}'.",})return findings- @classmethod- def _require_drive_refs_resolved(cls, *, tenant_id: str, agent_id: str, agent_soul: AgentSoulConfig) -> None:- """Hard save-time guard: dangling drive-backed refs are rejected (400)."""- findings = cls._drive_ref_findings(tenant_id=tenant_id, agent_id=agent_id, agent_soul=agent_soul)- if findings:- raise InvalidComposerConfigError("; ".join(str(finding["message"]) for finding in findings))-@classmethoddef get_workflow_candidates(cls, *, tenant_id: str, app_id: str, node_id: str, user_id: str) -> dict[str, Any]:"""Slash-menu data source for the workflow Agent node composer (ENG-615)."""diff --git a/api/services/agent/composer_validator.py b/api/services/agent/composer_validator.pyindex b9519272c4a..a1d5ce07655 100644--- a/api/services/agent/composer_validator.py+++ b/api/services/agent/composer_validator.py@@ -191,6 +191,8 @@ class ComposerConfigValidator:})continue+ if mention.kind in {MentionKind.SKILL, MentionKind.FILE}:+ continueif resolved is None:warnings.append({diff --git a/api/services/agent/prompt_mentions.py b/api/services/agent/prompt_mentions.pyindex 921d6838b26..27bed49c53b 100644--- a/api/services/agent/prompt_mentions.py+++ b/api/services/agent/prompt_mentions.py@@ -4,13 +4,14 @@ Slash-menu insertions are stored inline in the plain-string prompt as tokens:[§<kind>:<id>[:<label>]§]-``kind`` is a fixed lowercase word; ``id`` points at an item in the Agent config-lists (mentions are pointers — the entity itself lives in ``skills_files`` /-``tools`` / ``knowledge.datasets`` / ``human.contacts`` /-``previous_node_output_refs`` / ``declared_outputs``); ``label`` is an optional-plain-text fallback only (the backend always re-resolves by id, so renames never-break references). A single ``:`` separates all three fields; ``label`` is the-trailing remainder and may itself contain ``:``.+``kind`` is a fixed lowercase word; ``id`` points at an item in the Agent+runtime context. For prompt-owned entities that means Agent Soul lists such as+``tools`` / ``knowledge.datasets`` / ``human.contacts`` and workflow job lists+such as ``previous_node_output_refs`` / ``declared_outputs``. For drive-backed+``skill`` / ``file`` mentions the field stores a URL-encoded drive key and is+resolved against ``agent_drive_files`` at runtime. ``label`` is an optional+plain-text fallback only. A single ``:`` separates all three fields; ``label``+is the trailing remainder and may itself contain ``:``.The ``[§…§]`` wrapper uses the section sign ``§`` (U+00A7), which never appearsin Dify template syntax (``{{var}}`` / ``{{#a.b#}}``) nor in normal prompt text,@@ -55,7 +56,11 @@ MENTION_PATTERN = re.compile(_RESIDUAL_MENTION_PATTERN = re.compile(r"\[§([A-Za-z_][A-Za-z0-9_]*:[^§]*?)§\]")MAX_MENTIONS_PER_PROMPT = 200-MAX_MENTION_FIELD_LENGTH = 255+# Drive keys are validated up to 512 Unicode code points before URL encoding.+# Worst case, one code point becomes 4 UTF-8 bytes and each byte becomes a+# 3-character ``%XX`` escape, so a valid encoded drive key can reach 6144 chars.+MAX_MENTION_REF_ID_LENGTH = 6144+MAX_MENTION_LABEL_LENGTH = 255# Reserved ``tool`` mention id suffix: ``<provider>/*`` means "every tool of this# provider" (a provider hosts many tools, like an MCP server). Single tools use@@ -102,7 +107,7 @@ def parse_prompt_mentions(prompt: str) -> list[PromptMention]:for match in MENTION_PATTERN.finditer(prompt or ""):ref_id = match.group(2)label = match.group(3)- if len(ref_id) > MAX_MENTION_FIELD_LENGTH or (label is not None and len(label) > MAX_MENTION_FIELD_LENGTH):+ if len(ref_id) > MAX_MENTION_REF_ID_LENGTH or (label is not None and len(label) > MAX_MENTION_LABEL_LENGTH):continuementions.append(PromptMention(@@ -127,8 +132,8 @@ def expand_prompt_mentions(prompt: str, resolver: MentionResolver) -> str:def _replace(match: re.Match[str]) -> str:ref_id = match.group(2)label = match.group(3) or None- fallback = (label or ref_id)[:MAX_MENTION_FIELD_LENGTH]- if len(ref_id) > MAX_MENTION_FIELD_LENGTH or (label is not None and len(label) > MAX_MENTION_FIELD_LENGTH):+ fallback = (label or ref_id)[:MAX_MENTION_LABEL_LENGTH]+ if len(ref_id) > MAX_MENTION_REF_ID_LENGTH or (label is not None and len(label) > MAX_MENTION_LABEL_LENGTH):return fallbackmention = PromptMention(kind=MentionKind(match.group(1)),@@ -141,7 +146,7 @@ def expand_prompt_mentions(prompt: str, resolver: MentionResolver) -> str:resolved = resolver(mention)if resolved is None or not resolved.strip():return fallback- return resolved[:MAX_MENTION_FIELD_LENGTH]+ return resolved[:MAX_MENTION_LABEL_LENGTH]return scrub_mention_markers(MENTION_PATTERN.sub(_replace, prompt))@@ -163,27 +168,19 @@ def scrub_mention_markers(text: str) -> str:# inner is ``kind:id[:label]``; prefer the label, else the id.parts = match.group(1).split(":", 2)if len(parts) >= 3 and parts[2].strip():- return parts[2].strip()[:MAX_MENTION_FIELD_LENGTH]+ return parts[2].strip()[:MAX_MENTION_LABEL_LENGTH]if len(parts) >= 2 and parts[1].strip():- return parts[1].strip()[:MAX_MENTION_FIELD_LENGTH]- return match.group(1)[:MAX_MENTION_FIELD_LENGTH]+ return parts[1].strip()[:MAX_MENTION_LABEL_LENGTH]+ return match.group(1)[:MAX_MENTION_LABEL_LENGTH]return _RESIDUAL_MENTION_PATTERN.sub(_degrade, text)def build_soul_mention_resolver(agent_soul: AgentSoulConfig) -> MentionResolver:- """Resolve soul-surface mentions to canonical display names from the soul config."""+ """Resolve non-drive soul-surface mentions to canonical display names."""def _resolve(mention: PromptMention) -> str | None:match mention.kind:- case MentionKind.SKILL:- for skill in agent_soul.skills_files.skills:- if mention.ref_id in (skill.id, skill.name):- return skill.name or skill.id- case MentionKind.FILE:- for file in agent_soul.skills_files.files:- if mention.ref_id in (file.id, file.name):- return file.name or file.idcase MentionKind.TOOL:for tool in agent_soul.tools.dify_tools:prefixes = {prefix for prefix in (tool.provider, tool.provider_id, tool.plugin_id) if prefix}@@ -273,7 +270,8 @@ def _selector_from_ref(ref: WorkflowPreviousNodeOutputRef) -> tuple[str, str] |__all__ = ["ALL_PROVIDER_TOOLS_SUFFIX","MAX_MENTIONS_PER_PROMPT",- "MAX_MENTION_FIELD_LENGTH",+ "MAX_MENTION_LABEL_LENGTH",+ "MAX_MENTION_REF_ID_LENGTH","MENTION_PATTERN","NODE_JOB_PROMPT_ALLOWED_KINDS","SOUL_PROMPT_ALLOWED_KINDS",diff --git a/api/services/agent/skill_package_service.py b/api/services/agent/skill_package_service.pyindex 6452329904d..c4c25d48143 100644--- a/api/services/agent/skill_package_service.py+++ b/api/services/agent/skill_package_service.py@@ -4,11 +4,12 @@ A Skill is a ``.zip`` / ``.skill`` archive that must contain a ``SKILL.md`` entrfile (Anthropic Skills convention: YAML frontmatter with ``name`` + ``description``,followed by markdown instructions). This service validates the archive (extension,size, zip integrity, zip-slip safety, SKILL.md presence/encoding/fields) and-extracts a manifest the API can bind to an Agent config version's skill list.+extracts a manifest consumed by drive standardization.It does NOT execute or load the skill — the agent backend owns execution. It also-does not (here) standardize the package into the agent drive; that is ENG-594 (S6),-which consumes the manifest produced here.+does not persist anything into Agent Soul or bind anything to config versions;+``SkillStandardizeService`` consumes the manifest and commits the canonical drive+rows instead."""from __future__ import annotations@@ -22,8 +23,6 @@ import zipfileimport yamlfrom pydantic import BaseModel-from models.agent_config_entities import AgentSkillRefConfig-# Bounds — generous but finite so a hostile upload can't exhaust memory/disk._MAX_ARCHIVE_BYTES = 50 * 1024 * 1024_MAX_UNCOMPRESSED_BYTES = 200 * 1024 * 1024@@ -58,22 +57,6 @@ class SkillManifest(BaseModel):size: int # total uncompressed byteshash: str # sha256 of the archive bytes- def to_skill_ref(self, *, file_id: str, path: str | None = None) -> AgentSkillRefConfig:- """Build a config skill ref. ``path`` is the stable drive path (set by S6)."""- return AgentSkillRefConfig.model_validate(- {- "id": self.hash,- "name": self.name,- "description": self.description,- "file_id": file_id,- "path": path,- "size": self.size,- "hash": self.hash,- "entry_path": self.entry_path,- "manifest_files": self.files,- }- )-class SkillPackageService:"""Validate Skill archives and extract their manifest."""diff --git a/api/services/agent/skill_standardize_service.py b/api/services/agent/skill_standardize_service.pyindex f8e2c8c4633..7e64d6f0422 100644--- a/api/services/agent/skill_standardize_service.py+++ b/api/services/agent/skill_standardize_service.py@@ -9,10 +9,11 @@ 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 returned-skill ref records the stable drive paths + file ids (not just the raw upload id),-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.+payload is the slim drive-derived skill DTO the UI needs to work with the drive+catalog — ``name``, ``description``, ``path``, ``skill_md_key``, and+``archive_key`` — plus the extracted manifest for upload feedback. The console+``/skills/upload`` endpoints delegate to this service so "upload" now always means+drive-backed skill normalization rather than Agent Soul binding."""from __future__ import annotations@@ -23,7 +24,6 @@ import refrom typing import Anyfrom core.tools.tool_file_manager import ToolFileManager-from models.agent_config_entities import AgentSkillRefConfigfrom services.agent.skill_package_service import SkillPackageServicefrom services.agent_drive_service import AgentDriveService, DriveCommitItem, DriveFileRef, DriveSkillMetadata@@ -134,26 +134,20 @@ class SkillStandardizeService:],)- skill_ref = AgentSkillRefConfig.model_validate(- {- "id": manifest.hash,- "name": manifest.name,- "description": manifest.description,- "file_id": archive_tool_file.id,- "path": slug,- "size": manifest.size,- "hash": manifest.hash,- "entry_path": skill_md_key,- "skill_md_file_id": md_tool_file.id,- "skill_md_key": skill_md_key,- "full_archive_file_id": archive_tool_file.id,- "full_archive_key": archive_key,- # ENG-371: zip member listing — strong signals (scripts/*.sh) for infer-tools.- "manifest_files": manifest.files,- }+ drive_skill = next(+ skill+ for skill in self._drive.list_skills(tenant_id=tenant_id, agent_id=agent_id)+ if skill["skill_md_key"] == skill_md_key)+return {- "skill": skill_ref.model_dump(exclude_none=True),+ "skill": {+ "name": drive_skill["name"],+ "description": drive_skill["description"],+ "path": drive_skill["path"],+ "skill_md_key": drive_skill["skill_md_key"],+ "archive_key": drive_skill["archive_key"],+ },"manifest": manifest.model_dump(),}diff --git a/api/services/agent/skill_tool_inference_service.py b/api/services/agent/skill_tool_inference_service.pyindex 343ab370f81..a6d5e6b2de9 100644--- a/api/services/agent/skill_tool_inference_service.py+++ b/api/services/agent/skill_tool_inference_service.py@@ -19,15 +19,11 @@ from typing import Anyimport json_repairfrom pydantic import BaseModel, Field, ValidationError-from sqlalchemy import selectfrom core.errors.error import ProviderTokenNotInitErrorfrom core.model_manager import ModelManager-from extensions.ext_database import dbfrom graphon.model_runtime.entities.message_entities import SystemPromptMessage, UserPromptMessagefrom graphon.model_runtime.entities.model_entities import ModelType-from models.agent import Agent-from models.agent_config_entities import AgentSoulConfigfrom services.agent_drive_service import AgentDriveError, AgentDriveServicelogger = logging.getLogger(__name__)@@ -97,12 +93,8 @@ class SkillToolInferenceService:def infer(self, *, tenant_id: str, agent_id: str, slug: str) -> dict[str, Any]:skill_md = self._load_skill_md(tenant_id=tenant_id, agent_id=agent_id, slug=slug)- manifest_files = self._manifest_files_from_soul(tenant_id=tenant_id, agent_id=agent_id, slug=slug)user_prompt = f"SKILL.md of skill '{slug}':\n\n{skill_md}"- if manifest_files:- listing = "\n".join(manifest_files[:200])- user_prompt += f"\n\nFiles inside the skill package:\n{listing}"raw = self._invoke(tenant_id=tenant_id, user_prompt=user_prompt)try:@@ -138,37 +130,6 @@ class SkillToolInferenceService:)return str(preview["text"])- @staticmethod- def _manifest_files_from_soul(*, tenant_id: str, agent_id: str, slug: str) -> list[str]:- """The zip path listing standardize persisted onto the ref, if present.-- Degrades to an empty list (SKILL.md-only inference) for refs that- predate ``manifest_files``.- """- agent = db.session.scalar(select(Agent).where(Agent.tenant_id == tenant_id, Agent.id == agent_id).limit(1))- if agent is None or not agent.active_config_snapshot_id:- return []- from models.agent import AgentConfigSnapshot-- snapshot = db.session.scalar(- select(AgentConfigSnapshot).where(- AgentConfigSnapshot.tenant_id == tenant_id,- AgentConfigSnapshot.agent_id == agent_id,- AgentConfigSnapshot.id == agent.active_config_snapshot_id,- )- )- if snapshot is None:- return []- soul = AgentSoulConfig.model_validate(snapshot.config_snapshot_dict)- for skill in soul.skills_files.skills:- ref_slug = (skill.skill_md_key or "").split("/", 1)[0] or (skill.path or "").strip("/")- if ref_slug != slug:- continue- files = skill.get("manifest_files")- if isinstance(files, list):- return [str(item) for item in files]- return []-@staticmethoddef _invoke(*, tenant_id: str, user_prompt: str) -> str:try:diff --git a/api/services/agent_drive_service.py b/api/services/agent_drive_service.pyindex 62b6056412e..c20b3f570a3 100644--- a/api/services/agent_drive_service.py+++ b/api/services/agent_drive_service.py@@ -1,4 +1,4 @@-"""Agent 网盘 (agent drive) service — list/manifest + commit with lifecycle (ENG-591).+"""Agent 网盘 (agent drive) service — manifest/catalog + commit lifecycle.The agent drive is a per-agent path-like KV index over existing UploadFile /ToolFile records (see ``AgentDriveFile``). This service is the control plane:@@ -8,11 +8,13 @@ ToolFile records (see ``AgentDriveFile``). This service is the control plane:``FileAccessScope`` (Agent Files §3.1.2). We reuse the standard``file_factory.build_from_mapping`` + ``resolve_file_url`` rebuild, which alwaysfilters by ``tenant_id`` in the builders, so omitting the scope is safe.-* ``commit`` binds a batch of existing file refs to keys. Source ToolFiles must+* ``commit`` is the single mutation entry point for writes and removals.+ ``file_ref=None`` removes an exact key idempotently; otherwise the service+ binds the referenced UploadFile/ToolFile to the key. Source ToolFiles mustbelong to the current run user. Overwriting a key whose previous value is``value_owned_by_drive`` physically cleans the old value (storage + record),unless another drive entry still references it. Re-committing the same- ``key -> file_ref`` is idempotent.+ ``key -> file_ref`` is idempotent and still refreshes skill metadata."""from __future__ import annotations@@ -30,7 +32,6 @@ from sqlalchemy.exc import DataError, SQLAlchemyErrorfrom sqlalchemy.orm import Sessionfrom core.app.file_access.controller import DatabaseFileAccessController-from core.app.workflow.file_runtime import DifyWorkflowFileRuntimefrom core.db.session_factory import session_factoryfrom extensions.ext_storage import storagefrom factories import file_factory@@ -93,7 +94,7 @@ class DriveCommitItem(BaseModel):model_config = ConfigDict(extra="forbid")key: str- file_ref: DriveFileRef+ file_ref: DriveFileRef | None = None# Drive-owned values may be physically cleaned on overwrite/removal; refs to# files shared with other business records should set this False.value_owned_by_drive: bool = True@@ -385,6 +386,15 @@ class AgentDriveService:pending_storage_deletes: list[str],) -> dict[str, Any]:key = normalize_drive_key(item.key)+ if item.file_ref is None:+ return self._remove_one(+ session,+ tenant_id=tenant_id,+ agent_id=agent_id,+ key=key,+ pending_storage_deletes=pending_storage_deletes,+ )+skill_metadata = self._validate_skill_commit_fields(key=key, item=item)file_kind = AgentDriveFileKind(item.file_ref.kind)file_id = item.file_ref.id@@ -447,6 +457,45 @@ class AgentDriveService:session.add(row)return self._row_dict(row)+ def _remove_one(+ self,+ session: Session,+ *,+ tenant_id: str,+ agent_id: str,+ key: str,+ pending_storage_deletes: list[str],+ ) -> dict[str, Any]:+ existing = session.scalar(+ select(AgentDriveFile).where(+ AgentDriveFile.tenant_id == tenant_id,+ AgentDriveFile.agent_id == agent_id,+ AgentDriveFile.key == key,+ )+ )+ if existing is None:+ return {"key": key, "removed": True, "noop": True}+ result = {+ "key": key,+ "removed": True,+ "file_kind": existing.file_kind.value,+ "file_id": existing.file_id,+ "value_owned_by_drive": existing.value_owned_by_drive,+ "is_skill": existing.is_skill,+ "skill_metadata": existing.skill_metadata,+ }+ if existing.value_owned_by_drive:+ self._cleanup_value(+ session,+ tenant_id=tenant_id,+ file_kind=existing.file_kind,+ file_id=existing.file_id,+ exclude_row_id=existing.id,+ pending_storage_deletes=pending_storage_deletes,+ )+ session.delete(existing)+ return result+@staticmethoddef _row_dict(row: AgentDriveFile) -> dict[str, Any]:return {@@ -750,6 +799,11 @@ class AgentDriveService:else:mapping = {"transfer_method": "local_file", "upload_file_id": file_id}controller = DatabaseFileAccessController()+ # Keep workflow runtime wiring lazy: importing this service is part of+ # Agent v2 node bootstrap, while ``core.app.workflow`` re-exports the+ # node factory. A module-level import here would close that cycle.+ from core.app.workflow.file_runtime import DifyWorkflowFileRuntime+runtime = DifyWorkflowFileRuntime(file_access_controller=controller)try:if file_kind == AgentDriveFileKind.UPLOAD_FILE:diff --git a/api/tests/unit_tests/clients/agent_backend/test_request_builder.py b/api/tests/unit_tests/clients/agent_backend/test_request_builder.pyindex c0b308a5cb5..c91d0fd3e8a 100644--- a/api/tests/unit_tests/clients/agent_backend/test_request_builder.py+++ b/api/tests/unit_tests/clients/agent_backend/test_request_builder.py@@ -14,6 +14,7 @@ from dify_agent.layers.dify_plugin import (DifyPluginToolConfig,DifyPluginToolsLayerConfig,)+from dify_agent.layers.drive import DifyDriveLayerConfigfrom dify_agent.layers.execution_context import DIFY_EXECUTION_CONTEXT_LAYER_TYPE_ID, DifyExecutionContextLayerConfigfrom dify_agent.layers.knowledge import DIFY_KNOWLEDGE_BASE_LAYER_TYPE_ID, DifyKnowledgeBaseLayerConfigfrom dify_agent.layers.output import DIFY_OUTPUT_LAYER_TYPE_ID@@ -42,7 +43,7 @@ from clients.agent_backend import (extract_runtime_layer_specs,redact_for_agent_backend_log,)-from clients.agent_backend.request_builder import DIFY_SHELL_LAYER_ID+from clients.agent_backend.request_builder import DIFY_DRIVE_LAYER_ID, DIFY_SHELL_LAYER_IDdef _run_input() -> AgentBackendWorkflowNodeRunInput:@@ -331,6 +332,22 @@ def test_workflow_request_builder_adds_shell_layer_when_include_shell():assert shell_config.env[0].name == "PROJECT_NAME"+def test_workflow_request_builder_binds_shell_to_drive_when_configured():+ run_input = _run_input()+ run_input.include_shell = True+ run_input.drive_config = DifyDriveLayerConfig(drive_ref="agent-agent-1")++ request = AgentBackendRunRequestBuilder().build_for_workflow_node(run_input)+ layers = {layer.name: layer for layer in request.composition.layers}+ layer_names = [layer.name for layer in request.composition.layers]++ assert layers[DIFY_SHELL_LAYER_ID].deps == {+ "execution_context": DIFY_EXECUTION_CONTEXT_LAYER_ID,+ "drive": DIFY_DRIVE_LAYER_ID,+ }+ assert layer_names.index(DIFY_DRIVE_LAYER_ID) < layer_names.index(DIFY_SHELL_LAYER_ID)++def test_agent_app_request_builder_omits_shell_layer_by_default():request = AgentBackendRunRequestBuilder().build_for_agent_app(_agent_app_input())assert DIFY_SHELL_LAYER_ID not in {layer.name for layer in request.composition.layers}@@ -350,6 +367,21 @@ def test_agent_app_request_builder_adds_shell_layer_when_include_shell():assert shell_config.env[0].name == "APP_ENV"+def test_agent_app_request_builder_binds_shell_to_drive_when_configured():+ run_input = _agent_app_input(include_shell=True)+ run_input.drive_config = DifyDriveLayerConfig(drive_ref="agent-agent-1")++ request = AgentBackendRunRequestBuilder().build_for_agent_app(run_input)+ layers = {layer.name: layer for layer in request.composition.layers}+ layer_names = [layer.name for layer in request.composition.layers]++ assert layers[DIFY_SHELL_LAYER_ID].deps == {+ "execution_context": DIFY_EXECUTION_CONTEXT_LAYER_ID,+ "drive": DIFY_DRIVE_LAYER_ID,+ }+ assert layer_names.index(DIFY_DRIVE_LAYER_ID) < layer_names.index(DIFY_SHELL_LAYER_ID)++def test_agent_app_request_builder_adds_knowledge_layer_when_configured():run_input = _agent_app_input()run_input.knowledge = DifyKnowledgeBaseLayerConfig.model_validate(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 e94536aa012..bafdc3b46ac 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@@ -12,6 +12,7 @@ import iofrom types import SimpleNamespacefrom unittest.mock import patch+import pytestfrom flask import Flaskfrom controllers.console.app.agent import (@@ -152,27 +153,20 @@ def test_files_commit_validates_upload_and_returns_drive_ref():patch(f"{_MOD}.console_ns") as ns,patch(f"{_MOD}.db") as db_mock,patch(f"{_MOD}.AgentDriveService") as drive,- patch(f"{_MOD}.AgentComposerService") as composer,):ns.payload = {"upload_file_id": "0fa6f9bc-3416-4476-8857-a13129704dd9"}db_mock.session.scalar.return_value = uploaddrive.return_value.commit.return_value = [{"key": "files/sample qna.pdf", "size": 5, "mime_type": "application/pdf"}]- composer.add_drive_file_ref.return_value = "ver-2"body, status = raw(AgentDriveFilesApi(), _USER, _APP)assert status == 201assert body["file"]["drive_key"] == "files/sample qna.pdf"assert body["file"]["file_id"] == "uf-1"- assert body["config_version_id"] == "ver-2"item = drive.return_value.commit.call_args.kwargs["items"][0]assert item.value_owned_by_drive is Trueassert item.file_ref.kind == "upload_file"- file_ref = composer.add_drive_file_ref.call_args.kwargs["file_ref"]- assert file_ref.drive_key == "files/sample qna.pdf"- assert file_ref.name == "sample qna.pdf"- assert composer.add_drive_file_ref.call_args.kwargs["app_id"] == "app-1"def test_files_by_agent_commit_uses_agent_route_and_ignores_node_id():@@ -184,20 +178,16 @@ def test_files_by_agent_commit_uses_agent_route_and_ignores_node_id():patch(f"{_MOD}.console_ns") as ns,patch(f"{_MOD}.db") as db_mock,patch(f"{_MOD}.AgentDriveService") as drive,- patch(f"{_MOD}.AgentComposerService") as composer,):ns.payload = {"upload_file_id": "0fa6f9bc-3416-4476-8857-a13129704dd9"}db_mock.session.scalar.return_value = uploaddrive.return_value.commit.return_value = [{"key": "files/sample.pdf", "size": 5, "mime_type": "application/pdf"}]- composer.add_drive_file_ref.return_value = "ver-2"body, status = raw(AgentDriveFilesByAgentApi(), "tenant-1", _USER, "agent-1")assert status == 201- assert body["config_version_id"] == "ver-2"resolve_app.assert_called_once_with(tenant_id="tenant-1", agent_id="agent-1")- assert composer.add_drive_file_ref.call_args.kwargs["node_id"] is Nonedef test_files_commit_404_when_upload_not_in_tenant():@@ -234,13 +224,10 @@ def test_files_commit_resolves_workflow_node_agent():drive.return_value.commit.return_value = [{"key": "files/sample.pdf", "size": 5, "mime_type": "application/pdf"}]- composer.add_drive_file_ref.return_value = "ver-2"body, status = raw(AgentDriveFilesApi(), _USER, _WORKFLOW_APP)assert status == 201- assert body["config_version_id"] == "ver-2"assert drive.return_value.commit.call_args.kwargs["agent_id"] == "wf-agent-1"- assert composer.add_drive_file_ref.call_args.kwargs["node_id"] == "agent-node-1"def test_files_delete_updates_soul_then_drive():@@ -250,17 +237,15 @@ def test_files_delete_updates_soul_then_drive():calls: list[str] = []with _json_ctx(method="DELETE", query_string="key=files/sample.pdf"):with (- patch(f"{_MOD}.AgentComposerService") as composer,patch(f"{_MOD}.AgentDriveService") as drive,):- composer.remove_drive_refs.side_effect = lambda **kw: calls.append("soul") or "ver-2"- drive.return_value.delete.side_effect = lambda **kw: calls.append("drive") or ["files/sample.pdf"]+ drive.return_value.commit.side_effect = lambda **kw: (+ calls.append("drive") or [{"key": "files/sample.pdf", "removed": True}]+ )body = raw(AgentDriveFilesApi(), _USER, _APP)- assert calls == ["soul", "drive"] # soul-first ordering- assert body == {"result": "success", "removed_keys": ["files/sample.pdf"], "config_version_id": "ver-2"}- assert composer.remove_drive_refs.call_args.kwargs["file_key"] == "files/sample.pdf"- assert composer.remove_drive_refs.call_args.kwargs["app_id"] == "app-1"+ assert calls == ["drive"]+ assert body == {"result": "success", "removed_keys": ["files/sample.pdf"]}def test_files_by_agent_delete_uses_agent_route_and_ignores_node_id():@@ -268,16 +253,13 @@ def test_files_by_agent_delete_uses_agent_route_and_ignores_node_id():with _json_ctx(method="DELETE", query_string="key=files/sample.pdf&node_id=ignored"):with (patch(f"{_MOD}.resolve_agent_app_model", return_value=_APP) as resolve_app,- patch(f"{_MOD}.AgentComposerService") as composer,patch(f"{_MOD}.AgentDriveService") as drive,):- composer.remove_drive_refs.return_value = "ver-2"- drive.return_value.delete.return_value = ["files/sample.pdf"]+ drive.return_value.commit.return_value = [{"key": "files/sample.pdf", "removed": True}]body = raw(AgentDriveFilesByAgentApi(), "tenant-1", _USER, "agent-1")- assert body["config_version_id"] == "ver-2"+ assert body == {"result": "success", "removed_keys": ["files/sample.pdf"]}resolve_app.assert_called_once_with(tenant_id="tenant-1", agent_id="agent-1")- assert composer.remove_drive_refs.call_args.kwargs["node_id"] is Nonedef test_files_delete_resolves_workflow_node_agent():@@ -290,13 +272,11 @@ def test_files_delete_resolves_workflow_node_agent():patch(f"{_MOD}.AgentDriveService") as drive,):composer.resolve_workflow_node_agent_id.return_value = "wf-agent-1"- composer.remove_drive_refs.return_value = "ver-2"- drive.return_value.delete.return_value = ["files/sample.pdf"]+ drive.return_value.commit.return_value = [{"key": "files/sample.pdf", "removed": True}]body = raw(AgentDriveFilesApi(), _USER, _WORKFLOW_APP)- assert body["config_version_id"] == "ver-2"- assert drive.return_value.delete.call_args.kwargs["agent_id"] == "wf-agent-1"- assert composer.remove_drive_refs.call_args.kwargs["node_id"] == "agent-node-1"+ assert body == {"result": "success", "removed_keys": ["files/sample.pdf"]}+ assert drive.return_value.commit.call_args.kwargs["agent_id"] == "wf-agent-1"def test_files_delete_survives_drive_failure():@@ -305,14 +285,11 @@ def test_files_delete_survives_drive_failure():raw = _raw(AgentDriveFilesApi.delete)with _json_ctx(method="DELETE", query_string="key=files/sample.pdf"):with (- patch(f"{_MOD}.AgentComposerService") as composer,patch(f"{_MOD}.AgentDriveService") as drive,):- composer.remove_drive_refs.return_value = "ver-2"- drive.return_value.delete.side_effect = RuntimeError("storage down")- body = raw(AgentDriveFilesApi(), _USER, _APP)- # soul already updated; drive cleanup is best-effort and retryable- assert body == {"result": "success", "removed_keys": [], "config_version_id": "ver-2"}+ drive.return_value.commit.side_effect = RuntimeError("storage down")+ with pytest.raises(RuntimeError, match="storage down"):+ raw(AgentDriveFilesApi(), _USER, _APP)def test_skill_delete_uses_slug_prefix_and_is_idempotent():@@ -321,17 +298,18 @@ def test_skill_delete_uses_slug_prefix_and_is_idempotent():raw = _raw(AgentSkillApi.delete)with _json_ctx(method="DELETE"):with (- patch(f"{_MOD}.AgentComposerService") as composer,patch(f"{_MOD}.AgentDriveService") as drive,):- composer.remove_drive_refs.return_value = None # ref already gone- drive.return_value.delete.return_value = []+ drive.return_value.commit.return_value = [+ {"key": "tender-analyzer/SKILL.md", "removed": True},+ {"key": "tender-analyzer/.DIFY-SKILL-FULL.zip", "removed": True},+ ]body = raw(AgentSkillApi(), _USER, _APP, "tender-analyzer")- assert body == {"result": "success", "removed_keys": [], "config_version_id": None}- assert drive.return_value.delete.call_args.kwargs["prefix"] == "tender-analyzer/"- assert composer.remove_drive_refs.call_args.kwargs["skill_slug"] == "tender-analyzer"- assert composer.remove_drive_refs.call_args.kwargs["app_id"] == "app-1"+ assert body == {+ "result": "success",+ "removed_keys": ["tender-analyzer/SKILL.md", "tender-analyzer/.DIFY-SKILL-FULL.zip"],+ }def test_skill_delete_by_agent_uses_agent_route():@@ -339,16 +317,13 @@ def test_skill_delete_by_agent_uses_agent_route():with _json_ctx(method="DELETE", query_string="node_id=ignored"):with (patch(f"{_MOD}.resolve_agent_app_model", return_value=_APP) as resolve_app,- patch(f"{_MOD}.AgentComposerService") as composer,patch(f"{_MOD}.AgentDriveService") as drive,):- composer.remove_drive_refs.return_value = "ver-2"- drive.return_value.delete.return_value = ["tender-analyzer/SKILL.md"]+ drive.return_value.commit.return_value = [{"key": "tender-analyzer/SKILL.md", "removed": True}]body = raw(AgentSkillByAgentApi(), "tenant-1", _USER, "agent-1", "tender-analyzer")- assert body["config_version_id"] == "ver-2"+ assert body == {"result": "success", "removed_keys": ["tender-analyzer/SKILL.md"]}resolve_app.assert_called_once_with(tenant_id="tenant-1", agent_id="agent-1")- assert composer.remove_drive_refs.call_args.kwargs["node_id"] is Nonedef test_skill_delete_rejects_path_like_slug():diff --git a/api/tests/unit_tests/controllers/inner_api/plugin/test_agent_drive.py b/api/tests/unit_tests/controllers/inner_api/plugin/test_agent_drive.pyindex b8ad86017eb..8c38564b3d0 100644--- a/api/tests/unit_tests/controllers/inner_api/plugin/test_agent_drive.py+++ b/api/tests/unit_tests/controllers/inner_api/plugin/test_agent_drive.py@@ -8,12 +8,13 @@ controller's request parsing + error mapping, not auth (tested separately).from __future__ import annotationsimport inspect+from types import SimpleNamespacefrom unittest.mock import patchimport pytestfrom flask import Flask-from controllers.inner_api.plugin.agent_drive import AgentDriveCommitApi, AgentDriveManifestApi+from controllers.inner_api.plugin.agent_drive import AgentDriveCommitApi, AgentDriveManifestApi, AgentDriveSkillsApifrom services.agent_drive_service import AgentDriveError_MOD = "controllers.inner_api.plugin.agent_drive"@@ -52,6 +53,41 @@ def test_manifest_bad_drive_ref_is_400():assert body["code"] == "invalid_drive_ref"+def test_skills_requires_tenant_id_and_returns_items():+ raw = _raw(AgentDriveSkillsApi.get)++ with app.test_request_context("/"):+ body, status = raw(AgentDriveSkillsApi(), "agent-agent-1")+ assert status == 400+ assert body["code"] == "missing_tenant_id"++ with app.test_request_context("/?tenant_id=tenant-1"):+ with patch(f"{_MOD}.AgentDriveService") as svc:+ svc.return_value.list_skills.return_value = [+ {+ "path": "tender-analyzer",+ "skill_md_key": "tender-analyzer/SKILL.md",+ "archive_key": None,+ "name": "Tender Analyzer",+ "description": "Parses RFPs.",+ }+ ]+ result = raw(AgentDriveSkillsApi(), "agent-agent-1")++ assert result == {+ "items": [+ {+ "path": "tender-analyzer",+ "skill_md_key": "tender-analyzer/SKILL.md",+ "archive_key": None,+ "name": "Tender Analyzer",+ "description": "Parses RFPs.",+ }+ ]+ }+ assert svc.return_value.list_skills.call_args.kwargs == {"tenant_id": "tenant-1", "agent_id": "agent-1"}++def test_commit_parses_body_and_returns_items():raw = _raw(AgentDriveCommitApi.post)payload = {@@ -60,11 +96,35 @@ def test_commit_parses_body_and_returns_items():"items": [{"key": "a.txt", "file_ref": {"kind": "tool_file", "id": "tf-1"}}],}with app.test_request_context("/", method="POST", json=payload):- with patch(f"{_MOD}.AgentDriveService") as svc:+ with (+ patch(f"{_MOD}.get_user", return_value=SimpleNamespace(id="user-1")) as get_user,+ patch(f"{_MOD}.AgentDriveService") as svc,+ ):svc.return_value.commit.return_value = [{"key": "a.txt"}]result = raw(AgentDriveCommitApi(), "agent-agent-1")assert result == {"items": [{"key": "a.txt"}]}+ assert get_user.call_args.args == ("tenant-1", "user-1")assert svc.return_value.commit.call_args.kwargs["agent_id"] == "agent-1"+ assert svc.return_value.commit.call_args.kwargs["user_id"] == "user-1"+++def test_commit_canonicalizes_user_before_service_call():+ raw = _raw(AgentDriveCommitApi.post)+ payload = {+ "tenant_id": "tenant-1",+ "user_id": "session-1",+ "items": [{"key": "a.txt", "file_ref": {"kind": "tool_file", "id": "tf-1"}}],+ }+ with app.test_request_context("/", method="POST", json=payload):+ with (+ patch(f"{_MOD}.get_user", return_value=SimpleNamespace(id="end-user-1")),+ patch(f"{_MOD}.AgentDriveService") as svc,+ ):+ svc.return_value.commit.return_value = [{"key": "a.txt"}]+ result = raw(AgentDriveCommitApi(), "agent-agent-1")++ assert result == {"items": [{"key": "a.txt"}]}+ assert svc.return_value.commit.call_args.kwargs["user_id"] == "end-user-1"def test_commit_invalid_body_is_400():@@ -83,13 +143,16 @@ def test_commit_maps_service_error():"items": [{"key": "a.txt", "file_ref": {"kind": "tool_file", "id": "tf-1"}}],}with app.test_request_context("/", method="POST", json=payload):- with patch(f"{_MOD}.AgentDriveService") as svc:+ with (+ patch(f"{_MOD}.get_user", return_value=SimpleNamespace(id="user-1")),+ patch(f"{_MOD}.AgentDriveService") as svc,+ ):svc.return_value.commit.side_effect = AgentDriveError("source_not_found", "nope", status_code=404)body, status = raw(AgentDriveCommitApi(), "agent-agent-1")assert status == 404assert body["code"] == "source_not_found"[email protected]("api_cls", [AgentDriveManifestApi, AgentDriveCommitApi])[email protected]("api_cls", [AgentDriveManifestApi, AgentDriveSkillsApi, AgentDriveCommitApi])def test_endpoints_have_handlers(api_cls):assert callable(getattr(api_cls(), "get", None) or getattr(api_cls(), "post", None))diff --git a/api/tests/unit_tests/controllers/inner_api/test_knowledge_retrieval.py b/api/tests/unit_tests/controllers/inner_api/test_knowledge_retrieval.pyindex fa648e0335c..00eab81cbe6 100644--- a/api/tests/unit_tests/controllers/inner_api/test_knowledge_retrieval.py+++ b/api/tests/unit_tests/controllers/inner_api/test_knowledge_retrieval.py@@ -1,5 +1,7 @@-"""Unit tests for the inner knowledge retrieval controller."""+"""Unit tests for the plugin inner knowledge retrieval controller."""+from collections.abc import Iterator+from contextlib import contextmanagerfrom unittest.mock import patchimport pytest@@ -53,31 +55,38 @@ def _payload() -> dict[str, object]:}+@contextmanager+def _plugin_inner_auth() -> Iterator[None]:+ with (+ patch("configs.dify_config.PLUGIN_DAEMON_KEY", "plugin-daemon-key"),+ patch("configs.dify_config.INNER_API_KEY_FOR_PLUGIN", "inner-key"),+ ):+ yield++class TestInnerKnowledgeRetrieveApi:- def test_post_returns_401_when_api_key_missing(self, inner_api_app: Flask):- with patch("configs.dify_config.INNER_API", True):+ def test_post_returns_404_when_api_key_missing(self, inner_api_app: Flask):+ with _plugin_inner_auth():response = inner_api_app.test_client().post("/inner/api/knowledge/retrieve",json=_payload(),headers=_headers(api_key=None),)- assert response.status_code == 401- assert response.get_json()["code"] == "inner_api_unauthorized"+ assert response.status_code == 404- def test_post_returns_401_when_api_key_invalid(self, inner_api_app: Flask):- with patch("configs.dify_config.INNER_API", True), patch("configs.dify_config.INNER_API_KEY", "inner-key"):+ def test_post_returns_404_when_api_key_invalid(self, inner_api_app: Flask):+ with _plugin_inner_auth():response = inner_api_app.test_client().post("/inner/api/knowledge/retrieve",json=_payload(),headers=_headers(api_key="wrong-key"),)- assert response.status_code == 401- assert response.get_json()["code"] == "inner_api_unauthorized"+ assert response.status_code == 404def test_post_returns_400_for_invalid_body(self, inner_api_app: Flask):- with patch("configs.dify_config.INNER_API", True), patch("configs.dify_config.INNER_API_KEY", "inner-key"):+ with _plugin_inner_auth():response = inner_api_app.test_client().post("/inner/api/knowledge/retrieve",json={"caller": {"tenant_id": "tenant-1"}},@@ -91,7 +100,7 @@ class TestInnerKnowledgeRetrieveApi:def test_post_returns_404_for_service_not_found_error(self, mock_retrieve, inner_api_app: Flask):mock_retrieve.side_effect = InnerKnowledgeRetrieveAppNotFoundError("app missing")- with patch("configs.dify_config.INNER_API", True), patch("configs.dify_config.INNER_API_KEY", "inner-key"):+ with _plugin_inner_auth():response = inner_api_app.test_client().post("/inner/api/knowledge/retrieve",json=_payload(),@@ -105,7 +114,7 @@ class TestInnerKnowledgeRetrieveApi:def test_post_returns_403_for_service_forbidden_error(self, mock_retrieve, inner_api_app: Flask):mock_retrieve.side_effect = InnerKnowledgeRetrieveDatasetTenantMismatchError("wrong tenant")- with patch("configs.dify_config.INNER_API", True), patch("configs.dify_config.INNER_API_KEY", "inner-key"):+ with _plugin_inner_auth():response = inner_api_app.test_client().post("/inner/api/knowledge/retrieve",json=_payload(),@@ -119,7 +128,7 @@ class TestInnerKnowledgeRetrieveApi:def test_post_returns_422_for_retrieval_config_value_error(self, mock_retrieve, inner_api_app: Flask):mock_retrieve.side_effect = ValueError("invalid reranking config")- with patch("configs.dify_config.INNER_API", True), patch("configs.dify_config.INNER_API_KEY", "inner-key"):+ with _plugin_inner_auth():response = inner_api_app.test_client().post("/inner/api/knowledge/retrieve",json=_payload(),@@ -133,7 +142,7 @@ class TestInnerKnowledgeRetrieveApi:def test_post_returns_429_for_rate_limit_error(self, mock_retrieve, inner_api_app: Flask):mock_retrieve.side_effect = RateLimitExceededError("knowledge rate limited")- with patch("configs.dify_config.INNER_API", True), patch("configs.dify_config.INNER_API_KEY", "inner-key"):+ with _plugin_inner_auth():response = inner_api_app.test_client().post("/inner/api/knowledge/retrieve",json=_payload(),@@ -147,7 +156,7 @@ class TestInnerKnowledgeRetrieveApi:payload = _payload()payload["metadata_filtering"] = {"mode": "manual"}- with patch("configs.dify_config.INNER_API", True), patch("configs.dify_config.INNER_API_KEY", "inner-key"):+ with _plugin_inner_auth():response = inner_api_app.test_client().post("/inner/api/knowledge/retrieve",json=payload,@@ -161,7 +170,7 @@ class TestInnerKnowledgeRetrieveApi:payload = _payload()payload["metadata_filtering"] = {"mode": "automatic"}- with patch("configs.dify_config.INNER_API", True), patch("configs.dify_config.INNER_API_KEY", "inner-key"):+ with _plugin_inner_auth():response = inner_api_app.test_client().post("/inner/api/knowledge/retrieve",json=payload,@@ -175,7 +184,7 @@ class TestInnerKnowledgeRetrieveApi:def test_post_returns_502_for_external_knowledge_failure(self, mock_retrieve, inner_api_app: Flask):mock_retrieve.side_effect = ExternalKnowledgeRetrievalError("upstream failed")- with patch("configs.dify_config.INNER_API", True), patch("configs.dify_config.INNER_API_KEY", "inner-key"):+ with _plugin_inner_auth():response = inner_api_app.test_client().post("/inner/api/knowledge/retrieve",json=_payload(),@@ -219,7 +228,7 @@ class TestInnerKnowledgeRetrieveApi:),)- with patch("configs.dify_config.INNER_API", True), patch("configs.dify_config.INNER_API_KEY", "inner-key"):+ with _plugin_inner_auth():response = inner_api_app.test_client().post("/inner/api/knowledge/retrieve",json=_payload(),diff --git a/api/tests/unit_tests/core/app/apps/agent_app/test_runtime_request_builder.py b/api/tests/unit_tests/core/app/apps/agent_app/test_runtime_request_builder.pyindex 85a2423f6b1..0d1483e1b79 100644--- a/api/tests/unit_tests/core/app/apps/agent_app/test_runtime_request_builder.py+++ b/api/tests/unit_tests/core/app/apps/agent_app/test_runtime_request_builder.py@@ -226,19 +226,8 @@ class TestAgentAppRuntimeRequestBuilder:def _soul_with_model_and_skill() -> AgentSoulConfig:- from models.agent_config_entities import AgentSkillRefConfig-soul = _soul_with_model()- soul.skills_files.skills = [- AgentSkillRefConfig.model_validate(- {- "id": "abc",- "name": "Tender Analyzer",- "description": "Parses RFPs.",- "skill_md_key": "tender-analyzer/SKILL.md",- }- )- ]+ soul.prompt.system_prompt = "Use [§skill:tender-analyzer%2FSKILL.md:Tender Analyzer§]"return soul@@ -247,6 +236,28 @@ class TestAgentAppDriveLayer:monkeypatch.setattr("core.app.apps.agent_app.runtime_request_builder.dify_config.AGENT_DRIVE_MANIFEST_ENABLED", True)+ monkeypatch.setattr(+ "core.workflow.nodes.agent_v2.runtime_request_builder.AgentDriveService.list_skills",+ lambda self, *, tenant_id, agent_id: [+ {+ "path": "tender-analyzer",+ "skill_md_key": "tender-analyzer/SKILL.md",+ "archive_key": None,+ "name": "Tender Analyzer",+ "description": "Parses RFPs.",+ "size": 1,+ "mime_type": "text/markdown",+ "hash": None,+ "created_at": 1,+ }+ ],+ )+ monkeypatch.setattr(+ "core.workflow.nodes.agent_v2.runtime_request_builder.AgentDriveService.manifest",+ lambda self, *, tenant_id, agent_id, prefix="", include_download_url=False: [+ {"key": "tender-analyzer/SKILL.md", "is_skill": True}+ ],+ )builder = AgentAppRuntimeRequestBuilder(credentials_provider=_FakeCredentialsProvider(),plugin_tools_builder=_NoToolsBuilder(), # type: ignore[arg-type]@@ -256,12 +267,42 @@ class TestAgentAppDriveLayer:drive = next(layer for layer in result.request.composition.layers if layer.name == "drive")assert drive.type == "dify.drive"+ assert drive.deps == {"execution_context": "execution_context"}assert drive.config.drive_ref == "agent-agent-1"assert [skill.skill_md_key for skill in drive.config.skills] == ["tender-analyzer/SKILL.md"]+ assert drive.config.mentioned_skill_keys == ["tender-analyzer/SKILL.md"]# injected right after execution_context, mirroring the workflow surfacenames = [layer.name for layer in result.request.composition.layers]assert names.index("drive") == names.index("execution_context") + 1+ def test_drive_layer_injected_with_empty_catalog_and_shell_depends_on_it(self, monkeypatch: pytest.MonkeyPatch):+ monkeypatch.setattr(+ "core.app.apps.agent_app.runtime_request_builder.dify_config.AGENT_DRIVE_MANIFEST_ENABLED", True+ )+ monkeypatch.setattr("core.app.apps.agent_app.runtime_request_builder.dify_config.AGENT_SHELL_ENABLED", True)+ monkeypatch.setattr(+ "core.workflow.nodes.agent_v2.runtime_request_builder.AgentDriveService.list_skills",+ lambda self, *, tenant_id, agent_id: [],+ )+ monkeypatch.setattr(+ "core.workflow.nodes.agent_v2.runtime_request_builder.AgentDriveService.manifest",+ lambda self, *, tenant_id, agent_id, prefix="", include_download_url=False: [],+ )+ builder = AgentAppRuntimeRequestBuilder(+ credentials_provider=_FakeCredentialsProvider(),+ plugin_tools_builder=_NoToolsBuilder(), # type: ignore[arg-type]+ )++ result = builder.build(_ctx(_soul_with_model()))++ layers = {layer.name: layer for layer in result.request.composition.layers}+ assert layers["drive"].config.drive_ref == "agent-agent-1"+ assert layers["drive"].config.skills == []+ assert layers[DIFY_SHELL_LAYER_ID].deps == {+ "execution_context": "execution_context",+ "drive": "drive",+ }+def test_no_drive_layer_when_flag_disabled(self):builder = AgentAppRuntimeRequestBuilder(credentials_provider=_FakeCredentialsProvider(),@@ -269,3 +310,152 @@ class TestAgentAppDriveLayer:)result = builder.build(_ctx(_soul_with_model_and_skill()))assert all(layer.name != "drive" for layer in result.request.composition.layers)++ def test_agent_app_runtime_expands_skill_and_file_mentions_in_agent_soul_prompt(+ self,+ monkeypatch: pytest.MonkeyPatch,+ ):+ monkeypatch.setattr(+ "core.app.apps.agent_app.runtime_request_builder.dify_config.AGENT_DRIVE_MANIFEST_ENABLED", True+ )+ monkeypatch.setattr(+ "core.workflow.nodes.agent_v2.runtime_request_builder.AgentDriveService.list_skills",+ lambda self, *, tenant_id, agent_id: [+ {+ "path": "tender-analyzer",+ "skill_md_key": "tender-analyzer/SKILL.md",+ "archive_key": None,+ "name": "Tender Analyzer",+ "description": "Parses RFPs.",+ "size": 1,+ "mime_type": "text/markdown",+ "hash": None,+ "created_at": 1,+ }+ ],+ )+ monkeypatch.setattr(+ "core.workflow.nodes.agent_v2.runtime_request_builder.AgentDriveService.manifest",+ lambda self, *, tenant_id, agent_id, prefix="", include_download_url=False: [+ {"key": "tender-analyzer/SKILL.md", "is_skill": True},+ {"key": "files/sample.pdf", "is_skill": False},+ ],+ )+ soul = _soul_with_model()+ soul.prompt.system_prompt = (+ "Use [§skill:tender-analyzer%2FSKILL.md:Tender Analyzer§] and [§file:files%2Fsample.pdf:sample.pdf§]."+ )+ builder = AgentAppRuntimeRequestBuilder(+ credentials_provider=_FakeCredentialsProvider(),+ plugin_tools_builder=_NoToolsBuilder(), # type: ignore[arg-type]+ )++ result = builder.build(_ctx(soul))++ prompt_layer = next(layer for layer in result.request.composition.layers if layer.name == "agent_soul_prompt")+ assert prompt_layer.config.prefix == "Use Tender Analyzer and sample.pdf."+ assert "[§" not in prompt_layer.config.prefix++ def test_agent_app_runtime_missing_drive_mentions_fall_back_to_label_then_decoded_key(+ self,+ monkeypatch: pytest.MonkeyPatch,+ ):+ monkeypatch.setattr(+ "core.app.apps.agent_app.runtime_request_builder.dify_config.AGENT_DRIVE_MANIFEST_ENABLED", True+ )+ monkeypatch.setattr(+ "core.workflow.nodes.agent_v2.runtime_request_builder.AgentDriveService.list_skills",+ lambda self, *, tenant_id, agent_id: [],+ )+ monkeypatch.setattr(+ "core.workflow.nodes.agent_v2.runtime_request_builder.AgentDriveService.manifest",+ lambda self, *, tenant_id, agent_id, prefix="", include_download_url=False: [],+ )+ soul = _soul_with_model()+ soul.prompt.system_prompt = (+ "Use [§skill:ghost%2FSKILL.md:Ghost Skill§], [§file:files%2Fghost.txt:Ghost File§], "+ "and [§file:files%2Fmissing.txt§]."+ )+ builder = AgentAppRuntimeRequestBuilder(+ credentials_provider=_FakeCredentialsProvider(),+ plugin_tools_builder=_NoToolsBuilder(), # type: ignore[arg-type]+ )++ result = builder.build(_ctx(soul))++ prompt_layer = next(layer for layer in result.request.composition.layers if layer.name == "agent_soul_prompt")+ assert prompt_layer.config.prefix == "Use Ghost Skill, Ghost File, and files/missing.txt."+ assert "[§" not in prompt_layer.config.prefix++ def test_agent_app_runtime_expands_drive_mentions_in_agent_soul_prompt(self, monkeypatch: pytest.MonkeyPatch):+ monkeypatch.setattr(+ "core.app.apps.agent_app.runtime_request_builder.dify_config.AGENT_DRIVE_MANIFEST_ENABLED", True+ )+ monkeypatch.setattr(+ "core.workflow.nodes.agent_v2.runtime_request_builder.AgentDriveService.list_skills",+ lambda self, *, tenant_id, agent_id: [+ {+ "path": "tender-analyzer",+ "skill_md_key": "tender-analyzer/SKILL.md",+ "archive_key": None,+ "name": "Tender Analyzer",+ "description": "Parses RFPs.",+ "size": 1,+ "mime_type": "text/markdown",+ "hash": None,+ "created_at": 1,+ }+ ],+ )+ monkeypatch.setattr(+ "core.workflow.nodes.agent_v2.runtime_request_builder.AgentDriveService.manifest",+ lambda self, *, tenant_id, agent_id, prefix="", include_download_url=False: [+ {"key": "tender-analyzer/SKILL.md", "is_skill": True},+ {"key": "files/sample.pdf", "is_skill": False},+ ],+ )+ soul = _soul_with_model()+ soul.prompt.system_prompt = (+ "Use [§skill:tender-analyzer%2FSKILL.md:Tender Analyzer§] and [§file:files%2Fsample.pdf:sample.pdf§]"+ )+ builder = AgentAppRuntimeRequestBuilder(+ credentials_provider=_FakeCredentialsProvider(),+ plugin_tools_builder=_NoToolsBuilder(), # type: ignore[arg-type]+ )++ result = builder.build(_ctx(soul))++ prompt_layer = next(layer for layer in result.request.composition.layers if layer.name == "agent_soul_prompt")+ assert prompt_layer.config.prefix == "Use Tender Analyzer and sample.pdf"+ assert "[§" not in prompt_layer.config.prefix++ def test_agent_app_runtime_missing_drive_mentions_fall_back_without_marker_leak(+ self,+ monkeypatch: pytest.MonkeyPatch,+ ):+ monkeypatch.setattr(+ "core.app.apps.agent_app.runtime_request_builder.dify_config.AGENT_DRIVE_MANIFEST_ENABLED", True+ )+ monkeypatch.setattr(+ "core.workflow.nodes.agent_v2.runtime_request_builder.AgentDriveService.list_skills",+ lambda self, *, tenant_id, agent_id: [],+ )+ monkeypatch.setattr(+ "core.workflow.nodes.agent_v2.runtime_request_builder.AgentDriveService.manifest",+ lambda self, *, tenant_id, agent_id, prefix="", include_download_url=False: [],+ )+ soul = _soul_with_model()+ soul.prompt.system_prompt = (+ "Use [§skill:ghost%2FSKILL.md:Ghost Skill§], [§file:files%2Fghost.txt:Ghost File§], "+ "and [§file:files%2Fno-label.txt§]."+ )+ builder = AgentAppRuntimeRequestBuilder(+ credentials_provider=_FakeCredentialsProvider(),+ plugin_tools_builder=_NoToolsBuilder(), # type: ignore[arg-type]+ )++ result = builder.build(_ctx(soul))++ prompt_layer = next(layer for layer in result.request.composition.layers if layer.name == "agent_soul_prompt")+ assert prompt_layer.config.prefix == "Use Ghost Skill, Ghost File, and files/no-label.txt."+ assert "[§" not in prompt_layer.config.prefixdiff --git a/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_runtime_request_builder.py b/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_runtime_request_builder.pyindex 9313aea51e6..78e49769159 100644--- a/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_runtime_request_builder.py+++ b/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_runtime_request_builder.py@@ -834,57 +834,116 @@ def test_mentions_expand_in_soul_and_job_prompts_without_token_leak():def _soul_with_drive_skill() -> AgentSoulConfig:return AgentSoulConfig(- prompt={"system_prompt": "You are careful."},- model=AgentSoulModelConfig(plugin_id="langgenius/openai", model_provider="openai", model="gpt-test"),- skills_files={- "skills": [- {- "id": "abc123",- "name": "Tender Analyzer",- "description": "Parses RFPs.",- "skill_md_key": "tender-analyzer/SKILL.md",- "full_archive_key": "tender-analyzer/.DIFY-SKILL-FULL.zip",- },- {"id": "legacy", "name": "Legacy Skill"}, # pre-standardization: no drive key- ],- "files": [- {"name": "sample.pdf", "drive_key": "files/sample.pdf", "type": "application/pdf"},- {"name": "plain-upload.pdf", "file_id": "upload-1"}, # not drive-backed- ],+ prompt={+ "system_prompt": (+ "You are careful. Use [§skill:tender-analyzer%2FSKILL.md:Tender Analyzer§] "+ "and [§file:files%2Fsample.pdf:sample.pdf§]."+ )},+ model=AgentSoulModelConfig(plugin_id="langgenius/openai", model_provider="openai", model="gpt-test"),+ )+++def _mock_drive_catalog(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(+ "core.workflow.nodes.agent_v2.runtime_request_builder.AgentDriveService.list_skills",+ lambda self, *, tenant_id, agent_id: [+ {+ "path": "tender-analyzer",+ "skill_md_key": "tender-analyzer/SKILL.md",+ "archive_key": "tender-analyzer/.DIFY-SKILL-FULL.zip",+ "name": "Tender Analyzer",+ "description": "Parses RFPs.",+ "size": 123,+ "mime_type": "text/markdown",+ "hash": "hash-1",+ "created_at": 1,+ }+ ],+ )+ monkeypatch.setattr(+ "core.workflow.nodes.agent_v2.runtime_request_builder.AgentDriveService.manifest",+ lambda self, *, tenant_id, agent_id, prefix="", include_download_url=False: [+ {"key": "tender-analyzer/SKILL.md", "is_skill": True},+ {"key": "tender-analyzer/.DIFY-SKILL-FULL.zip", "is_skill": False},+ {"key": "files/sample.pdf", "is_skill": False},+ ],)-def test_build_drive_layer_config_catalogs_only_drive_backed_refs():+def _mock_empty_drive_catalog(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(+ "core.workflow.nodes.agent_v2.runtime_request_builder.AgentDriveService.list_skills",+ lambda self, *, tenant_id, agent_id: [],+ )+ monkeypatch.setattr(+ "core.workflow.nodes.agent_v2.runtime_request_builder.AgentDriveService.manifest",+ lambda self, *, tenant_id, agent_id, prefix="", include_download_url=False: [],+ )+++def test_build_drive_layer_config_catalogs_drive_skills_and_mentions(monkeypatch: pytest.MonkeyPatch):from core.workflow.nodes.agent_v2.runtime_request_builder import build_drive_layer_config- config, warnings = build_drive_layer_config(_soul_with_drive_skill(), agent_id="agent-1")+ _mock_drive_catalog(monkeypatch)+ config, warnings = build_drive_layer_config(_soul_with_drive_skill(), tenant_id="tenant-1", agent_id="agent-1")assert config is not Noneassert config.drive_ref == "agent-agent-1"assert [skill.skill_md_key for skill in config.skills] == ["tender-analyzer/SKILL.md"]assert config.skills[0].archive_key == "tender-analyzer/.DIFY-SKILL-FULL.zip"- assert [file.key for file in config.files] == ["files/sample.pdf"]- assert [w["code"] for w in warnings] == ["skill_ref_dangling"]- assert "Legacy Skill" in warnings[0]["message"]+ assert config.mentioned_skill_keys == ["tender-analyzer/SKILL.md"]+ assert config.mentioned_file_keys == ["files/sample.pdf"]+ assert warnings == []-def test_build_drive_layer_config_skips_when_nothing_configured():+def test_build_drive_layer_config_emits_drive_ref_when_catalog_is_empty(monkeypatch: pytest.MonkeyPatch):from core.workflow.nodes.agent_v2.runtime_request_builder import build_drive_layer_config+ _mock_empty_drive_catalog(monkeypatch)soul = AgentSoulConfig(model=AgentSoulModelConfig(plugin_id="langgenius/openai", model_provider="openai", model="gpt-test"))- assert build_drive_layer_config(soul, agent_id="agent-1") == (None, [])+ config, warnings = build_drive_layer_config(soul, tenant_id="tenant-1", agent_id="agent-1")++ assert config is not None+ assert config.drive_ref == "agent-agent-1"+ assert config.skills == []+ assert config.mentioned_skill_keys == []+ assert config.mentioned_file_keys == []+ assert warnings == []+++def test_workflow_run_request_contains_drive_layer_with_empty_catalog(monkeypatch: pytest.MonkeyPatch):+ monkeypatch.setattr(+ "core.workflow.nodes.agent_v2.runtime_request_builder.dify_config.AGENT_DRIVE_MANIFEST_ENABLED", True+ )+ monkeypatch.setattr("core.workflow.nodes.agent_v2.runtime_request_builder.dify_config.AGENT_SHELL_ENABLED", True)+ _mock_empty_drive_catalog(monkeypatch)++ result = WorkflowAgentRuntimeRequestBuilder(credentials_provider=FakeCredentialsProvider()).build(_context())++ dumped = result.request.model_dump(mode="json")+ layers = {layer["name"]: layer for layer in dumped["composition"]["layers"]}+ assert layers["drive"]["config"] == {+ "drive_ref": "agent-agent-1",+ "skills": [],+ "mentioned_skill_keys": [],+ "mentioned_file_keys": [],+ }+ assert layers[DIFY_SHELL_LAYER_ID]["deps"] == {+ "execution_context": DIFY_EXECUTION_CONTEXT_LAYER_ID,+ "drive": "drive",+ }def test_build_drive_layer_config_requires_agent_identity():from core.workflow.nodes.agent_v2.runtime_request_builder import build_drive_layer_config- config, warnings = build_drive_layer_config(_soul_with_drive_skill(), agent_id=None)+ config, warnings = build_drive_layer_config(_soul_with_drive_skill(), tenant_id="tenant-1", agent_id=None)assert config is None- assert [w["code"] for w in warnings] == ["skill_ref_dangling"]+ assert [w["code"] for w in warnings] == ["drive_ref_dangling"]def test_workflow_run_request_contains_drive_layer_when_flag_enabled(monkeypatch: pytest.MonkeyPatch):@@ -892,6 +951,7 @@ def test_workflow_run_request_contains_drive_layer_when_flag_enabled(monkeypatchmonkeypatch.setattr("core.workflow.nodes.agent_v2.runtime_request_builder.dify_config.AGENT_DRIVE_MANIFEST_ENABLED", True)+ _mock_drive_catalog(monkeypatch)context = _context()context.snapshot.config_snapshot = _soul_with_drive_skill()@@ -904,21 +964,21 @@ def test_workflow_run_request_contains_drive_layer_when_flag_enabled(monkeypatchassert layer_names.index("drive") == layer_names.index("execution_context") + 1drive = next(layer for layer in dumped["composition"]["layers"] if layer["name"] == "drive")assert drive["type"] == "dify.drive"+ assert drive["deps"] == {"execution_context": "execution_context"}assert drive["config"]["drive_ref"] == "agent-agent-1"assert drive["config"]["skills"] == [{+ "path": "tender-analyzer","name": "Tender Analyzer","description": "Parses RFPs.","skill_md_key": "tender-analyzer/SKILL.md","archive_key": "tender-analyzer/.DIFY-SKILL-FULL.zip",}]- assert drive["config"]["files"] == [- {"name": "sample.pdf", "key": "files/sample.pdf", "size": None, "mime_type": "application/pdf"}- ]- # the dangling legacy ref degraded to a warning instead of failing the run+ assert drive["config"]["mentioned_skill_keys"] == ["tender-analyzer/SKILL.md"]+ assert drive["config"]["mentioned_file_keys"] == ["files/sample.pdf"]warnings = result.metadata["runtime_support"]["unsupported_runtime_warnings"]- assert any(w["code"] == "skill_ref_dangling" for w in warnings)+ assert warnings == []# the drive layer is non-sensitive and must survive into persistable specsfrom dify_agent.protocol import extract_runtime_layer_specs@@ -926,6 +986,51 @@ def test_workflow_run_request_contains_drive_layer_when_flag_enabled(monkeypatchassert any(spec.name == "drive" and spec.type == "dify.drive" for spec in specs)+def test_workflow_runtime_expands_drive_mentions_in_agent_soul_prompt(monkeypatch: pytest.MonkeyPatch):+ monkeypatch.setattr(+ "core.workflow.nodes.agent_v2.runtime_request_builder.dify_config.AGENT_DRIVE_MANIFEST_ENABLED", True+ )+ _mock_drive_catalog(monkeypatch)+ context = _context()+ context.snapshot.config_snapshot = _soul_with_drive_skill()++ result = WorkflowAgentRuntimeRequestBuilder(credentials_provider=FakeCredentialsProvider()).build(context)++ soul_prompt = next(layer for layer in result.request.composition.layers if layer.name == "agent_soul_prompt")+ assert soul_prompt.config.prefix == "You are careful. Use Tender Analyzer and sample.pdf."+ assert "[§" not in soul_prompt.config.prefix+++def test_workflow_runtime_missing_drive_mentions_fall_back_to_label_then_decoded_key(monkeypatch: pytest.MonkeyPatch):+ monkeypatch.setattr(+ "core.workflow.nodes.agent_v2.runtime_request_builder.dify_config.AGENT_DRIVE_MANIFEST_ENABLED", True+ )+ monkeypatch.setattr(+ "core.workflow.nodes.agent_v2.runtime_request_builder.AgentDriveService.list_skills",+ lambda self, *, tenant_id, agent_id: [],+ )+ monkeypatch.setattr(+ "core.workflow.nodes.agent_v2.runtime_request_builder.AgentDriveService.manifest",+ lambda self, *, tenant_id, agent_id, prefix="", include_download_url=False: [],+ )+ context = _context()+ context.snapshot.config_snapshot = AgentSoulConfig(+ prompt={+ "system_prompt": (+ "Use [§skill:ghost%2FSKILL.md:Ghost Skill§], [§file:files%2Fghost.txt:Ghost File§], "+ "and [§file:files%2Fno-label.txt§]."+ )+ },+ model=AgentSoulModelConfig(plugin_id="langgenius/openai", model_provider="openai", model="gpt-test"),+ )++ result = WorkflowAgentRuntimeRequestBuilder(credentials_provider=FakeCredentialsProvider()).build(context)++ soul_prompt = next(layer for layer in result.request.composition.layers if layer.name == "agent_soul_prompt")+ assert soul_prompt.config.prefix == "Use Ghost Skill, Ghost File, and files/no-label.txt."+ assert "[§" not in soul_prompt.config.prefix++def test_workflow_run_request_has_no_drive_layer_when_flag_disabled():context = _context()context.snapshot.config_snapshot = _soul_with_drive_skill()@@ -934,20 +1039,20 @@ def test_workflow_run_request_has_no_drive_layer_when_flag_disabled():dumped = result.request.model_dump(mode="json")assert all(layer["name"] != "drive" for layer in dumped["composition"]["layers"])- warnings = result.metadata["runtime_support"]["unsupported_runtime_warnings"]- assert any(w["code"] == "drive_manifest_disabled" for w in warnings)+ assert result.metadata["runtime_support"]["unsupported_runtime_warnings"] == []-def test_build_drive_layer_config_all_refs_dangling_yields_no_config():+def test_build_drive_layer_config_missing_mentions_warn_but_keep_skill_catalog(monkeypatch: pytest.MonkeyPatch):from core.workflow.nodes.agent_v2.runtime_request_builder import build_drive_layer_config+ _mock_drive_catalog(monkeypatch)soul = AgentSoulConfig(model=AgentSoulModelConfig(plugin_id="langgenius/openai", model_provider="openai", model="gpt-test"),- skills_files={"skills": [{"id": "legacy", "name": "Legacy"}], "files": [{"name": "u.pdf", "file_id": "u1"}]},+ prompt={"system_prompt": "Use [§skill:ghost%2FSKILL.md:Ghost§]"},)- config, warnings = build_drive_layer_config(soul, agent_id="agent-1")- assert config is None- assert [w["code"] for w in warnings] == ["skill_ref_dangling"]+ config, warnings = build_drive_layer_config(soul, tenant_id="tenant-1", agent_id="agent-1")+ assert config is not None+ assert [w["code"] for w in warnings] == ["mention_target_missing"]# ── ENG-635: ask_human layer gating + feature manifest ───────────────────────diff --git a/api/tests/unit_tests/migrations/test_agent_drive_skill_metadata_refactor.py b/api/tests/unit_tests/migrations/test_agent_drive_skill_metadata_refactor.pynew file mode 100644index 00000000000..cd97559725e--- /dev/null+++ b/api/tests/unit_tests/migrations/test_agent_drive_skill_metadata_refactor.py@@ -0,0 +1,122 @@+from __future__ import annotations++import importlib.util+import json+from pathlib import Path++import sqlalchemy as sa+from alembic.migration import MigrationContext+from alembic.operations import Operations++_MIGRATION_PATH = (+ Path(__file__).resolve().parents[3]+ / "migrations/versions/2026_06_18_2300-b2515f9d4c2a_agent_drive_skill_metadata_refactor.py"+)+++def _load_migration_module():+ spec = importlib.util.spec_from_file_location("agent_drive_skill_metadata_refactor", _MIGRATION_PATH)+ if spec is None or spec.loader is None:+ raise RuntimeError("failed to load migration module")+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++def _create_pre_upgrade_schema(engine: sa.Engine) -> None:+ metadata = sa.MetaData()+ sa.Table(+ "agent_drive_files",+ metadata,+ sa.Column("tenant_id", sa.String(36), nullable=False),+ sa.Column("agent_id", sa.String(36), nullable=False),+ sa.Column("key", sa.String(512), nullable=False),+ sa.Column("file_kind", sa.String(32), nullable=False),+ sa.Column("file_id", sa.String(36), nullable=False),+ sa.Column("value_owned_by_drive", sa.Boolean(), nullable=False, server_default=sa.text("false")),+ sa.Column("size", sa.BigInteger(), nullable=True),+ sa.Column("hash", sa.String(255), nullable=True),+ sa.Column("mime_type", sa.String(255), nullable=True),+ sa.Column("created_by", sa.String(36), nullable=True),+ sa.Column("id", sa.String(36), primary_key=True),+ sa.Column("created_at", sa.DateTime(), nullable=False),+ sa.Column("updated_at", sa.DateTime(), nullable=False),+ sa.UniqueConstraint("tenant_id", "agent_id", "key", name="agent_drive_file_scope_key_unique"),+ )+ sa.Table(+ "agent_config_snapshots",+ metadata,+ sa.Column("id", sa.String(36), primary_key=True),+ sa.Column("config_snapshot", sa.Text(), nullable=False),+ )+ metadata.create_all(engine)+++def _run_migration_step(module: object, engine: sa.Engine, step_name: str) -> None:+ with engine.begin() as connection:+ context = MigrationContext.configure(connection)+ operations = Operations(context)+ original_op = module.op+ module.op = operations+ try:+ getattr(module, step_name)()+ finally:+ module.op = original_op+++def test_upgrade_adds_skill_columns_and_index_and_strips_snapshot_data() -> None:+ engine = sa.create_engine("sqlite:///:memory:")+ _create_pre_upgrade_schema(engine)+ snapshot = {+ "prompt": {"system_prompt": "Use [§skill:legacy:Legacy§]"},+ "skills_files": {"skills": [{"name": "Legacy"}], "files": [{"name": "u.pdf"}]},+ }+ with engine.begin() as connection:+ connection.execute(+ sa.text("INSERT INTO agent_config_snapshots (id, config_snapshot) VALUES (:id, :config_snapshot)"),+ {"id": "snap-1", "config_snapshot": json.dumps(snapshot)},+ )++ module = _load_migration_module()+ _run_migration_step(module, engine, "upgrade")++ inspector = sa.inspect(engine)+ columns = {column["name"] for column in inspector.get_columns("agent_drive_files")}+ assert {"is_skill", "skill_metadata"}.issubset(columns)+ indexes = {index["name"] for index in inspector.get_indexes("agent_drive_files")}+ assert "agent_drive_files_tenant_agent_is_skill_key_idx" in indexes++ with engine.begin() as connection:+ stored_snapshot = connection.execute(+ sa.text("SELECT config_snapshot FROM agent_config_snapshots WHERE id = :id"),+ {"id": "snap-1"},+ ).scalar_one()+ assert "skills_files" not in json.loads(stored_snapshot)+++def test_downgrade_drops_skill_columns_and_index_without_reconstructing_legacy_data() -> None:+ engine = sa.create_engine("sqlite:///:memory:")+ _create_pre_upgrade_schema(engine)+ with engine.begin() as connection:+ connection.execute(+ sa.text("INSERT INTO agent_config_snapshots (id, config_snapshot) VALUES (:id, :config_snapshot)"),+ {"id": "snap-1", "config_snapshot": json.dumps({"prompt": {"system_prompt": "hello"}})},+ )++ module = _load_migration_module()+ _run_migration_step(module, engine, "upgrade")+ _run_migration_step(module, engine, "downgrade")++ inspector = sa.inspect(engine)+ columns = {column["name"] for column in inspector.get_columns("agent_drive_files")}+ assert "is_skill" not in columns+ assert "skill_metadata" not in columns+ indexes = {index["name"] for index in inspector.get_indexes("agent_drive_files")}+ assert "agent_drive_files_tenant_agent_is_skill_key_idx" not in indexes++ with engine.begin() as connection:+ stored_snapshot = connection.execute(+ sa.text("SELECT config_snapshot FROM agent_config_snapshots WHERE id = :id"),+ {"id": "snap-1"},+ ).scalar_one()+ assert "skills_files" not in json.loads(stored_snapshot)diff --git a/api/tests/unit_tests/services/agent/test_agent_services.py b/api/tests/unit_tests/services/agent/test_agent_services.pyindex 01db8caede4..2cad3d81af1 100644--- a/api/tests/unit_tests/services/agent/test_agent_services.py+++ b/api/tests/unit_tests/services/agent/test_agent_services.py@@ -17,7 +17,6 @@ from models.agent import (WorkflowAgentNodeBinding,)from models.agent_config_entities import (- AgentFileRefConfig,DeclaredArrayItem,DeclaredOutputChildConfig,DeclaredOutputConfig,@@ -2649,18 +2648,17 @@ def test_workspace_dify_tools_returns_provider_and_tool_granularities(monkeypatcassert {entry["granularity"] for entry in entries[1:]} == {"tool"}-# ── ENG-623 §4.4: drive-backed ref validation ────────────────────────────────+# ── ENG-623 §4.4: drive-backed prompt mention validation ─────────────────────def _drive_soul(**overrides):from services.entities.agent_entities import AgentSoulConfigbase = {- "skills_files": {- "skills": [- {"id": "sk-1", "name": "Tender Analyzer", "skill_md_key": "tender-analyzer/SKILL.md"},- ],- "files": [{"name": "sample.pdf", "drive_key": "files/sample.pdf"}],+ "prompt": {+ "system_prompt": (+ "Use [§skill:tender-analyzer%2FSKILL.md:Tender Analyzer§] and [§file:files%2Fsample.pdf:sample.pdf§]."+ )},}base.update(overrides)@@ -2680,47 +2678,47 @@ def _patch_drive_keys(monkeypatch, existing_keys):return captured-def test_drive_ref_findings_reports_missing_keys(monkeypatch: pytest.MonkeyPatch):+def test_drive_mention_findings_reports_missing_keys(monkeypatch: pytest.MonkeyPatch):_patch_drive_keys(monkeypatch, existing_keys=["tender-analyzer/SKILL.md"])- findings = AgentComposerService._drive_ref_findings(- tenant_id="tenant-1", agent_id="agent-1", agent_soul=_drive_soul()+ findings = AgentComposerService._drive_mention_findings(+ tenant_id="tenant-1",+ agent_id="agent-1",+ prompt=_drive_soul().prompt.system_prompt,)- assert [(f["code"], f["id"]) for f in findings] == [("file_ref_dangling", "files/sample.pdf")]- assert str(findings[0]["message"]).startswith("file_ref_dangling: ")+ assert [(f["code"], f["id"]) for f in findings] == [("mention_target_missing", "files/sample.pdf")]+ assert findings[0]["kind"] == "file"+ assert str(findings[0]["message"]).startswith("file 'sample.pdf' has no drive entry")-def test_drive_ref_findings_clean_when_all_keys_exist(monkeypatch: pytest.MonkeyPatch):+def test_drive_mention_findings_clean_when_all_keys_exist(monkeypatch: pytest.MonkeyPatch):_patch_drive_keys(monkeypatch, existing_keys=["tender-analyzer/SKILL.md", "files/sample.pdf"])assert (- AgentComposerService._drive_ref_findings(tenant_id="tenant-1", agent_id="agent-1", agent_soul=_drive_soul())+ AgentComposerService._drive_mention_findings(+ tenant_id="tenant-1",+ agent_id="agent-1",+ prompt=_drive_soul().prompt.system_prompt,+ )== [])-def test_drive_ref_findings_skips_refs_without_drive_keys(monkeypatch: pytest.MonkeyPatch):- # No drive-backed ref at all -> no DB roundtrip, no findings.- soul = _drive_soul(- skills_files={"skills": [{"id": "legacy", "name": "Legacy"}], "files": [{"name": "u.pdf", "file_id": "u-1"}]}+def test_drive_mention_findings_skips_prompt_without_drive_mentions(monkeypatch: pytest.MonkeyPatch):+ # No drive-backed mention at all -> no DB roundtrip, no findings.+ soul = _drive_soul(prompt={"system_prompt": "Use [§knowledge:kb-1:Docs§]."})+ findings = AgentComposerService._drive_mention_findings(+ tenant_id="tenant-1",+ agent_id="agent-1",+ prompt=soul.prompt.system_prompt,)- findings = AgentComposerService._drive_ref_findings(tenant_id="tenant-1", agent_id="agent-1", agent_soul=soul)assert findings == []-def test_require_drive_refs_resolved_raises_with_stable_code(monkeypatch: pytest.MonkeyPatch):- from services.agent.errors import InvalidComposerConfigError-- _patch_drive_keys(monkeypatch, existing_keys=[])-- with pytest.raises(InvalidComposerConfigError, match="skill_ref_dangling"):- AgentComposerService._require_drive_refs_resolved(- tenant_id="tenant-1", agent_id="agent-1", agent_soul=_drive_soul()- )---def test_collect_validation_findings_appends_drive_findings_with_agent_context(monkeypatch: pytest.MonkeyPatch):+def test_collect_validation_findings_appends_drive_mention_findings_with_agent_context(+ monkeypatch: pytest.MonkeyPatch,+):from services.entities.agent_entities import ComposerSavePayload_patch_drive_keys(monkeypatch, existing_keys=[])@@ -2737,149 +2735,14 @@ def test_collect_validation_findings_appends_drive_findings_with_agent_context(m)codes = {w["code"] for w in findings["warnings"]}- assert {"skill_ref_dangling", "file_ref_dangling"} <= codes+ assert codes >= {"mention_target_missing"}+ assert {w["id"] for w in findings["warnings"] if w["code"] == "mention_target_missing"} == {+ "tender-analyzer/SKILL.md",+ "files/sample.pdf",+ }# without agent context the drive check is skipped entirelyfindings_no_agent = AgentComposerService.collect_validation_findings(tenant_id="tenant-1", payload=payload)- assert all(w["code"] not in {"skill_ref_dangling", "file_ref_dangling"} for w in findings_no_agent["warnings"])---# ── ENG-625 D5: soul-first ref removal ───────────────────────────────────────---def _patch_remove_drive_refs_env(monkeypatch: pytest.MonkeyPatch, *, soul_dict):- """Wire the classmethod's collaborators so soul editing + versioning is observable."""- from types import SimpleNamespace-- import services.agent.composer_service as module-- agent = SimpleNamespace(id="agent-1", active_config_snapshot_id="snap-1", updated_by=None)- snapshot = SimpleNamespace(id="snap-1", tenant_id="tenant-1", agent_id="agent-1", config_snapshot_dict=soul_dict)- committed: dict[str, object] = {}-- fake_session = SimpleNamespace(scalar=lambda stmt: agent, commit=lambda: committed.setdefault("committed", True))- monkeypatch.setattr(module.db, "session", fake_session)- monkeypatch.setattr(AgentComposerService, "_require_version", classmethod(lambda cls, **kwargs: snapshot))-- captured: dict[str, object] = {}-- def fake_update(cls, *, current_snapshot, account_id, agent_soul, operation, version_note):- captured["agent_soul"] = agent_soul- captured["version_note"] = version_note- return SimpleNamespace(id="snap-2")-- monkeypatch.setattr(AgentComposerService, "_update_current_version", classmethod(fake_update))- return agent, captured, committed---def test_remove_drive_refs_drops_skill_by_slug_and_versions(monkeypatch: pytest.MonkeyPatch):- soul_dict = {- "skills_files": {- "skills": [- {"id": "sk-1", "name": "Tender Analyzer", "skill_md_key": "tender-analyzer/SKILL.md"},- {"id": "sk-2", "name": "Other", "skill_md_key": "other-skill/SKILL.md"},- ],- "files": [],- }- }- agent, captured, committed = _patch_remove_drive_refs_env(monkeypatch, soul_dict=soul_dict)-- version_id = AgentComposerService.remove_drive_refs(- tenant_id="tenant-1", agent_id="agent-1", account_id="acc-1", skill_slug="tender-analyzer"- )-- assert version_id == "snap-2"- assert agent.active_config_snapshot_id == "snap-2"- kept = [s.skill_md_key for s in captured["agent_soul"].skills_files.skills]- assert kept == ["other-skill/SKILL.md"]- assert "Tender Analyzer" in str(captured["version_note"])- assert committed.get("committed") is True---def test_remove_drive_refs_is_noop_when_ref_absent(monkeypatch: pytest.MonkeyPatch):- soul_dict = {"skills_files": {"skills": [], "files": []}}- agent, captured, committed = _patch_remove_drive_refs_env(monkeypatch, soul_dict=soul_dict)-- assert (- AgentComposerService.remove_drive_refs(- tenant_id="tenant-1", agent_id="agent-1", account_id="acc-1", file_key="files/none.pdf"- )- is None- )- assert "agent_soul" not in captured- assert committed == {}---def test_remove_drive_refs_drops_file_by_key(monkeypatch: pytest.MonkeyPatch):- soul_dict = {- "skills_files": {- "skills": [],- "files": [- {"name": "keep.pdf", "drive_key": "files/keep.pdf"},- {"name": "drop.pdf", "drive_key": "files/drop.pdf"},- ],- }- }- _, captured, _ = _patch_remove_drive_refs_env(monkeypatch, soul_dict=soul_dict)-- version_id = AgentComposerService.remove_drive_refs(- tenant_id="tenant-1", agent_id="agent-1", account_id="acc-1", file_key="files/drop.pdf"- )-- assert version_id == "snap-2"- assert [f.drive_key for f in captured["agent_soul"].skills_files.files] == ["files/keep.pdf"]---def test_add_drive_file_ref_adds_or_replaces_file_and_versions(monkeypatch: pytest.MonkeyPatch):- soul_dict = {- "skills_files": {- "skills": [],- "files": [- {"name": "old.pdf", "drive_key": "files/old.pdf"},- {"name": "stale.pdf", "drive_key": "files/new.pdf"},- ],- }- }- agent, captured, committed = _patch_remove_drive_refs_env(monkeypatch, soul_dict=soul_dict)-- version_id = AgentComposerService.add_drive_file_ref(- tenant_id="tenant-1",- agent_id="agent-1",- account_id="acc-1",- file_ref=AgentFileRefConfig(name="new.pdf", file_id="uf-1", drive_key="files/new.pdf", type="application/pdf"),- )-- assert version_id == "snap-2"- assert agent.active_config_snapshot_id == "snap-2"- assert [f.drive_key for f in captured["agent_soul"].skills_files.files] == ["files/old.pdf", "files/new.pdf"]- assert captured["agent_soul"].skills_files.files[-1].name == "new.pdf"- assert "new.pdf" in str(captured["version_note"])- assert committed.get("committed") is True---def test_add_drive_file_ref_syncs_workflow_binding_snapshot(monkeypatch: pytest.MonkeyPatch):- binding = SimpleNamespace(agent_id="agent-1", current_snapshot_id="snap-1", updated_by=None)- _patch_remove_drive_refs_env(monkeypatch, soul_dict={"skills_files": {"skills": [], "files": []}})- monkeypatch.setattr(- AgentComposerService, "_get_draft_workflow", classmethod(lambda cls, **kwargs: SimpleNamespace(id="wf-1"))- )- monkeypatch.setattr(AgentComposerService, "_get_workflow_binding", classmethod(lambda cls, **kwargs: binding))-- AgentComposerService.add_drive_file_ref(- tenant_id="tenant-1",- agent_id="agent-1",- account_id="acc-1",- file_ref=AgentFileRefConfig(name="new.pdf", file_id="uf-1", drive_key="files/new.pdf"),- app_id="app-1",- node_id="agent-node-1",- )-- assert binding.current_snapshot_id == "snap-2"- assert binding.updated_by == "acc-1"---def test_remove_drive_refs_requires_exactly_one_scope():- with pytest.raises(ValueError):- AgentComposerService.remove_drive_refs(tenant_id="t", agent_id="a", account_id="u")+ assert all(w["code"] != "mention_target_missing" for w in findings_no_agent["warnings"])# ── ENG-623/625: resolver helpers + save-path drive guard ────────────────────@@ -2917,58 +2780,7 @@ def test_resolve_workflow_node_agent_id_degrades_without_workflow_or_binding(monassert AgentComposerService.resolve_workflow_node_agent_id(tenant_id="t", app_id="a", node_id="n") == "agent-7"-def test_remove_drive_refs_returns_none_without_agent_or_snapshot(monkeypatch: pytest.MonkeyPatch):- from types import SimpleNamespace-- import services.agent.composer_service as module-- monkeypatch.setattr(module.db, "session", SimpleNamespace(scalar=lambda stmt: None))- assert AgentComposerService.remove_drive_refs(tenant_id="t", agent_id="a", account_id="u", skill_slug="s") is None-- agent_without_snapshot = SimpleNamespace(id="a", active_config_snapshot_id=None)- monkeypatch.setattr(module.db, "session", SimpleNamespace(scalar=lambda stmt: agent_without_snapshot))- assert AgentComposerService.remove_drive_refs(tenant_id="t", agent_id="a", account_id="u", skill_slug="s") is None---def test_save_workflow_composer_guards_drive_refs_for_existing_agent_strategies(monkeypatch: pytest.MonkeyPatch):- from types import SimpleNamespace-- from services.entities.agent_entities import ComposerSavePayload-- payload = ComposerSavePayload.model_validate(- {- "variant": "workflow",- "save_strategy": "save_to_current_version",- "agent_soul": _drive_soul().model_dump(mode="json"),- "soul_lock": {"locked": False},- }- )- monkeypatch.setattr(- AgentComposerService, "_get_draft_workflow", classmethod(lambda cls, **kwargs: SimpleNamespace(id="wf-1"))- )- monkeypatch.setattr(- AgentComposerService,- "_get_workflow_binding",- classmethod(lambda cls, **kwargs: SimpleNamespace(agent_id="agent-1")),- )- guarded: dict[str, str] = {}-- def fake_guard(cls, *, tenant_id, agent_id, agent_soul):- guarded["agent_id"] = agent_id- raise InvalidComposerConfigError("skill_ref_dangling: boom")-- from services.agent.errors import InvalidComposerConfigError-- monkeypatch.setattr(AgentComposerService, "_require_drive_refs_resolved", classmethod(fake_guard))-- with pytest.raises(InvalidComposerConfigError, match="skill_ref_dangling"):- AgentComposerService.save_workflow_composer(- tenant_id="t-1", app_id="app-1", node_id="n-1", account_id="acc-1", payload=payload- )- assert guarded["agent_id"] == "agent-1"---def test_save_workflow_composer_guards_drive_refs_for_inline_node_job_only(monkeypatch: pytest.MonkeyPatch):+def test_save_workflow_composer_reports_drive_mentions_for_inline_node_job_only(monkeypatch: pytest.MonkeyPatch):payload = ComposerSavePayload.model_validate({"variant": "workflow",@@ -3006,26 +2818,27 @@ def test_save_workflow_composer_guards_drive_refs_for_inline_node_job_only(monkemonkeypatch.setattr(AgentComposerService, "_serialize_workflow_state", classmethod(lambda cls, **kwargs: {"state": "ok"}))- monkeypatch.setattr(- AgentComposerService, "collect_validation_findings", classmethod(lambda cls, **kwargs: {"warnings": []})- )guarded: dict[str, str] = {}- def fake_guard(cls, *, tenant_id, agent_id, agent_soul):+ def fake_collect(cls, *, tenant_id, payload, agent_id=None):guarded["tenant_id"] = tenant_idguarded["agent_id"] = agent_id+ return {"warnings": [{"code": "mention_target_missing", "id": "files/sample.pdf"}]}- monkeypatch.setattr(AgentComposerService, "_require_drive_refs_resolved", classmethod(fake_guard))+ monkeypatch.setattr(AgentComposerService, "collect_validation_findings", classmethod(fake_collect))result = AgentComposerService.save_workflow_composer(tenant_id="t-1", app_id="app-1", node_id="n-1", account_id="acc-1", payload=payload)- assert result == {"state": "ok", "validation": {"warnings": []}}+ assert result == {+ "state": "ok",+ "validation": {"warnings": [{"code": "mention_target_missing", "id": "files/sample.pdf"}]},+ }assert guarded == {"tenant_id": "t-1", "agent_id": "agent-1"}-def test_save_workflow_composer_skips_drive_refs_for_roster_node_job_only(monkeypatch: pytest.MonkeyPatch):+def test_save_workflow_composer_reports_drive_mentions_for_roster_node_job_only(monkeypatch: pytest.MonkeyPatch):payload = ComposerSavePayload.model_validate({"variant": "workflow",@@ -3063,29 +2876,17 @@ def test_save_workflow_composer_skips_drive_refs_for_roster_node_job_only(monkeymonkeypatch.setattr(AgentComposerService, "_serialize_workflow_state", classmethod(lambda cls, **kwargs: {"state": "ok"}))- monkeypatch.setattr(- AgentComposerService, "collect_validation_findings", classmethod(lambda cls, **kwargs: {"warnings": []})- )+ captured: dict[str, str | None] = {}- def fail_guard(cls, *, tenant_id, agent_id, agent_soul):- raise AssertionError("roster node-job-only saves must not validate agent drive refs")+ def fake_collect(cls, *, tenant_id, payload, agent_id=None):+ captured["agent_id"] = agent_id+ return {"warnings": []}- monkeypatch.setattr(AgentComposerService, "_require_drive_refs_resolved", classmethod(fail_guard))+ monkeypatch.setattr(AgentComposerService, "collect_validation_findings", classmethod(fake_collect))result = AgentComposerService.save_workflow_composer(tenant_id="t-1", app_id="app-1", node_id="n-1", account_id="acc-1", payload=payload)assert result == {"state": "ok", "validation": {"warnings": []}}---def test_remove_drive_refs_noop_when_skill_slug_unmatched(monkeypatch: pytest.MonkeyPatch):- soul_dict = {"skills_files": {"skills": [{"name": "Other", "skill_md_key": "other/SKILL.md"}], "files": []}}- _, captured, committed = _patch_remove_drive_refs_env(monkeypatch, soul_dict=soul_dict)- assert (- AgentComposerService.remove_drive_refs(- tenant_id="t-1", agent_id="agent-1", account_id="acc-1", skill_slug="ghost"- )- is None- )- assert committed == {}+ assert captured["agent_id"] == "agent-1"diff --git a/api/tests/unit_tests/services/agent/test_composer_candidates.py b/api/tests/unit_tests/services/agent/test_composer_candidates.pyindex 5eb9acf8b81..863ebafc994 100644--- a/api/tests/unit_tests/services/agent/test_composer_candidates.py+++ b/api/tests/unit_tests/services/agent/test_composer_candidates.py@@ -118,10 +118,6 @@ def test_previous_outputs_capped_and_flagged():def _soul() -> AgentSoulConfig:return AgentSoulConfig.model_validate({- "skills_files": {- "skills": [{"id": "sk-1", "name": "tender-analyzer"}],- "files": [{"id": "f-1", "name": "qna_report.pdf"}],- },"tools": {"cli_tools": [{"id": "ct-1", "name": "ffmpeg"},@@ -144,7 +140,6 @@ def test_soul_candidates_lists_configured_items_only():)assert truncated is False- assert [item["kind"] for item in lists["skills_files"]] == ["skill", "file"]assert [item["name"] for item in lists["cli_tools"]] == ["ffmpeg"]# the stable mention id flows through so the frontend can mint [§cli_tool:<id>§]assert [item["id"] for item in lists["cli_tools"]] == ["ct-1"]@@ -158,35 +153,19 @@ def test_soul_candidates_lists_configured_items_only():assert lists["dify_tools"][0]["id"] == "tavily/tavily_search"-def test_candidates_response_preserves_skill_and_file_candidate_shapes():+def test_candidates_response_omits_legacy_skill_file_candidates():response = AgentComposerCandidatesResponse.model_validate({"variant": "agent_app","allowed_node_job_candidates": {},"allowed_soul_candidates": {- "skills_files": [- {"kind": "skill", "id": "sk-1", "name": "tender-analyzer", "path": "skills/tender.md"},- {- "kind": "file",- "id": "f-1",- "name": "qna_report.pdf",- "transfer_method": "local_file",- "reference": "upload-1",- "url": "https://files.example/qna_report.pdf",- },- ]+ "cli_tools": [],},"capabilities": {"human_roster_available": False},}).model_dump(mode="json")- skill, file = response["allowed_soul_candidates"]["skills_files"]- assert skill["kind"] == "skill"- assert skill["path"] == "skills/tender.md"- assert file["kind"] == "file"- assert file["transfer_method"] == "local_file"- assert file["reference"] == "upload-1"- assert file["url"] == "https://files.example/qna_report.pdf"+ assert "skills_files" not in response["allowed_soul_candidates"]def test_soul_candidates_empty_config_yields_empty_lists():diff --git a/api/tests/unit_tests/services/agent/test_composer_mention_validation.py b/api/tests/unit_tests/services/agent/test_composer_mention_validation.pyindex e332b48ab1e..ffbec86f4e6 100644--- a/api/tests/unit_tests/services/agent/test_composer_mention_validation.py+++ b/api/tests/unit_tests/services/agent/test_composer_mention_validation.py@@ -171,7 +171,6 @@ def test_configured_but_deleted_dataset_surfaces_as_placeholder():def test_unresolved_non_knowledge_mentions_warn_target_missing():findings = _findings(_soul_payload("use [§skill:nope:Ghost Skill§] and [§human:missing§]"))codes = [(w["code"], w["kind"]) for w in findings["warnings"]]- assert ("mention_target_missing", "skill") in codesassert ("mention_target_missing", "human") in codesassert findings["knowledge_retrieval_placeholder"] == []diff --git a/api/tests/unit_tests/services/agent/test_prompt_mentions.py b/api/tests/unit_tests/services/agent/test_prompt_mentions.pyindex b85a0a752e1..b8b908d432f 100644--- a/api/tests/unit_tests/services/agent/test_prompt_mentions.py+++ b/api/tests/unit_tests/services/agent/test_prompt_mentions.py@@ -7,11 +7,13 @@ guarantees no mention-shaped marker survives to the model.from __future__ import annotations+from urllib.parse import quote+import pytestfrom models.agent_config_entities import AgentSoulConfig, WorkflowNodeJobConfigfrom services.agent.prompt_mentions import (- MAX_MENTION_FIELD_LENGTH,+ MAX_MENTION_REF_ID_LENGTH,NODE_JOB_PROMPT_ALLOWED_KINDS,SOUL_PROMPT_ALLOWED_KINDS,MentionKind,@@ -26,11 +28,11 @@ from services.agent.prompt_mentions import (def test_parse_extracts_kind_id_and_optional_label():- prompt = "Use [§skill:abc-1:tender-analyzer§] then ask [§human:c-1§]."+ prompt = "Use [§skill:tender-analyzer%2FSKILL.md:tender-analyzer§] then ask [§human:c-1§]."mentions = parse_prompt_mentions(prompt)assert [(m.kind, m.ref_id, m.label) for m in mentions] == [- (MentionKind.SKILL, "abc-1", "tender-analyzer"),+ (MentionKind.SKILL, "tender-analyzer%2FSKILL.md", "tender-analyzer"),(MentionKind.HUMAN, "c-1", None),]assert prompt[mentions[0].start : mentions[0].end] == mentions[0].raw@@ -48,10 +50,16 @@ def test_parse_ignores_legacy_template_forms_and_unknown_kinds():def test_parse_skips_oversized_id_or_label():- long_id = "x" * (MAX_MENTION_FIELD_LENGTH + 1)+ long_id = "x" * (MAX_MENTION_REF_ID_LENGTH + 1)assert parse_prompt_mentions(f"[§skill:{long_id}§]") == []+def test_parse_accepts_long_unicode_encoded_drive_key_within_drive_limit():+ encoded_drive_key = quote("你" * 512)+ mentions = parse_prompt_mentions(f"[§skill:{encoded_drive_key}:Long Skill§]")+ assert [(mention.kind, mention.ref_id) for mention in mentions] == [(MentionKind.SKILL, encoded_drive_key)]++# ── expand + scrub ────────────────────────────────────────────────────────────@@ -88,10 +96,6 @@ def test_expand_empty_prompt_is_noop():def soul() -> AgentSoulConfig:return AgentSoulConfig.model_validate({- "skills_files": {- "skills": [{"id": "sk-1", "name": "tender-analyzer"}],- "files": [{"id": "f-1", "name": "qna_report.pdf"}],- },"tools": {"dify_tools": [{@@ -112,17 +116,13 @@ def soul() -> AgentSoulConfig:def test_soul_resolver_resolves_each_kind(soul: AgentSoulConfig):resolver = build_soul_mention_resolver(soul)prompt = (- "Use [§skill:sk-1§] with [§file:f-1§], search via "- "[§tool:tavily/tavily_search:tavily§], run [§cli_tool:ct-1:ffmpeg§], "+ "Use [§tool:tavily/tavily_search:tavily§], run [§cli_tool:ct-1:ffmpeg§], ""ground in [§knowledge:ds-1§], ask [§human:c-1§].")expanded = expand_prompt_mentions(prompt, resolver)- assert expanded == (- "Use tender-analyzer with qna_report.pdf, search via tavily_search, "- "run ffmpeg, ground in 产品手册, ask EMAIL · David Hayes."- )+ assert expanded == ("Use tavily_search, run ffmpeg, ground in 产品手册, ask EMAIL · David Hayes.")def test_soul_resolver_unknown_ids_degrade(soul: AgentSoulConfig):diff --git a/api/tests/unit_tests/services/agent/test_skill_package_service.py b/api/tests/unit_tests/services/agent/test_skill_package_service.pyindex a29f641cfe2..c88b72b3fcc 100644--- a/api/tests/unit_tests/services/agent/test_skill_package_service.py+++ b/api/tests/unit_tests/services/agent/test_skill_package_service.py@@ -121,16 +121,3 @@ def test_read_member_bytes_roundtrip_and_errors():with pytest.raises(SkillPackageError) as bad_zip:service.read_member_bytes(content=b"not a zip", member_path="SKILL.md")assert bad_zip.value.code == "invalid_archive"---def test_to_skill_ref_carries_metadata():- manifest = _extract({"SKILL.md": _SKILL_MD.encode()})- ref = manifest.to_skill_ref(file_id="upload-1", path="pdf-toolkit/.DIFY-SKILL-FULL.zip")-- assert ref.name == "PDF Toolkit"- assert ref.file_id == "upload-1"- assert ref.path == "pdf-toolkit/.DIFY-SKILL-FULL.zip"- assert ref.id == manifest.hash- dumped = ref.model_dump()- assert dumped["hash"] == manifest.hash- assert dumped["entry_path"] == "SKILL.md"diff --git a/api/tests/unit_tests/services/agent/test_skill_standardize_service.py b/api/tests/unit_tests/services/agent/test_skill_standardize_service.pyindex cd27e1b40d0..fa47c9bd905 100644--- a/api/tests/unit_tests/services/agent/test_skill_standardize_service.py+++ b/api/tests/unit_tests/services/agent/test_skill_standardize_service.py@@ -43,6 +43,19 @@ def test_standardize_creates_drive_owned_toolfiles_and_commits_archive_members()]drive = MagicMock()drive.commit.return_value = []+ drive.list_skills.return_value = [+ {+ "path": "pdf-toolkit",+ "skill_md_key": "pdf-toolkit/SKILL.md",+ "archive_key": "pdf-toolkit/.DIFY-SKILL-FULL.zip",+ "name": "PDF Toolkit",+ "description": "Work with PDFs.",+ "size": len(_SKILL_MD),+ "mime_type": "text/markdown",+ "hash": None,+ "created_at": None,+ },+ ]service = SkillStandardizeService(tool_file_manager=tool_files, drive_service=drive)result = service.standardize(@@ -76,18 +89,16 @@ def test_standardize_creates_drive_owned_toolfiles_and_commits_archive_members()assert all(item.value_owned_by_drive for item in items)assert [item.file_ref.id for item in items] == ["md-tool-file", "zip-tool-file", "script-tool-file"]assert items[0].is_skill is True+ assert items[0].skill_metadata is not Noneassert items[0].skill_metadata.name == "PDF Toolkit"assert items[0].skill_metadata.manifest_files == ["SKILL.md", "scripts/run.py"]assert items[1].is_skill is Falseassert items[2].is_skill is False- # The returned skill ref carries stable drive paths + file ids.+ # The returned upload response carries only the drive-derived fields the UI needs.skill = result["skill"]assert skill["path"] == "pdf-toolkit"assert skill["name"] == "PDF Toolkit"- assert skill["full_archive_file_id"] == "zip-tool-file"- assert skill["skill_md_file_id"] == "md-tool-file"+ assert skill["archive_key"] == "pdf-toolkit/.DIFY-SKILL-FULL.zip"assert skill["skill_md_key"] == "pdf-toolkit/SKILL.md"- # ENG-371: zip member listing persisted for infer-tools signals- assert "SKILL.md" in skill["manifest_files"]- assert "scripts/run.py" in skill["manifest_files"]+ assert result["manifest"]["files"] == ["SKILL.md", "scripts/run.py"]diff --git a/api/tests/unit_tests/services/agent/test_skill_tool_inference_service.py b/api/tests/unit_tests/services/agent/test_skill_tool_inference_service.pyindex c0b6e6490f4..25678bb4f4d 100644--- a/api/tests/unit_tests/services/agent/test_skill_tool_inference_service.py+++ b/api/tests/unit_tests/services/agent/test_skill_tool_inference_service.py@@ -29,13 +29,8 @@ def _service(preview=_SKILL_MD_PREVIEW):return SkillToolInferenceService(drive_service=drive), drive-def _patch_soul_files(monkeypatch, files):- monkeypatch.setattr(SkillToolInferenceService, "_manifest_files_from_soul", staticmethod(lambda **kwargs: files))---def test_infer_returns_suggestions_with_inferred_from(monkeypatch: pytest.MonkeyPatch):+def test_infer_returns_suggestions_with_inferred_from(monkeypatch):service, drive = _service()- _patch_soul_files(monkeypatch, ["SKILL.md", "scripts/transcribe.sh"])raw = ('{"inferable": true, "reason": null, "cli_tools": [{"name": "ffmpeg",'' "description": "transcoding for step 2", "command": "ffmpeg",'@@ -53,9 +48,8 @@ def test_infer_returns_suggestions_with_inferred_from(monkeypatch: pytest.Monkeydrive.preview.assert_called_once_with(tenant_id="t-1", agent_id="a-1", key="audio-transcribe/SKILL.md")-def test_infer_threads_manifest_files_into_the_prompt(monkeypatch: pytest.MonkeyPatch):+def test_infer_threads_skill_md_into_the_prompt(monkeypatch):service, _ = _service()- _patch_soul_files(monkeypatch, ["scripts/run.sh"])captured: dict[str, str] = {}def fake_invoke(*, tenant_id, user_prompt):@@ -65,22 +59,20 @@ def test_infer_threads_manifest_files_into_the_prompt(monkeypatch: pytest.Monkeywith patch.object(SkillToolInferenceService, "_invoke", staticmethod(fake_invoke)):service.infer(tenant_id="t-1", agent_id="a-1", slug="audio-transcribe")- assert "scripts/run.sh" in captured["prompt"]+ assert "Files inside the skill package" not in captured["prompt"]assert "ffmpeg" in captured["prompt"] # SKILL.md body present-def test_infer_not_inferable_passes_reason_through(monkeypatch: pytest.MonkeyPatch):+def test_infer_not_inferable_passes_reason_through(monkeypatch):service, _ = _service()- _patch_soul_files(monkeypatch, [])raw = '{"inferable": false, "cli_tools": [], "reason": "SKILL.md 未描述任何外部命令依赖"}'with patch.object(SkillToolInferenceService, "_invoke", staticmethod(lambda **kwargs: raw)):result = service.infer(tenant_id="t-1", agent_id="a-1", slug="audio-transcribe")assert result == {"inferable": False, "cli_tools": [], "reason": "SKILL.md 未描述任何外部命令依赖"}-def test_infer_retries_once_then_422(monkeypatch: pytest.MonkeyPatch):+def test_infer_retries_once_then_422(monkeypatch):service, _ = _service()- _patch_soul_files(monkeypatch, [])calls: list[int] = []def bad_invoke(**kwargs):@@ -96,9 +88,8 @@ def test_infer_retries_once_then_422(monkeypatch: pytest.MonkeyPatch):assert exc_info.value.status_code == 422-def test_infer_repairs_slightly_malformed_json(monkeypatch: pytest.MonkeyPatch):+def test_infer_repairs_slightly_malformed_json(monkeypatch):service, _ = _service()- _patch_soul_files(monkeypatch, [])raw = 'Here you go: {"inferable": true, "cli_tools": [], "reason": null,}'with patch.object(SkillToolInferenceService, "_invoke", staticmethod(lambda **kwargs: raw)):result = service.infer(tenant_id="t-1", agent_id="a-1", slug="audio-transcribe")@@ -123,10 +114,10 @@ def test_binary_skill_md_maps_to_404():assert exc_info.value.code == "skill_not_found"-# ── real-path coverage: _invoke / _manifest_files_from_soul / passthrough ────+# ── real-path coverage: _invoke / passthrough ────────────────────────────────-def test_invoke_maps_missing_default_model_to_400(monkeypatch: pytest.MonkeyPatch):+def test_invoke_maps_missing_default_model_to_400(monkeypatch):import services.agent.skill_tool_inference_service as modulefrom core.errors.error import ProviderTokenNotInitError@@ -140,7 +131,7 @@ def test_invoke_maps_missing_default_model_to_400(monkeypatch: pytest.MonkeyPatcassert exc_info.value.status_code == 400-def test_invoke_maps_model_failure_to_422_and_success_returns_text(monkeypatch: pytest.MonkeyPatch):+def test_invoke_maps_model_failure_to_422_and_success_returns_text(monkeypatch):import services.agent.skill_tool_inference_service as modulefake_manager = MagicMock()@@ -171,55 +162,3 @@ def test_load_skill_md_passes_through_non_missing_drive_errors():with pytest.raises(SkillToolInferenceError) as exc_info:service.infer(tenant_id="t-1", agent_id="a-1", slug="x")assert exc_info.value.code == "agent_not_found"---def _patch_inference_db(monkeypatch: pytest.MonkeyPatch, *, agent, snapshot):- from types import SimpleNamespace-- import services.agent.skill_tool_inference_service as module-- results = iter([agent, snapshot])- monkeypatch.setattr(module.db, "session", SimpleNamespace(scalar=lambda stmt: next(results)))---def test_manifest_files_from_soul_reads_active_snapshot(monkeypatch: pytest.MonkeyPatch):- from types import SimpleNamespace-- soul_dict = {- "skills_files": {- "skills": [- {"name": "Other", "skill_md_key": "other/SKILL.md", "manifest_files": ["x.md"]},- {"name": "Audio", "skill_md_key": "audio-transcribe/SKILL.md", "manifest_files": ["scripts/a.sh"]},- ]- }- }- agent = SimpleNamespace(active_config_snapshot_id="snap-1")- snapshot = SimpleNamespace(config_snapshot_dict=soul_dict)- _patch_inference_db(monkeypatch, agent=agent, snapshot=snapshot)-- files = SkillToolInferenceService._manifest_files_from_soul(- tenant_id="t-1", agent_id="a-1", slug="audio-transcribe"- )- assert files == ["scripts/a.sh"]---def test_manifest_files_from_soul_degrades_when_agent_or_snapshot_missing(monkeypatch: pytest.MonkeyPatch):- _patch_inference_db(monkeypatch, agent=None, snapshot=None)- assert SkillToolInferenceService._manifest_files_from_soul(tenant_id="t", agent_id="a", slug="s") == []-- from types import SimpleNamespace-- _patch_inference_db(monkeypatch, agent=SimpleNamespace(active_config_snapshot_id="snap-1"), snapshot=None)- assert SkillToolInferenceService._manifest_files_from_soul(tenant_id="t", agent_id="a", slug="s") == []---def test_manifest_files_from_soul_empty_when_slug_not_in_soul(monkeypatch: pytest.MonkeyPatch):- from types import SimpleNamespace-- soul_dict = {"skills_files": {"skills": [{"name": "Other", "skill_md_key": "other/SKILL.md"}]}}- _patch_inference_db(- monkeypatch,- agent=SimpleNamespace(active_config_snapshot_id="snap-1"),- snapshot=SimpleNamespace(config_snapshot_dict=soul_dict),- )- assert SkillToolInferenceService._manifest_files_from_soul(tenant_id="t", agent_id="a", slug="ghost") == []diff --git a/api/tests/unit_tests/services/test_agent_drive_service.py b/api/tests/unit_tests/services/test_agent_drive_service.pyindex afc3f08124a..e4a22b64a48 100644--- a/api/tests/unit_tests/services/test_agent_drive_service.py+++ b/api/tests/unit_tests/services/test_agent_drive_service.py@@ -15,7 +15,7 @@ from sqlalchemy import delete, selectfrom core.db.session_factory import session_factoryfrom extensions.storage.storage_type import StorageType-from models.agent import Agent, AgentDriveFile, AgentScope, AgentSource+from models.agent import Agent, AgentDriveFile, AgentDriveFileKind, AgentScope, AgentSourcefrom models.enums import CreatorUserRolefrom models.model import UploadFilefrom models.tools import ToolFile@@ -133,6 +133,123 @@ def test_commit_then_manifest_lists_the_entry():assert AgentDriveService().manifest(tenant_id=TENANT, agent_id=AGENT, prefix="other/") == []+def test_commit_skill_row_persists_metadata_and_lists_catalog() -> None:+ tf = _seed_tool_file(name="SKILL.md")+ AgentDriveService().commit(+ tenant_id=TENANT,+ user_id=USER,+ agent_id=AGENT,+ items=[+ DriveCommitItem(+ key="tender-analyzer/SKILL.md",+ file_ref={"kind": "tool_file", "id": tf},+ is_skill=True,+ skill_metadata=DriveSkillMetadata(name="Tender Analyzer", description="Parses RFPs."),+ )+ ],+ )++ with session_factory.create_session() as session:+ row = session.scalar(select(AgentDriveFile).where(AgentDriveFile.key == "tender-analyzer/SKILL.md"))+ assert row is not None+ assert row.is_skill is True+ assert row.skill_metadata == '{"description":"Parses RFPs.","name":"Tender Analyzer"}'++ skills = AgentDriveService().list_skills(tenant_id=TENANT, agent_id=AGENT)+ assert len(skills) == 1+ assert skills[0]["path"] == "tender-analyzer"+ assert skills[0]["skill_md_key"] == "tender-analyzer/SKILL.md"+ assert skills[0]["archive_key"] is None+ assert skills[0]["name"] == "Tender Analyzer"+ assert skills[0]["description"] == "Parses RFPs."+ assert skills[0]["size"] == 5+ assert skills[0]["mime_type"] == "text/plain"+++def test_commit_rejects_skill_row_without_skill_metadata() -> None:+ tf = _seed_tool_file(name="SKILL.md")++ with pytest.raises(AgentDriveError) as exc_info:+ AgentDriveService().commit(+ tenant_id=TENANT,+ user_id=USER,+ agent_id=AGENT,+ items=[+ DriveCommitItem(+ key="tender-analyzer/SKILL.md",+ file_ref={"kind": "tool_file", "id": tf},+ is_skill=True,+ )+ ],+ )++ assert exc_info.value.code == "invalid_skill_metadata"++[email protected]("raw_metadata", [None, '{"description":"oops"}'])+def test_list_skills_raises_controlled_error_for_invalid_stored_metadata(raw_metadata: str | None) -> None:+ tf = _seed_tool_file(name="SKILL.md")++ with session_factory.create_session() as session:+ session.add(+ AgentDriveFile(+ id="44444444-4444-4444-4444-444444444444",+ tenant_id=TENANT,+ agent_id=AGENT,+ key="broken-skill/SKILL.md",+ file_kind=AgentDriveFileKind.TOOL_FILE,+ file_id=tf,+ value_owned_by_drive=True,+ is_skill=True,+ skill_metadata=raw_metadata,+ size=5,+ mime_type="text/plain",+ created_by=USER,+ )+ )+ session.commit()++ with pytest.raises(AgentDriveError) as exc_info:+ AgentDriveService().list_skills(tenant_id=TENANT, agent_id=AGENT)++ assert exc_info.value.code == "invalid_skill_metadata"+++def test_commit_rejects_non_skill_row_with_skill_metadata() -> None:+ tf = _seed_tool_file()+ with pytest.raises(AgentDriveError, match="skill metadata"):+ AgentDriveService().commit(+ tenant_id=TENANT,+ user_id=USER,+ agent_id=AGENT,+ items=[+ DriveCommitItem(+ key="files/report.txt",+ file_ref={"kind": "tool_file", "id": tf},+ skill_metadata=DriveSkillMetadata(name="Bad", description=""),+ )+ ],+ )+++def test_commit_rejects_non_canonical_skill_key() -> None:+ tf = _seed_tool_file(name="README.md")+ with pytest.raises(AgentDriveError, match="canonical"):+ AgentDriveService().commit(+ tenant_id=TENANT,+ user_id=USER,+ agent_id=AGENT,+ items=[+ DriveCommitItem(+ key="tender-analyzer/README.md",+ file_ref={"kind": "tool_file", "id": tf},+ is_skill=True,+ skill_metadata=DriveSkillMetadata(name="Tender Analyzer", description=""),+ )+ ],+ )++def test_commit_rejects_tool_file_not_owned_by_user():other = _seed_tool_file(user_id="99999999-9999-9999-9999-999999999999")with pytest.raises(AgentDriveError) as exc_info:@@ -247,6 +364,49 @@ def test_recommit_same_value_is_idempotent_and_keeps_value():assert len(rows) == 1+def test_recommit_same_skill_value_updates_metadata_without_cleaning_backing_file() -> None:+ tf = _seed_tool_file(name="SKILL.md")+ AgentDriveService().commit(+ tenant_id=TENANT,+ user_id=USER,+ agent_id=AGENT,+ items=[+ DriveCommitItem(+ key="tender-analyzer/SKILL.md",+ file_ref={"kind": "tool_file", "id": tf},+ value_owned_by_drive=True,+ is_skill=True,+ skill_metadata=DriveSkillMetadata(name="Tender Analyzer", description="v1"),+ )+ ],+ )++ with patch("services.agent_drive_service.storage") as storage_mock:+ AgentDriveService().commit(+ tenant_id=TENANT,+ user_id=USER,+ agent_id=AGENT,+ items=[+ DriveCommitItem(+ key="tender-analyzer/SKILL.md",+ file_ref={"kind": "tool_file", "id": tf},+ value_owned_by_drive=False,+ is_skill=True,+ skill_metadata=DriveSkillMetadata(name="Tender Analyzer v2", description="v2"),+ )+ ],+ )+ storage_mock.delete.assert_not_called()++ with session_factory.create_session() as session:+ row = session.scalar(select(AgentDriveFile).where(AgentDriveFile.key == "tender-analyzer/SKILL.md"))+ assert row is not None+ assert row.file_id == tf+ assert row.value_owned_by_drive is False+ assert row.skill_metadata == '{"description":"v2","name":"Tender Analyzer v2"}'+ assert session.scalar(select(ToolFile).where(ToolFile.id == tf)) is not None++def _seed_upload_file(*, name: str = "u.txt") -> str:upload = UploadFile(tenant_id=TENANT,@@ -319,7 +479,7 @@ def test_manifest_includes_internal_download_url():with (patch("services.agent_drive_service.file_factory.build_from_mapping", return_value=object()),- patch("services.agent_drive_service.DifyWorkflowFileRuntime") as runtime_cls,+ patch("core.app.workflow.file_runtime.DifyWorkflowFileRuntime") as runtime_cls,):runtime_cls.return_value.resolve_file_url.return_value = "http://internal/files/x?sign=1"items = AgentDriveService().manifest(tenant_id=TENANT, agent_id=AGENT, include_download_url=True)@@ -349,16 +509,31 @@ def test_delete_by_key_cleans_drive_owned_value():_commit("files/doomed.txt", tf, owned=True)with patch("services.agent_drive_service.storage") as storage_mock:- removed = AgentDriveService().delete(tenant_id=TENANT, agent_id=AGENT, key="files/doomed.txt")+ removed = AgentDriveService().commit(+ tenant_id=TENANT,+ user_id=USER,+ agent_id=AGENT,+ items=[DriveCommitItem(key="files/doomed.txt", file_ref=None)],+ )storage_mock.delete.assert_called_once()- assert removed == ["files/doomed.txt"]+ assert removed == [+ {+ "key": "files/doomed.txt",+ "file_kind": "tool_file",+ "file_id": tf,+ "value_owned_by_drive": True,+ "is_skill": False,+ "skill_metadata": None,+ "removed": True,+ }+ ]with session_factory.create_session() as session:assert session.scalar(select(ToolFile).where(ToolFile.id == tf)) is Noneassert list(session.scalars(select(AgentDriveFile))) == []-def test_delete_by_prefix_removes_all_skill_keys():+def test_commit_null_batch_removes_multiple_skill_keys():md = _seed_tool_file(name="SKILL.md")zf = _seed_tool_file(name="full.zip")_commit("tender-analyzer/SKILL.md", md, owned=True)@@ -367,9 +542,20 @@ def test_delete_by_prefix_removes_all_skill_keys():_commit("files/other.txt", other, owned=True)with patch("services.agent_drive_service.storage"):- removed = AgentDriveService().delete(tenant_id=TENANT, agent_id=AGENT, prefix="tender-analyzer/")+ removed = AgentDriveService().commit(+ tenant_id=TENANT,+ user_id=USER,+ agent_id=AGENT,+ items=[+ DriveCommitItem(key="tender-analyzer/SKILL.md", file_ref=None),+ DriveCommitItem(key="tender-analyzer/.DIFY-SKILL-FULL.zip", file_ref=None),+ ],+ )- assert sorted(removed) == ["tender-analyzer/.DIFY-SKILL-FULL.zip", "tender-analyzer/SKILL.md"]+ assert sorted(item["key"] for item in removed) == [+ "tender-analyzer/.DIFY-SKILL-FULL.zip",+ "tender-analyzer/SKILL.md",+ ]with session_factory.create_session() as session:# both skill ToolFiles physically removed, the unrelated file untouchedassert session.scalar(select(ToolFile).where(ToolFile.id == md)) is None@@ -379,28 +565,30 @@ def test_delete_by_prefix_removes_all_skill_keys():assert keys == ["files/other.txt"]-def test_delete_is_idempotent():- assert AgentDriveService().delete(tenant_id=TENANT, agent_id=AGENT, key="files/never-there.txt") == []- assert AgentDriveService().delete(tenant_id=TENANT, agent_id=AGENT, prefix="ghost-skill/") == []---def test_delete_requires_exactly_one_scope():- with pytest.raises(AgentDriveError) as exc_info:- AgentDriveService().delete(tenant_id=TENANT, agent_id=AGENT)- assert exc_info.value.code == "invalid_delete_scope"- with pytest.raises(AgentDriveError):- AgentDriveService().delete(tenant_id=TENANT, agent_id=AGENT, prefix="a/", key="a/b")+def test_commit_null_is_idempotent_for_missing_keys():+ removed = AgentDriveService().commit(+ tenant_id=TENANT,+ user_id=USER,+ agent_id=AGENT,+ items=[DriveCommitItem(key="files/never-there.txt", file_ref=None)],+ )+ assert removed == [{"key": "files/never-there.txt", "removed": True, "noop": True}]-def test_delete_keeps_shared_value_records():+def test_commit_null_keeps_shared_value_records():tf = _seed_tool_file(name="shared.txt")_commit("files/shared.txt", tf, owned=False)with patch("services.agent_drive_service.storage") as storage_mock:- removed = AgentDriveService().delete(tenant_id=TENANT, agent_id=AGENT, key="files/shared.txt")+ removed = AgentDriveService().commit(+ tenant_id=TENANT,+ user_id=USER,+ agent_id=AGENT,+ items=[DriveCommitItem(key="files/shared.txt", file_ref=None)],+ )storage_mock.delete.assert_not_called()- assert removed == ["files/shared.txt"]+ assert removed[0]["key"] == "files/shared.txt"with session_factory.create_session() as session:# only the KV row dropped; the shared ToolFile survivesassert session.scalar(select(ToolFile).where(ToolFile.id == tf)) is not None@@ -502,7 +690,7 @@ def test_upload_file_download_url_uses_attachment_filename():upload_file_id = _seed_upload_file(name="report.pdf")_commit_upload("files/report.pdf", upload_file_id)- with patch("services.agent_drive_service.DifyWorkflowFileRuntime") as runtime_cls:+ with patch("core.app.workflow.file_runtime.DifyWorkflowFileRuntime") as runtime_cls:runtime_cls.return_value.resolve_upload_file_url.return_value = "https://files.example/report.pdf"url = AgentDriveService().download_url(tenant_id=TENANT, agent_id=AGENT, key="files/report.pdf")diff --git a/api/uv.lock b/api/uv.lockindex 048d991a49e..6e998f6f6ed 100644--- a/api/uv.lock+++ b/api/uv.lock@@ -1304,7 +1304,7 @@ requires-dist = [{ name = "pydantic-ai-slim", extras = ["anthropic", "google", "openai"], marker = "extra == 'server'", specifier = ">=1.85.1,<2.0.0" },{ name = "pydantic-settings", marker = "extra == 'server'", specifier = ">=2.12.0,<3.0.0" },{ name = "redis", marker = "extra == 'server'", specifier = ">=7.4.0,<8.0.0" },- { name = "shell-session-manager", marker = "extra == 'server'", specifier = "==2.2.0" },+ { name = "shell-session-manager", marker = "extra == 'server'", specifier = "==2.2.1" },{ name = "typer", specifier = ">=0.16.1,<0.17" },{ name = "typing-extensions", specifier = ">=4.12.2,<5.0.0" },{ name = "uvicorn", extras = ["standard"], marker = "extra == 'server'", specifier = "==0.46.0" },diff --git a/dify-agent/docker/local-sandbox/Dockerfile b/dify-agent/docker/local-sandbox/Dockerfilenew file mode 100644index 00000000000..2dd3dbb677a--- /dev/null+++ b/dify-agent/docker/local-sandbox/Dockerfile@@ -0,0 +1,59 @@+# Local sandbox image for shellctl-managed Dify Agent workspaces.+#+# Build this from the dify-agent package root:+# docker build -f docker/local-sandbox/Dockerfile -t dify-agent-local-sandbox:local .+#+# This image merges the former shellctl-only image with the sandbox-visible+# Agent Stub client CLI. It runs shellctl by default, and shellctl-managed jobs+# can call `dify-agent ...` without installing extra packages at runtime.++FROM python:3.12-slim-bookworm AS base++ENV PYTHONDONTWRITEBYTECODE=1 \+ PYTHONUNBUFFERED=1 \+ PIP_NO_CACHE_DIR=1 \+ DIFY_AGENT_STUB_DRIVE_BASE=/mnt/drive++RUN apt-get update \+ && apt-get install -y --no-install-recommends \+ ca-certificates \+ curl \+ tmux \+ && rm -rf /var/lib/apt/lists/*++ENV UV_VERSION=0.8.9+RUN python -m pip install --no-cache-dir "uv==${UV_VERSION}"++WORKDIR /opt/dify-agent+++FROM base AS packages++ENV SHELL_SESSION_MANAGER_VERSION=2.2.1++COPY pyproject.toml uv.lock README.md ./+COPY src ./src++RUN uv sync --frozen --no-dev --no-editable --extra grpc \+ && uv pip install --python .venv/bin/python "shell-session-manager==${SHELL_SESSION_MANAGER_VERSION}"+++FROM base AS production++ENV VIRTUAL_ENV=/opt/dify-agent/.venv+ENV PATH="${VIRTUAL_ENV}/bin:${PATH}"++COPY --from=packages ${VIRTUAL_ENV} ${VIRTUAL_ENV}++RUN ln -s ${VIRTUAL_ENV}/bin/dify-agent /usr/local/bin/dify-agent \+ && ln -s ${VIRTUAL_ENV}/bin/shellctl /usr/local/bin/shellctl \+ && useradd --create-home --shell /bin/sh dify \+ && mkdir -p /mnt/drive \+ && chown -R dify:dify /home/dify /mnt/drive++USER dify+WORKDIR /home/dify++EXPOSE 5004++CMD ["shellctl", "serve", "--listen", "0.0.0.0:5004"]diff --git a/dify-agent/docker/shellctl/Dockerfile b/dify-agent/docker/shellctl/Dockerfiledeleted file mode 100644index 24f6460064c..00000000000--- a/dify-agent/docker/shellctl/Dockerfile+++ /dev/null@@ -1,25 +0,0 @@-FROM python:3.13-slim--ENV PYTHONDONTWRITEBYTECODE=1 \- PYTHONUNBUFFERED=1 \- PIP_NO_CACHE_DIR=1--RUN apt-get update \- && apt-get install -y --no-install-recommends \- ca-certificates \- curl \- tmux \- && rm -rf /var/lib/apt/lists/*--RUN python -m pip install --no-cache-dir \- shell-session-manager==2.2.0 \- uv--RUN useradd --create-home --shell /bin/sh dify--USER dify-WORKDIR /home/dify--EXPOSE 5004--CMD ["shellctl", "serve", "--listen", "0.0.0.0:5004"]diff --git a/dify-agent/docs/dify-agent/get-started/index.md b/dify-agent/docs/dify-agent/get-started/index.mdindex 78a7db84371..347e85e3d81 100644--- a/dify-agent/docs/dify-agent/get-started/index.md+++ b/dify-agent/docs/dify-agent/get-started/index.md@@ -51,6 +51,9 @@ DIFY_AGENT_REDIS_PREFIX=dify-agentDIFY_AGENT_PLUGIN_DAEMON_URL=http://localhost:5002DIFY_AGENT_PLUGIN_DAEMON_API_KEY=replace-with-plugin-daemon-server-key++DIFY_AGENT_INNER_API_URL=http://localhost:5001+DIFY_AGENT_INNER_API_KEY=replace-with-dify-inner-api-key-for-pluginEOF```@@ -63,12 +66,16 @@ The minimum settings are:- `DIFY_AGENT_PLUGIN_DAEMON_API_KEY`: API key sent by the server to the plugindaemon. In a Dify Docker setup this is usually the value previously configuredas `PLUGIN_DAEMON_KEY`.+- `DIFY_AGENT_INNER_API_URL`: Dify API service root for `/inner/api/...` calls.+- `DIFY_AGENT_INNER_API_KEY`: API key sent to Dify API inner plugin endpoints.+ In Docker this should match `PLUGIN_DIFY_INNER_API_KEY`, which maps to Dify+ API `INNER_API_KEY_FOR_PLUGIN`.See `.example.env` for the full server settings template.If you plan to run `dify.shell`, also configure `DIFY_AGENT_SHELLCTL_ENTRYPOINT`and, when shell jobs need to call back with the `dify-agent` command, set-`DIFY_AGENT_STUB_URL` plus a 32-byte base64url+`DIFY_AGENT_STUB_API_BASE_URL` plus a 32-byte base64url`DIFY_AGENT_SERVER_SECRET_KEY` as documented in `.example.env`.## Start the Dify Agent serverdiff --git a/dify-agent/docs/dify-agent/guide/index.md b/dify-agent/docs/dify-agent/guide/index.mdindex 27ec96ab349..89d9e0599c7 100644--- a/dify-agent/docs/dify-agent/guide/index.md+++ b/dify-agent/docs/dify-agent/guide/index.md@@ -36,11 +36,13 @@ also reads `.env` and `dify-agent/.env` when present.| `DIFY_AGENT_RUN_RETENTION_SECONDS` | `259200` | Seconds to retain Redis run records and per-run event streams; defaults to 3 days. || `DIFY_AGENT_PLUGIN_DAEMON_URL` | `http://localhost:5002` | Base URL for the Dify plugin daemon. || `DIFY_AGENT_PLUGIN_DAEMON_API_KEY` | empty | API key sent to the Dify plugin daemon. |+| `DIFY_AGENT_INNER_API_URL` | `http://localhost:5001` | Dify API service root used when dify-agent calls `/inner/api/...` endpoints. |+| `DIFY_AGENT_INNER_API_KEY` | empty | API key sent to Dify API inner plugin endpoints. Set this to Dify API `INNER_API_KEY_FOR_PLUGIN` (Docker: `PLUGIN_DIFY_INNER_API_KEY`). || `DIFY_AGENT_SHELLCTL_ENTRYPOINT` | empty | Base URL for the shellctl server used by `dify.shell`; required when runs include the shell layer. || `DIFY_AGENT_SHELLCTL_AUTH_TOKEN` | empty | Optional bearer token sent to the shellctl server. |-| `DIFY_AGENT_STUB_URL` | empty | Public Agent Stub URL reachable from shellctl-managed remote machines. Use `http(s)://.../agent-stub` for HTTP or `grpc://host:port` for gRPC; enables `DIFY_AGENT_STUB_*` env injection for user `shell.run` jobs. |-| `DIFY_AGENT_STUB_GRPC_BIND_ADDRESS` | empty | Optional `host:port` bind override used only when `DIFY_AGENT_STUB_URL` uses `grpc://`. |-| `DIFY_AGENT_SERVER_SECRET_KEY` | empty | Server-wide root secret used to derive Agent Stub JWE keys; required when `DIFY_AGENT_STUB_URL` is set and must be unpadded base64url for 32 bytes. |+| `DIFY_AGENT_STUB_API_BASE_URL` | empty | Public Agent Stub API base URL reachable from shellctl-managed remote machines. HTTP may be the service root or `/agent-stub`; gRPC must be `grpc://host:port`. Enables `DIFY_AGENT_STUB_*` env injection for user `shell.run` jobs. |+| `DIFY_AGENT_STUB_GRPC_BIND_ADDRESS` | empty | Optional `host:port` bind override used only when `DIFY_AGENT_STUB_API_BASE_URL` uses `grpc://`. |+| `DIFY_AGENT_SERVER_SECRET_KEY` | empty | Server-wide root secret used to derive Agent Stub JWE keys; required when `DIFY_AGENT_STUB_API_BASE_URL` is set and must be unpadded base64url for 32 bytes. || `DIFY_AGENT_PLUGIN_DAEMON_CONNECT_TIMEOUT` | `10` | Plugin-daemon HTTP connect timeout in seconds. || `DIFY_AGENT_PLUGIN_DAEMON_READ_TIMEOUT` | `600` | Plugin-daemon HTTP read timeout in seconds. || `DIFY_AGENT_PLUGIN_DAEMON_WRITE_TIMEOUT` | `30` | Plugin-daemon HTTP write timeout in seconds. |@@ -58,10 +60,12 @@ DIFY_AGENT_SHUTDOWN_GRACE_SECONDS=30DIFY_AGENT_RUN_RETENTION_SECONDS=259200DIFY_AGENT_PLUGIN_DAEMON_URL=http://localhost:5002DIFY_AGENT_PLUGIN_DAEMON_API_KEY=replace-with-daemon-key+DIFY_AGENT_INNER_API_URL=http://localhost:5001+DIFY_AGENT_INNER_API_KEY=replace-with-dify-inner-api-key-for-pluginDIFY_AGENT_SHELLCTL_ENTRYPOINT=http://127.0.0.1:5004DIFY_AGENT_SHELLCTL_AUTH_TOKEN=replace-with-shellctl-token# Generate with: python -c 'import base64, secrets; print(base64.urlsafe_b64encode(secrets.token_bytes(32)).rstrip(b"=").decode())'-DIFY_AGENT_STUB_URL=https://agent.example.com/agent-stub+DIFY_AGENT_STUB_API_BASE_URL=https://agent.example.com/agent-stubDIFY_AGENT_SERVER_SECRET_KEY=replace-with-base64url-32-byte-secret```diff --git a/dify-agent/docs/dify-agent/user-manual/shell-layer/index.md b/dify-agent/docs/dify-agent/user-manual/shell-layer/index.mdindex eb2e39f298d..91842f05dbc 100644--- a/dify-agent/docs/dify-agent/user-manual/shell-layer/index.md+++ b/dify-agent/docs/dify-agent/user-manual/shell-layer/index.md@@ -55,10 +55,14 @@ To let commands inside user-visible shell jobs call back to the Dify Agent servewith `dify-agent ...`, also enable the Agent Stub:```env-DIFY_AGENT_STUB_URL=https://agent.example.com/agent-stub+DIFY_AGENT_STUB_API_BASE_URL=https://agent.example.com/agent-stubDIFY_AGENT_SERVER_SECRET_KEY=replace-with-base64url-32-byte-secret```+HTTP `DIFY_AGENT_STUB_API_BASE_URL` may be either the service root or the+explicit `/agent-stub` API root; the server normalizes the service root to+`/agent-stub`. Other HTTP paths are rejected at startup.+`DIFY_AGENT_SERVER_SECRET_KEY` must be unpadded base64url text for exactly 32decoded bytes. One way to generate it is:@@ -69,10 +73,14 @@ python -c 'import base64, secrets; print(base64.urlsafe_b64encode(secrets.token_## Client request shapeA client adds the shell layer as an ordinary composition layer. Basic shell jobs-do not need dependencies. To inject `DIFY_AGENT_STUB_URL` and-`DIFY_AGENT_STUB_AUTH_JWE` into user-visible `shell.run` jobs, declare the-execution-context layer as the shell layer's `execution_context` dependency. A-typical run still also includes:+do not need dependencies. To inject `DIFY_AGENT_STUB_API_BASE_URL`,+`DIFY_AGENT_STUB_AUTH_JWE`, and `DIFY_AGENT_STUB_DRIVE_BASE` into user-visible+`shell.run` jobs, declare the execution-context layer as the shell layer's+`execution_context` dependency. When the run also includes `dify.drive`, declare+it as the shell layer's `drive` dependency; the injected drive base is then+computed from the fixed Agent Stub drive mount and the drive reference, for+example `/mnt/drive/agent-123`. Without a drive dependency, the CLI keeps the+historical `/mnt/drive` fallback. A typical run still also includes:- a prompt layer that supplies the task;- an execution-context layer carrying tenant/user context;@@ -194,33 +202,34 @@ Here is the analysis of the sales dataset:* **SHA-256 Hash:** `e86521a0d759037a09b059cb3cb2419f0a3f06e674db8151ccf2f93811dac0b8`````-## Running shellctl in Docker+## Running the local sandbox in Docker-Build the shellctl image from the Dify Agent package root:+Build the local sandbox image from the Dify Agent package root:```bash-docker build -f docker/shellctl/Dockerfile -t dify-agent-shellctl:local .+docker build -f docker/local-sandbox/Dockerfile -t dify-agent-local-sandbox:local .```Run it with a bearer token and publish the API on localhost:```bash-docker run --rm --name dify-agent-shellctl \+docker run --rm --name dify-agent-local-sandbox \-e SHELLCTL_AUTH_TOKEN=replace-with-a-token \-p 127.0.0.1:5004:5004 \- dify-agent-shellctl:local+ dify-agent-local-sandbox:local```The image starts `shellctl serve --listen 0.0.0.0:5004` as the non-root-`dify` user and leaves shellctl state/runtime directories at their package-defaults.+`dify` user. It also sets the fallback `DIFY_AGENT_STUB_DRIVE_BASE=/mnt/drive`+and pre-creates that directory with write access for the same user.## Docker image contents-The provided `docker/shellctl/Dockerfile` installs:+The provided `docker/local-sandbox/Dockerfile` installs:- `tmux`, required by `shellctl` to manage shell jobs;-- `shell-session-manager==2.2.0`, which provides the `shellctl` CLI/server;+- `shell-session-manager==2.2.1`, which provides the `shellctl` CLI/server;- `uv`, so uv shebang scripts with PEP 723 metadata can run inside the shellworkspace;+- the `dify-agent` Agent Stub client CLI, including its gRPC transport extra;- a non-root default user named `dify`.diff --git a/dify-agent/pyproject.toml b/dify-agent/pyproject.tomlindex 03f2525ace7..c6f1138e087 100644--- a/dify-agent/pyproject.toml+++ b/dify-agent/pyproject.toml@@ -26,7 +26,7 @@ server = ["pydantic-ai-slim[anthropic,google,openai]>=1.85.1,<2.0.0","pydantic-settings>=2.12.0,<3.0.0","redis>=7.4.0,<8.0.0",- "shell-session-manager==2.2.0",+ "shell-session-manager==2.2.1","uvicorn[standard]==0.46.0",]diff --git a/dify-agent/src/dify_agent/agent_stub/cli/_drive.py b/dify-agent/src/dify_agent/agent_stub/cli/_drive.pyindex 19611592c0e..d3d6241449b 100644--- a/dify-agent/src/dify_agent/agent_stub/cli/_drive.py+++ b/dify-agent/src/dify_agent/agent_stub/cli/_drive.py@@ -11,6 +11,7 @@ ToolFile ids back into the drive.from __future__ import annotationsimport stat+from concurrent.futures import ThreadPoolExecutorfrom dataclasses import dataclassfrom pathlib import Path, PurePosixPathfrom tempfile import TemporaryDirectory@@ -32,6 +33,7 @@ from dify_agent.agent_stub.protocol.agent_stub import (AgentStubDriveFileRef,AgentStubDriveItem,AgentStubDriveManifestResponse,+ DEFAULT_AGENT_STUB_DRIVE_BASE,)_SKILL_MD_FILENAME = "SKILL.md"@@ -81,11 +83,15 @@ def list_drive_from_environment(prefix: str, json_output: bool) -> str | AgentStreturn _format_manifest(response)-def pull_drive_from_environment(prefix: str, drive_base: str = "/mnt/drive") -> list[Path]:+def pull_drive_from_environment(+ targets: list[str] | None = None,+ drive_base: str = DEFAULT_AGENT_STUB_DRIVE_BASE,+) -> list[Path]:"""Pull drive files into one local drive base via signed download URLs.Args:- prefix: Optional drive-key prefix forwarded to the manifest request.+ targets: Optional drive-key targets or prefixes. An empty list preserves+ the historical whole-drive pull by using ``[""]``.drive_base: Local base directory that receives downloaded drive files.Returns:@@ -117,16 +123,24 @@ def pull_drive_from_environment(prefix: str, drive_base: str = "/mnt/drive") ->"""environment = read_agent_stub_environment()- response = request_agent_stub_drive_manifest_sync(- url=environment.url,- auth_jwe=environment.auth_jwe,- prefix=prefix,- include_download_url=True,- )+ manifest_targets = targets or [""]+ with ThreadPoolExecutor(max_workers=min(len(manifest_targets), 4)) as executor:+ responses = list(+ executor.map(+ lambda target: request_agent_stub_drive_manifest_sync(+ url=environment.url,+ auth_jwe=environment.auth_jwe,+ prefix=target,+ include_download_url=True,+ ),+ manifest_targets,+ )+ )base_path = Path(drive_base).expanduser().resolve()base_path.mkdir(parents=True, exist_ok=True)written_paths: list[Path] = []- for item in response.items:+ deduplicated_items = {item.key: item for response in responses for item in response.items}+ for item in [deduplicated_items[key] for key in sorted(deduplicated_items)]:download_url = item.download_urlif not isinstance(download_url, str) or not download_url:raise AgentStubValidationError(f"drive manifest item is missing download_url: {item.key}")diff --git a/dify-agent/src/dify_agent/agent_stub/cli/_env.py b/dify-agent/src/dify_agent/agent_stub/cli/_env.pyindex 1c906db8723..da268f6a369 100644--- a/dify-agent/src/dify_agent/agent_stub/cli/_env.py+++ b/dify-agent/src/dify_agent/agent_stub/cli/_env.py@@ -8,8 +8,10 @@ import osfrom dify_agent.agent_stub.protocol.agent_stub import (AGENT_STUB_AUTH_JWE_ENV_VAR,- AGENT_STUB_URL_ENV_VAR,- normalize_agent_stub_url,+ AGENT_STUB_DRIVE_BASE_ENV_VAR,+ AGENT_STUB_API_BASE_URL_ENV_VAR,+ DEFAULT_AGENT_STUB_DRIVE_BASE,+ normalize_agent_stub_api_base_url,)@@ -28,32 +30,44 @@ class AgentStubEnvironment:def has_agent_stub_environment(env: Mapping[str, str] | None = None) -> bool:"""Return whether both required Agent Stub environment variables exist."""values = env or os.environ- return bool(values.get(AGENT_STUB_URL_ENV_VAR) and values.get(AGENT_STUB_AUTH_JWE_ENV_VAR))+ return bool(values.get(AGENT_STUB_API_BASE_URL_ENV_VAR) and values.get(AGENT_STUB_AUTH_JWE_ENV_VAR))def read_agent_stub_environment(env: Mapping[str, str] | None = None) -> AgentStubEnvironment:"""Read and validate the Agent Stub environment variables."""values = env or os.environ- url = (values.get(AGENT_STUB_URL_ENV_VAR) or "").strip()+ url = (values.get(AGENT_STUB_API_BASE_URL_ENV_VAR) or "").strip()auth_jwe = (values.get(AGENT_STUB_AUTH_JWE_ENV_VAR) or "").strip()missing: list[str] = []if not url:- missing.append(AGENT_STUB_URL_ENV_VAR)+ missing.append(AGENT_STUB_API_BASE_URL_ENV_VAR)if not auth_jwe:missing.append(AGENT_STUB_AUTH_JWE_ENV_VAR)if missing:names = ", ".join(missing)raise MissingAgentStubEnvironmentError(f"missing required Agent Stub environment variables: {names}")try:- normalized_url = normalize_agent_stub_url(url)+ normalized_url = normalize_agent_stub_api_base_url(url)except ValueError as exc:- raise MissingAgentStubEnvironmentError(f"invalid {AGENT_STUB_URL_ENV_VAR}: {exc}") from exc+ raise MissingAgentStubEnvironmentError(f"invalid {AGENT_STUB_API_BASE_URL_ENV_VAR}: {exc}") from excreturn AgentStubEnvironment(url=normalized_url, auth_jwe=auth_jwe)+def read_agent_stub_drive_base(env: Mapping[str, str] | None = None) -> str:+ """Read the sandbox-local drive base used by ``dify-agent drive pull``.++ The variable is optional because older Agent Stub environments only injected+ URL/auth values. Blank values keep the historical ``/mnt/drive`` fallback.+ """+ values = env or os.environ+ configured_drive_base = (values.get(AGENT_STUB_DRIVE_BASE_ENV_VAR) or "").strip()+ return configured_drive_base or DEFAULT_AGENT_STUB_DRIVE_BASE++__all__ = ["AgentStubEnvironment","MissingAgentStubEnvironmentError","has_agent_stub_environment",+ "read_agent_stub_drive_base","read_agent_stub_environment",]diff --git a/dify-agent/src/dify_agent/agent_stub/cli/main.py b/dify-agent/src/dify_agent/agent_stub/cli/main.pyindex 466a53339e7..c5c722d7e03 100644--- a/dify-agent/src/dify_agent/agent_stub/cli/main.py+++ b/dify-agent/src/dify_agent/agent_stub/cli/main.py@@ -21,9 +21,14 @@ from dify_agent.agent_stub.cli._drive import (pull_drive_from_environment,push_drive_from_environment,)-from dify_agent.agent_stub.cli._env import MissingAgentStubEnvironmentError, has_agent_stub_environment+from dify_agent.agent_stub.cli._env import (+ MissingAgentStubEnvironmentError,+ has_agent_stub_environment,+ read_agent_stub_drive_base,+)from dify_agent.agent_stub.cli._files import download_file_from_environment, upload_file_from_environmentfrom dify_agent.agent_stub.client._errors import AgentStubClientError+from dify_agent.agent_stub.protocol.agent_stub import AGENT_STUB_DRIVE_BASE_ENV_VAR, DEFAULT_AGENT_STUB_DRIVE_BASEapp = typer.Typer(@@ -78,11 +83,22 @@ def drive_list(@drive_app.command("pull")def drive_pull(- path_prefix: str = typer.Argument("", metavar="PATH_PREFIX"),- drive_base: str = typer.Option("/mnt/drive", "--drive-base", help="Local base directory for pulled drive files."),+ targets: list[str] = typer.Argument(None, metavar="TARGET"),+ drive_base: str | None = typer.Option(+ None,+ "--drive-base",+ help=(+ f"Local base directory for pulled drive files. Defaults to ${AGENT_STUB_DRIVE_BASE_ENV_VAR} "+ f"or {DEFAULT_AGENT_STUB_DRIVE_BASE}."+ ),+ ),) -> None:- """Pull drive files into one local directory tree."""- _run_drive_pull(path_prefix=path_prefix, drive_base=drive_base)+ """Pull one or more drive keys/prefixes into one local directory tree.++ Passing no ``TARGET`` preserves the historical whole-drive behavior by+ pulling from the empty prefix.+ """+ _run_drive_pull(targets=targets, drive_base=drive_base)@drive_app.command("push")@@ -207,9 +223,9 @@ def _run_drive_list(*, path_prefix: str, json_output: bool) -> None:typer.echo(response)-def _run_drive_pull(*, path_prefix: str, drive_base: str) -> None:+def _run_drive_pull(*, targets: list[str] | None, drive_base: str | None) -> None:try:- response = pull_drive_from_environment(prefix=path_prefix, drive_base=drive_base)+ response = pull_drive_from_environment(targets=targets, drive_base=drive_base or read_agent_stub_drive_base())except MissingAgentStubEnvironmentError as exc:typer.echo(str(exc), err=True)raise SystemExit(2) from excdiff --git a/dify-agent/src/dify_agent/agent_stub/protocol/__init__.py b/dify-agent/src/dify_agent/agent_stub/protocol/__init__.pyindex 18ea874a2a6..b607b3daa09 100644--- a/dify-agent/src/dify_agent/agent_stub/protocol/__init__.py+++ b/dify-agent/src/dify_agent/agent_stub/protocol/__init__.py@@ -2,8 +2,10 @@from .agent_stub import (AGENT_STUB_AUTH_JWE_ENV_VAR,+ AGENT_STUB_DRIVE_BASE_ENV_VAR,AGENT_STUB_PROTOCOL_VERSION,- AGENT_STUB_URL_ENV_VAR,+ AGENT_STUB_API_BASE_URL_ENV_VAR,+ DEFAULT_AGENT_STUB_DRIVE_BASE,AgentStubConnectRequest,AgentStubConnectResponse,AgentStubDriveCommitItem,@@ -20,19 +22,22 @@ from .agent_stub import (AgentStubFileUploadResponse,AgentStubURLScheme,agent_stub_connections_url,+ agent_stub_drive_base_for_ref,agent_stub_drive_commit_url,agent_stub_drive_manifest_url,agent_stub_file_download_request_url,agent_stub_file_upload_request_url,is_canonical_dify_file_reference,- normalize_agent_stub_url,+ normalize_agent_stub_api_base_url,parse_agent_stub_endpoint,)__all__ = ["AGENT_STUB_AUTH_JWE_ENV_VAR",+ "AGENT_STUB_DRIVE_BASE_ENV_VAR","AGENT_STUB_PROTOCOL_VERSION",- "AGENT_STUB_URL_ENV_VAR",+ "AGENT_STUB_API_BASE_URL_ENV_VAR",+ "DEFAULT_AGENT_STUB_DRIVE_BASE","AgentStubConnectRequest","AgentStubConnectResponse","AgentStubDriveCommitItem",@@ -49,11 +54,12 @@ __all__ = ["AgentStubFileUploadResponse","AgentStubURLScheme","agent_stub_connections_url",+ "agent_stub_drive_base_for_ref","agent_stub_drive_commit_url","agent_stub_drive_manifest_url","agent_stub_file_download_request_url","agent_stub_file_upload_request_url","is_canonical_dify_file_reference",- "normalize_agent_stub_url",+ "normalize_agent_stub_api_base_url","parse_agent_stub_endpoint",]diff --git a/dify-agent/src/dify_agent/agent_stub/protocol/agent_stub.py b/dify-agent/src/dify_agent/agent_stub/protocol/agent_stub.pyindex 16d5fa79532..a6a0d4793fe 100644--- a/dify-agent/src/dify_agent/agent_stub/protocol/agent_stub.py+++ b/dify-agent/src/dify_agent/agent_stub/protocol/agent_stub.py@@ -19,8 +19,10 @@ from pydantic import BaseModel, ConfigDict, Field, JsonValue, model_validatorAGENT_STUB_PROTOCOL_VERSION: Final[int] = 1-AGENT_STUB_URL_ENV_VAR: Final[str] = "DIFY_AGENT_STUB_URL"+AGENT_STUB_API_BASE_URL_ENV_VAR: Final[str] = "DIFY_AGENT_STUB_API_BASE_URL"AGENT_STUB_AUTH_JWE_ENV_VAR: Final[str] = "DIFY_AGENT_STUB_AUTH_JWE"+AGENT_STUB_DRIVE_BASE_ENV_VAR: Final[str] = "DIFY_AGENT_STUB_DRIVE_BASE"+DEFAULT_AGENT_STUB_DRIVE_BASE: Final[str] = "/mnt/drive"type AgentStubURLScheme = Literal["http", "https", "grpc"]@@ -44,14 +46,25 @@ class AgentStubEndpoint:return self.scheme == "grpc"+def agent_stub_drive_base_for_ref(drive_ref: str | None) -> str:+ """Return the fixed sandbox-local Agent Stub drive base for one drive ref."""+ normalized_ref = (drive_ref or "").strip()+ if not normalized_ref:+ return DEFAULT_AGENT_STUB_DRIVE_BASE+ drive_ref_parts = normalized_ref.split("/")+ if normalized_ref.startswith("/") or any(part in {"", ".", ".."} for part in drive_ref_parts):+ raise ValueError("Agent Stub drive_ref must be a safe relative path")+ return f"{DEFAULT_AGENT_STUB_DRIVE_BASE.rstrip('/')}/{'/'.join(drive_ref_parts)}"++def parse_agent_stub_endpoint(url: str) -> AgentStubEndpoint:"""Parse one Agent Stub endpoint URL for HTTP or gRPC transport selection.- HTTP(S) endpoints are normalized by trimming whitespace and removing a final- trailing slash from the path while preserving the configured base path.- gRPC endpoints must be plain ``grpc://host:port`` targets with no path,- query string, or fragment because transport routing happens on the gRPC- service name instead of an HTTP URL path.+ HTTP(S) endpoints accept either the service root or the explicit+ ``/agent-stub`` API root and normalize to the latter. gRPC endpoints must be+ plain ``grpc://host:port`` targets with no path, query string, or fragment+ because transport routing happens on the gRPC service name instead of an+ HTTP URL path."""stripped = url.strip()if not stripped:@@ -85,6 +98,10 @@ def parse_agent_stub_endpoint(url: str) -> AgentStubEndpoint:)normalized_path = parsed.path.rstrip("/")+ if normalized_path in {"", "/"}:+ normalized_path = "/agent-stub"+ elif normalized_path != "/agent-stub":+ raise ValueError("HTTP Agent Stub API base URL path must be empty or /agent-stub")normalized_url = urlunsplit((scheme, parsed.netloc, normalized_path, "", ""))return AgentStubEndpoint(url=normalized_url,@@ -95,8 +112,8 @@ def parse_agent_stub_endpoint(url: str) -> AgentStubEndpoint:)-def normalize_agent_stub_url(url: str) -> str:- """Return the normalized Agent Stub URL used across settings and CLI env."""+def normalize_agent_stub_api_base_url(url: str) -> str:+ """Return the normalized Agent Stub API base URL used across settings and CLI env."""return parse_agent_stub_endpoint(url).url@@ -233,8 +250,10 @@ class AgentStubDriveCommitItem(BaseModel):"""One drive key to file binding committed through the Agent Stub."""key: str- file_ref: AgentStubDriveFileRef+ file_ref: AgentStubDriveFileRef | None = Nonevalue_owned_by_drive: bool = True+ is_skill: bool = False+ skill_metadata: dict[str, str] | None = Nonemodel_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid")@@ -254,11 +273,14 @@ class AgentStubDriveItem(BaseModel):size: int | None = Nonehash: str | None = Nonemime_type: str | None = None- file_kind: Literal["upload_file", "tool_file"]- file_id: str+ file_kind: Literal["upload_file", "tool_file"] | None = None+ file_id: str | None = Nonecreated_at: int | None = Nonedownload_url: str | None = Nonevalue_owned_by_drive: bool | None = None+ removed: bool | None = None+ is_skill: bool | None = None+ skill_metadata: str | None = Nonemodel_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid")@@ -292,8 +314,10 @@ def _format_url_host(host: str) -> str:__all__ = ["AGENT_STUB_AUTH_JWE_ENV_VAR",+ "AGENT_STUB_DRIVE_BASE_ENV_VAR","AGENT_STUB_PROTOCOL_VERSION",- "AGENT_STUB_URL_ENV_VAR",+ "AGENT_STUB_API_BASE_URL_ENV_VAR",+ "DEFAULT_AGENT_STUB_DRIVE_BASE","AgentStubConnectRequest","AgentStubConnectResponse","AgentStubEndpoint",@@ -310,11 +334,12 @@ __all__ = ["AgentStubFileUploadResponse","AgentStubURLScheme","agent_stub_connections_url",+ "agent_stub_drive_base_for_ref","agent_stub_drive_commit_url","agent_stub_drive_manifest_url","agent_stub_file_download_request_url","agent_stub_file_upload_request_url","is_canonical_dify_file_reference",- "normalize_agent_stub_url",+ "normalize_agent_stub_api_base_url","parse_agent_stub_endpoint",]diff --git a/dify-agent/src/dify_agent/agent_stub/server/__init__.py b/dify-agent/src/dify_agent/agent_stub/server/__init__.pyindex 4521aa7bc01..b820cd0101c 100644--- a/dify-agent/src/dify_agent/agent_stub/server/__init__.py+++ b/dify-agent/src/dify_agent/agent_stub/server/__init__.py@@ -1,12 +1 @@"""Server-only helpers for running or embedding the Dify Agent Stub server."""--from .app import app, create_agent_stub_app-from .grpc_runtime import start_agent_stub_grpc_server-from .router import create_agent_stub_router--__all__ = [- "app",- "create_agent_stub_app",- "create_agent_stub_router",- "start_agent_stub_grpc_server",-]diff --git a/dify-agent/src/dify_agent/agent_stub/server/agent_stub_drive.py b/dify-agent/src/dify_agent/agent_stub/server/agent_stub_drive.pyindex 463cbd4a706..8c86e5bc806 100644--- a/dify-agent/src/dify_agent/agent_stub/server/agent_stub_drive.py+++ b/dify-agent/src/dify_agent/agent_stub/server/agent_stub_drive.py@@ -70,8 +70,8 @@ class DifyApiAgentStubDriveRequestHandler:so this module validates the raw success payload directly."""- dify_api_base_url: str- dify_api_inner_api_key: str+ inner_api_url: str+ inner_api_key: strtimeout: httpx.Timeout | float = 30.0async def get_manifest(@@ -139,13 +139,13 @@ class DifyApiAgentStubDriveRequestHandler:return f"agent-{agent_id}"async def _get_inner_api(self, path: str, params: Mapping[str, str]) -> object:- url = f"{self.dify_api_base_url.rstrip('/')}{path}"+ url = f"{self.inner_api_url.rstrip('/')}{path}"async with httpx.AsyncClient(timeout=self.timeout, follow_redirects=True, trust_env=False) as client:try:response = await client.get(url,params=dict(params),- headers={"X-Inner-Api-Key": self.dify_api_inner_api_key},+ headers={"X-Inner-Api-Key": self.inner_api_key},)except httpx.TimeoutException as exc:raise AgentStubDriveRequestError(504, "Dify API drive request timed out") from exc@@ -154,13 +154,13 @@ class DifyApiAgentStubDriveRequestHandler:return self._normalize_payload(response)async def _post_inner_api(self, path: str, payload: Mapping[str, Any]) -> object:- url = f"{self.dify_api_base_url.rstrip('/')}{path}"+ url = f"{self.inner_api_url.rstrip('/')}{path}"async with httpx.AsyncClient(timeout=self.timeout, follow_redirects=True, trust_env=False) as client:try:response = await client.post(url,json=dict(payload),- headers={"X-Inner-Api-Key": self.dify_api_inner_api_key},+ headers={"X-Inner-Api-Key": self.inner_api_key},)except httpx.TimeoutException as exc:raise AgentStubDriveRequestError(504, "Dify API drive request timed out") from excdiff --git a/dify-agent/src/dify_agent/agent_stub/server/agent_stub_files.py b/dify-agent/src/dify_agent/agent_stub/server/agent_stub_files.pyindex 06765f0897e..cedbb6e862d 100644--- a/dify-agent/src/dify_agent/agent_stub/server/agent_stub_files.py+++ b/dify-agent/src/dify_agent/agent_stub/server/agent_stub_files.py@@ -98,8 +98,8 @@ class DifyApiAgentStubFileRequestHandler:contract without exposing raw ``httpx`` or Pydantic exceptions."""- dify_api_base_url: str- dify_api_inner_api_key: str+ inner_api_url: str+ inner_api_key: strtimeout: httpx.Timeout | float = 30.0async def create_upload_request(@@ -174,13 +174,13 @@ class DifyApiAgentStubFileRequestHandler:return execution_contextasync def _post_inner_api(self, path: str, payload: Mapping[str, Any]) -> dict[str, Any]:- url = f"{self.dify_api_base_url.rstrip('/')}{path}"+ url = f"{self.inner_api_url.rstrip('/')}{path}"async with httpx.AsyncClient(timeout=self.timeout, follow_redirects=True, trust_env=False) as client:try:response = await client.post(url,json=dict(payload),- headers={"X-Inner-Api-Key": self.dify_api_inner_api_key},+ headers={"X-Inner-Api-Key": self.inner_api_key},)except httpx.TimeoutException as exc:raise AgentStubFileRequestError(504, "Dify API file request timed out") from excdiff --git a/dify-agent/src/dify_agent/agent_stub/server/cli.py b/dify-agent/src/dify_agent/agent_stub/server/cli.pyindex 734a66f20aa..ed16c1fc43a 100644--- a/dify-agent/src/dify_agent/agent_stub/server/cli.py+++ b/dify-agent/src/dify_agent/agent_stub/server/cli.py@@ -28,7 +28,7 @@ def main(argv: list[str] | None = None) -> None:Side effects:Starts either ``dify_agent.agent_stub.server.app:app`` via``uvicorn.run`` or the grpclib Agent Stub server depending on the- configured ``DIFY_AGENT_STUB_URL`` scheme.+ configured ``DIFY_AGENT_STUB_API_BASE_URL`` scheme."""parser = argparse.ArgumentParser(prog="dify-agent-stub-server")parser.add_argument("--host", default=None)@@ -36,7 +36,10 @@ def main(argv: list[str] | None = None) -> None:parser.add_argument("--reload", action="store_true")args = parser.parse_args(argv)settings = ServerSettings()- if settings.agent_stub_url is not None and parse_agent_stub_endpoint(settings.agent_stub_url).is_grpc:+ if (+ settings.agent_stub_api_base_url is not None+ and parse_agent_stub_endpoint(settings.agent_stub_api_base_url).is_grpc+ ):asyncio.run(_serve_grpc(settings=settings, host=args.host, port=args.port))returnuvicorn.run(@@ -49,14 +52,14 @@ def main(argv: list[str] | None = None) -> None:async def _serve_grpc(*, settings: ServerSettings, host: str | None, port: int | None) -> None:bind_target = derive_agent_stub_grpc_bind_target(- public_url=settings.agent_stub_url or "",+ public_url=settings.agent_stub_api_base_url or "",bind_address=settings.agent_stub_grpc_bind_address,)if host is not None or port is not None:bind_target = AgentStubGRPCBindTarget(host=host or bind_target.host, port=port or bind_target.port)server = await start_agent_stub_grpc_server(- public_url=settings.agent_stub_url or "",+ public_url=settings.agent_stub_api_base_url or "",bind_address=bind_target.address,token_codec=settings.create_agent_stub_token_codec(),file_request_handler=settings.create_agent_stub_file_request_handler(),diff --git a/dify-agent/src/dify_agent/agent_stub/server/shell_agent_stub_env.py b/dify-agent/src/dify_agent/agent_stub/server/shell_agent_stub_env.pyindex 1ed72213e86..b4711c213ac 100644--- a/dify-agent/src/dify_agent/agent_stub/server/shell_agent_stub_env.py+++ b/dify-agent/src/dify_agent/agent_stub/server/shell_agent_stub_env.py@@ -1,8 +1,9 @@"""Server-side environment injection helpers for Agent Stub forwarding.Only user-visible ``shell.run`` commands receive these variables. Internal-lifecycle commands remain free of Agent Stub credentials so workspace setup and-cleanup cannot accidentally inherit user-facing forwarding state.+lifecycle commands remain free of Agent Stub credentials and drive-base defaults+so workspace setup and cleanup cannot accidentally inherit user-facing forwarding+state."""from __future__ import annotations@@ -11,8 +12,10 @@ from typing import Protocolfrom dify_agent.agent_stub.protocol.agent_stub import (AGENT_STUB_AUTH_JWE_ENV_VAR,- AGENT_STUB_URL_ENV_VAR,- normalize_agent_stub_url,+ AGENT_STUB_DRIVE_BASE_ENV_VAR,+ AGENT_STUB_API_BASE_URL_ENV_VAR,+ agent_stub_drive_base_for_ref,+ normalize_agent_stub_api_base_url,)from dify_agent.layers.execution_context import DifyExecutionContextLayerConfig@@ -25,23 +28,31 @@ class ShellAgentStubTokenFactory(Protocol):def build_shell_agent_stub_env(*,- agent_stub_url: str | None,+ agent_stub_api_base_url: str | None,+ agent_stub_drive_ref: str | None = None,execution_context: DifyExecutionContextLayerConfig | None,token_factory: ShellAgentStubTokenFactory | None,session_id: str | None,) -> dict[str, str] | None:- """Build the shell-visible Agent Stub environment for one user command."""- if agent_stub_url is None or execution_context is None or token_factory is None:+ """Build the shell-visible Agent Stub environment for one user command.++ ``agent_stub_drive_ref`` is the storage reference from the bound+ ``dify.drive`` layer. The sandbox-local base is fixed by the Agent Stub+ contract and derived here at shell-run injection time.+ """+ if agent_stub_api_base_url is None or execution_context is None or token_factory is None:return Nonereturn {- AGENT_STUB_URL_ENV_VAR: normalize_agent_stub_url(agent_stub_url),+ AGENT_STUB_API_BASE_URL_ENV_VAR: normalize_agent_stub_api_base_url(agent_stub_api_base_url),AGENT_STUB_AUTH_JWE_ENV_VAR: token_factory(execution_context, session_id=session_id),+ AGENT_STUB_DRIVE_BASE_ENV_VAR: agent_stub_drive_base_for_ref(agent_stub_drive_ref),}__all__ = ["AGENT_STUB_AUTH_JWE_ENV_VAR",- "AGENT_STUB_URL_ENV_VAR",+ "AGENT_STUB_DRIVE_BASE_ENV_VAR",+ "AGENT_STUB_API_BASE_URL_ENV_VAR","ShellAgentStubTokenFactory","build_shell_agent_stub_env",]diff --git a/dify-agent/src/dify_agent/layers/drive/__init__.py b/dify-agent/src/dify_agent/layers/drive/__init__.pyindex 38ef6e66664..a38f77ed65a 100644--- a/dify-agent/src/dify_agent/layers/drive/__init__.py+++ b/dify-agent/src/dify_agent/layers/drive/__init__.py@@ -1,4 +1,4 @@-"""Client-safe exports for the Dify drive declaration layer DTOs.+"""Client-safe exports for the Dify drive runtime catalog DTOs.The layer implementation lives in the sibling ``layer`` module. Keep thispackage root import-safe for client code that only builds run requests.@@ -6,14 +6,12 @@ package root import-safe for client code that only builds run requests.from dify_agent.layers.drive.configs import (DIFY_DRIVE_LAYER_TYPE_ID,- DifyDriveFileConfig,DifyDriveLayerConfig,DifyDriveSkillConfig,)__all__ = ["DIFY_DRIVE_LAYER_TYPE_ID",- "DifyDriveFileConfig","DifyDriveLayerConfig","DifyDriveSkillConfig",]diff --git a/dify-agent/src/dify_agent/layers/drive/configs.py b/dify-agent/src/dify_agent/layers/drive/configs.pyindex d07dbcb7cfb..f74a24298fd 100644--- a/dify-agent/src/dify_agent/layers/drive/configs.py+++ b/dify-agent/src/dify_agent/layers/drive/configs.py@@ -1,11 +1,9 @@"""Client-safe DTOs for the Dify drive declaration layer.-The drive layer is a config-only manifest of the Skills & Files an agent has-in its drive. It is an index, never the content: each entry carries only a-display name, a model-facing description, and the drive key needed to fetch-the real bytes through the back proxy (``GET /inner/api/drive/<drive_ref>/-manifest`` → internal download URL). Inlining SKILL.md bodies here would break-the PRD's dynamic-loading principle and bloat every run request.+The drive layer carries the runtime drive catalog plus the prompt-mentioned+targets that must be pulled eagerly when the layer enters. It is still config+only: skills are declared as metadata, not content, and plain files are listed+only when the prompt explicitly mentions their drive keys.The API backend catalogs and writes this config; the Agent backend consumes it(ENG-387: pull via back proxy, lazy-load SKILL.md, materialize files).@@ -22,7 +20,7 @@ DIFY_DRIVE_LAYER_TYPE_ID: Final[str] = "dify.drive"class DifyDriveSkillConfig(BaseModel):- """Runtime declaration of one standardized skill — an index, not content."""+ """Runtime declaration of one standardized skill — metadata, not content."""model_config = ConfigDict(extra="forbid")@@ -33,35 +31,23 @@ class DifyDriveSkillConfig(BaseModel):skill_md_key: str# "<slug>/.DIFY-SKILL-FULL.zip" — full archive for restoring the complete skill.archive_key: str | None = None---class DifyDriveFileConfig(BaseModel):- """Runtime declaration of one plain drive file."""-- model_config = ConfigDict(extra="forbid")-- name: str- # "files/<filename>" — the drive key of the file value.- key: str- size: int | None = None- mime_type: str | None = None+ path: strclass DifyDriveLayerConfig(LayerConfig):- """Config-only declaration layer: API writes the catalog, the agent pulls- the listed entries through the back proxy using ``drive_ref``."""+ """Drive runtime catalog plus eager-pull instructions for mentioned targets."""# "agent-<agent_id>" — storage addressing, deliberately explicit instead of# derived from execution context so a shared (non-agent-bound) drive stays# possible later.drive_ref: strskills: list[DifyDriveSkillConfig] = Field(default_factory=list)- files: list[DifyDriveFileConfig] = Field(default_factory=list)+ mentioned_skill_keys: list[str] = Field(default_factory=list)+ mentioned_file_keys: list[str] = Field(default_factory=list)__all__ = ["DIFY_DRIVE_LAYER_TYPE_ID",- "DifyDriveFileConfig","DifyDriveLayerConfig","DifyDriveSkillConfig",]diff --git a/dify-agent/src/dify_agent/layers/drive/layer.py b/dify-agent/src/dify_agent/layers/drive/layer.pyindex 42f7011a51c..e38704d2b9d 100644--- a/dify-agent/src/dify_agent/layers/drive/layer.py+++ b/dify-agent/src/dify_agent/layers/drive/layer.py@@ -1,34 +1,328 @@-"""Inert Dify drive declaration layer.--Registering this layer makes ``dify.drive`` a known composition type id so a-run that carries the declaration never fails as "unknown layer type", even-before the consumption work (ENG-387) lands. It deliberately contributes no-prompt and no tools: a model that can see skill names but cannot read SKILL.md-would only hallucinate. The skills prompt (including the "pull SKILL.md via-drive" guidance) ships together with the consumption implementation.+"""Runtime Dify drive layer with eager pull for prompt-mentioned targets.++The API backend sends the full drive skill catalog plus the ordered drive keys+mentioned in the prompt. When the layer enters a run context it eagerly pulls+those mentioned skills/files from the Dify inner drive bridge, materializes them+under the fixed Agent Stub drive base for ``drive_ref``, and contributes a+concise prompt block describing what was loaded and what other skills remain+available for lazy pull."""-from dataclasses import dataclass-from typing import ClassVar+from __future__ import annotations++import asyncio+from dataclasses import dataclass, field+from pathlib import Path, PurePosixPath+from tempfile import TemporaryDirectory+from typing import Any, ClassVar, cast+from uuid import uuid4+from zipfile import BadZipFile, ZipFile, ZipInfo+import httpxfrom typing_extensions import Self, override-from agenton.layers import EmptyRuntimeState, NoLayerDeps, PlainLayer+from agenton.layers import EmptyRuntimeState, Layer, LayerDeps, PlainLayer+from dify_agent.agent_stub.protocol import agent_stub_drive_base_for_reffrom dify_agent.layers.drive.configs import DIFY_DRIVE_LAYER_TYPE_ID, DifyDriveLayerConfig+_SKILL_ARCHIVE_FILENAME = ".DIFY-SKILL-FULL.zip"+_DOWNLOAD_CONCURRENCY = 4+++class DifyDriveLayerError(RuntimeError):+ """Raised when one eager-pull drive operation fails."""+++class DifyDriveDeps(LayerDeps):+ execution_context: Layer[Any, Any, Any, Any, Any, Any] # pyright: ignore[reportUninitializedInstanceVariable]+++@dataclass(frozen=True, slots=True)+class _DriveManifestItem:+ key: str+ download_url: str+ size: int | None = None+@dataclass(slots=True)-class DifyDriveLayer(PlainLayer[NoLayerDeps, DifyDriveLayerConfig, EmptyRuntimeState]):- """Config-only carrier of the drive Skills & Files manifest."""+class DifyDriveLayer(PlainLayer[DifyDriveDeps, DifyDriveLayerConfig, EmptyRuntimeState]):+ """Drive runtime layer that eagerly materializes prompt-mentioned drive targets."""type_id: ClassVar[str | None] = DIFY_DRIVE_LAYER_TYPE_IDconfig: DifyDriveLayerConfig+ inner_api_url: str+ inner_api_key: str+ _loaded_skill_bodies: dict[str, str] = field(default_factory=dict)+ _pulled_file_paths: dict[str, str] = field(default_factory=dict)@classmethod@overridedef from_config(cls, config: DifyDriveLayerConfig) -> Self:- return cls(config=config)+ del config+ raise TypeError("DifyDriveLayer requires server-side Dify API settings and must use a provider factory.")++ @classmethod+ def from_config_with_settings(+ cls,+ config: DifyDriveLayerConfig,+ *,+ inner_api_url: str,+ inner_api_key: str,+ ) -> Self:+ return cls(+ config=DifyDriveLayerConfig.model_validate(config),+ inner_api_url=inner_api_url.rstrip("/"),+ inner_api_key=inner_api_key,+ )++ @property+ @override+ def prefix_prompts(self) -> list[str]:+ return [self.build_prompt_context()]++ @override+ async def on_context_create(self) -> None:+ await self._pull_mentioned_targets()++ @override+ async def on_context_resume(self) -> None:+ await self._pull_mentioned_targets()++ def build_prompt_context(self) -> str:+ sections: list[str] = []++ loaded_skill_sections: list[str] = []+ for skill_key in self.config.mentioned_skill_keys:+ body = self._loaded_skill_bodies.get(skill_key)+ if body is None:+ continue+ skill = next((item for item in self.config.skills if item.skill_md_key == skill_key), None)+ if skill is None:+ continue+ loaded_skill_sections.append(f"Path: {skill.path}\nName: {skill.name}\nSKILL.md:\n{body}")+ if loaded_skill_sections:+ sections.append("Loaded mentioned skills:\n\n" + "\n\n".join(loaded_skill_sections))++ mentioned_files = [+ f"- {key} -> {self._pulled_file_paths[key]}"+ for key in self.config.mentioned_file_keys+ if key in self._pulled_file_paths+ ]+ if mentioned_files:+ sections.append("Mentioned files pulled to local drive:\n" + "\n".join(mentioned_files))++ other_skills = [+ f"- {skill.path}: {skill.name} — {skill.description}"+ for skill in self.config.skills+ if skill.skill_md_key not in set(self.config.mentioned_skill_keys)+ ]+ if other_skills:+ sections.append("Other available skills:\n" + "\n".join(other_skills))++ if not sections:+ return ""+ sections.append(+ "Additional drive skills/files can be pulled lazily later with the Agent Stub drive commands if needed."+ )+ return "\n\n".join(sections)++ async def _pull_mentioned_targets(self) -> None:+ self._loaded_skill_bodies = {}+ self._pulled_file_paths = {}+ targets: list[tuple[str, bool]] = [+ (self._skill_prefix(skill_key), False) for skill_key in self.config.mentioned_skill_keys+ ] + [(file_key, True) for file_key in self.config.mentioned_file_keys]+ if not targets:+ return++ tenant_id = self._require_tenant_id()+ manifest_items = await self._fetch_manifest_items(tenant_id=tenant_id, targets=targets)+ written_paths = await self._download_items(manifest_items)+ self._pulled_file_paths = written_paths+ for file_key in self.config.mentioned_file_keys:+ if file_key not in written_paths:+ raise DifyDriveLayerError(f"missing pulled file for mentioned drive key {file_key}")+ for skill_key in self.config.mentioned_skill_keys:+ skill_path = written_paths.get(skill_key)+ if skill_path is None:+ raise DifyDriveLayerError(f"missing pulled SKILL.md for mentioned skill {skill_key}")+ try:+ self._loaded_skill_bodies[skill_key] = Path(skill_path).read_text(encoding="utf-8")+ except (OSError, UnicodeError) as exc:+ raise DifyDriveLayerError(f"failed to load pulled SKILL.md for mentioned skill {skill_key}") from exc++ async def _fetch_manifest_items(+ self,+ *,+ tenant_id: str,+ targets: list[tuple[str, bool]],+ ) -> list[_DriveManifestItem]:+ semaphore = asyncio.Semaphore(_DOWNLOAD_CONCURRENCY)++ async with httpx.AsyncClient(timeout=30.0, follow_redirects=True, trust_env=False) as client:++ async def fetch_one(target: tuple[str, bool]) -> list[_DriveManifestItem]:+ prefix, exact = target+ try:+ async with semaphore:+ response = await client.get(+ f"{self.inner_api_url}/inner/api/drive/{self.config.drive_ref}/manifest",+ params={+ "tenant_id": tenant_id,+ "prefix": prefix,+ "include_download_url": "true",+ },+ headers={"X-Inner-Api-Key": self.inner_api_key},+ )+ except (httpx.InvalidURL, httpx.TimeoutException, httpx.RequestError) as exc:+ raise DifyDriveLayerError(f"drive manifest request failed for {prefix}") from exc+ if response.is_error:+ raise DifyDriveLayerError(f"drive manifest request failed for {prefix}: {response.status_code}")+ try:+ payload = response.json()+ except ValueError as exc:+ raise DifyDriveLayerError(f"drive manifest response is invalid for {prefix}") from exc+ items = payload.get("items") if isinstance(payload, dict) else None+ if not isinstance(items, list):+ raise DifyDriveLayerError(f"drive manifest response is invalid for {prefix}")+ manifest_items: list[_DriveManifestItem] = []+ for item in items:+ if not isinstance(item, dict):+ continue+ key = item.get("key")+ download_url = item.get("download_url")+ if not isinstance(key, str) or not isinstance(download_url, str) or not download_url:+ raise DifyDriveLayerError(f"drive manifest item is missing download_url for {prefix}")+ if exact and key != prefix:+ continue+ manifest_items.append(_DriveManifestItem(key=key, download_url=download_url, size=item.get("size")))+ return manifest_items++ grouped_items = await asyncio.gather(*(fetch_one(target) for target in targets))++ deduplicated: dict[str, _DriveManifestItem] = {}+ for items in grouped_items:+ for item in items:+ deduplicated.setdefault(item.key, item)+ return [deduplicated[key] for key in sorted(deduplicated)]++ async def _download_items(self, items: list[_DriveManifestItem]) -> dict[str, str]:+ base_path = Path(agent_stub_drive_base_for_ref(self.config.drive_ref))+ try:+ base_path.mkdir(parents=True, exist_ok=True)+ except OSError as exc:+ raise DifyDriveLayerError(f"failed to prepare drive base {base_path}") from exc+ semaphore = asyncio.Semaphore(_DOWNLOAD_CONCURRENCY)+ archive_paths: list[Path] = []+ canonical_skill_dirs = {item.key.rsplit("/", 1)[0] for item in items if item.key.endswith("/SKILL.md")}++ async with httpx.AsyncClient(timeout=30.0, follow_redirects=True, trust_env=False) as client:++ async def download_one(item: _DriveManifestItem) -> tuple[str, str]:+ try:+ async with semaphore:+ response = await client.get(item.download_url)+ except (httpx.InvalidURL, httpx.TimeoutException, httpx.RequestError) as exc:+ raise DifyDriveLayerError(f"drive download failed for {item.key}") from exc+ if response.is_error:+ raise DifyDriveLayerError(f"drive download failed for {item.key}: {response.status_code}")+ payload = response.content+ if item.size is not None and len(payload) != item.size:+ raise DifyDriveLayerError(f"downloaded drive file size mismatch for {item.key}")+ try:+ destination = _resolve_drive_destination(base_path, item.key)+ destination.parent.mkdir(parents=True, exist_ok=True)+ temp_path = destination.with_name(f"{destination.name}.tmp-{uuid4().hex}")+ temp_path.write_bytes(payload)+ temp_path.replace(destination)+ except OSError as exc:+ raise DifyDriveLayerError(f"failed to materialize drive file {item.key}") from exc+ if destination.name == _SKILL_ARCHIVE_FILENAME:+ archive_paths.append(destination)+ return item.key, str(destination)++ pairs = await asyncio.gather(*(download_one(item) for item in items))+ for archive_path in sorted(archive_paths):+ archive_skill_dir = archive_path.parent.relative_to(base_path).as_posix()+ skip_entry_names = {"SKILL.md"} if archive_skill_dir in canonical_skill_dirs else set()+ _extract_skill_archive(archive_path, skip_entry_names=skip_entry_names)+ return {key: path for key, path in pairs}++ def _require_tenant_id(self) -> str:+ execution_context = self.deps.execution_context.config+ tenant_id = getattr(execution_context, "tenant_id", None)+ if not isinstance(tenant_id, str) or not tenant_id.strip():+ raise DifyDriveLayerError("DifyDriveLayer requires execution_context.tenant_id")+ return cast(str, tenant_id).strip()++ @staticmethod+ def _skill_prefix(skill_key: str) -> str:+ return f"{skill_key.rsplit('/', 1)[0]}/"+++def _resolve_drive_destination(base_path: Path, drive_key: str) -> Path:+ destination = (base_path / Path(drive_key)).resolve()+ try:+ destination.relative_to(base_path)+ except ValueError as exc:+ raise DifyDriveLayerError(f"drive key resolves outside the drive base: {drive_key}") from exc+ return destination+++def _extract_skill_archive(archive_path: Path, *, skip_entry_names: set[str]) -> None:+ target_dir = archive_path.parent.resolve()+ try:+ with TemporaryDirectory(dir=target_dir, prefix=".dify-skill-extract-") as staging_dir_name:+ staging_dir = Path(staging_dir_name).resolve()+ with ZipFile(archive_path) as archive:+ for zip_info in archive.infolist():+ if zip_info.filename.replace("\\", "/").rstrip("/") in skip_entry_names:+ continue+ destination = _resolve_zip_entry_destination(staging_dir, zip_info.filename)+ if _is_zip_symlink(zip_info):+ raise DifyDriveLayerError(+ f"skill archive contains unsupported symlink entry: {zip_info.filename}"+ )+ if zip_info.is_dir():+ destination.mkdir(parents=True, exist_ok=True)+ continue+ destination.parent.mkdir(parents=True, exist_ok=True)+ with archive.open(zip_info) as source_file:+ temp_path = destination.with_name(f"{destination.name}.tmp-{uuid4().hex}")+ temp_path.write_bytes(source_file.read())+ temp_path.replace(destination)+ for staged_path in sorted(staging_dir.rglob("*")):+ if staged_path.is_dir():+ continue+ relative_path = staged_path.relative_to(staging_dir)+ destination = (target_dir / relative_path).resolve()+ destination.parent.mkdir(parents=True, exist_ok=True)+ staged_path.replace(destination)+ except DifyDriveLayerError:+ raise+ except (BadZipFile, OSError) as exc:+ raise DifyDriveLayerError(f"downloaded skill archive is invalid: {archive_path.name}") from exc+++def _resolve_zip_entry_destination(target_dir: Path, entry_name: str) -> Path:+ normalized_name = entry_name.replace("\\", "/")+ pure_path = PurePosixPath(normalized_name)+ if not normalized_name or normalized_name.startswith("/") or pure_path.is_absolute():+ raise DifyDriveLayerError(f"skill archive contains unsafe absolute path: {entry_name}")+ if any(part in {"", ".", ".."} for part in pure_path.parts):+ raise DifyDriveLayerError(f"skill archive contains unsafe path traversal entry: {entry_name}")+ destination = (target_dir / Path(*pure_path.parts)).resolve()+ try:+ destination.relative_to(target_dir)+ except ValueError as exc:+ raise DifyDriveLayerError(f"skill archive entry resolves outside the skill directory: {entry_name}") from exc+ return destination+++def _is_zip_symlink(zip_info: ZipInfo) -> bool:+ file_mode = zip_info.external_attr >> 16+ return (file_mode & 0o170000) == 0o120000-__all__ = ["DifyDriveLayer"]+__all__ = ["DifyDriveLayer", "DifyDriveLayerError"]diff --git a/dify-agent/src/dify_agent/layers/knowledge/layer.py b/dify-agent/src/dify_agent/layers/knowledge/layer.pyindex 16605a9ceb3..02c9f07dd56 100644--- a/dify-agent/src/dify_agent/layers/knowledge/layer.py+++ b/dify-agent/src/dify_agent/layers/knowledge/layer.py@@ -67,8 +67,8 @@ class DifyKnowledgeBaseLayer(PlainLayer[DifyKnowledgeBaseDeps, DifyKnowledgeBasetype_id: ClassVar[str | None] = DIFY_KNOWLEDGE_BASE_LAYER_TYPE_IDconfig: DifyKnowledgeBaseLayerConfig- dify_api_inner_url: str- dify_api_inner_api_key: str+ inner_api_url: str+ inner_api_key: str@classmethod@override@@ -84,14 +84,14 @@ class DifyKnowledgeBaseLayer(PlainLayer[DifyKnowledgeBaseDeps, DifyKnowledgeBasecls,config: DifyKnowledgeBaseLayerConfig,*,- dify_api_inner_url: str,- dify_api_inner_api_key: str,+ inner_api_url: str,+ inner_api_key: str,) -> Self:"""Create the layer from public config plus server-only API settings."""return cls(config=DifyKnowledgeBaseLayerConfig.model_validate(config),- dify_api_inner_url=dify_api_inner_url,- dify_api_inner_api_key=dify_api_inner_api_key,+ inner_api_url=inner_api_url,+ inner_api_key=inner_api_key,)async def get_tools(self, *, http_client: httpx.AsyncClient) -> list[Tool[object]]:@@ -114,8 +114,8 @@ class DifyKnowledgeBaseLayer(PlainLayer[DifyKnowledgeBaseDeps, DifyKnowledgeBaseexecution_context = self.deps.execution_context.configcaller = _build_caller_context(execution_context)client = DifyKnowledgeBaseClient(- base_url=self.dify_api_inner_url,- api_key=self.dify_api_inner_api_key,+ base_url=self.inner_api_url,+ api_key=self.inner_api_key,http_client=http_client,)diff --git a/dify-agent/src/dify_agent/layers/shell/layer.py b/dify-agent/src/dify_agent/layers/shell/layer.pyindex 52824e20050..5db17d68499 100644--- a/dify-agent/src/dify_agent/layers/shell/layer.py+++ b/dify-agent/src/dify_agent/layers/shell/layer.py@@ -49,6 +49,7 @@ from typing_extensions import Self, overridefrom agenton.layers import LayerDeps, PydanticAILayer, PydanticAIPrompt, PydanticAIToolfrom dify_agent.agent_stub.server.shell_agent_stub_env import ShellAgentStubTokenFactory, build_shell_agent_stub_env+from dify_agent.layers.drive.layer import DifyDriveLayerfrom dify_agent.layers.execution_context.layer import DifyExecutionContextLayerfrom dify_agent.layers.shell.configs import DIFY_SHELL_LAYER_TYPE_ID, DifyShellLayerConfig@@ -168,8 +169,13 @@ type ShellInterruptToolResult = ShellJobStatusObservation | ShellToolErrorObservclass DifyShellLayerDeps(LayerDeps):- """Optional direct-layer dependencies used by the shell runtime layer."""+ """Optional direct-layer dependencies used by the shell runtime layer.+ The drive dependency supplies the drive ref for injected+ Agent Stub CLI commands; the execution context supplies the token principal.+ """++ drive: DifyDriveLayer | None # pyright: ignore[reportUninitializedInstanceVariable]execution_context: DifyExecutionContextLayer | None # pyright: ignore[reportUninitializedInstanceVariable]@@ -307,7 +313,7 @@ class DifyShellLayer(PydanticAILayer[DifyShellLayerDeps, object, DifyShellLayerCconfig: DifyShellLayerConfigshellctl_entrypoint: strshellctl_client_factory: ShellctlClientFactory- agent_stub_url: str | None = None+ agent_stub_api_base_url: str | None = Noneagent_stub_token_factory: ShellAgentStubTokenFactory | None = None_shellctl_client: ShellctlClientProtocol | None = None@@ -325,7 +331,7 @@ class DifyShellLayer(PydanticAILayer[DifyShellLayerDeps, object, DifyShellLayerC*,shellctl_entrypoint: str | None,shellctl_client_factory: ShellctlClientFactory,- agent_stub_url: str | None = None,+ agent_stub_api_base_url: str | None = None,agent_stub_token_factory: ShellAgentStubTokenFactory | None = None,) -> Self:"""Create the layer from public config plus server-only shell settings."""@@ -338,7 +344,7 @@ class DifyShellLayer(PydanticAILayer[DifyShellLayerDeps, object, DifyShellLayerCconfig=config,shellctl_entrypoint=normalized_entrypoint,shellctl_client_factory=shellctl_client_factory,- agent_stub_url=agent_stub_url,+ agent_stub_api_base_url=agent_stub_api_base_url,agent_stub_token_factory=agent_stub_token_factory,)layer.bind_deps({})@@ -760,8 +766,10 @@ class DifyShellLayer(PydanticAILayer[DifyShellLayerDeps, object, DifyShellLayerC"""Build per-command Agent Stub env only for user-visible ``shell.run``."""execution_context_layer = self.deps.execution_contextexecution_context = execution_context_layer.config if execution_context_layer is not None else None+ drive_layer = self.deps.drivereturn build_shell_agent_stub_env(- agent_stub_url=self.agent_stub_url,+ agent_stub_api_base_url=self.agent_stub_api_base_url,+ agent_stub_drive_ref=drive_layer.config.drive_ref if drive_layer is not None else None,execution_context=execution_context,token_factory=self.agent_stub_token_factory,session_id=self.runtime_state.session_id,diff --git a/dify-agent/src/dify_agent/runtime/compositor_factory.py b/dify-agent/src/dify_agent/runtime/compositor_factory.pyindex a637dce7767..0cfab33ad0d 100644--- a/dify-agent/src/dify_agent/runtime/compositor_factory.py+++ b/dify-agent/src/dify_agent/runtime/compositor_factory.py@@ -6,7 +6,7 @@ state-free Dify structured output layer, the optional Dify ask-human layer, theDify execution-context layer, the stateful Dify shell layer, and the Difyplugin/knowledge business-layer family:-- ``dify.drive`` for the inert Skills & Files drive declaration,+- ``dify.drive`` for drive-backed skill catalog + eager pull,- ``dify.execution_context`` for shared tenant/user/run daemon context,- ``dify.shell`` for shellctl-backed shell job control,- ``dify.plugin.llm`` for plugin-backed model selection,@@ -38,6 +38,7 @@ from dify_agent.agent_stub.server.tokens.agent_stub import AgentStubTokenCodecfrom dify_agent.layers.ask_human.layer import DifyAskHumanLayerfrom dify_agent.layers.dify_plugin.llm_layer import DifyPluginLLMLayerfrom dify_agent.layers.dify_plugin.tools_layer import DifyPluginToolsLayer+from dify_agent.layers.drive import DifyDriveLayerConfigfrom dify_agent.layers.drive.layer import DifyDriveLayerfrom dify_agent.layers.execution_context.configs import DifyExecutionContextLayerConfigfrom dify_agent.layers.execution_context.layer import DifyExecutionContextLayer@@ -54,11 +55,11 @@ def create_default_layer_providers(*,plugin_daemon_url: str = "http://localhost:5002",plugin_daemon_api_key: str = "",- dify_api_inner_url: str = "http://localhost:5001",- dify_api_inner_api_key: str = "",+ inner_api_url: str = "http://localhost:5001",+ inner_api_key: str = "",shellctl_entrypoint: str | None = None,shellctl_auth_token: str | None = None,- agent_stub_url: str | None = None,+ agent_stub_api_base_url: str | None = None,agent_stub_token_codec: AgentStubTokenCodec | None = None,) -> tuple[DifyAgentLayerProvider, ...]:"""Return the server provider set of safe config-constructible layers.@@ -89,10 +90,14 @@ def create_default_layer_providers(LayerProvider.from_layer_type(PydanticAIHistoryLayer),LayerProvider.from_layer_type(DifyOutputLayer),LayerProvider.from_layer_type(DifyAskHumanLayer),- # Inert declaration layer: makes ``dify.drive`` a known type id so runs- # carrying the Skills & Files manifest never fail before the consumption- # work (ENG-387) lands. Deliberately contributes no prompt and no tools.- LayerProvider.from_layer_type(DifyDriveLayer),+ LayerProvider.from_factory(+ layer_type=DifyDriveLayer,+ create=lambda config: DifyDriveLayer.from_config_with_settings(+ DifyDriveLayerConfig.model_validate(config),+ inner_api_url=inner_api_url,+ inner_api_key=inner_api_key,+ ),+ ),LayerProvider.from_factory(layer_type=DifyExecutionContextLayer,create=lambda config: DifyExecutionContextLayer.from_config_with_settings(@@ -107,7 +112,7 @@ def create_default_layer_providers(DifyShellLayerConfig.model_validate(config),shellctl_entrypoint=shellctl_entrypoint,shellctl_client_factory=create_shellctl_client_factory(token=shellctl_token),- agent_stub_url=agent_stub_url,+ agent_stub_api_base_url=agent_stub_api_base_url,agent_stub_token_factory=agent_stub_token_factory,),),@@ -117,8 +122,8 @@ def create_default_layer_providers(layer_type=DifyKnowledgeBaseLayer,create=lambda config: DifyKnowledgeBaseLayer.from_config_with_settings(DifyKnowledgeBaseLayerConfig.model_validate(config),- dify_api_inner_url=dify_api_inner_url,- dify_api_inner_api_key=dify_api_inner_api_key,+ inner_api_url=inner_api_url,+ inner_api_key=inner_api_key,),),)diff --git a/dify-agent/src/dify_agent/server/app.py b/dify-agent/src/dify_agent/server/app.pyindex 42b406799bb..cc3760da393 100644--- a/dify-agent/src/dify_agent/server/app.py+++ b/dify-agent/src/dify_agent/server/app.py@@ -10,7 +10,7 @@ stay state-only: they borrow the lifespan-owned clients through the runner andreceive shell-layer server settings through provider construction rather thanreading environment variables themselves. The standard server always mounts theHTTP Agent Stub router and additionally starts the optional grpclib Agent Stub-server when ``DIFY_AGENT_STUB_URL`` uses ``grpc://``.+server when ``DIFY_AGENT_STUB_API_BASE_URL`` uses ``grpc://``."""from collections.abc import AsyncGenerator@@ -41,11 +41,11 @@ def create_app(settings: ServerSettings | None = None) -> FastAPI:layer_providers = create_default_layer_providers(plugin_daemon_url=resolved_settings.plugin_daemon_url,plugin_daemon_api_key=resolved_settings.plugin_daemon_api_key,- dify_api_inner_url=resolved_settings.dify_api_inner_url,- dify_api_inner_api_key=resolved_settings.dify_api_inner_api_key or "",+ inner_api_url=resolved_settings.inner_api_url,+ inner_api_key=resolved_settings.inner_api_key or "",shellctl_entrypoint=resolved_settings.shellctl_entrypoint,shellctl_auth_token=resolved_settings.shellctl_auth_token,- agent_stub_url=resolved_settings.agent_stub_url,+ agent_stub_api_base_url=resolved_settings.agent_stub_api_base_url,agent_stub_token_codec=agent_stub_token_codec,)sandbox_file_service = (@@ -72,11 +72,11 @@ def create_app(settings: ServerSettings | None = None) -> FastAPI:)grpc_server = Noneif (- resolved_settings.agent_stub_url is not None- and parse_agent_stub_endpoint(resolved_settings.agent_stub_url).is_grpc+ resolved_settings.agent_stub_api_base_url is not None+ and parse_agent_stub_endpoint(resolved_settings.agent_stub_api_base_url).is_grpc):grpc_server = await start_agent_stub_grpc_server(- public_url=resolved_settings.agent_stub_url,+ public_url=resolved_settings.agent_stub_api_base_url,bind_address=resolved_settings.agent_stub_grpc_bind_address,token_codec=agent_stub_token_codec,file_request_handler=agent_stub_file_request_handler,diff --git a/dify-agent/src/dify_agent/server/settings.py b/dify-agent/src/dify_agent/server/settings.pyindex b85fcffdc36..7c16a8e50b1 100644--- a/dify-agent/src/dify_agent/server/settings.py+++ b/dify-agent/src/dify_agent/server/settings.py@@ -5,9 +5,9 @@ Outbound HTTP client settings describe the FastAPI lifespan-ownedDify API inner calls. Layers and Agenton providers do not own those clients, sothese settings are process resource limits rather than per-run lifecycle knobs.Endpoint URLs and API keys stay service-specific. The Agent Stub also uses this-settings model directly: the public Agent Stub URL, server secret, optional gRPC-bind override, and optional Dify inner API file/drive request settings all live-here under the longstanding ``DIFY_AGENT_...`` environment-variable namespace.+settings model directly: the public Agent Stub API base URL, server secret,+optional gRPC bind override, and optional Dify inner API bridge settings all+live here under the ``DIFY_AGENT_...`` environment-variable namespace."""import httpx@@ -17,7 +17,7 @@ from typing import ClassVarfrom pydantic import AnyHttpUrl, Field, TypeAdapter, field_validator, model_validatorfrom pydantic_settings import BaseSettings, SettingsConfigDict-from dify_agent.agent_stub.protocol.agent_stub import normalize_agent_stub_url, parse_agent_stub_endpoint+from dify_agent.agent_stub.protocol.agent_stub import normalize_agent_stub_api_base_url, parse_agent_stub_endpointfrom dify_agent.agent_stub.server.agent_stub_drive import DifyApiAgentStubDriveRequestHandlerfrom dify_agent.agent_stub.server.agent_stub_files import DifyApiAgentStubFileRequestHandlerfrom dify_agent.agent_stub.server.grpc_bind import normalize_agent_stub_grpc_bind_address@@ -35,12 +35,11 @@ class ServerSettings(BaseSettings):run_retention_seconds: int = Field(default=DEFAULT_RUN_RETENTION_SECONDS, ge=1)plugin_daemon_url: str = "http://localhost:5002"plugin_daemon_api_key: str = ""- dify_api_inner_url: str = "http://localhost:5001"- dify_api_base_url: str | None = None- dify_api_inner_api_key: str | None = None+ inner_api_url: str = "http://localhost:5001"+ inner_api_key: str | None = Noneshellctl_entrypoint: str | None = Noneshellctl_auth_token: str | None = None- agent_stub_url: str | None = Field(default=None, validation_alias="DIFY_AGENT_STUB_URL")+ agent_stub_api_base_url: str | None = Field(default=None, validation_alias="DIFY_AGENT_STUB_API_BASE_URL")agent_stub_grpc_bind_address: str | None = Field(default=None, validation_alias="DIFY_AGENT_STUB_GRPC_BIND_ADDRESS")server_secret_key: str | None = Noneoutbound_http_connect_timeout: float = Field(default=10.0, ge=0)@@ -58,9 +57,9 @@ class ServerSettings(BaseSettings):populate_by_name=True,)- @field_validator("agent_stub_url")+ @field_validator("agent_stub_api_base_url")@classmethod- def normalize_agent_stub_url_value(cls, value: str | None) -> str | None:+ def normalize_agent_stub_api_base_url_value(cls, value: str | None) -> str | None:"""Normalize the public Agent Stub URL while still validating its scheme."""if value is None:return None@@ -69,8 +68,8 @@ class ServerSettings(BaseSettings):return Noneif stripped.startswith(("http://", "https://")):validated = str(TypeAdapter(AnyHttpUrl).validate_python(stripped))- return normalize_agent_stub_url(validated)- return normalize_agent_stub_url(stripped)+ return normalize_agent_stub_api_base_url(validated)+ return normalize_agent_stub_api_base_url(stripped)@field_validator("agent_stub_grpc_bind_address")@classmethod@@ -95,24 +94,22 @@ class ServerSettings(BaseSettings):_ = decode_server_secret_key(stripped)return stripped- @field_validator("dify_api_base_url")+ @field_validator("inner_api_url")@classmethod- def normalize_dify_api_base_url(cls, value: str | None) -> str | None:- """Normalize the trusted Dify API base URL used for file request calls."""- if value is None:- return None+ def normalize_inner_api_url(cls, value: str) -> str:+ """Normalize the trusted Dify API base URL used for inner API calls."""stripped = value.strip()if not stripped:- return None+ raise ValueError("DIFY_AGENT_INNER_API_URL must not be empty")validated = str(TypeAdapter(AnyHttpUrl).validate_python(stripped))parsed = validated.rstrip("/")if "?" in parsed or "#" in parsed:- raise ValueError("DIFY_AGENT_DIFY_API_BASE_URL must not include a query string or fragment")+ raise ValueError("DIFY_AGENT_INNER_API_URL must not include a query string or fragment")return parsed- @field_validator("dify_api_inner_api_key")+ @field_validator("inner_api_key")@classmethod- def normalize_dify_api_inner_api_key(cls, value: str | None) -> str | None:+ def normalize_inner_api_key(cls, value: str | None) -> str | None:"""Normalize the optional trusted Dify inner API key."""if value is None:return None@@ -121,16 +118,16 @@ class ServerSettings(BaseSettings):@model_validator(mode="after")def validate_agent_stub_requirements(self) -> "ServerSettings":- """Require Agent Stub settings while allowing knowledge-only inner API keys."""- if self.agent_stub_url is not None and self.server_secret_key is None:- raise ValueError("DIFY_AGENT_SERVER_SECRET_KEY is required when DIFY_AGENT_STUB_URL is set.")+ """Require Agent Stub settings while allowing deployments without inner API calls."""+ if self.agent_stub_api_base_url is not None and self.server_secret_key is None:+ raise ValueError("DIFY_AGENT_SERVER_SECRET_KEY is required when DIFY_AGENT_STUB_API_BASE_URL is set.")if self.agent_stub_grpc_bind_address is not None:- if self.agent_stub_url is None:- raise ValueError("DIFY_AGENT_STUB_URL is required when DIFY_AGENT_STUB_GRPC_BIND_ADDRESS is set.")- if not parse_agent_stub_endpoint(self.agent_stub_url).is_grpc:- raise ValueError("DIFY_AGENT_STUB_GRPC_BIND_ADDRESS requires a grpc:// DIFY_AGENT_STUB_URL.")- if self.dify_api_base_url is not None and self.dify_api_inner_api_key is None:- raise ValueError("DIFY_AGENT_DIFY_API_INNER_API_KEY is required when DIFY_AGENT_DIFY_API_BASE_URL is set.")+ if self.agent_stub_api_base_url is None:+ raise ValueError(+ "DIFY_AGENT_STUB_API_BASE_URL is required when DIFY_AGENT_STUB_GRPC_BIND_ADDRESS is set."+ )+ if not parse_agent_stub_endpoint(self.agent_stub_api_base_url).is_grpc:+ raise ValueError("DIFY_AGENT_STUB_GRPC_BIND_ADDRESS requires a grpc:// DIFY_AGENT_STUB_API_BASE_URL.")return selfdef create_agent_stub_token_codec(self) -> AgentStubTokenCodec | None:@@ -141,11 +138,11 @@ class ServerSettings(BaseSettings):def create_agent_stub_file_request_handler(self) -> DifyApiAgentStubFileRequestHandler | None:"""Return the Dify API file bridge when both Dify API settings are configured."""- if self.dify_api_base_url is None or self.dify_api_inner_api_key is None:+ if self.inner_api_key is None:return Nonereturn DifyApiAgentStubFileRequestHandler(- dify_api_base_url=self.dify_api_base_url,- dify_api_inner_api_key=self.dify_api_inner_api_key,+ inner_api_url=self.inner_api_url,+ inner_api_key=self.inner_api_key,)def create_agent_stub_drive_request_handler(self) -> DifyApiAgentStubDriveRequestHandler | None:@@ -154,11 +151,11 @@ class ServerSettings(BaseSettings):Drive manifest and commit requests should honor the same outbound timeoutsettings as the server's other trusted Dify API HTTP calls."""- if self.dify_api_base_url is None or self.dify_api_inner_api_key is None:+ if self.inner_api_key is None:return Nonereturn DifyApiAgentStubDriveRequestHandler(- dify_api_base_url=self.dify_api_base_url,- dify_api_inner_api_key=self.dify_api_inner_api_key,+ inner_api_url=self.inner_api_url,+ inner_api_key=self.inner_api_key,timeout=self.create_outbound_http_timeout(),)diff --git a/dify-agent/tests/local/dify_agent/agent_stub/cli/test_drive.py b/dify-agent/tests/local/dify_agent/agent_stub/cli/test_drive.pyindex ff52bb6b4f8..6e45e14a034 100644--- a/dify-agent/tests/local/dify_agent/agent_stub/cli/test_drive.py+++ b/dify-agent/tests/local/dify_agent/agent_stub/cli/test_drive.py@@ -23,7 +23,7 @@ from dify_agent.agent_stub.protocol.agent_stub import (def test_list_drive_from_environment_returns_manifest_json_model(monkeypatch: pytest.MonkeyPatch) -> None:- monkeypatch.setenv("DIFY_AGENT_STUB_URL", "https://agent.example.com/agent-stub")+ monkeypatch.setenv("DIFY_AGENT_STUB_API_BASE_URL", "https://agent.example.com/agent-stub")monkeypatch.setenv("DIFY_AGENT_STUB_AUTH_JWE", "test-jwe")captured: dict[str, object] = {}@@ -56,7 +56,7 @@ def test_list_drive_from_environment_returns_manifest_json_model(monkeypatch: pydef test_list_drive_from_environment_returns_human_readable_listing(monkeypatch: pytest.MonkeyPatch) -> None:- monkeypatch.setenv("DIFY_AGENT_STUB_URL", "https://agent.example.com/agent-stub")+ monkeypatch.setenv("DIFY_AGENT_STUB_API_BASE_URL", "https://agent.example.com/agent-stub")monkeypatch.setenv("DIFY_AGENT_STUB_AUTH_JWE", "test-jwe")captured: dict[str, object] = {}@@ -99,7 +99,7 @@ def test_pull_drive_from_environment_writes_files_under_drive_base(monkeypatch: pytest.MonkeyPatch,tmp_path: Path,) -> None:- monkeypatch.setenv("DIFY_AGENT_STUB_URL", "https://agent.example.com/agent-stub")+ monkeypatch.setenv("DIFY_AGENT_STUB_API_BASE_URL", "https://agent.example.com/agent-stub")monkeypatch.setenv("DIFY_AGENT_STUB_AUTH_JWE", "test-jwe")captured: dict[str, object] = {}@@ -128,7 +128,7 @@ def test_pull_drive_from_environment_writes_files_under_drive_base(lambda **_kwargs: b"hello world",)- results = pull_drive_from_environment(prefix="skills/", drive_base=str(tmp_path))+ results = pull_drive_from_environment(targets=["skills/"], drive_base=str(tmp_path))assert results == [tmp_path / "skills" / "example" / "SKILL.md"]assert results[0].read_bytes() == b"hello world"@@ -146,7 +146,7 @@ def test_pull_drive_from_environment_auto_extracts_skill_archive(archive.writestr("nested/helper.py", "print('x')\n")archive_bytes = archive_buffer.getvalue()- monkeypatch.setenv("DIFY_AGENT_STUB_URL", "https://agent.example.com/agent-stub")+ monkeypatch.setenv("DIFY_AGENT_STUB_API_BASE_URL", "https://agent.example.com/agent-stub")monkeypatch.setenv("DIFY_AGENT_STUB_AUTH_JWE", "test-jwe")monkeypatch.setattr("dify_agent.agent_stub.cli._drive.request_agent_stub_drive_manifest_sync",@@ -169,7 +169,7 @@ def test_pull_drive_from_environment_auto_extracts_skill_archive(lambda **_kwargs: archive_bytes,)- results = pull_drive_from_environment(prefix="skills/foo", drive_base=str(tmp_path))+ results = pull_drive_from_environment(targets=["skills/foo"], drive_base=str(tmp_path))archive_path = tmp_path / "skills" / "foo" / ".DIFY-SKILL-FULL.zip"assert results == [archive_path]@@ -182,7 +182,7 @@ def test_pull_drive_from_environment_rejects_traversal_keys(monkeypatch: pytest.MonkeyPatch,tmp_path: Path,) -> None:- monkeypatch.setenv("DIFY_AGENT_STUB_URL", "https://agent.example.com/agent-stub")+ monkeypatch.setenv("DIFY_AGENT_STUB_API_BASE_URL", "https://agent.example.com/agent-stub")monkeypatch.setenv("DIFY_AGENT_STUB_AUTH_JWE", "test-jwe")monkeypatch.setattr("dify_agent.agent_stub.cli._drive.request_agent_stub_drive_manifest_sync",@@ -202,7 +202,7 @@ def test_pull_drive_from_environment_rejects_traversal_keys()with pytest.raises(AgentStubValidationError, match="outside the drive base"):- _ = pull_drive_from_environment(prefix="", drive_base=str(tmp_path))+ _ = pull_drive_from_environment(targets=[""], drive_base=str(tmp_path))def test_pull_drive_from_environment_rejects_skill_archive_path_traversal(@@ -215,7 +215,7 @@ def test_pull_drive_from_environment_rejects_skill_archive_path_traversal(archive.writestr("../escape.txt", "escape")archive_bytes = archive_buffer.getvalue()- monkeypatch.setenv("DIFY_AGENT_STUB_URL", "https://agent.example.com/agent-stub")+ monkeypatch.setenv("DIFY_AGENT_STUB_API_BASE_URL", "https://agent.example.com/agent-stub")monkeypatch.setenv("DIFY_AGENT_STUB_AUTH_JWE", "test-jwe")monkeypatch.setattr("dify_agent.agent_stub.cli._drive.request_agent_stub_drive_manifest_sync",@@ -239,7 +239,7 @@ def test_pull_drive_from_environment_rejects_skill_archive_path_traversal()with pytest.raises(AgentStubValidationError, match="path traversal"):- _ = pull_drive_from_environment(prefix="skills/foo", drive_base=str(tmp_path))+ _ = pull_drive_from_environment(targets=["skills/foo"], drive_base=str(tmp_path))assert not (tmp_path / "skills" / "foo" / "SKILL.md").exists()@@ -252,7 +252,7 @@ def test_pull_drive_from_environment_rejects_skill_archive_absolute_entry(archive.writestr("/escape.txt", "escape")archive_bytes = archive_buffer.getvalue()- monkeypatch.setenv("DIFY_AGENT_STUB_URL", "https://agent.example.com/agent-stub")+ monkeypatch.setenv("DIFY_AGENT_STUB_API_BASE_URL", "https://agent.example.com/agent-stub")monkeypatch.setenv("DIFY_AGENT_STUB_AUTH_JWE", "test-jwe")monkeypatch.setattr("dify_agent.agent_stub.cli._drive.request_agent_stub_drive_manifest_sync",@@ -276,7 +276,7 @@ def test_pull_drive_from_environment_rejects_skill_archive_absolute_entry()with pytest.raises(AgentStubValidationError, match="absolute path"):- _ = pull_drive_from_environment(prefix="skills/foo", drive_base=str(tmp_path))+ _ = pull_drive_from_environment(targets=["skills/foo"], drive_base=str(tmp_path))def test_pull_drive_from_environment_rejects_skill_archive_symlink_entry(@@ -290,7 +290,7 @@ def test_pull_drive_from_environment_rejects_skill_archive_symlink_entry(archive.writestr(symlink_info, "outside.txt")archive_bytes = archive_buffer.getvalue()- monkeypatch.setenv("DIFY_AGENT_STUB_URL", "https://agent.example.com/agent-stub")+ monkeypatch.setenv("DIFY_AGENT_STUB_API_BASE_URL", "https://agent.example.com/agent-stub")monkeypatch.setenv("DIFY_AGENT_STUB_AUTH_JWE", "test-jwe")monkeypatch.setattr("dify_agent.agent_stub.cli._drive.request_agent_stub_drive_manifest_sync",@@ -314,7 +314,7 @@ def test_pull_drive_from_environment_rejects_skill_archive_symlink_entry()with pytest.raises(AgentStubValidationError, match="symlink entry"):- _ = pull_drive_from_environment(prefix="skills/foo", drive_base=str(tmp_path))+ _ = pull_drive_from_environment(targets=["skills/foo"], drive_base=str(tmp_path))def test_pull_drive_from_environment_rejects_invalid_skill_archive(@@ -323,7 +323,7 @@ def test_pull_drive_from_environment_rejects_invalid_skill_archive() -> None:archive_bytes = b"not-a-zip"- monkeypatch.setenv("DIFY_AGENT_STUB_URL", "https://agent.example.com/agent-stub")+ monkeypatch.setenv("DIFY_AGENT_STUB_API_BASE_URL", "https://agent.example.com/agent-stub")monkeypatch.setenv("DIFY_AGENT_STUB_AUTH_JWE", "test-jwe")monkeypatch.setattr("dify_agent.agent_stub.cli._drive.request_agent_stub_drive_manifest_sync",@@ -347,14 +347,14 @@ def test_pull_drive_from_environment_rejects_invalid_skill_archive()with pytest.raises(AgentStubTransferError, match="downloaded skill archive is invalid"):- _ = pull_drive_from_environment(prefix="skills/foo", drive_base=str(tmp_path))+ _ = pull_drive_from_environment(targets=["skills/foo"], drive_base=str(tmp_path))def test_pull_drive_from_environment_rejects_missing_download_url(monkeypatch: pytest.MonkeyPatch,tmp_path: Path,) -> None:- monkeypatch.setenv("DIFY_AGENT_STUB_URL", "https://agent.example.com/agent-stub")+ monkeypatch.setenv("DIFY_AGENT_STUB_API_BASE_URL", "https://agent.example.com/agent-stub")monkeypatch.setenv("DIFY_AGENT_STUB_AUTH_JWE", "test-jwe")monkeypatch.setattr("dify_agent.agent_stub.cli._drive.request_agent_stub_drive_manifest_sync",@@ -373,14 +373,14 @@ def test_pull_drive_from_environment_rejects_missing_download_url()with pytest.raises(AgentStubValidationError, match="missing download_url"):- _ = pull_drive_from_environment(prefix="skills/", drive_base=str(tmp_path))+ _ = pull_drive_from_environment(targets=["skills/"], drive_base=str(tmp_path))def test_pull_drive_from_environment_rejects_size_mismatch(monkeypatch: pytest.MonkeyPatch,tmp_path: Path,) -> None:- monkeypatch.setenv("DIFY_AGENT_STUB_URL", "https://agent.example.com/agent-stub")+ monkeypatch.setenv("DIFY_AGENT_STUB_API_BASE_URL", "https://agent.example.com/agent-stub")monkeypatch.setenv("DIFY_AGENT_STUB_AUTH_JWE", "test-jwe")monkeypatch.setattr("dify_agent.agent_stub.cli._drive.request_agent_stub_drive_manifest_sync",@@ -404,13 +404,92 @@ def test_pull_drive_from_environment_rejects_size_mismatch()with pytest.raises(AgentStubTransferError, match="size mismatch"):- _ = pull_drive_from_environment(prefix="skills/", drive_base=str(tmp_path))+ _ = pull_drive_from_environment(targets=["skills/"], drive_base=str(tmp_path))+++def test_pull_drive_from_environment_requests_multiple_targets_and_deduplicates_overlaps(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ monkeypatch.setenv("DIFY_AGENT_STUB_API_BASE_URL", "https://agent.example.com/agent-stub")+ monkeypatch.setenv("DIFY_AGENT_STUB_AUTH_JWE", "test-jwe")+ captured_prefixes: list[str] = []++ def fake_manifest(**kwargs):+ captured_prefixes.append(kwargs["prefix"])+ if kwargs["prefix"] == "skills/foo":+ return AgentStubDriveManifestResponse(+ items=[+ AgentStubDriveItem(+ key="skills/foo/SKILL.md",+ size=5,+ hash=None,+ mime_type="text/markdown",+ file_kind="tool_file",+ file_id="tool-file-1",+ download_url="https://files.example.com/skill-md",+ )+ ]+ )+ return AgentStubDriveManifestResponse(+ items=[+ AgentStubDriveItem(+ key="skills/foo/SKILL.md",+ size=5,+ hash=None,+ mime_type="text/markdown",+ file_kind="tool_file",+ file_id="tool-file-1",+ download_url="https://files.example.com/skill-md",+ ),+ AgentStubDriveItem(+ key="files/a.txt",+ size=1,+ hash=None,+ mime_type="text/plain",+ file_kind="tool_file",+ file_id="tool-file-2",+ download_url="https://files.example.com/a-txt",+ ),+ ]+ )++ downloaded_urls: list[str] = []+ monkeypatch.setattr("dify_agent.agent_stub.cli._drive.request_agent_stub_drive_manifest_sync", fake_manifest)+ monkeypatch.setattr(+ "dify_agent.agent_stub.cli._drive.download_file_bytes_from_signed_url_sync",+ lambda *, download_url: (+ downloaded_urls.append(download_url) or (b"hello" if download_url.endswith("skill-md") else b"a")+ ),+ )++ results = pull_drive_from_environment(targets=["skills/foo", "files/a.txt"], drive_base=str(tmp_path))++ assert captured_prefixes == ["skills/foo", "files/a.txt"]+ assert results == [tmp_path / "files" / "a.txt", tmp_path / "skills" / "foo" / "SKILL.md"]+ assert downloaded_urls == ["https://files.example.com/a-txt", "https://files.example.com/skill-md"]+++def test_pull_drive_from_environment_without_targets_preserves_whole_drive_pull(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ monkeypatch.setenv("DIFY_AGENT_STUB_API_BASE_URL", "https://agent.example.com/agent-stub")+ monkeypatch.setenv("DIFY_AGENT_STUB_AUTH_JWE", "test-jwe")+ captured_prefixes: list[str] = []+ monkeypatch.setattr(+ "dify_agent.agent_stub.cli._drive.request_agent_stub_drive_manifest_sync",+ lambda **kwargs: captured_prefixes.append(kwargs["prefix"]) or AgentStubDriveManifestResponse(items=[]),+ )++ assert pull_drive_from_environment(drive_base=str(tmp_path)) == []+ assert captured_prefixes == [""]def test_push_drive_from_environment_commits_single_file(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:source = tmp_path / "report.pdf"source.write_bytes(b"report")- monkeypatch.setenv("DIFY_AGENT_STUB_URL", "https://agent.example.com/agent-stub")+ monkeypatch.setenv("DIFY_AGENT_STUB_API_BASE_URL", "https://agent.example.com/agent-stub")monkeypatch.setenv("DIFY_AGENT_STUB_AUTH_JWE", "test-jwe")monkeypatch.setattr("dify_agent.agent_stub.cli._drive.upload_tool_file_resource_from_environment",@@ -448,6 +527,8 @@ def test_push_drive_from_environment_commits_single_file(monkeypatch: pytest.Mon"key": "files/report.pdf","file_ref": {"kind": "tool_file", "id": "tool-file-1"},"value_owned_by_drive": True,+ "is_skill": False,+ "skill_metadata": None,}@@ -457,7 +538,7 @@ def test_push_drive_from_environment_requires_skill_md_for_non_recursive_directo) -> None:skill_dir = tmp_path / "skill"skill_dir.mkdir()- monkeypatch.setenv("DIFY_AGENT_STUB_URL", "https://agent.example.com/agent-stub")+ monkeypatch.setenv("DIFY_AGENT_STUB_API_BASE_URL", "https://agent.example.com/agent-stub")monkeypatch.setenv("DIFY_AGENT_STUB_AUTH_JWE", "test-jwe")with pytest.raises(AgentStubValidationError, match="SKILL.md"):@@ -472,7 +553,7 @@ def test_push_drive_from_environment_standardizes_non_recursive_skill_directory(skill_dir.mkdir()(skill_dir / "SKILL.md").write_text("# Example\n", encoding="utf-8")(skill_dir / "helper.py").write_text("print('x')\n", encoding="utf-8")- monkeypatch.setenv("DIFY_AGENT_STUB_URL", "https://agent.example.com/agent-stub")+ monkeypatch.setenv("DIFY_AGENT_STUB_API_BASE_URL", "https://agent.example.com/agent-stub")monkeypatch.setenv("DIFY_AGENT_STUB_AUTH_JWE", "test-jwe")uploaded_paths: list[str] = []@@ -527,7 +608,7 @@ def test_push_drive_from_environment_non_recursive_archive_excludes_transient_enpycache_dir = skill_dir / "__pycache__"pycache_dir.mkdir()(pycache_dir / "helper.pyc").write_bytes(b"compiled")- monkeypatch.setenv("DIFY_AGENT_STUB_URL", "https://agent.example.com/agent-stub")+ monkeypatch.setenv("DIFY_AGENT_STUB_API_BASE_URL", "https://agent.example.com/agent-stub")monkeypatch.setenv("DIFY_AGENT_STUB_AUTH_JWE", "test-jwe")archive_entries: list[str] = []@@ -578,7 +659,7 @@ def test_push_drive_from_environment_non_recursive_rejects_symlinked_archive_entoutside = tmp_path / "outside.txt"outside.write_text("outside", encoding="utf-8")(skill_dir / "linked.txt").symlink_to(outside)- monkeypatch.setenv("DIFY_AGENT_STUB_URL", "https://agent.example.com/agent-stub")+ monkeypatch.setenv("DIFY_AGENT_STUB_API_BASE_URL", "https://agent.example.com/agent-stub")monkeypatch.setenv("DIFY_AGENT_STUB_AUTH_JWE", "test-jwe")with pytest.raises(AgentStubValidationError, match="symlink"):@@ -594,7 +675,7 @@ def test_push_drive_from_environment_rejects_symlinked_recursive_files(outside = tmp_path / "outside.txt"outside.write_text("outside", encoding="utf-8")(root / "linked.txt").symlink_to(outside)- monkeypatch.setenv("DIFY_AGENT_STUB_URL", "https://agent.example.com/agent-stub")+ monkeypatch.setenv("DIFY_AGENT_STUB_API_BASE_URL", "https://agent.example.com/agent-stub")monkeypatch.setenv("DIFY_AGENT_STUB_AUTH_JWE", "test-jwe")with pytest.raises(AgentStubValidationError, match="symlink"):@@ -611,7 +692,7 @@ def test_push_drive_from_environment_recursive_keeps_user_files_that_skill_packanode_modules_dir = root / "node_modules"node_modules_dir.mkdir()(node_modules_dir / "module.js").write_text("export default 1\n", encoding="utf-8")- monkeypatch.setenv("DIFY_AGENT_STUB_URL", "https://agent.example.com/agent-stub")+ monkeypatch.setenv("DIFY_AGENT_STUB_API_BASE_URL", "https://agent.example.com/agent-stub")monkeypatch.setenv("DIFY_AGENT_STUB_AUTH_JWE", "test-jwe")uploaded_paths: list[str] = []diff --git a/dify-agent/tests/local/dify_agent/agent_stub/cli/test_files.py b/dify-agent/tests/local/dify_agent/agent_stub/cli/test_files.pyindex c5b093128fd..f2de6e8edc5 100644--- a/dify-agent/tests/local/dify_agent/agent_stub/cli/test_files.py+++ b/dify-agent/tests/local/dify_agent/agent_stub/cli/test_files.py@@ -25,7 +25,7 @@ def test_upload_file_from_environment_requests_signed_url_and_normalizes_output() -> None:source = tmp_path / "report.pdf"source.write_bytes(b"report-bytes")- monkeypatch.setenv("DIFY_AGENT_STUB_URL", "https://agent.example.com/agent-stub")+ monkeypatch.setenv("DIFY_AGENT_STUB_API_BASE_URL", "https://agent.example.com/agent-stub")monkeypatch.setenv("DIFY_AGENT_STUB_AUTH_JWE", "test-jwe")monkeypatch.setattr(@@ -68,7 +68,7 @@ def test_upload_tool_file_resource_from_environment_preserves_tool_file_id() -> None:source = tmp_path / "report.pdf"source.write_bytes(b"report-bytes")- monkeypatch.setenv("DIFY_AGENT_STUB_URL", "https://agent.example.com/agent-stub")+ monkeypatch.setenv("DIFY_AGENT_STUB_API_BASE_URL", "https://agent.example.com/agent-stub")monkeypatch.setenv("DIFY_AGENT_STUB_AUTH_JWE", "test-jwe")monkeypatch.setattr(@@ -96,7 +96,7 @@ def test_download_file_from_environment_saves_bytes_and_renames_on_collision(target_dir = tmp_path / "downloads"target_dir.mkdir()(target_dir / "report.pdf").write_bytes(b"existing")- monkeypatch.setenv("DIFY_AGENT_STUB_URL", "https://agent.example.com/agent-stub")+ monkeypatch.setenv("DIFY_AGENT_STUB_API_BASE_URL", "https://agent.example.com/agent-stub")monkeypatch.setenv("DIFY_AGENT_STUB_AUTH_JWE", "test-jwe")monkeypatch.setattr(@@ -133,7 +133,7 @@ def test_download_file_from_environment_sanitizes_server_filename() -> None:target_dir = tmp_path / "downloads"target_dir.mkdir()- monkeypatch.setenv("DIFY_AGENT_STUB_URL", "https://agent.example.com/agent-stub")+ monkeypatch.setenv("DIFY_AGENT_STUB_API_BASE_URL", "https://agent.example.com/agent-stub")monkeypatch.setenv("DIFY_AGENT_STUB_AUTH_JWE", "test-jwe")monkeypatch.setattr(@@ -171,7 +171,7 @@ def test_upload_file_from_environment_rejects_non_canonical_reference() -> None:source = tmp_path / "report.pdf"source.write_bytes(b"report-bytes")- monkeypatch.setenv("DIFY_AGENT_STUB_URL", "https://agent.example.com/agent-stub")+ monkeypatch.setenv("DIFY_AGENT_STUB_API_BASE_URL", "https://agent.example.com/agent-stub")monkeypatch.setenv("DIFY_AGENT_STUB_AUTH_JWE", "test-jwe")monkeypatch.setattr(@@ -193,7 +193,7 @@ def test_upload_tool_file_resource_from_environment_rejects_missing_id() -> None:source = tmp_path / "report.pdf"source.write_bytes(b"report-bytes")- monkeypatch.setenv("DIFY_AGENT_STUB_URL", "https://agent.example.com/agent-stub")+ monkeypatch.setenv("DIFY_AGENT_STUB_API_BASE_URL", "https://agent.example.com/agent-stub")monkeypatch.setenv("DIFY_AGENT_STUB_AUTH_JWE", "test-jwe")monkeypatch.setattr(diff --git a/dify-agent/tests/local/dify_agent/agent_stub/cli/test_main.py b/dify-agent/tests/local/dify_agent/agent_stub/cli/test_main.pyindex 8699ac99e13..d66b801778c 100644--- a/dify-agent/tests/local/dify_agent/agent_stub/cli/test_main.py+++ b/dify-agent/tests/local/dify_agent/agent_stub/cli/test_main.py@@ -26,7 +26,7 @@ def test_cli_connect_reports_missing_environment_variables(capsys: pytest.Capturcaptured = capsys.readouterr()assert exc_info.value.code == 2- assert "DIFY_AGENT_STUB_URL" in captured.err+ assert "DIFY_AGENT_STUB_API_BASE_URL" in captured.errassert "DIFY_AGENT_STUB_AUTH_JWE" in captured.err@@ -34,7 +34,7 @@ def test_cli_connect_supports_json_output(monkeypatch: pytest.MonkeyPatch,capsys: pytest.CaptureFixture[str],) -> None:- monkeypatch.setenv("DIFY_AGENT_STUB_URL", "https://agent.example.com/agent-stub")+ monkeypatch.setenv("DIFY_AGENT_STUB_API_BASE_URL", "https://agent.example.com/agent-stub")monkeypatch.setenv("DIFY_AGENT_STUB_AUTH_JWE", "test-jwe")def fake_connect_from_environment(*, argv: list[str]) -> AgentStubConnectResponse:@@ -53,7 +53,7 @@ def test_cli_unknown_command_auto_forwards_when_agent_stub_env_is_present(monkeypatch: pytest.MonkeyPatch,capsys: pytest.CaptureFixture[str],) -> None:- monkeypatch.setenv("DIFY_AGENT_STUB_URL", "https://agent.example.com/agent-stub")+ monkeypatch.setenv("DIFY_AGENT_STUB_API_BASE_URL", "https://agent.example.com/agent-stub")monkeypatch.setenv("DIFY_AGENT_STUB_AUTH_JWE", "test-jwe")def fake_connect_from_environment(*, argv: list[str]) -> AgentStubConnectResponse:@@ -78,7 +78,7 @@ def test_cli_unknown_command_reports_missing_environment_variables(assert exc_info.value.code == 2assert "Usage: dify-agent" in captured.outassert "connect" in captured.out- assert "DIFY_AGENT_STUB_URL" in captured.err+ assert "DIFY_AGENT_STUB_API_BASE_URL" in captured.errassert "DIFY_AGENT_STUB_AUTH_JWE" in captured.err@@ -92,11 +92,11 @@ def test_cli_connect_help_routes_to_typer_help(capsys: pytest.CaptureFixture[strassert "--json" in captured.out-def test_cli_reports_invalid_agent_stub_url_environment_value(+def test_cli_reports_invalid_agent_stub_api_base_url_environment_value(monkeypatch: pytest.MonkeyPatch,capsys: pytest.CaptureFixture[str],) -> None:- monkeypatch.setenv("DIFY_AGENT_STUB_URL", "https://agent.example.com/agent-stub?x=1")+ monkeypatch.setenv("DIFY_AGENT_STUB_API_BASE_URL", "https://agent.example.com/agent-stub?x=1")monkeypatch.setenv("DIFY_AGENT_STUB_AUTH_JWE", "test-jwe")with pytest.raises(SystemExit) as exc_info:@@ -104,7 +104,7 @@ def test_cli_reports_invalid_agent_stub_url_environment_value(captured = capsys.readouterr()assert exc_info.value.code == 2- assert "invalid DIFY_AGENT_STUB_URL" in captured.err+ assert "invalid DIFY_AGENT_STUB_API_BASE_URL" in captured.errassert "query string or fragment" in captured.err@@ -117,13 +117,13 @@ def test_cli_reports_invalid_agent_stub_url_environment_value(("grpc://agent.example.com", "explicit port"),],)-def test_cli_reports_structurally_invalid_agent_stub_url_environment_value(+def test_cli_reports_structurally_invalid_agent_stub_api_base_url_environment_value(monkeypatch: pytest.MonkeyPatch,capsys: pytest.CaptureFixture[str],invalid_url: str,expected_message: str,) -> None:- monkeypatch.setenv("DIFY_AGENT_STUB_URL", invalid_url)+ monkeypatch.setenv("DIFY_AGENT_STUB_API_BASE_URL", invalid_url)monkeypatch.setenv("DIFY_AGENT_STUB_AUTH_JWE", "test-jwe")with pytest.raises(SystemExit) as exc_info:@@ -131,14 +131,14 @@ def test_cli_reports_structurally_invalid_agent_stub_url_environment_value(captured = capsys.readouterr()assert exc_info.value.code == 2- assert "invalid DIFY_AGENT_STUB_URL" in captured.err+ assert "invalid DIFY_AGENT_STUB_API_BASE_URL" in captured.errassert expected_message in captured.err-def test_cli_connect_accepts_grpc_agent_stub_url(+def test_cli_connect_accepts_grpc_agent_stub_api_base_url(monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]) -> None:- monkeypatch.setenv("DIFY_AGENT_STUB_URL", "grpc://agent.example.com:9091")+ monkeypatch.setenv("DIFY_AGENT_STUB_API_BASE_URL", "grpc://agent.example.com:9091")monkeypatch.setenv("DIFY_AGENT_STUB_AUTH_JWE", "test-jwe")def fake_connect_from_environment(*, argv: list[str]) -> AgentStubConnectResponse:@@ -252,7 +252,10 @@ def test_cli_drive_pull_prints_downloaded_paths() -> None:monkeypatch.setattr("dify_agent.agent_stub.cli.main.pull_drive_from_environment",- lambda *, prefix, drive_base: [Path(drive_base) / prefix / "SKILL.md", Path(drive_base) / prefix / "helper.py"],+ lambda *, targets, drive_base: [+ Path(drive_base) / targets[0] / "SKILL.md",+ Path(drive_base) / targets[0] / "helper.py",+ ],)with pytest.raises(SystemExit) as exc_info:@@ -266,6 +269,83 @@ def test_cli_drive_pull_prints_downloaded_paths(]+def test_cli_drive_pull_forwards_multiple_targets(+ monkeypatch: pytest.MonkeyPatch,+ capsys: pytest.CaptureFixture[str],+) -> None:+ captured_kwargs: dict[str, object] = {}++ def fake_pull_drive_from_environment(*, targets, drive_base):+ captured_kwargs["targets"] = targets+ captured_kwargs["drive_base"] = drive_base+ return [Path(drive_base) / "skills" / "foo" / "SKILL.md"]++ monkeypatch.setattr(+ "dify_agent.agent_stub.cli.main.pull_drive_from_environment",+ fake_pull_drive_from_environment,+ )++ with pytest.raises(SystemExit) as exc_info:+ main(["drive", "pull", "skills/foo", "files/a.txt", "--drive-base", "/tmp/drive"])++ captured = capsys.readouterr()+ assert exc_info.value.code == 0+ assert captured_kwargs == {"targets": ["skills/foo", "files/a.txt"], "drive_base": "/tmp/drive"}+ assert captured.out.strip() == "/tmp/drive/skills/foo/SKILL.md"+++def test_cli_drive_pull_uses_environment_drive_base_default(+ monkeypatch: pytest.MonkeyPatch,+ capsys: pytest.CaptureFixture[str],+) -> None:+ monkeypatch.setenv("DIFY_AGENT_STUB_DRIVE_BASE", "/env/drive")+ captured_kwargs: dict[str, object] = {}++ def fake_pull_drive_from_environment(*, targets, drive_base):+ captured_kwargs["targets"] = targets+ captured_kwargs["drive_base"] = drive_base+ return [Path(drive_base) / "skills" / "foo" / "SKILL.md"]++ monkeypatch.setattr(+ "dify_agent.agent_stub.cli.main.pull_drive_from_environment",+ fake_pull_drive_from_environment,+ )++ with pytest.raises(SystemExit) as exc_info:+ main(["drive", "pull", "skills/foo"])++ captured = capsys.readouterr()+ assert exc_info.value.code == 0+ assert captured_kwargs == {"targets": ["skills/foo"], "drive_base": "/env/drive"}+ assert captured.out.strip() == "/env/drive/skills/foo/SKILL.md"+++def test_cli_drive_pull_keeps_historical_drive_base_when_env_is_missing(+ monkeypatch: pytest.MonkeyPatch,+ capsys: pytest.CaptureFixture[str],+) -> None:+ monkeypatch.delenv("DIFY_AGENT_STUB_DRIVE_BASE", raising=False)+ captured_kwargs: dict[str, object] = {}++ def fake_pull_drive_from_environment(*, targets, drive_base):+ captured_kwargs["targets"] = targets+ captured_kwargs["drive_base"] = drive_base+ return [Path(drive_base) / "skills" / "foo" / "SKILL.md"]++ monkeypatch.setattr(+ "dify_agent.agent_stub.cli.main.pull_drive_from_environment",+ fake_pull_drive_from_environment,+ )++ with pytest.raises(SystemExit) as exc_info:+ main(["drive", "pull", "skills/foo"])++ captured = capsys.readouterr()+ assert exc_info.value.code == 0+ assert captured_kwargs == {"targets": ["skills/foo"], "drive_base": "/mnt/drive"}+ assert captured.out.strip() == "/mnt/drive/skills/foo/SKILL.md"++def test_cli_drive_push_prints_commit_json(monkeypatch: pytest.MonkeyPatch,capsys: pytest.CaptureFixture[str],diff --git a/dify-agent/tests/local/dify_agent/agent_stub/client/test_agent_stub_client.py b/dify-agent/tests/local/dify_agent/agent_stub/client/test_agent_stub_client.pyindex f62cc4564e9..dcca5144607 100644--- a/dify-agent/tests/local/dify_agent/agent_stub/client/test_agent_stub_client.py+++ b/dify-agent/tests/local/dify_agent/agent_stub/client/test_agent_stub_client.py@@ -66,7 +66,9 @@ def test_connect_agent_stub_sync_posts_connections_request_with_authorization()def test_connect_agent_stub_sync_rejects_invalid_base_url() -> None:- with pytest.raises(AgentStubValidationError, match="invalid DIFY_AGENT_STUB_URL|invalid Agent Stub base URL"):+ with pytest.raises(+ AgentStubValidationError, match="invalid DIFY_AGENT_STUB_API_BASE_URL|invalid Agent Stub base URL"+ ):_ = connect_agent_stub_sync(url="https://agent.example.com/agent-stub?x=1",auth_jwe="test-jwe",diff --git a/dify-agent/tests/local/dify_agent/agent_stub/protocol/test_agent_stub_protocol.py b/dify-agent/tests/local/dify_agent/agent_stub/protocol/test_agent_stub_protocol.pyindex dccde1b42b5..f4bc75291fc 100644--- a/dify-agent/tests/local/dify_agent/agent_stub/protocol/test_agent_stub_protocol.py+++ b/dify-agent/tests/local/dify_agent/agent_stub/protocol/test_agent_stub_protocol.py@@ -13,11 +13,12 @@ from dify_agent.agent_stub.protocol.agent_stub import (AgentStubDriveFileRef,AgentStubFileMapping,agent_stub_connections_url,+ agent_stub_drive_base_for_ref,agent_stub_drive_commit_url,agent_stub_drive_manifest_url,agent_stub_file_download_request_url,agent_stub_file_upload_request_url,- normalize_agent_stub_url,+ normalize_agent_stub_api_base_url,parse_agent_stub_endpoint,)@@ -36,6 +37,12 @@ def test_agent_stub_connections_url_handles_trailing_slash_and_no_trailing_slash)+def test_agent_stub_connections_url_normalizes_service_root_to_agent_stub_base() -> None:+ assert agent_stub_connections_url("https://agent.example.com") == (+ "https://agent.example.com/agent-stub/connections"+ )++def test_agent_stub_file_request_urls_handle_trailing_slash() -> None:assert agent_stub_file_upload_request_url("https://agent.example.com/agent-stub/") == ("https://agent.example.com/agent-stub/files/upload-request"@@ -54,23 +61,52 @@ def test_agent_stub_drive_request_urls_handle_trailing_slash() -> None:)-def test_normalize_agent_stub_url_rejects_query_and_fragment() -> None:+def test_agent_stub_drive_base_for_ref_uses_fixed_mount_with_drive_ref() -> None:+ assert agent_stub_drive_base_for_ref("agent-1") == "/mnt/drive/agent-1"+ assert agent_stub_drive_base_for_ref("shared/drive") == "/mnt/drive/shared/drive"+++def test_agent_stub_drive_base_for_ref_uses_default_without_drive_ref() -> None:+ assert agent_stub_drive_base_for_ref(None) == "/mnt/drive"+ assert agent_stub_drive_base_for_ref(" ") == "/mnt/drive"+++ "drive_ref",+ ["/agent-1", "../agent-1", "agent-1/..", "agent-1/./files", "agent-1//files"],+)+def test_agent_stub_drive_base_for_ref_rejects_unsafe_refs(drive_ref: str) -> None:+ with pytest.raises(ValueError, match="safe relative path"):+ _ = agent_stub_drive_base_for_ref(drive_ref)+++def test_normalize_agent_stub_api_base_url_rejects_query_and_fragment() -> None:with pytest.raises(ValueError, match="query string or fragment"):- _ = normalize_agent_stub_url("https://agent.example.com/agent-stub?x=1")+ _ = normalize_agent_stub_api_base_url("https://agent.example.com/agent-stub?x=1")with pytest.raises(ValueError, match="query string or fragment"):- _ = normalize_agent_stub_url("https://agent.example.com/agent-stub#fragment")+ _ = normalize_agent_stub_api_base_url("https://agent.example.com/agent-stub#fragment")+++def test_normalize_agent_stub_api_base_url_accepts_service_root_or_agent_stub_root_only() -> None:+ assert normalize_agent_stub_api_base_url("https://agent.example.com") == "https://agent.example.com/agent-stub"+ assert normalize_agent_stub_api_base_url("https://agent.example.com/agent-stub/") == (+ "https://agent.example.com/agent-stub"+ )++ with pytest.raises(ValueError, match="empty or /agent-stub"):+ _ = normalize_agent_stub_api_base_url("https://agent.example.com/foo")def test_parse_agent_stub_endpoint_rejects_invalid_schemes_and_missing_host() -> None:with pytest.raises(ValueError, match="http, https, or grpc"):- _ = normalize_agent_stub_url("not-a-url")+ _ = normalize_agent_stub_api_base_url("not-a-url")with pytest.raises(ValueError, match="http, https, or grpc"):- _ = normalize_agent_stub_url("ftp://agent.example.com/agent-stub")+ _ = normalize_agent_stub_api_base_url("ftp://agent.example.com/agent-stub")with pytest.raises(ValueError, match="include a host"):- _ = normalize_agent_stub_url("https:///agent-stub")+ _ = normalize_agent_stub_api_base_url("https:///agent-stub")def test_parse_agent_stub_endpoint_accepts_grpc_host_and_port() -> None:@@ -128,8 +164,8 @@ def test_agent_stub_drive_commit_request_validates_file_refs() -> None:with pytest.raises(ValidationError, match="tool_file"):_ = AgentStubDriveFileRef(kind="bad_kind", id="tool-file-1") # pyright: ignore[reportArgumentType]- with pytest.raises(ValidationError, match="file_ref"):- _ = AgentStubDriveCommitItem.model_validate({"key": "skills/example/SKILL.md"})+ item_without_file_ref = AgentStubDriveCommitItem.model_validate({"key": "skills/example/SKILL.md"})+ assert item_without_file_ref.file_ref is None@pytest.mark.parametrize("transfer_method", ["tool_file", "local_file", "datasource_file"])diff --git a/dify-agent/tests/local/dify_agent/agent_stub/server/test_agent_stub_app.py b/dify-agent/tests/local/dify_agent/agent_stub/server/test_agent_stub_app.pyindex e1a53a11bb4..e683a7ea6db 100644--- a/dify-agent/tests/local/dify_agent/agent_stub/server/test_agent_stub_app.py+++ b/dify-agent/tests/local/dify_agent/agent_stub/server/test_agent_stub_app.py@@ -29,7 +29,7 @@ def _execution_context() -> DifyExecutionContextLayerConfig:def test_create_agent_stub_app_exposes_same_stub_routes_as_module_app() -> None:stub_app_module = importlib.import_module("dify_agent.agent_stub.server.app")settings = ServerSettings(- agent_stub_url="https://agent.example.com/agent-stub",+ agent_stub_api_base_url="https://agent.example.com/agent-stub",server_secret_key=_base64url_secret(b"1" * 32),)@@ -60,10 +60,10 @@ def test_create_agent_stub_app_can_serve_requests() -> None:def test_create_agent_stub_app_wires_configured_file_handler_for_upload_requests(monkeypatch) -> None:settings = ServerSettings(- agent_stub_url="https://agent.example.com/agent-stub",+ agent_stub_api_base_url="https://agent.example.com/agent-stub",server_secret_key=_base64url_secret(b"1" * 32),- dify_api_base_url="https://api.example.com",- dify_api_inner_api_key="inner-secret",+ inner_api_url="https://api.example.com",+ inner_api_key="inner-secret",)token_codec = settings.create_agent_stub_token_codec()assert token_codec is not None@@ -94,10 +94,10 @@ def test_create_agent_stub_app_wires_configured_file_handler_for_upload_requestsdef test_create_agent_stub_app_wires_configured_drive_handler_for_manifest_requests(monkeypatch) -> None:settings = ServerSettings(- agent_stub_url="https://agent.example.com/agent-stub",+ agent_stub_api_base_url="https://agent.example.com/agent-stub",server_secret_key=_base64url_secret(b"1" * 32),- dify_api_base_url="https://api.example.com",- dify_api_inner_api_key="inner-secret",+ inner_api_url="https://api.example.com",+ inner_api_key="inner-secret",)token_codec = settings.create_agent_stub_token_codec()assert token_codec is not Nonediff --git a/dify-agent/tests/local/dify_agent/agent_stub/server/test_agent_stub_drive.py b/dify-agent/tests/local/dify_agent/agent_stub/server/test_agent_stub_drive.pyindex b0d07f68e00..7de8faa8d58 100644--- a/dify-agent/tests/local/dify_agent/agent_stub/server/test_agent_stub_drive.py+++ b/dify-agent/tests/local/dify_agent/agent_stub/server/test_agent_stub_drive.py@@ -71,8 +71,8 @@ def test_dify_api_agent_stub_drive_handler_injects_execution_context_for_manifes_patch_async_client(monkeypatch, handler)drive_handler = DifyApiAgentStubDriveRequestHandler(- dify_api_base_url="https://api.example.com",- dify_api_inner_api_key="inner-secret",+ inner_api_url="https://api.example.com",+ inner_api_key="inner-secret",)async def scenario() -> None:@@ -119,8 +119,8 @@ def test_dify_api_agent_stub_drive_handler_injects_execution_context_for_commit(_patch_async_client(monkeypatch, handler)drive_handler = DifyApiAgentStubDriveRequestHandler(- dify_api_base_url="https://api.example.com",- dify_api_inner_api_key="inner-secret",+ inner_api_url="https://api.example.com",+ inner_api_key="inner-secret",)async def scenario() -> None:@@ -142,8 +142,8 @@ def test_dify_api_agent_stub_drive_handler_injects_execution_context_for_commit(def test_dify_api_agent_stub_drive_handler_rejects_missing_agent_id() -> None:drive_handler = DifyApiAgentStubDriveRequestHandler(- dify_api_base_url="https://api.example.com",- dify_api_inner_api_key="inner-secret",+ inner_api_url="https://api.example.com",+ inner_api_key="inner-secret",)principal = _principal()principal.execution_context = principal.execution_context.model_copy(update={"agent_id": None})@@ -162,8 +162,8 @@ def test_dify_api_agent_stub_drive_handler_rejects_missing_agent_id() -> None:def test_dify_api_agent_stub_drive_handler_rejects_missing_user_id_for_commit() -> None:drive_handler = DifyApiAgentStubDriveRequestHandler(- dify_api_base_url="https://api.example.com",- dify_api_inner_api_key="inner-secret",+ inner_api_url="https://api.example.com",+ inner_api_key="inner-secret",)principal = _principal()principal.execution_context = principal.execution_context.model_copy(update={"user_id": None})@@ -196,8 +196,8 @@ def test_dify_api_agent_stub_drive_handler_maps_invalid_json_response(monkeypatc_patch_async_client(monkeypatch, handler)drive_handler = DifyApiAgentStubDriveRequestHandler(- dify_api_base_url="https://api.example.com",- dify_api_inner_api_key="inner-secret",+ inner_api_url="https://api.example.com",+ inner_api_key="inner-secret",)async def scenario() -> None:@@ -218,8 +218,8 @@ def test_dify_api_agent_stub_drive_handler_rejects_malformed_success_payload(mon_patch_async_client(monkeypatch, handler)drive_handler = DifyApiAgentStubDriveRequestHandler(- dify_api_base_url="https://api.example.com",- dify_api_inner_api_key="inner-secret",+ inner_api_url="https://api.example.com",+ inner_api_key="inner-secret",)async def scenario() -> None:@@ -240,8 +240,8 @@ def test_dify_api_agent_stub_drive_handler_preserves_non_2xx_detail(monkeypatch)_patch_async_client(monkeypatch, handler)drive_handler = DifyApiAgentStubDriveRequestHandler(- dify_api_base_url="https://api.example.com",- dify_api_inner_api_key="inner-secret",+ inner_api_url="https://api.example.com",+ inner_api_key="inner-secret",)async def scenario() -> None:diff --git a/dify-agent/tests/local/dify_agent/agent_stub/server/test_agent_stub_files.py b/dify-agent/tests/local/dify_agent/agent_stub/server/test_agent_stub_files.pyindex c9b0c3fab6d..3c713aedc34 100644--- a/dify-agent/tests/local/dify_agent/agent_stub/server/test_agent_stub_files.py+++ b/dify-agent/tests/local/dify_agent/agent_stub/server/test_agent_stub_files.py@@ -59,8 +59,8 @@ def test_dify_api_agent_stub_file_handler_injects_execution_context_for_upload(m_patch_async_client(monkeypatch, handler)file_handler = DifyApiAgentStubFileRequestHandler(- dify_api_base_url="https://api.example.com",- dify_api_inner_api_key="inner-secret",+ inner_api_url="https://api.example.com",+ inner_api_key="inner-secret",)async def scenario() -> None:@@ -97,8 +97,8 @@ def test_dify_api_agent_stub_file_handler_injects_execution_context_for_download_patch_async_client(monkeypatch, handler)file_handler = DifyApiAgentStubFileRequestHandler(- dify_api_base_url="https://api.example.com",- dify_api_inner_api_key="inner-secret",+ inner_api_url="https://api.example.com",+ inner_api_key="inner-secret",)async def scenario() -> None:@@ -115,8 +115,8 @@ def test_dify_api_agent_stub_file_handler_injects_execution_context_for_downloaddef test_dify_api_agent_stub_file_handler_rejects_missing_user_id() -> None:file_handler = DifyApiAgentStubFileRequestHandler(- dify_api_base_url="https://api.example.com",- dify_api_inner_api_key="inner-secret",+ inner_api_url="https://api.example.com",+ inner_api_key="inner-secret",)principal = _principal()principal.execution_context = principal.execution_context.model_copy(update={"user_id": None})@@ -141,8 +141,8 @@ def test_dify_api_agent_stub_file_handler_maps_non_2xx_response(monkeypatch) ->_patch_async_client(monkeypatch, handler)file_handler = DifyApiAgentStubFileRequestHandler(- dify_api_base_url="https://api.example.com",- dify_api_inner_api_key="inner-secret",+ inner_api_url="https://api.example.com",+ inner_api_key="inner-secret",)async def scenario() -> None:@@ -166,8 +166,8 @@ def test_dify_api_agent_stub_file_handler_maps_error_envelope(monkeypatch) -> No_patch_async_client(monkeypatch, handler)file_handler = DifyApiAgentStubFileRequestHandler(- dify_api_base_url="https://api.example.com",- dify_api_inner_api_key="inner-secret",+ inner_api_url="https://api.example.com",+ inner_api_key="inner-secret",)async def scenario() -> None:@@ -193,8 +193,8 @@ def test_dify_api_agent_stub_file_handler_rejects_upload_response_missing_url(mo_patch_async_client(monkeypatch, handler)file_handler = DifyApiAgentStubFileRequestHandler(- dify_api_base_url="https://api.example.com",- dify_api_inner_api_key="inner-secret",+ inner_api_url="https://api.example.com",+ inner_api_key="inner-secret",)async def scenario() -> None:@@ -218,8 +218,8 @@ def test_dify_api_agent_stub_file_handler_rejects_invalid_download_response_sche_patch_async_client(monkeypatch, handler)file_handler = DifyApiAgentStubFileRequestHandler(- dify_api_base_url="https://api.example.com",- dify_api_inner_api_key="inner-secret",+ inner_api_url="https://api.example.com",+ inner_api_key="inner-secret",)async def scenario() -> None:diff --git a/dify-agent/tests/local/dify_agent/agent_stub/server/test_cli.py b/dify-agent/tests/local/dify_agent/agent_stub/server/test_cli.pyindex 0d1f5b89c0e..cb40a3b583b 100644--- a/dify-agent/tests/local/dify_agent/agent_stub/server/test_cli.py+++ b/dify-agent/tests/local/dify_agent/agent_stub/server/test_cli.py@@ -43,7 +43,7 @@ def test_stub_server_cli_passes_explicit_uvicorn_settings(monkeypatch) -> None:}-def test_stub_server_cli_switches_to_grpc_when_agent_stub_url_uses_grpc(monkeypatch) -> None:+def test_stub_server_cli_switches_to_grpc_when_agent_stub_api_base_url_uses_grpc(monkeypatch) -> None:captured: dict[str, object] = {}async def fake_serve_grpc(*, settings, host, port) -> None:@@ -51,7 +51,7 @@ def test_stub_server_cli_switches_to_grpc_when_agent_stub_url_uses_grpc(monkeypamonkeypatch.setattr(cli_module, "_serve_grpc", fake_serve_grpc)monkeypatch.setattr(- cli_module, "ServerSettings", lambda: type("Settings", (), {"agent_stub_url": "grpc://agent:9091"})()+ cli_module, "ServerSettings", lambda: type("Settings", (), {"agent_stub_api_base_url": "grpc://agent:9091"})())cli_module.main(["--host", "0.0.0.0", "--port", "9092"])@@ -84,7 +84,7 @@ def test_serve_grpc_derives_default_bind_target_and_closes_server(monkeypatch) -"Settings",(),{- "agent_stub_url": "grpc://agent.example.com:9091",+ "agent_stub_api_base_url": "grpc://agent.example.com:9091","agent_stub_grpc_bind_address": None,"create_agent_stub_token_codec": lambda self: "token-codec","create_agent_stub_file_request_handler": lambda self: "file-handler",@@ -124,7 +124,7 @@ def test_serve_grpc_applies_cli_host_port_overrides(monkeypatch) -> None:"Settings",(),{- "agent_stub_url": "grpc://agent.example.com:9091",+ "agent_stub_api_base_url": "grpc://agent.example.com:9091","agent_stub_grpc_bind_address": "127.0.0.1:9191","create_agent_stub_token_codec": lambda self: None,"create_agent_stub_file_request_handler": lambda self: None,diff --git a/dify-agent/tests/local/dify_agent/layers/drive/test_configs.py b/dify-agent/tests/local/dify_agent/layers/drive/test_configs.pyindex 3052827c5b2..96d781caa72 100644--- a/dify-agent/tests/local/dify_agent/layers/drive/test_configs.py+++ b/dify-agent/tests/local/dify_agent/layers/drive/test_configs.py@@ -5,12 +5,10 @@ from pydantic import ValidationErrorfrom dify_agent.layers.drive import (DIFY_DRIVE_LAYER_TYPE_ID,- DifyDriveFileConfig,DifyDriveLayerConfig,DifyDriveSkillConfig,)from dify_agent.layers.drive.layer import DifyDriveLayer-from dify_agent.runtime.compositor_factory import create_default_layer_providersdef test_type_id_is_frozen_contract() -> None:@@ -24,23 +22,24 @@ def test_layer_config_round_trips_manifest_entries() -> None:"drive_ref": "agent-019e9112","skills": [{+ "path": "tender-analyzer","name": "Tender Analyzer","description": "Parses RFP documents step by step.","skill_md_key": "tender-analyzer/SKILL.md","archive_key": "tender-analyzer/.DIFY-SKILL-FULL.zip",}],- "files": [{"name": "sample.pdf", "key": "files/sample.pdf", "size": 1024, "mime_type": "application/pdf"}],+ "mentioned_skill_keys": ["tender-analyzer/SKILL.md"],+ "mentioned_file_keys": ["files/sample.pdf"],})dumped = config.model_dump(mode="json")assert dumped["drive_ref"] == "agent-019e9112"+ assert "drive_base" not in dumpedassert dumped["skills"][0]["skill_md_key"] == "tender-analyzer/SKILL.md"- assert dumped["files"][0]["key"] == "files/sample.pdf"- # the declaration is an index only — there is no field that could carry file content+ assert dumped["mentioned_file_keys"] == ["files/sample.pdf"]assert "content" not in DifyDriveSkillConfig.model_fields- assert "content" not in DifyDriveFileConfig.model_fieldsdef test_layer_config_rejects_unknown_fields() -> None:@@ -48,11 +47,13 @@ def test_layer_config_rejects_unknown_fields() -> None:DifyDriveLayerConfig.model_validate({"drive_ref": "agent-1", "skill_md_body": "# inline content"})-def test_inert_layer_is_registered_and_constructible_from_config() -> None:- providers = create_default_layer_providers()- provider = next(p for p in providers if p.type_id == DIFY_DRIVE_LAYER_TYPE_ID)-- layer = provider.create_layer({"drive_ref": "agent-1", "skills": [], "files": []})+def test_drive_layer_is_registered_and_constructible_from_config() -> None:+ layer = DifyDriveLayer.from_config_with_settings(+ DifyDriveLayerConfig(drive_ref="agent-1", skills=[], mentioned_skill_keys=[], mentioned_file_keys=[]),+ inner_api_url="https://api.example.com",+ inner_api_key="secret",+ )assert isinstance(layer, DifyDriveLayer)assert layer.config.drive_ref == "agent-1"+ assert not hasattr(layer, "local_drive_base")diff --git a/dify-agent/tests/local/dify_agent/layers/drive/test_layer.py b/dify-agent/tests/local/dify_agent/layers/drive/test_layer.pynew file mode 100644index 00000000000..c95526f046d--- /dev/null+++ b/dify-agent/tests/local/dify_agent/layers/drive/test_layer.py@@ -0,0 +1,200 @@+"""Behavior tests for the runtime Dify drive layer."""++from __future__ import annotations++from pathlib import Path+import pytest++from agenton.layers import EmptyRuntimeState, LayerConfig, NoLayerDeps, PlainLayer+from dify_agent.layers.drive import DifyDriveLayerConfig, DifyDriveSkillConfig+from dify_agent.layers.drive.layer import DifyDriveLayer, DifyDriveLayerError, _DriveManifestItem+++class _FakeExecutionContextConfig(LayerConfig):+ tenant_id: str+++class _FakeExecutionContextLayer(PlainLayer[NoLayerDeps, _FakeExecutionContextConfig, EmptyRuntimeState]):+ type_id = None++ def __init__(self, tenant_id: str) -> None:+ self.config = _FakeExecutionContextConfig(tenant_id=tenant_id)+++def _build_layer(tmp_path: Path) -> DifyDriveLayer:+ layer = DifyDriveLayer.from_config_with_settings(+ DifyDriveLayerConfig(+ drive_ref="agent-1",+ skills=[+ DifyDriveSkillConfig(+ path="tender-analyzer",+ name="Tender Analyzer",+ description="Parses RFPs.",+ skill_md_key="tender-analyzer/SKILL.md",+ archive_key="tender-analyzer/.DIFY-SKILL-FULL.zip",+ ),+ DifyDriveSkillConfig(+ path="other-skill",+ name="Other Skill",+ description="Fallback catalog entry.",+ skill_md_key="other-skill/SKILL.md",+ archive_key=None,+ ),+ ],+ mentioned_skill_keys=["tender-analyzer/SKILL.md"],+ mentioned_file_keys=["files/report.pdf"],+ ),+ inner_api_url="https://api.example.com",+ inner_api_key="secret",+ )+ layer.bind_deps({"execution_context": _FakeExecutionContextLayer("tenant-1")})+ return layer+++async def test_on_context_create_loads_mentioned_targets_into_prompt(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ layer = _build_layer(tmp_path)++ async def _fetch_manifest_items(*, tenant_id: str, targets: list[tuple[str, bool]]) -> list[_DriveManifestItem]:+ assert tenant_id == "tenant-1"+ assert targets == [("tender-analyzer/", False), ("files/report.pdf", True)]+ return [+ _DriveManifestItem(key="tender-analyzer/SKILL.md", download_url="https://files/skill-md"),+ _DriveManifestItem(key="files/report.pdf", download_url="https://files/report"),+ ]++ async def _download_items(items: list[_DriveManifestItem]) -> dict[str, str]:+ assert {item.key for item in items} == {"files/report.pdf", "tender-analyzer/SKILL.md"}+ skill_path = tmp_path / "tender-analyzer" / "SKILL.md"+ skill_path.parent.mkdir(parents=True, exist_ok=True)+ skill_path.write_text("# Tender Analyzer\nUse carefully.\n", encoding="utf-8")+ file_path = tmp_path / "files" / "report.pdf"+ file_path.parent.mkdir(parents=True, exist_ok=True)+ file_path.write_bytes(b"pdf")+ return {+ "tender-analyzer/SKILL.md": str(skill_path),+ "files/report.pdf": str(file_path),+ }++ monkeypatch.setattr(layer, "_fetch_manifest_items", _fetch_manifest_items)+ monkeypatch.setattr(layer, "_download_items", _download_items)++ await layer.on_context_create()++ prompt = layer.build_prompt_context()+ assert "Loaded mentioned skills" in prompt+ assert "# Tender Analyzer\nUse carefully." in prompt+ assert f"files/report.pdf -> {tmp_path / 'files' / 'report.pdf'}" in prompt+ assert "Other available skills" in prompt+ assert "other-skill: Other Skill — Fallback catalog entry." in prompt+++async def test_on_context_resume_loads_mentioned_targets_into_prompt(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ layer = _build_layer(tmp_path)++ async def _fetch_manifest_items(*, tenant_id: str, targets: list[tuple[str, bool]]) -> list[_DriveManifestItem]:+ assert tenant_id == "tenant-1"+ assert targets == [("tender-analyzer/", False), ("files/report.pdf", True)]+ return [+ _DriveManifestItem(key="tender-analyzer/SKILL.md", download_url="https://files/skill-md"),+ _DriveManifestItem(key="files/report.pdf", download_url="https://files/report"),+ ]++ async def _download_items(items: list[_DriveManifestItem]) -> dict[str, str]:+ assert {item.key for item in items} == {"files/report.pdf", "tender-analyzer/SKILL.md"}+ skill_path = tmp_path / "tender-analyzer" / "SKILL.md"+ skill_path.parent.mkdir(parents=True, exist_ok=True)+ skill_path.write_text("# Tender Analyzer\nUse carefully.\n", encoding="utf-8")+ file_path = tmp_path / "files" / "report.pdf"+ file_path.parent.mkdir(parents=True, exist_ok=True)+ file_path.write_bytes(b"pdf")+ return {+ "tender-analyzer/SKILL.md": str(skill_path),+ "files/report.pdf": str(file_path),+ }++ monkeypatch.setattr(layer, "_fetch_manifest_items", _fetch_manifest_items)+ monkeypatch.setattr(layer, "_download_items", _download_items)++ await layer.on_context_resume()++ prompt = layer.build_prompt_context()+ assert "Loaded mentioned skills" in prompt+ assert "# Tender Analyzer\nUse carefully." in prompt+ assert f"files/report.pdf -> {tmp_path / 'files' / 'report.pdf'}" in prompt+ assert "Other available skills" in prompt+ assert "other-skill: Other Skill — Fallback catalog entry." in prompt+++async def test_on_context_create_raises_when_mentioned_file_is_missing(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ layer = _build_layer(tmp_path)++ async def _fetch_manifest_items(*, tenant_id: str, targets: list[tuple[str, bool]]) -> list[_DriveManifestItem]:+ del tenant_id, targets+ return [_DriveManifestItem(key="tender-analyzer/SKILL.md", download_url="https://files/skill-md")]++ async def _download_items(items: list[_DriveManifestItem]) -> dict[str, str]:+ del items+ skill_path = tmp_path / "tender-analyzer" / "SKILL.md"+ skill_path.parent.mkdir(parents=True, exist_ok=True)+ skill_path.write_text("# Tender Analyzer\nUse carefully.\n", encoding="utf-8")+ return {"tender-analyzer/SKILL.md": str(skill_path)}++ monkeypatch.setattr(layer, "_fetch_manifest_items", _fetch_manifest_items)+ monkeypatch.setattr(layer, "_download_items", _download_items)++ with pytest.raises(DifyDriveLayerError, match="missing pulled file"):+ await layer.on_context_create()+++async def test_on_context_resume_raises_when_mentioned_targets_are_missing(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ layer = _build_layer(tmp_path)++ async def _fetch_manifest_items(*, tenant_id: str, targets: list[tuple[str, bool]]) -> list[_DriveManifestItem]:+ del tenant_id, targets+ return []++ async def _download_items(items: list[_DriveManifestItem]) -> dict[str, str]:+ assert items == []+ return {}++ monkeypatch.setattr(layer, "_fetch_manifest_items", _fetch_manifest_items)+ monkeypatch.setattr(layer, "_download_items", _download_items)++ with pytest.raises(DifyDriveLayerError, match="missing pulled file"):+ await layer.on_context_resume()+++async def test_on_context_create_raises_when_manifest_is_empty_for_mentioned_targets(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ layer = _build_layer(tmp_path)++ async def _fetch_manifest_items(*, tenant_id: str, targets: list[tuple[str, bool]]) -> list[_DriveManifestItem]:+ del tenant_id, targets+ return []++ async def _download_items(items: list[_DriveManifestItem]) -> dict[str, str]:+ assert items == []+ return {}++ monkeypatch.setattr(layer, "_fetch_manifest_items", _fetch_manifest_items)+ monkeypatch.setattr(layer, "_download_items", _download_items)++ with pytest.raises(DifyDriveLayerError, match="missing pulled file"):+ await layer.on_context_create()diff --git a/dify-agent/tests/local/dify_agent/layers/knowledge/test_layer.py b/dify-agent/tests/local/dify_agent/layers/knowledge/test_layer.pyindex 5db74d6f452..28fadcb903b 100644--- a/dify-agent/tests/local/dify_agent/layers/knowledge/test_layer.py+++ b/dify-agent/tests/local/dify_agent/layers/knowledge/test_layer.py@@ -56,8 +56,8 @@ def _knowledge_provider() -> LayerProvider[DifyKnowledgeBaseLayer]:layer_type=DifyKnowledgeBaseLayer,create=lambda config: DifyKnowledgeBaseLayer.from_config_with_settings(DifyKnowledgeBaseLayerConfig.model_validate(config),- dify_api_inner_url="http://dify-api",- dify_api_inner_api_key="inner-secret",+ inner_api_url="http://dify-api",+ inner_api_key="inner-secret",),)diff --git a/dify-agent/tests/local/dify_agent/layers/shell/test_layer.py b/dify-agent/tests/local/dify_agent/layers/shell/test_layer.pyindex 61368295fad..30352d87c5e 100644--- a/dify-agent/tests/local/dify_agent/layers/shell/test_layer.py+++ b/dify-agent/tests/local/dify_agent/layers/shell/test_layer.py@@ -8,7 +8,13 @@ import pytestfrom agenton.compositor import Compositor, LayerNode, LayerProviderfrom agenton.layers import LifecycleState-from dify_agent.agent_stub.server.shell_agent_stub_env import AGENT_STUB_AUTH_JWE_ENV_VAR, AGENT_STUB_URL_ENV_VAR+from dify_agent.agent_stub.server.shell_agent_stub_env import (+ AGENT_STUB_AUTH_JWE_ENV_VAR,+ AGENT_STUB_DRIVE_BASE_ENV_VAR,+ AGENT_STUB_API_BASE_URL_ENV_VAR,+)+from dify_agent.layers.drive import DifyDriveLayerConfig+from dify_agent.layers.drive.layer import DifyDriveLayerfrom dify_agent.layers.execution_context import DifyExecutionContextLayerConfigfrom dify_agent.layers.execution_context.layer import DifyExecutionContextLayerfrom dify_agent.layers.shell import (@@ -231,6 +237,14 @@ def _execution_context_layer() -> DifyExecutionContextLayer:)+def _drive_layer() -> DifyDriveLayer:+ return DifyDriveLayer.from_config_with_settings(+ DifyDriveLayerConfig(drive_ref="agent-1"),+ inner_api_url="https://api.example.com",+ inner_api_key="secret",+ )++def _shell_provider(*, client_factory: ShellctlClientFactory) -> LayerProvider[DifyShellLayer]:return LayerProvider.from_factory(layer_type=DifyShellLayer,@@ -606,12 +620,12 @@ def test_shell_layer_injects_agent_stub_env_only_for_user_visible_shell_run() ->DifyShellLayerConfig(),shellctl_entrypoint="http://shellctl",shellctl_client_factory=lambda _entrypoint: client,- agent_stub_url="https://agent.example.com/agent-stub",+ agent_stub_api_base_url="https://agent.example.com/agent-stub",agent_stub_token_factory=lambda execution_context, *, session_id: (f"token-for:{execution_context.tenant_id}:{session_id}"),)- layer.deps = layer.deps_type(execution_context=_execution_context_layer())+ layer.deps = layer.deps_type(drive=_drive_layer(), execution_context=_execution_context_layer())tools = {tool.name: tool for tool in layer.tools}async def scenario() -> None:@@ -629,8 +643,9 @@ def test_shell_layer_injects_agent_stub_env_only_for_user_visible_shell_run() ->internal_run_calls = [call for call in client.run_calls if not call.script.endswith("\npwd")]assert user_run_call.env == {- AGENT_STUB_URL_ENV_VAR: "https://agent.example.com/agent-stub",+ AGENT_STUB_API_BASE_URL_ENV_VAR: "https://agent.example.com/agent-stub",AGENT_STUB_AUTH_JWE_ENV_VAR: f"token-for:tenant-1:{layer.runtime_state.session_id}",+ AGENT_STUB_DRIVE_BASE_ENV_VAR: "/mnt/drive/agent-1",}assert internal_run_callsassert all(call.env is None for call in internal_run_calls)@@ -721,8 +736,9 @@ def test_run_remote_script_can_inject_agent_stub_env_for_server_owned_uploads()del timeoutassert cwd == "~/workspace/abc12ff"assert env == {- AGENT_STUB_URL_ENV_VAR: "https://agent.example.com/agent-stub",+ AGENT_STUB_API_BASE_URL_ENV_VAR: "https://agent.example.com/agent-stub",AGENT_STUB_AUTH_JWE_ENV_VAR: "token-for:tenant-1:abc12ff",+ AGENT_STUB_DRIVE_BASE_ENV_VAR: "/mnt/drive/agent-1",}return _job_result("remote-upload", status=JobStatusName.EXITED, done=True, exit_code=0, output="{}")@@ -731,12 +747,12 @@ def test_run_remote_script_can_inject_agent_stub_env_for_server_owned_uploads()DifyShellLayerConfig(),shellctl_entrypoint="http://shellctl",shellctl_client_factory=lambda _entrypoint: client,- agent_stub_url="https://agent.example.com/agent-stub",+ agent_stub_api_base_url="https://agent.example.com/agent-stub",agent_stub_token_factory=lambda execution_context, *, session_id: (f"token-for:{execution_context.tenant_id}:{session_id}"),)- layer.deps = layer.deps_type(execution_context=_execution_context_layer())+ layer.deps = layer.deps_type(drive=_drive_layer(), execution_context=_execution_context_layer())async def scenario() -> None:async with layer.resource_context():@@ -761,7 +777,7 @@ def test_run_remote_script_raises_when_agent_stub_env_is_unavailable() -> None:DifyShellLayerConfig(),shellctl_entrypoint="http://shellctl",shellctl_client_factory=lambda _entrypoint: client,- agent_stub_url="https://agent.example.com/agent-stub",+ agent_stub_api_base_url="https://agent.example.com/agent-stub",agent_stub_token_factory=lambda execution_context, *, session_id: (f"token-for:{execution_context.tenant_id}:{session_id}"),@@ -791,7 +807,7 @@ def test_shell_layer_skips_agent_stub_env_without_execution_context_dependency()DifyShellLayerConfig(),shellctl_entrypoint="http://shellctl",shellctl_client_factory=lambda _entrypoint: client,- agent_stub_url="https://agent.example.com/agent-stub",+ agent_stub_api_base_url="https://agent.example.com/agent-stub",agent_stub_token_factory=lambda execution_context, *, session_id: (f"token-for:{execution_context.tenant_id}:{session_id}"),diff --git a/dify-agent/tests/local/dify_agent/runtime/test_compositor_factory.py b/dify-agent/tests/local/dify_agent/runtime/test_compositor_factory.pyindex 687b03bcb27..87582e654e8 100644--- a/dify-agent/tests/local/dify_agent/runtime/test_compositor_factory.py+++ b/dify-agent/tests/local/dify_agent/runtime/test_compositor_factory.py@@ -84,7 +84,7 @@ def test_default_layer_providers_build_agent_stub_token_factory_from_agent_stub_providers = create_default_layer_providers(shellctl_entrypoint="http://shellctl.example",- agent_stub_url="https://agent.example.com/agent-stub",+ agent_stub_api_base_url="https://agent.example.com/agent-stub",agent_stub_token_codec=codec,)shell_provider = next(provider for provider in providers if provider.type_id == DIFY_SHELL_LAYER_TYPE_ID)diff --git a/dify-agent/tests/local/dify_agent/server/test_app.py b/dify-agent/tests/local/dify_agent/server/test_app.pyindex 3983ef43506..8e40bd683b9 100644--- a/dify-agent/tests/local/dify_agent/server/test_app.py+++ b/dify-agent/tests/local/dify_agent/server/test_app.py@@ -189,13 +189,12 @@ def test_create_app_creates_scheduler_and_closes_after_shutdown(monkeypatch: pytrun_retention_seconds=7,plugin_daemon_url="http://plugin-daemon",plugin_daemon_api_key="daemon-secret",- dify_api_inner_url="http://dify-api",+ inner_api_url="http://dify-api",+ inner_api_key="inner-secret",shellctl_entrypoint="http://shellctl",shellctl_auth_token="shell-secret",- agent_stub_url="https://agent.example.com/agent-stub",+ agent_stub_api_base_url="https://agent.example.com/agent-stub",server_secret_key=_base64url_secret(b"1" * 32),- dify_api_base_url="https://api.example.com",- dify_api_inner_api_key="inner-secret",outbound_http_connect_timeout=1,outbound_http_read_timeout=2,outbound_http_write_timeout=3,@@ -238,10 +237,10 @@ def test_create_app_creates_scheduler_and_closes_after_shutdown(monkeypatch: pyt))assert isinstance(knowledge_layer, DifyKnowledgeBaseLayer)- assert knowledge_layer.dify_api_inner_url == "http://dify-api"- assert knowledge_layer.dify_api_inner_api_key == "inner-secret"+ assert knowledge_layer.inner_api_url == "http://dify-api"+ assert knowledge_layer.inner_api_key == "inner-secret"assert shell_layer.shellctl_entrypoint == "http://shellctl"- assert shell_layer.agent_stub_url == "https://agent.example.com/agent-stub"+ assert shell_layer.agent_stub_api_base_url == "https://agent.example.com/agent-stub"shellctl_client = shell_layer.shellctl_client_factory("http://shellctl")assert isinstance(shellctl_client, ShellctlClient)assert shellctl_client.token == "shell-secret"@@ -277,7 +276,7 @@ def test_create_app_wires_authenticated_agent_stub_connection_route(monkeypatch:fake_redis, fake_http_client = _patch_app_lifecycle(monkeypatch)settings = ServerSettings(redis_url="redis://example.invalid/0",- agent_stub_url="https://agent.example.com/agent-stub",+ agent_stub_api_base_url="https://agent.example.com/agent-stub",server_secret_key=_base64url_secret(b"1" * 32),)token_codec = settings.create_agent_stub_token_codec()@@ -303,10 +302,10 @@ def test_create_app_wires_authenticated_agent_stub_file_upload_route(monkeypatchfake_redis, fake_http_client = _patch_app_lifecycle(monkeypatch)settings = ServerSettings(redis_url="redis://example.invalid/0",- agent_stub_url="https://agent.example.com/agent-stub",+ agent_stub_api_base_url="https://agent.example.com/agent-stub",server_secret_key=_base64url_secret(b"1" * 32),- dify_api_base_url="https://api.example.com",- dify_api_inner_api_key="inner-secret",+ inner_api_url="https://api.example.com",+ inner_api_key="inner-secret",)token_codec = settings.create_agent_stub_token_codec()assert token_codec is not None@@ -342,10 +341,10 @@ def test_create_app_wires_authenticated_agent_stub_drive_manifest_route(monkeypafake_redis, fake_http_client = _patch_app_lifecycle(monkeypatch)settings = ServerSettings(redis_url="redis://example.invalid/0",- agent_stub_url="https://agent.example.com/agent-stub",+ agent_stub_api_base_url="https://agent.example.com/agent-stub",server_secret_key=_base64url_secret(b"1" * 32),- dify_api_base_url="https://api.example.com",- dify_api_inner_api_key="inner-secret",+ inner_api_url="https://api.example.com",+ inner_api_key="inner-secret",)token_codec = settings.create_agent_stub_token_codec()assert token_codec is not None@@ -409,7 +408,7 @@ def test_create_app_starts_and_stops_agent_stub_grpc_server_for_grpc_url(monkeypsettings = ServerSettings(redis_url="redis://example.invalid/0",- agent_stub_url="grpc://agent.example.com:9091",+ agent_stub_api_base_url="grpc://agent.example.com:9091",agent_stub_grpc_bind_address="0.0.0.0:9191",server_secret_key=_base64url_secret(b"1" * 32),)@@ -485,8 +484,8 @@ def test_create_dify_api_inner_http_client_uses_generic_outbound_httpx_constructdef test_server_settings_use_generic_outbound_http_args_for_shared_clients() -> None:model_fields = ServerSettings.model_fields- assert "dify_api_inner_url" in model_fields- assert "dify_api_inner_api_key" in model_fields+ assert "inner_api_url" in model_fields+ assert "inner_api_key" in model_fieldsassert "outbound_http_connect_timeout" in model_fieldsassert "outbound_http_read_timeout" in model_fieldsassert "outbound_http_write_timeout" in model_fieldsdiff --git a/dify-agent/tests/local/dify_agent/server/test_sandbox_files.py b/dify-agent/tests/local/dify_agent/server/test_sandbox_files.pyindex 35e83667d17..939e28f5309 100644--- a/dify-agent/tests/local/dify_agent/server/test_sandbox_files.py+++ b/dify-agent/tests/local/dify_agent/server/test_sandbox_files.py@@ -10,7 +10,11 @@ import pytestfrom agenton.compositor import CompositorSessionSnapshot, LayerProviderfrom agenton.compositor.schemas import LayerSessionSnapshotfrom agenton.layers.base import LifecycleState-from dify_agent.agent_stub.server.shell_agent_stub_env import AGENT_STUB_AUTH_JWE_ENV_VAR, AGENT_STUB_URL_ENV_VAR+from dify_agent.agent_stub.server.shell_agent_stub_env import (+ AGENT_STUB_AUTH_JWE_ENV_VAR,+ AGENT_STUB_DRIVE_BASE_ENV_VAR,+ AGENT_STUB_API_BASE_URL_ENV_VAR,+)from dify_agent.layers.execution_context import DifyExecutionContextLayerConfigfrom dify_agent.layers.execution_context.layer import DifyExecutionContextLayerfrom dify_agent.layers.shell import DifyShellLayerConfig@@ -189,7 +193,7 @@ def _service(DifyShellLayerConfig.model_validate(config),shellctl_entrypoint="http://shellctl",shellctl_client_factory=lambda _entrypoint: client,- agent_stub_url="https://agent.example.com/agent-stub",+ agent_stub_api_base_url="https://agent.example.com/agent-stub",agent_stub_token_factory=lambda execution_context, *, session_id: (f"token-for:{execution_context.tenant_id}:{session_id}"),@@ -335,8 +339,9 @@ def test_upload_file_injects_agent_stub_env_and_returns_mapping() -> None:assert cwd == "~/workspace/abc12ff"assert timeout == 30.0assert env == {- AGENT_STUB_URL_ENV_VAR: "https://agent.example.com/agent-stub",+ AGENT_STUB_API_BASE_URL_ENV_VAR: "https://agent.example.com/agent-stub",AGENT_STUB_AUTH_JWE_ENV_VAR: "token-for:tenant-1:abc12ff",+ AGENT_STUB_DRIVE_BASE_ENV_VAR: "/mnt/drive",}assert 'dify-agent", "file", "upload"' in scriptreturn _job_result(diff --git a/dify-agent/tests/local/dify_agent/server/test_settings.py b/dify-agent/tests/local/dify_agent/server/test_settings.pyindex 1862e5995e2..da37eb16747 100644--- a/dify-agent/tests/local/dify_agent/server/test_settings.py+++ b/dify-agent/tests/local/dify_agent/server/test_settings.py@@ -49,12 +49,21 @@ def test_server_settings_defaults_shellctl_auth_token_to_none(def test_server_settings_reads_agent_stub_settings_from_env(monkeypatch: pytest.MonkeyPatch) -> None:- monkeypatch.setenv("DIFY_AGENT_STUB_URL", "https://agent.example.com/agent-stub/")+ monkeypatch.setenv("DIFY_AGENT_STUB_API_BASE_URL", "https://agent.example.com/agent-stub/")monkeypatch.setenv("DIFY_AGENT_SERVER_SECRET_KEY", _base64url_secret(secrets.token_bytes(32)))settings = ServerSettings()- assert settings.agent_stub_url == "https://agent.example.com/agent-stub"+ assert settings.agent_stub_api_base_url == "https://agent.example.com/agent-stub"+++def test_server_settings_normalizes_agent_stub_service_root_from_env(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("DIFY_AGENT_STUB_API_BASE_URL", "https://agent.example.com")+ monkeypatch.setenv("DIFY_AGENT_SERVER_SECRET_KEY", _base64url_secret(secrets.token_bytes(32)))++ settings = ServerSettings()++ assert settings.agent_stub_api_base_url == "https://agent.example.com/agent-stub"def test_server_settings_ignores_obsolete_legacy_settings_namespace(monkeypatch: pytest.MonkeyPatch) -> None:@@ -63,45 +72,53 @@ def test_server_settings_ignores_obsolete_legacy_settings_namespace(monkeypatch:settings = ServerSettings()- assert settings.agent_stub_url is None+ assert settings.agent_stub_api_base_url is None-def test_server_settings_rejects_agent_stub_url_with_query_or_fragment() -> None:+def test_server_settings_rejects_agent_stub_api_base_url_with_query_or_fragment() -> None:secret = _base64url_secret(secrets.token_bytes(32))with pytest.raises(ValidationError, match="query string or fragment"):_ = ServerSettings(- agent_stub_url="https://agent.example.com/agent-stub?x=1",+ agent_stub_api_base_url="https://agent.example.com/agent-stub?x=1",server_secret_key=secret,)with pytest.raises(ValidationError, match="query string or fragment"):_ = ServerSettings(- agent_stub_url="https://agent.example.com/agent-stub#fragment",+ agent_stub_api_base_url="https://agent.example.com/agent-stub#fragment",server_secret_key=secret,)-def test_server_settings_rejects_public_agent_stub_url_without_secret_key() -> None:+def test_server_settings_rejects_agent_stub_api_base_url_with_unexpected_path() -> None:+ with pytest.raises(ValidationError, match="empty or /agent-stub"):+ _ = ServerSettings(+ agent_stub_api_base_url="https://agent.example.com/foo",+ server_secret_key=_base64url_secret(secrets.token_bytes(32)),+ )+++def test_server_settings_rejects_public_agent_stub_api_base_url_without_secret_key() -> None:with pytest.raises(ValidationError, match="DIFY_AGENT_SERVER_SECRET_KEY"):- _ = ServerSettings(agent_stub_url="https://agent.example.com/agent-stub")+ _ = ServerSettings(agent_stub_api_base_url="https://agent.example.com/agent-stub")-def test_server_settings_accepts_grpc_agent_stub_url_and_bind_override() -> None:+def test_server_settings_accepts_grpc_agent_stub_api_base_url_and_bind_override() -> None:settings = ServerSettings(- agent_stub_url="grpc://agent.example.com:9091",+ agent_stub_api_base_url="grpc://agent.example.com:9091",agent_stub_grpc_bind_address="0.0.0.0:9191",server_secret_key=_base64url_secret(secrets.token_bytes(32)),)- assert settings.agent_stub_url == "grpc://agent.example.com:9091"+ assert settings.agent_stub_api_base_url == "grpc://agent.example.com:9091"assert settings.agent_stub_grpc_bind_address == "0.0.0.0:9191"def test_server_settings_rejects_grpc_bind_override_without_grpc_url() -> None:with pytest.raises(ValidationError, match="grpc://"):_ = ServerSettings(- agent_stub_url="https://agent.example.com/agent-stub",+ agent_stub_api_base_url="https://agent.example.com/agent-stub",agent_stub_grpc_bind_address="0.0.0.0:9191",server_secret_key=_base64url_secret(secrets.token_bytes(32)),)@@ -122,36 +139,33 @@ def test_server_settings_rejects_padded_or_quoted_server_secret_key() -> None:_ = ServerSettings(server_secret_key=f'"{secret}"')-def test_server_settings_normalizes_dify_api_base_url_from_env(monkeypatch: pytest.MonkeyPatch) -> None:- monkeypatch.setenv("DIFY_AGENT_DIFY_API_BASE_URL", "https://api.example.com/")- monkeypatch.setenv("DIFY_AGENT_DIFY_API_INNER_API_KEY", "inner-secret")+def test_server_settings_normalizes_inner_api_url_from_env(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("DIFY_AGENT_INNER_API_URL", "https://api.example.com/")+ monkeypatch.setenv("DIFY_AGENT_INNER_API_KEY", "inner-secret")settings = ServerSettings()- assert settings.dify_api_base_url == "https://api.example.com"- assert settings.dify_api_inner_api_key == "inner-secret"-+ assert settings.inner_api_url == "https://api.example.com"+ assert settings.inner_api_key == "inner-secret"-def test_server_settings_requires_inner_api_key_when_dify_api_base_url_is_set() -> None:- with pytest.raises(ValidationError, match="DIFY_AGENT_DIFY_API_INNER_API_KEY"):- _ = ServerSettings(dify_api_base_url="https://api.example.com")- settings = ServerSettings(dify_api_inner_api_key="inner-secret")- assert settings.dify_api_inner_api_key == "inner-secret"- assert settings.dify_api_base_url is None+def test_server_settings_allows_inner_api_url_without_key_until_a_bridge_is_used() -> None:+ settings = ServerSettings(inner_api_key="inner-secret")+ assert settings.inner_api_key == "inner-secret"+ assert settings.inner_api_url == "http://localhost:5001"-def test_server_settings_rejects_dify_api_base_url_with_query_or_fragment() -> None:+def test_server_settings_rejects_inner_api_url_with_query_or_fragment() -> None:with pytest.raises(ValidationError, match="query string or fragment"):_ = ServerSettings(- dify_api_base_url="https://api.example.com?x=1",- dify_api_inner_api_key="inner-secret",+ inner_api_url="https://api.example.com?x=1",+ inner_api_key="inner-secret",)with pytest.raises(ValidationError, match="query string or fragment"):_ = ServerSettings(- dify_api_base_url="https://api.example.com#frag",- dify_api_inner_api_key="inner-secret",+ inner_api_url="https://api.example.com#frag",+ inner_api_key="inner-secret",)@@ -173,15 +187,15 @@ def test_server_settings_create_agent_stub_file_request_handler_returns_none_witdef test_server_settings_create_agent_stub_file_request_handler_returns_handler_when_configured() -> None:settings = ServerSettings(- dify_api_base_url="https://api.example.com",- dify_api_inner_api_key="inner-secret",+ inner_api_url="https://api.example.com",+ inner_api_key="inner-secret",)handler = settings.create_agent_stub_file_request_handler()assert isinstance(handler, DifyApiAgentStubFileRequestHandler)- assert handler.dify_api_base_url == "https://api.example.com"- assert handler.dify_api_inner_api_key == "inner-secret"+ assert handler.inner_api_url == "https://api.example.com"+ assert handler.inner_api_key == "inner-secret"def test_server_settings_create_agent_stub_drive_request_handler_returns_none_without_full_settings() -> None:@@ -190,8 +204,8 @@ def test_server_settings_create_agent_stub_drive_request_handler_returns_none_widef test_server_settings_create_agent_stub_drive_request_handler_returns_handler_when_configured() -> None:settings = ServerSettings(- dify_api_base_url="https://api.example.com",- dify_api_inner_api_key="inner-secret",+ inner_api_url="https://api.example.com",+ inner_api_key="inner-secret",outbound_http_connect_timeout=11,outbound_http_read_timeout=22,outbound_http_write_timeout=33,@@ -201,8 +215,8 @@ def test_server_settings_create_agent_stub_drive_request_handler_returns_handlerhandler = settings.create_agent_stub_drive_request_handler()assert isinstance(handler, DifyApiAgentStubDriveRequestHandler)- assert handler.dify_api_base_url == "https://api.example.com"- assert handler.dify_api_inner_api_key == "inner-secret"+ assert handler.inner_api_url == "https://api.example.com"+ assert handler.inner_api_key == "inner-secret"timeout = cast(httpx.Timeout, handler.timeout)assert timeout.connect == 11assert timeout.read == 22diff --git a/dify-agent/tests/local/dify_agent/test_import_boundaries.py b/dify-agent/tests/local/dify_agent/test_import_boundaries.pyindex ecc2d548574..104f12031f0 100644--- a/dify-agent/tests/local/dify_agent/test_import_boundaries.py+++ b/dify-agent/tests/local/dify_agent/test_import_boundaries.py@@ -111,7 +111,7 @@ def test_protocol_and_dify_plugin_exports_do_not_import_server_only_modules() ->],assertions=["assert hasattr(dify_agent_protocol, 'PydanticAIStreamRunEvent')",- "assert dify_agent_layers_drive.__all__ == ['DIFY_DRIVE_LAYER_TYPE_ID', 'DifyDriveFileConfig', 'DifyDriveLayerConfig', 'DifyDriveSkillConfig']",+ "assert dify_agent_layers_drive.__all__ == ['DIFY_DRIVE_LAYER_TYPE_ID', 'DifyDriveLayerConfig', 'DifyDriveSkillConfig']","assert dify_agent_layers_execution_context.__all__ == ['DIFY_EXECUTION_CONTEXT_LAYER_TYPE_ID', 'DifyExecutionContextAgentMode', 'DifyExecutionContextInvokeFrom', 'DifyExecutionContextLayerConfig', 'DifyExecutionContextUserFrom']","assert dify_agent_layers_ask_human.__all__ == ['AskHumanAction', 'AskHumanActionStyle', 'AskHumanField', 'AskHumanFieldType', 'AskHumanFileField', 'AskHumanFileListField', 'AskHumanParagraphField', 'AskHumanResultStatus', 'AskHumanSelectField', 'AskHumanSelectOption', 'AskHumanSelectedAction', 'AskHumanToolArgs', 'AskHumanToolResult', 'AskHumanUrgency', 'DEFAULT_ASK_HUMAN_TOOL_DESCRIPTION', 'DIFY_ASK_HUMAN_LAYER_TYPE_ID', 'DifyAskHumanLayerConfig']","assert dify_agent_layers_dify_plugin.__all__ == ['DIFY_PLUGIN_LLM_LAYER_TYPE_ID', 'DIFY_PLUGIN_TOOLS_LAYER_TYPE_ID', 'DifyPluginCredentialValue', 'DifyPluginLLMLayerConfig', 'DifyPluginToolCredentialType', 'DifyPluginToolConfig', 'DifyPluginToolOption', 'DifyPluginToolParameter', 'DifyPluginToolParameterForm', 'DifyPluginToolParameterType', 'DifyPluginToolsLayerConfig', 'DifyPluginToolValue']",@@ -159,6 +159,14 @@ def test_agent_stub_client_and_protocol_imports_are_client_safe() -> None:)+def test_server_settings_import_does_not_import_agent_stub_app() -> None:+ _run_import_check(+ blocked_imports=["dify_agent.agent_stub.server.app"],+ imports=["dify_agent.server.settings"],+ assertions=["assert hasattr(dify_agent_server_settings, 'ServerSettings')"],+ )++def test_agenton_collection_roots_do_not_eagerly_import_pydantic_ai_implementations() -> None:_run_import_check(blocked_imports=[diff --git a/dify-agent/tests/local/test_packaging.py b/dify-agent/tests/local/test_packaging.pyindex bc76ede8ed7..b2e6b24dc38 100644--- a/dify-agent/tests/local/test_packaging.py+++ b/dify-agent/tests/local/test_packaging.py@@ -22,7 +22,7 @@ SERVER_RUNTIME_DEPENDENCIES = {"pydantic-ai-slim[anthropic,google,openai]>=1.85.1,<2.0.0","pydantic-settings>=2.12.0,<3.0.0","redis>=7.4.0,<8.0.0",- "shell-session-manager==2.2.0",+ "shell-session-manager==2.2.1","uvicorn[standard]==0.46.0",}@@ -65,11 +65,24 @@ def test_default_package_discovery_excludes_example_packages() -> None:assert "dify_agent_examples*" not in find_config["include"]-def test_project_declares_console_script_and_shellctl_docker_version() -> None:+def test_project_declares_console_script_and_local_sandbox_docker_version() -> None:pyproject = _read_pyproject()scripts = pyproject["project"]["scripts"]- dockerfile = (PROJECT_ROOT / "docker" / "shellctl" / "Dockerfile").read_text(encoding="utf-8")+ dockerfile = (PROJECT_ROOT / "docker" / "local-sandbox" / "Dockerfile").read_text(encoding="utf-8")assert scripts["dify-agent"] == "dify_agent.agent_stub.cli.main:main"assert scripts["dify-agent-stub-server"] == "dify_agent.agent_stub.server.cli:main"- assert "shell-session-manager==2.2.0" in dockerfile+ assert "SHELL_SESSION_MANAGER_VERSION=2.2.1" in dockerfile+++def test_local_sandbox_dockerfile_installs_stub_client_and_shellctl() -> None:+ dockerfile = (PROJECT_ROOT / "docker" / "local-sandbox" / "Dockerfile").read_text(encoding="utf-8")++ assert "uv sync --frozen --no-dev --no-editable --extra grpc" in dockerfile+ assert "SHELL_SESSION_MANAGER_VERSION=2.2.1" in dockerfile+ assert "shell-session-manager==${SHELL_SESSION_MANAGER_VERSION}" in dockerfile+ assert "DIFY_AGENT_STUB_DRIVE_BASE=/mnt/drive" in dockerfile+ assert "ln -s ${VIRTUAL_ENV}/bin/dify-agent /usr/local/bin/dify-agent" in dockerfile+ assert "ln -s ${VIRTUAL_ENV}/bin/shellctl /usr/local/bin/shellctl" in dockerfile+ assert "mkdir -p /mnt/drive" in dockerfile+ assert '["shellctl", "serve", "--listen", "0.0.0.0:5004"]' in dockerfilediff --git a/dify-agent/uv.lock b/dify-agent/uv.lockindex bd99e89a439..bc20927b44e 100644--- a/dify-agent/uv.lock+++ b/dify-agent/uv.lock@@ -639,7 +639,7 @@ requires-dist = [{ name = "pydantic-ai-slim", extras = ["anthropic", "google", "openai"], marker = "extra == 'server'", specifier = ">=1.85.1,<2.0.0" },{ name = "pydantic-settings", marker = "extra == 'server'", specifier = ">=2.12.0,<3.0.0" },{ name = "redis", marker = "extra == 'server'", specifier = ">=7.4.0,<8.0.0" },- { name = "shell-session-manager", marker = "extra == 'server'", specifier = "==2.2.0" },+ { name = "shell-session-manager", marker = "extra == 'server'", specifier = "==2.2.1" },{ name = "typer", specifier = ">=0.16.1,<0.17" },{ name = "typing-extensions", specifier = ">=4.12.2,<5.0.0" },{ name = "uvicorn", extras = ["standard"], marker = "extra == 'server'", specifier = "==0.46.0" },@@ -3286,7 +3286,7 @@ wheels = [[[package]]name = "shell-session-manager"-version = "2.2.0"+version = "2.2.1"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "aiosqlite" },@@ -3298,9 +3298,9 @@ dependencies = [{ name = "typer" },{ name = "uvicorn" },]-sdist = { url = "https://files.pythonhosted.org/packages/c5/84/aa6a86e7686b0c1e67b17ce4f5db6a42f115f1269d1f85362e22416b5829/shell_session_manager-2.2.0.tar.gz", hash = "sha256:ed31f12eecd30ad342dab9713651e2cb259b9beea6a6043842b73616c21b3070", size = 49479, upload-time = "2026-06-02T12:49:34.988Z" }+sdist = { url = "https://files.pythonhosted.org/packages/54/c3/83701914c5194e0390b93a05685ddfceda425348523254f43fdcb5024a37/shell_session_manager-2.2.1.tar.gz", hash = "sha256:421531c8bca5a586e9245282e13fdbe2566fca34e72a7320749c745cc2a935ee", size = 51380, upload-time = "2026-06-19T12:21:58.67Z" }wheels = [- { url = "https://files.pythonhosted.org/packages/82/cc/71fa09d0d865ee652312067d9d13c51b7800cdc0e54afe0e076ad1a29520/shell_session_manager-2.2.0-py3-none-any.whl", hash = "sha256:338cca9716facec60cc3985c1d88837c2f23abbc17ff2b61e58b4e4a0f9f19ad", size = 47240, upload-time = "2026-06-02T12:49:33.585Z" },+ { url = "https://files.pythonhosted.org/packages/5f/b6/b8d84ff7e59661cef85a1f021f500c798451121775f5aafd7b670ba63117/shell_session_manager-2.2.1-py3-none-any.whl", hash = "sha256:b7452dd5d50b5f55d2a108a2c422ed9883a817e2145f884844d072ec95dcaff8", size = 48895, upload-time = "2026-06-19T12:21:57.183Z" },][[package]]diff --git a/packages/contracts/generated/api/console/agent/types.gen.ts b/packages/contracts/generated/api/console/agent/types.gen.tsindex fb096b9c520..aa21f2ce651 100644--- a/packages/contracts/generated/api/console/agent/types.gen.ts+++ b/packages/contracts/generated/api/console/agent/types.gen.ts@@ -227,7 +227,6 @@ export type MessageFeedbackPayload = {}export type AgentDriveDeleteResponse = {- config_version_id?: string | nullremoved_keys?: Array<string>result: string}@@ -237,7 +236,6 @@ export type AgentDriveFilePayload = {}export type AgentDriveFileCommitResponse = {- config_version_id?: string | nullfile: AgentDriveFileResponse}@@ -321,7 +319,7 @@ export type SandboxUploadResponse = {export type AgentSkillUploadResponse = {manifest: SkillManifest- skill: AgentSkillRefConfig+ skill: AgentUploadedSkillResponse}export type SkillToolInferenceResult = {@@ -517,7 +515,6 @@ export type AgentSoulConfig = {prompt?: AgentSoulPromptConfigsandbox?: AgentSoulSandboxConfigschema_version?: number- skills_files?: AgentSoulSkillsFilesConfigtools?: AgentSoulToolsConfig}@@ -567,14 +564,6 @@ export type AgentComposerSoulCandidatesResponse = {dify_tools?: Array<AgentComposerDifyToolCandidateResponse>human_contacts?: Array<AgentHumanContactConfig>knowledge_datasets?: Array<AgentKnowledgeDatasetConfig>- skills_files?: Array<- | ({- kind: 'skill'- } & AgentComposerSkillCandidateResponse)- | ({- kind: 'file'- } & AgentComposerFileCandidateResponse)- >}export type ComposerCandidateCapabilities = {@@ -813,18 +802,12 @@ export type SkillManifest = {size: number}-export type AgentSkillRefConfig = {- description?: string | null- file_id?: string | null- full_archive_file_id?: string | null- full_archive_key?: string | null- id?: string | null- manifest_files?: Array<string> | null- name?: string | null- path?: string | null- skill_md_file_id?: string | null- skill_md_key?: string | null- [key: string]: unknown+export type AgentUploadedSkillResponse = {+ archive_key?: string | null+ description: string+ name: string+ path: string+ skill_md_key: string}export type CliToolSuggestion = {@@ -971,11 +954,6 @@ export type AgentSoulSandboxConfig = {provider?: string | null}-export type AgentSoulSkillsFilesConfig = {- files?: Array<AgentFileRefConfig>- skills?: Array<AgentSkillRefConfig>-}-export type AgentSoulToolsConfig = {cli_tools?: Array<AgentCliToolConfig>dify_tools?: Array<AgentSoulDifyToolConfig>@@ -1098,37 +1076,6 @@ export type AgentKnowledgeDatasetConfig = {[key: string]: unknown}-export type AgentComposerSkillCandidateResponse = {- description?: string | null- file_id?: string | null- full_archive_file_id?: string | null- full_archive_key?: string | null- id?: string | null- kind?: 'skill'- manifest_files?: Array<string> | null- name?: string | null- path?: string | null- skill_md_file_id?: string | null- skill_md_key?: string | null- [key: string]: unknown-}--export type AgentComposerFileCandidateResponse = {- drive_key?: string | null- file_id?: string | null- id?: string | null- kind?: 'file'- name?: string | null- reference?: string | null- remote_url?: string | null- tenant_id?: string | null- transfer_method?: string | null- type?: string | null- upload_file_id?: string | null- url?: string | null- [key: string]: unknown-}-export type AgentModerationProviderConfig = {api_based_extension_id?: string | nullinputs_config?: AgentModerationIoConfig | null@@ -1323,21 +1270,6 @@ export type AgentSandboxProviderConfig = {[key: string]: unknown}-export type AgentFileRefConfig = {- drive_key?: string | null- file_id?: string | null- id?: string | null- name?: string | null- reference?: string | null- remote_url?: string | null- tenant_id?: string | null- transfer_method?: string | null- type?: string | null- upload_file_id?: string | null- url?: string | null- [key: string]: unknown-}-export type AgentSoulDifyToolConfig = {credential_ref?: AgentSoulDifyToolCredentialRef | nullcredential_type?: 'api-key' | 'oauth2' | 'unauthorized'@@ -1406,6 +1338,21 @@ export type DeclaredOutputFileConfig = {mime_types?: Array<string>}+export type AgentFileRefConfig = {+ drive_key?: string | null+ file_id?: string | null+ id?: string | null+ name?: string | null+ reference?: string | null+ remote_url?: string | null+ tenant_id?: string | null+ transfer_method?: string | null+ type?: string | null+ upload_file_id?: string | null+ url?: string | null+ [key: string]: unknown+}+export type AgentCliToolAuthorizationStatus= | 'allowed'| 'authorized'diff --git a/packages/contracts/generated/api/console/agent/zod.gen.ts b/packages/contracts/generated/api/console/agent/zod.gen.tsindex e97bb5b71f9..cb4107f2d53 100644--- a/packages/contracts/generated/api/console/agent/zod.gen.ts+++ b/packages/contracts/generated/api/console/agent/zod.gen.ts@@ -99,7 +99,6 @@ export const zMessageFeedbackPayload = z.object({* AgentDriveDeleteResponse*/export const zAgentDriveDeleteResponse = z.object({- config_version_id: z.string().nullish(),removed_keys: z.array(z.string()).optional(),result: z.string(),})@@ -457,7 +456,6 @@ export const zAgentDriveFileResponse = z.object({* AgentDriveFileCommitResponse*/export const zAgentDriveFileCommitResponse = z.object({- config_version_id: z.string().nullish(),file: zAgentDriveFileResponse,})@@ -663,19 +661,14 @@ export const zSkillManifest = z.object({})/**- * AgentSkillRefConfig+ * AgentUploadedSkillResponse*/-export const zAgentSkillRefConfig = z.object({- description: z.string().nullish(),- file_id: z.string().max(255).nullish(),- full_archive_file_id: z.string().max(255).nullish(),- full_archive_key: z.string().max(512).nullish(),- id: z.string().max(255).nullish(),- manifest_files: z.array(z.string()).nullish(),- name: z.string().max(255).nullish(),- path: z.string().nullish(),- skill_md_file_id: z.string().max(255).nullish(),- skill_md_key: z.string().max(512).nullish(),+export const zAgentUploadedSkillResponse = z.object({+ archive_key: z.string().nullish(),+ description: z.string(),+ name: z.string(),+ path: z.string(),+ skill_md_key: z.string(),})/**@@ -683,7 +676,7 @@ export const zAgentSkillRefConfig = z.object({*/export const zAgentSkillUploadResponse = z.object({manifest: zSkillManifest,- skill: zAgentSkillRefConfig,+ skill: zAgentUploadedSkillResponse,})/**@@ -1038,41 +1031,6 @@ export const zAgentKnowledgeDatasetConfig = z.object({name: z.string().max(255).nullish(),})-/**- * AgentComposerSkillCandidateResponse- */-export const zAgentComposerSkillCandidateResponse = z.object({- description: z.string().nullish(),- file_id: z.string().max(255).nullish(),- full_archive_file_id: z.string().max(255).nullish(),- full_archive_key: z.string().max(512).nullish(),- id: z.string().max(255).nullish(),- kind: z.literal('skill').optional().default('skill'),- manifest_files: z.array(z.string()).nullish(),- name: z.string().max(255).nullish(),- path: z.string().nullish(),- skill_md_file_id: z.string().max(255).nullish(),- skill_md_key: z.string().max(512).nullish(),-})--/**- * AgentComposerFileCandidateResponse- */-export const zAgentComposerFileCandidateResponse = z.object({- drive_key: z.string().max(512).nullish(),- file_id: z.string().max(255).nullish(),- id: z.string().max(255).nullish(),- kind: z.literal('file').optional().default('file'),- name: z.string().max(255).nullish(),- reference: z.string().max(255).nullish(),- remote_url: z.string().nullish(),- tenant_id: z.string().max(255).nullish(),- transfer_method: z.string().max(64).nullish(),- type: z.string().max(64).nullish(),- upload_file_id: z.string().max(255).nullish(),- url: z.string().nullish(),-})-/*** SimpleAccount*/@@ -1393,39 +1351,6 @@ export const zAgentSoulSandboxConfig = z.object({provider: z.string().nullish(),})-/**- * AgentFileRefConfig- */-export const zAgentFileRefConfig = z.object({- drive_key: z.string().max(512).nullish(),- file_id: z.string().max(255).nullish(),- id: z.string().max(255).nullish(),- name: z.string().max(255).nullish(),- reference: z.string().max(255).nullish(),- remote_url: z.string().nullish(),- tenant_id: z.string().max(255).nullish(),- transfer_method: z.string().max(64).nullish(),- type: z.string().max(64).nullish(),- upload_file_id: z.string().max(255).nullish(),- url: z.string().nullish(),-})--/**- * AgentSoulSkillsFilesConfig- */-export const zAgentSoulSkillsFilesConfig = z.object({- files: z.array(zAgentFileRefConfig).optional(),- skills: z.array(zAgentSkillRefConfig).optional(),-})--/**- * WorkflowNodeJobMetadata- */-export const zWorkflowNodeJobMetadata = z.object({- agent_soul: z.record(z.string(), z.unknown()).nullish(),- file_refs: z.array(zAgentFileRefConfig).nullish(),-})-/*** DeclaredArrayItem*@@ -1469,6 +1394,31 @@ export const zDeclaredOutputFileConfig = z.object({mime_types: z.array(z.string()).optional(),})+/**+ * AgentFileRefConfig+ */+export const zAgentFileRefConfig = z.object({+ drive_key: z.string().max(512).nullish(),+ file_id: z.string().max(255).nullish(),+ id: z.string().max(255).nullish(),+ name: z.string().max(255).nullish(),+ reference: z.string().max(255).nullish(),+ remote_url: z.string().nullish(),+ tenant_id: z.string().max(255).nullish(),+ transfer_method: z.string().max(64).nullish(),+ type: z.string().max(64).nullish(),+ upload_file_id: z.string().max(255).nullish(),+ url: z.string().nullish(),+})++/**+ * WorkflowNodeJobMetadata+ */+export const zWorkflowNodeJobMetadata = z.object({+ agent_soul: z.record(z.string(), z.unknown()).nullish(),+ file_refs: z.array(zAgentFileRefConfig).nullish(),+})+/*** AgentCliToolAuthorizationStatus*@@ -1579,22 +1529,6 @@ export const zAgentComposerSoulCandidatesResponse = z.object({dify_tools: z.array(zAgentComposerDifyToolCandidateResponse).optional(),human_contacts: z.array(zAgentHumanContactConfig).optional(),knowledge_datasets: z.array(zAgentKnowledgeDatasetConfig).optional(),- skills_files: z- .array(- z.union([- z- .object({- kind: z.literal('skill'),- })- .and(zAgentComposerSkillCandidateResponse),- z- .object({- kind: z.literal('file'),- })- .and(zAgentComposerFileCandidateResponse),- ]),- )- .optional(),})/**@@ -1814,7 +1748,6 @@ export const zAgentSoulConfig = z.object({prompt: zAgentSoulPromptConfig.optional(),sandbox: zAgentSoulSandboxConfig.optional(),schema_version: z.int().optional().default(1),- skills_files: zAgentSoulSkillsFilesConfig.optional(),tools: zAgentSoulToolsConfig.optional(),})diff --git a/packages/contracts/generated/api/console/apps/orpc.gen.ts b/packages/contracts/generated/api/console/apps/orpc.gen.tsindex f24407a17d4..7a93572885e 100644--- a/packages/contracts/generated/api/console/apps/orpc.gen.ts+++ b/packages/contracts/generated/api/console/apps/orpc.gen.ts@@ -926,11 +926,11 @@ export const drive = {}/**- * Delete one drive file by key; soul ref first, then the KV row (ENG-625 D5)+ * Delete one drive file by key via drive commit-null semantics*/export const delete_ = oc.route({- description: 'Delete one drive file by key; soul ref first, then the KV row (ENG-625 D5)',+ description: 'Delete one drive file by key via drive commit-null semantics',inputStructure: 'detailed',method: 'DELETE',operationId: 'deleteAppsByAppIdAgentFiles',@@ -1056,12 +1056,11 @@ export const inferTools = {}/**- * Delete a standardized skill: soul ref first, then the <slug>/ drive prefix (ENG-625 D5)+ * Delete a standardized skill by removing its known drive keys via commit-null*/export const delete2 = oc.route({- description:- 'Delete a standardized skill: soul ref first, then the <slug>/ drive prefix (ENG-625 D5)',+ description: 'Delete a standardized skill by removing its known drive keys via commit-null',inputStructure: 'detailed',method: 'DELETE',operationId: 'deleteAppsByAppIdAgentSkillsBySlug',diff --git a/packages/contracts/generated/api/console/apps/types.gen.ts b/packages/contracts/generated/api/console/apps/types.gen.tsindex a3ab6a37c56..fa56590f0a4 100644--- a/packages/contracts/generated/api/console/apps/types.gen.ts+++ b/packages/contracts/generated/api/console/apps/types.gen.ts@@ -217,7 +217,6 @@ export type AgentDriveSkillInspectResponse = {}export type AgentDriveDeleteResponse = {- config_version_id?: string | nullremoved_keys?: Array<string>result: string}@@ -227,7 +226,6 @@ export type AgentDriveFilePayload = {}export type AgentDriveFileCommitResponse = {- config_version_id?: string | nullfile: AgentDriveFileResponse}@@ -239,7 +237,7 @@ export type AgentLogResponse = {export type AgentSkillUploadResponse = {manifest: SkillManifest- skill: AgentSkillRefConfig+ skill: AgentUploadedSkillResponse}export type SkillToolInferenceResult = {@@ -1370,18 +1368,12 @@ export type SkillManifest = {size: number}-export type AgentSkillRefConfig = {- description?: string | null- file_id?: string | null- full_archive_file_id?: string | null- full_archive_key?: string | null- id?: string | null- manifest_files?: Array<string> | null- name?: string | null- path?: string | null- skill_md_file_id?: string | null- skill_md_key?: string | null- [key: string]: unknown+export type AgentUploadedSkillResponse = {+ archive_key?: string | null+ description: string+ name: string+ path: string+ skill_md_key: string}export type CliToolSuggestion = {@@ -1803,7 +1795,6 @@ export type AgentSoulConfig = {prompt?: AgentSoulPromptConfigsandbox?: AgentSoulSandboxConfigschema_version?: number- skills_files?: AgentSoulSkillsFilesConfigtools?: AgentSoulToolsConfig}@@ -1900,14 +1891,6 @@ export type AgentComposerSoulCandidatesResponse = {dify_tools?: Array<AgentComposerDifyToolCandidateResponse>human_contacts?: Array<AgentHumanContactConfig>knowledge_datasets?: Array<AgentKnowledgeDatasetConfig>- skills_files?: Array<- | ({- kind: 'skill'- } & AgentComposerSkillCandidateResponse)- | ({- kind: 'file'- } & AgentComposerFileCandidateResponse)- >}export type ComposerCandidateCapabilities = {@@ -2169,11 +2152,6 @@ export type AgentSoulSandboxConfig = {provider?: string | null}-export type AgentSoulSkillsFilesConfig = {- files?: Array<AgentFileRefConfig>- skills?: Array<AgentSkillRefConfig>-}-export type AgentSoulToolsConfig = {cli_tools?: Array<AgentCliToolConfig>dify_tools?: Array<AgentSoulDifyToolConfig>@@ -2307,37 +2285,6 @@ export type AgentKnowledgeDatasetConfig = {[key: string]: unknown}-export type AgentComposerSkillCandidateResponse = {- description?: string | null- file_id?: string | null- full_archive_file_id?: string | null- full_archive_key?: string | null- id?: string | null- kind?: 'skill'- manifest_files?: Array<string> | null- name?: string | null- path?: string | null- skill_md_file_id?: string | null- skill_md_key?: string | null- [key: string]: unknown-}--export type AgentComposerFileCandidateResponse = {- drive_key?: string | null- file_id?: string | null- id?: string | null- kind?: 'file'- name?: string | null- reference?: string | null- remote_url?: string | null- tenant_id?: string | null- transfer_method?: string | null- type?: string | null- upload_file_id?: string | null- url?: string | null- [key: string]: unknown-}-export type CheckResultView = {passed: booleanreason?: string | null@@ -2488,21 +2435,6 @@ export type AgentSandboxProviderConfig = {[key: string]: unknown}-export type AgentFileRefConfig = {- drive_key?: string | null- file_id?: string | null- id?: string | null- name?: string | null- reference?: string | null- remote_url?: string | null- tenant_id?: string | null- transfer_method?: string | null- type?: string | null- upload_file_id?: string | null- url?: string | null- [key: string]: unknown-}-export type AgentSoulDifyToolConfig = {credential_ref?: AgentSoulDifyToolCredentialRef | nullcredential_type?: 'api-key' | 'oauth2' | 'unauthorized'@@ -2528,6 +2460,21 @@ export type AgentSoulDifyToolConfig = {tool_name?: string | null}+export type AgentFileRefConfig = {+ drive_key?: string | null+ file_id?: string | null+ id?: string | null+ name?: string | null+ reference?: string | null+ remote_url?: string | null+ tenant_id?: string | null+ transfer_method?: string | null+ type?: string | null+ upload_file_id?: string | null+ url?: string | null+ [key: string]: unknown+}+export type OutputErrorStrategy = 'default_value' | 'fail_branch' | 'stop'export type DeclaredOutputRetryConfig = {diff --git a/packages/contracts/generated/api/console/apps/zod.gen.ts b/packages/contracts/generated/api/console/apps/zod.gen.tsindex be116b5c795..043fc11261f 100644--- a/packages/contracts/generated/api/console/apps/zod.gen.ts+++ b/packages/contracts/generated/api/console/apps/zod.gen.ts@@ -120,7 +120,6 @@ export const zAgentDrivePreviewResponse = z.object({* AgentDriveDeleteResponse*/export const zAgentDriveDeleteResponse = z.object({- config_version_id: z.string().nullish(),removed_keys: z.array(z.string()).optional(),result: z.string(),})@@ -1011,7 +1010,6 @@ export const zAgentDriveFileResponse = z.object({* AgentDriveFileCommitResponse*/export const zAgentDriveFileCommitResponse = z.object({- config_version_id: z.string().nullish(),file: zAgentDriveFileResponse,})@@ -1043,19 +1041,14 @@ export const zSkillManifest = z.object({})/**- * AgentSkillRefConfig+ * AgentUploadedSkillResponse*/-export const zAgentSkillRefConfig = z.object({- description: z.string().nullish(),- file_id: z.string().max(255).nullish(),- full_archive_file_id: z.string().max(255).nullish(),- full_archive_key: z.string().max(512).nullish(),- id: z.string().max(255).nullish(),- manifest_files: z.array(z.string()).nullish(),- name: z.string().max(255).nullish(),- path: z.string().nullish(),- skill_md_file_id: z.string().max(255).nullish(),- skill_md_key: z.string().max(512).nullish(),+export const zAgentUploadedSkillResponse = z.object({+ archive_key: z.string().nullish(),+ description: z.string(),+ name: z.string(),+ path: z.string(),+ skill_md_key: z.string(),})/**@@ -1063,7 +1056,7 @@ export const zAgentSkillRefConfig = z.object({*/export const zAgentSkillUploadResponse = z.object({manifest: zSkillManifest,- skill: zAgentSkillRefConfig,+ skill: zAgentUploadedSkillResponse,})/**@@ -2645,41 +2638,6 @@ export const zAgentKnowledgeDatasetConfig = z.object({name: z.string().max(255).nullish(),})-/**- * AgentComposerSkillCandidateResponse- */-export const zAgentComposerSkillCandidateResponse = z.object({- description: z.string().nullish(),- file_id: z.string().max(255).nullish(),- full_archive_file_id: z.string().max(255).nullish(),- full_archive_key: z.string().max(512).nullish(),- id: z.string().max(255).nullish(),- kind: z.literal('skill').optional().default('skill'),- manifest_files: z.array(z.string()).nullish(),- name: z.string().max(255).nullish(),- path: z.string().nullish(),- skill_md_file_id: z.string().max(255).nullish(),- skill_md_key: z.string().max(512).nullish(),-})--/**- * AgentComposerFileCandidateResponse- */-export const zAgentComposerFileCandidateResponse = z.object({- drive_key: z.string().max(512).nullish(),- file_id: z.string().max(255).nullish(),- id: z.string().max(255).nullish(),- kind: z.literal('file').optional().default('file'),- name: z.string().max(255).nullish(),- reference: z.string().max(255).nullish(),- remote_url: z.string().nullish(),- tenant_id: z.string().max(255).nullish(),- transfer_method: z.string().max(64).nullish(),- type: z.string().max(64).nullish(),- upload_file_id: z.string().max(255).nullish(),- url: z.string().nullish(),-})-/*** CheckResultView*@@ -2898,14 +2856,6 @@ export const zAgentFileRefConfig = z.object({url: z.string().nullish(),})-/**- * AgentSoulSkillsFilesConfig- */-export const zAgentSoulSkillsFilesConfig = z.object({- files: z.array(zAgentFileRefConfig).optional(),- skills: z.array(zAgentSkillRefConfig).optional(),-})-/*** WorkflowNodeJobMetadata*/@@ -3060,22 +3010,6 @@ export const zAgentComposerSoulCandidatesResponse = z.object({dify_tools: z.array(zAgentComposerDifyToolCandidateResponse).optional(),human_contacts: z.array(zAgentHumanContactConfig).optional(),knowledge_datasets: z.array(zAgentKnowledgeDatasetConfig).optional(),- skills_files: z- .array(- z.union([- z- .object({- kind: z.literal('skill'),- })- .and(zAgentComposerSkillCandidateResponse),- z- .object({- kind: z.literal('file'),- })- .and(zAgentComposerFileCandidateResponse),- ]),- )- .optional(),})/**@@ -3372,7 +3306,6 @@ export const zAgentSoulConfig = z.object({prompt: zAgentSoulPromptConfig.optional(),sandbox: zAgentSoulSandboxConfig.optional(),schema_version: z.int().optional().default(1),- skills_files: zAgentSoulSkillsFilesConfig.optional(),tools: zAgentSoulToolsConfig.optional(),})diff --git a/web/app/components/app/workflow-log/__tests__/filter.spec.tsx b/web/app/components/app/workflow-log/__tests__/filter.spec.tsxindex 91fcdebe142..1b9a0e5935f 100644--- a/web/app/components/app/workflow-log/__tests__/filter.spec.tsx+++ b/web/app/components/app/workflow-log/__tests__/filter.spec.tsx@@ -171,7 +171,7 @@ describe('Filter', () => {const statusTrigger = screen.getByRole('combobox', { name: 'Success' })const statusChip = statusTrigger.parentElement!- const clearButton = within(statusChip).getByRole('button', { name: 'common.operation.clear' })+ const clearButton = within(statusChip).getByRole('button', { name: /common\.operation\.clear Success/ })await user.click(clearButton)@@ -286,7 +286,7 @@ describe('Filter', () => {const periodTrigger = screen.getByRole('combobox', { name: 'appLog.filter.period.last7days' })const periodChip = periodTrigger.parentElement!- const clearButton = within(periodChip).getByRole('button', { name: 'common.operation.clear' })+ const clearButton = within(periodChip).getByRole('button', { name: /common\.operation\.clear appLog\.filter\.period\.last7days/ })await user.click(clearButton)expect(setQueryParams).toHaveBeenCalledWith({diff --git a/web/app/components/base/chat/chat/hooks.ts b/web/app/components/base/chat/chat/hooks.tsindex 85eb1893cee..db0ce1d1251 100644--- a/web/app/components/base/chat/chat/hooks.ts+++ b/web/app/components/base/chat/chat/hooks.ts@@ -64,10 +64,12 @@ export const useChat = (stopChat?: (taskId: string) => void,clearChatList?: boolean,clearChatListCallback?: (state: boolean) => void,+ initialConversationId?: string,) => {const { t } = useTranslation()const { formatTime } = useTimestamp()- const conversationIdRef = useRef('')+ const conversationIdRef = useRef(initialConversationId ?? '')+ const initialConversationIdRef = useRef(initialConversationId ?? '')const hasStopRespondedRef = useRef(false)const [isResponding, setIsResponding] = useState(false)const isRespondingRef = useRef(false)@@ -145,6 +147,12 @@ export const useChat = (}}, [])+ useEffect(() => {+ initialConversationIdRef.current = initialConversationId ?? ''+ if (initialConversationId && !conversationIdRef.current)+ conversationIdRef.current = initialConversationId+ }, [initialConversationId])+/** Find the target node by bfs and then operate on it */const produceChatTreeNode = useCallback((targetId: string, operation: (node: ChatItemInTree) => void) => {return produce(chatTreeRef.current, (draft) => {@@ -203,7 +211,7 @@ export const useChat = (}, [stopChat, handleResponding])const handleRestart = useCallback((cb?: any) => {- conversationIdRef.current = ''+ conversationIdRef.current = initialConversationIdRef.currenttaskIdRef.current = ''handleStop()setChatTree([])diff --git a/web/app/components/base/chip/__tests__/index.spec.tsx b/web/app/components/base/chip/__tests__/index.spec.tsxindex 133c1ea2a95..95dd3e0e05c 100644--- a/web/app/components/base/chip/__tests__/index.spec.tsx+++ b/web/app/components/base/chip/__tests__/index.spec.tsx@@ -122,7 +122,9 @@ describe('Chip', () => {it('should show left icon by default', () => {const { container } = renderChip()- expect(container.querySelector('.i-ri-filter-3-line')).toBeInTheDocument()+ const icon = container.querySelector('.i-ri-filter-3-line')+ expect(icon).toBeInTheDocument()+ expect(icon).toHaveAttribute('aria-hidden')})it('should hide left icon when showLeftIcon is false', () => {@@ -140,6 +142,7 @@ describe('Chip', () => {renderChip({ leftIcon: <CustomIcon /> })expect(screen.getByTestId('custom-icon'))!.toBeInTheDocument()+ expect(screen.getByTestId('custom-icon').closest('[aria-hidden="true"]')).toBeInTheDocument()})it('should apply custom className to trigger', () => {@@ -161,6 +164,15 @@ describe('Chip', () => {const panel = document.body.querySelector(`.${customPanelClass}`)expect(panel)!.toBeInTheDocument()})++ it('should use visible focus styles on the trigger', () => {+ const { container } = renderChip()++ expect(getTrigger(container)).toHaveClass(+ 'focus-visible:ring-2',+ 'focus-visible:ring-state-accent-solid',+ )+ })})describe('State Management', () => {@@ -207,7 +219,15 @@ describe('Chip', () => {it('should call onClear when clear button is clicked', async () => {const { user } = renderChip({ value: 'active' })- const clearButton = screen.getByRole('button', { name: 'common.operation.clear' })+ const clearButton = screen.getByRole('button', { name: /common\.operation\.clear/ })+ expect(clearButton).toHaveAccessibleName(/Active/)+ expect(clearButton).toHaveClass(+ 'outline-hidden',+ 'focus-visible:ring-2',+ 'focus-visible:ring-state-accent-solid',+ 'focus-visible:ring-inset',+ )+ expect(clearButton.querySelector('.i-ri-close-circle-fill')).toHaveAttribute('aria-hidden')await user.click(clearButton)@@ -221,7 +241,7 @@ describe('Chip', () => {expect(screen.queryByRole('listbox')).not.toBeInTheDocument()expect(trigger).not.toHaveAttribute('data-popup-open')- const clearButton = screen.getByRole('button', { name: 'common.operation.clear' })+ const clearButton = screen.getByRole('button', { name: /common\.operation\.clear/ })await user.click(clearButton)@@ -326,7 +346,7 @@ describe('Chip', () => {// The trigger should not display any item name textexpect(trigger?.textContent?.trim()).toBeFalsy()- expect(screen.queryByRole('button', { name: 'common.operation.clear' })).not.toBeInTheDocument()+ expect(screen.queryByRole('button', { name: /common\.operation\.clear/ })).not.toBeInTheDocument()})it('should allow selecting already selected item', async () => {@@ -368,7 +388,7 @@ describe('Chip', () => {renderChip({ value: 0, items: numericItems })expect(screen.getByRole('combobox', { name: 'Zero' })).toBeInTheDocument()- expect(screen.getByRole('button', { name: 'common.operation.clear' })).toBeInTheDocument()+ expect(screen.getByRole('button', { name: /common\.operation\.clear/ })).toBeInTheDocument()})it('should handle items with additional properties', async () => {diff --git a/web/app/components/base/chip/index.tsx b/web/app/components/base/chip/index.tsxindex 20507033aba..3aa78cd86f6 100644--- a/web/app/components/base/chip/index.tsx+++ b/web/app/components/base/chip/index.tsx@@ -45,6 +45,9 @@ function Chip<T extends ItemValue>({const selectedItem = items.find(item => Object.is(item.value, value))const triggerContent = selectedItem?.triggerName || selectedItem?.name || ''const hasValue = selectedItem !== undefined && value !== ''+ const clearLabel = triggerContent+ ? `${t('operation.clear', { ns: 'common' })} ${triggerContent}`+ : t('operation.clear', { ns: 'common' })return (<Select@@ -63,14 +66,14 @@ function Chip<T extends ItemValue>({<SelectTriggeraria-label={triggerContent || t('placeholder.select', { ns: 'common' })}className={cn(- 'h-auto min-h-8 w-fit max-w-full cursor-pointer items-center rounded-lg border-[0.5px] border-transparent bg-components-input-bg-normal px-2 py-1 hover:bg-state-base-hover-alt focus-visible:bg-state-base-hover-alt data-popup-open:bg-state-base-hover-alt! data-popup-open:hover:bg-state-base-hover-alt [&>*:last-child]:hidden',+ 'h-auto min-h-8 w-fit max-w-full cursor-pointer items-center rounded-lg border-[0.5px] border-transparent bg-components-input-bg-normal px-2 py-1 hover:bg-state-base-hover-alt focus-visible:bg-state-base-hover-alt focus-visible:ring-2 focus-visible:ring-state-accent-solid data-popup-open:bg-state-base-hover-alt! data-popup-open:hover:bg-state-base-hover-alt [&>*:last-child]:hidden',hasValue && 'border-components-button-secondary-border! bg-components-button-secondary-bg! pr-6 shadow-xs hover:border-components-button-secondary-border-hover hover:bg-components-button-secondary-bg-hover! data-popup-open:border-components-button-secondary-border-hover! data-popup-open:bg-components-button-secondary-bg-hover! data-popup-open:hover:border-components-button-secondary-border-hover data-popup-open:hover:bg-components-button-secondary-bg-hover!',className,)}><span className="flex min-w-0 grow items-center gap-1 text-left">{showLeftIcon && (- <span className="p-0.5">+ <span aria-hidden="true" className="p-0.5">{leftIcon || (<span aria-hidden className={cn('i-ri-filter-3-line block size-4 text-text-tertiary', hasValue && 'text-text-secondary')} />)}@@ -87,8 +90,8 @@ function Chip<T extends ItemValue>({{hasValue && (<buttontype="button"- aria-label={t('operation.clear', { ns: 'common' })}- className="group/clear absolute top-1/2 right-2 -translate-y-1/2 cursor-pointer border-none bg-transparent p-px"+ aria-label={clearLabel}+ className="group/clear absolute top-1/2 right-1.5 flex size-5 -translate-y-1/2 cursor-pointer touch-manipulation items-center justify-center rounded-md border-none bg-transparent p-0 outline-hidden focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:ring-inset"onClick={onClear}><span aria-hidden className="i-ri-close-circle-fill block size-3.5 text-text-quaternary group-hover/clear:text-text-tertiary" />diff --git a/web/app/components/base/sort/__tests__/index.spec.tsx b/web/app/components/base/sort/__tests__/index.spec.tsxindex ea85e8f3fef..99db843a758 100644--- a/web/app/components/base/sort/__tests__/index.spec.tsx+++ b/web/app/components/base/sort/__tests__/index.spec.tsx@@ -43,7 +43,7 @@ describe('Sort component — real portal integration', () => {const sortButton = getSortButton()expect(sortButton).toBeInstanceOf(HTMLElement)- expect(sortButton.querySelector('svg')).toBeInTheDocument()+ expect(sortButton.querySelector('.i-ri-sort-asc')).toBeInTheDocument()})it('opens and closes the menu', async () => {@@ -98,8 +98,8 @@ describe('Sort component — real portal integration', () => {if (!nameRow)throw new Error('Name option row not found in menu')- expect(statusRow.querySelector('svg')).toBeInTheDocument()- expect(nameRow.querySelector('svg')).not.toBeInTheDocument()+ expect(statusRow.querySelector('.i-ri-check-line')).toBeInTheDocument()+ expect(nameRow.querySelector('.i-ri-check-line')).not.toBeInTheDocument()})it('shows empty selection label when value is unknown', () => {diff --git a/web/app/components/base/sort/index.tsx b/web/app/components/base/sort/index.tsxindex 67091379fd4..00f3a51a139 100644--- a/web/app/components/base/sort/index.tsx+++ b/web/app/components/base/sort/index.tsx@@ -6,7 +6,6 @@ import {DropdownMenuRadioItem,DropdownMenuTrigger,} from '@langgenius/dify-ui/dropdown-menu'-import { RiArrowDownSLine, RiCheckLine, RiSortAsc, RiSortDesc } from '@remixicon/react'import { useMemo } from 'react'import { useTranslation } from 'react-i18next'@@ -39,7 +38,7 @@ function Sort({<DropdownMenu><div className="relative"><DropdownMenuTrigger- className="flex min-h-8 cursor-pointer items-center rounded-l-lg border-none bg-components-input-bg-normal px-2 py-1 hover:bg-state-base-hover-alt data-popup-open:bg-state-base-hover-alt! data-popup-open:hover:bg-state-base-hover-alt"+ className="flex min-h-8 cursor-pointer items-center rounded-l-lg border-none bg-components-input-bg-normal px-2 py-1 outline-hidden hover:bg-state-base-hover-alt focus-visible:ring-2 focus-visible:ring-state-accent-solid data-popup-open:bg-state-base-hover-alt! data-popup-open:hover:bg-state-base-hover-alt"><div className="flex items-center gap-0.5 px-1"><div className="system-sm-regular text-text-tertiary">{t('filter.sortBy', { ns: 'appLog' })}</div>@@ -47,12 +46,12 @@ function Sort({{triggerContent}</div></div>- <RiArrowDownSLine className="size-4 text-text-tertiary" />+ <span aria-hidden className="i-ri-arrow-down-s-line size-4 text-text-tertiary" /></DropdownMenuTrigger><DropdownMenuContentplacement="bottom-start"sideOffset={4}- popupClassName="relative w-[240px] rounded-xl border-[0.5px] bg-components-panel-bg-blur p-0"+ popupClassName="relative w-[240px] rounded-xl bg-components-panel-bg-blur p-0"><DropdownMenuRadioGroupvalue={value}@@ -64,10 +63,10 @@ function Sort({key={item.value}value={item.value}closeOnClick- className="gap-2 rounded-lg px-2 py-[6px] pl-3"+ className="mx-0 gap-2 rounded-lg px-2 py-[6px]"><div title={item.name} className="grow truncate system-sm-medium text-text-secondary">{item.name}</div>- {value === item.value && <RiCheckLine className="size-4 shrink-0 text-util-colors-blue-light-blue-light-600" />}+ {value === item.value && <span aria-hidden className="i-ri-check-line size-4 shrink-0 text-util-colors-blue-light-blue-light-600" />}</DropdownMenuRadioItem>))}</DropdownMenuRadioGroup>@@ -77,11 +76,11 @@ function Sort({<buttontype="button"aria-label={t(`filter.${order ? 'ascending' : 'descending'}`, { ns: 'appLog' })}- className="ml-px cursor-pointer rounded-r-lg border-none bg-components-button-tertiary-bg p-2 hover:bg-components-button-tertiary-bg-hover focus-visible:ring-1 focus-visible:ring-components-input-border-active focus-visible:outline-hidden"+ className="ml-px cursor-pointer rounded-r-lg border-none bg-components-button-tertiary-bg p-2 outline-hidden hover:bg-components-button-tertiary-bg-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid"onClick={() => onSelect(`${order ? '' : '-'}${value}`)}>- {!order && <RiSortAsc className="size-4 text-components-button-tertiary-text" aria-hidden="true" />}- {order && <RiSortDesc className="size-4 text-components-button-tertiary-text" aria-hidden="true" />}+ {!order && <span aria-hidden className="i-ri-sort-asc size-4 text-components-button-tertiary-text" />}+ {order && <span aria-hidden className="i-ri-sort-desc size-4 text-components-button-tertiary-text" />}</button></div>diff --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 a2d3ba5c750..72850ab8355 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@@ -501,6 +501,15 @@ describe('FeaturesTrigger', () => {expect(mockInvalidateQueries).toHaveBeenCalledWith({queryKey: consoleQuery.agent.get.key(),})+ expect(mockInvalidateQueries).toHaveBeenCalledWith({+ queryKey: consoleQuery.agent.byAgentId.referencingWorkflows.get.queryOptions({+ input: {+ params: {+ agent_id: 'agent-1',+ },+ },+ }).queryKey,+ })})})@@ -535,6 +544,15 @@ describe('FeaturesTrigger', () => {expect(mockInvalidateQueries).not.toHaveBeenCalledWith({queryKey: consoleQuery.agent.get.key(),})+ expect(mockInvalidateQueries).not.toHaveBeenCalledWith({+ queryKey: consoleQuery.agent.byAgentId.referencingWorkflows.get.queryOptions({+ input: {+ params: {+ agent_id: 'agent-1',+ },+ },+ }).queryKey,+ })})it('should pass publish params to workflow publish mutation', async () => {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 ab41536fd85..1c751385912 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@@ -29,7 +29,7 @@ import {// useWorkflowRunValidation,} from '@/app/components/workflow/hooks'import { useHooksStore } from '@/app/components/workflow/hooks-store'-import { hasValidRosterAgentBinding, isAgentV2NodeData } from '@/app/components/workflow/nodes/agent-v2/types'+import { isAgentV2NodeData } from '@/app/components/workflow/nodes/agent-v2/types'import {useStore,useWorkflowStore,@@ -64,6 +64,20 @@ const FeaturesTrigger = () => {const lastPublishedHasUserInput = useStore(s => s.lastPublishedHasUserInput)const nodes = useNodes()+ const rosterAgentIds = useMemo(() => {+ return Array.from(new Set(nodes.flatMap((node) => {+ const binding = isAgentV2NodeData(node.data) ? node.data.agent_binding : undefined+ if (+ binding?.binding_type !== 'roster_agent'+ || typeof binding.agent_id !== 'string'+ || binding.agent_id.length === 0+ ) {+ return []+ }++ return [binding.agent_id]+ })))+ }, [nodes])const hasWorkflowNodes = nodes.length > 0const startNode = nodes.find(node => node.data.type === BlockEnum.Start)const endNode = nodes.find(node => node.data.type === BlockEnum.End)@@ -169,10 +183,19 @@ const FeaturesTrigger = () => {updatePublishedWorkflow(appID!)updateAppDetail()invalidateAppTriggers(appID!)- if (nodes.some(node => isAgentV2NodeData(node.data) && hasValidRosterAgentBinding(node.data))) {+ if (rosterAgentIds.length > 0) {void queryClient.invalidateQueries({queryKey: consoleQuery.agent.get.key(),})+ void Promise.all(rosterAgentIds.map(agentId => queryClient.invalidateQueries({+ queryKey: consoleQuery.agent.byAgentId.referencingWorkflows.get.queryOptions({+ input: {+ params: {+ agent_id: agentId,+ },+ },+ }).queryKey,+ })))}workflowStore.getState().setPublishedAt(res.created_at)workflowStore.getState().setLastPublishedHasUserInput(hasUserInputNode)@@ -182,7 +205,7 @@ const FeaturesTrigger = () => {else {throw new Error('Checklist failed')}- }, [needWarningNodes, handleCheckBeforePublish, publishWorkflow, appID, t, updatePublishedWorkflow, updateAppDetail, invalidateAppTriggers, nodes, queryClient, workflowStore, hasUserInputNode, resetWorkflowVersionHistory])+ }, [needWarningNodes, handleCheckBeforePublish, publishWorkflow, appID, t, updatePublishedWorkflow, updateAppDetail, invalidateAppTriggers, rosterAgentIds, queryClient, workflowStore, hasUserInputNode, resetWorkflowVersionHistory])const onPublisherToggle = useCallback((state: boolean) => {if (state)diff --git a/web/app/components/workflow/block-selector/__tests__/blocks.spec.tsx b/web/app/components/workflow/block-selector/__tests__/blocks.spec.tsxindex a417f974ba8..d9dfc4fa04e 100644--- a/web/app/components/workflow/block-selector/__tests__/blocks.spec.tsx+++ b/web/app/components/workflow/block-selector/__tests__/blocks.spec.tsx@@ -356,7 +356,7 @@ describe('Blocks', () => {)await user.click(screen.getByRole('button', { name: 'Agent' }))- await user.click(await screen.findByRole('button', { name: 'agentV2.roster.nodeSelector.startFromScratch' }))+ await user.click(await screen.findByRole('option', { name: 'agentV2.roster.nodeSelector.startFromScratch' }))expect(onSelect).toHaveBeenCalledWith(BlockEnum.AgentV2, {agent_binding: {diff --git a/web/app/components/workflow/block-selector/agent-selector.tsx b/web/app/components/workflow/block-selector/agent-selector.tsxindex 05268025ee5..1239b559b87 100644--- a/web/app/components/workflow/block-selector/agent-selector.tsx+++ b/web/app/components/workflow/block-selector/agent-selector.tsx@@ -5,7 +5,6 @@ import type { AgentRosterNodeData } from './types'import { cn } from '@langgenius/dify-ui/cn'import {Combobox,- ComboboxEmpty,ComboboxInput,ComboboxInputGroup,ComboboxItem,@@ -32,6 +31,14 @@ import BlockIcon from '../block-icon'const AGENT_SELECTOR_PAGE_SIZE = 8+type AgentSelectorOption+ = | AgentInviteOptionResponse+ | AgentSelectorActionOption++type AgentSelectorActionOption+ = | 'start-from-scratch'+ | 'manage-in-agent-console'+export function AgentSelectorContent({open,onOpenChange,@@ -60,20 +67,41 @@ export function AgentSelectorContent({}),})const agents = agentsQuery.data?.data ?? []+ const actionOptions: AgentSelectorActionOption[] = onStartFromScratch+ ? ['start-from-scratch', 'manage-in-agent-console']+ : ['manage-in-agent-console']+ const options: AgentSelectorOption[] = [...agents, ...actionOptions]+ const getOptionLabel = (option: AgentSelectorOption) => {+ if (isAgentSelectorActionOption(option)) {+ if (option === 'start-from-scratch')+ return t('roster.nodeSelector.startFromScratch', { ns: 'agentV2' })++ return t('roster.nodeSelector.manageInAgentConsole', { ns: 'agentV2' })+ }++ return option.name+ }const handleInputValueChange = (nextSearchText: string, details: ComboboxRootChangeEventDetails) => {if (details.reason !== 'item-press')setSearchText(nextSearchText)}- const handleValueChange = (agent: AgentInviteOptionResponse | null) => {- if (!agent)+ const handleValueChange = (option: AgentSelectorOption | null) => {+ if (!option)return- if (!agent.active_config_snapshot_id) {+ if (isAgentSelectorActionOption(option)) {+ if (option === 'start-from-scratch')+ onStartFromScratch?.()++ return+ }++ if (!option.active_config_snapshot_id) {toast.error(t('nodes.agent.modelNotSelected', { ns: 'workflow' }))return}- onSelect(toAgentRosterNodeData(agent))+ onSelect(toAgentRosterNodeData(option))}const handleOpenChange = (nextOpen: boolean) => {if (!nextOpen)@@ -83,12 +111,12 @@ export function AgentSelectorContent({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>+ <Combobox<AgentSelectorOption>filter={null}inputValue={searchText}- items={agents}- itemToStringLabel={getAgentLabel}- itemToStringValue={getAgentValue}+ items={options}+ itemToStringLabel={getOptionLabel}+ itemToStringValue={getAgentSelectorOptionValue}open={open}value={null}onInputValueChange={handleInputValueChange}@@ -105,54 +133,38 @@ export function AgentSelectorContent({/></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 className="max-h-none overflow-visible p-0">+ <div role="presentation" 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 && (+ <>+ {agents.length === 0 && (+ <ComboboxStatus className="px-3 py-2 system-xs-regular">+ {debouncedSearchText+ ? t('roster.emptySearch', { ns: 'agentV2' })+ : t('roster.empty', { ns: 'agentV2' })}+ </ComboboxStatus>)}- </ComboboxList>- <ComboboxEmpty className="px-3 py-2 system-xs-regular">- {debouncedSearchText- ? t('roster.emptySearch', { ns: 'agentV2' })- : t('roster.empty', { ns: 'agentV2' })}- </ComboboxEmpty>- </>- )}- </div>+ {agents.map(agent => (+ <AgentSelectorItem key={agent.id} agent={agent} />+ ))}+ </>+ )}+ </div>+ <div role="presentation" className="border-t border-divider-subtle p-1">+ {actionOptions.map(option => (+ <AgentSelectorActionItem key={option} option={option} />+ ))}+ </div>+ </ComboboxList></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>)}@@ -189,12 +201,15 @@ function AgentSelectorLoadingSkeleton({)}-function getAgentLabel(agent: AgentInviteOptionResponse) {- return agent.name+function getAgentSelectorOptionValue(option: AgentSelectorOption) {+ if (isAgentSelectorActionOption(option))+ return option++ return option.id}-function getAgentValue(agent: AgentInviteOptionResponse) {- return agent.id+function isAgentSelectorActionOption(option: AgentSelectorOption): option is AgentSelectorActionOption {+ return typeof option === 'string'}function toAgentRosterNodeData(agent: AgentInviteOptionResponse): AgentRosterNodeData {@@ -252,6 +267,38 @@ function AgentSelectorItem({)}+function AgentSelectorActionItem({+ option,+}: {+ option: AgentSelectorActionOption+}) {+ const { t } = useTranslation('agentV2')+ const isStartFromScratch = option === 'start-from-scratch'++ return (+ <ComboboxItem+ value={option}+ render={isStartFromScratch ? undefined : <Link href="/roster" />}+ className="flex min-h-7 w-full grid-cols-none items-center gap-2 rounded-md px-2 py-1.5 text-left system-sm-regular text-text-secondary hover:bg-state-base-hover hover:text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden data-highlighted:bg-state-base-hover data-highlighted:text-text-secondary"+ >+ <ComboboxItemText className="flex items-center gap-2 px-0 system-sm-regular text-text-secondary">+ <span+ aria-hidden+ className={cn(+ 'size-4 shrink-0 text-text-tertiary',+ isStartFromScratch ? 'i-ri-add-line' : 'i-ri-arrow-right-up-line',+ )}+ />+ <span className="min-w-0 flex-1 truncate">+ {isStartFromScratch+ ? t('roster.nodeSelector.startFromScratch')+ : t('roster.nodeSelector.manageInAgentConsole')}+ </span>+ </ComboboxItemText>+ </ComboboxItem>+ )+}+export function AgentBlockItem({block,onSelect,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.tsxindex 16963ba9011..6031e3d8b41 100644--- a/web/app/components/workflow/nodes/agent-v2/__tests__/hooks.spec.tsx+++ b/web/app/components/workflow/nodes/agent-v2/__tests__/hooks.spec.tsx@@ -132,6 +132,9 @@ describe('useCreateInlineAgentBinding', () => {body: {variant: 'workflow',save_strategy: 'node_job_only',+ binding: {+ binding_type: 'inline_agent',+ },soul_lock: {locked: false,},@@ -189,6 +192,9 @@ describe('useCreateInlineAgentBinding', () => {body: {variant: 'workflow',save_strategy: 'node_job_only',+ binding: {+ binding_type: 'inline_agent',+ },soul_lock: {locked: false,},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.tsxindex f1799608382..5b2a15c8ac1 100644--- a/web/app/components/workflow/nodes/agent-v2/__tests__/node.spec.tsx+++ b/web/app/components/workflow/nodes/agent-v2/__tests__/node.spec.tsx@@ -128,7 +128,7 @@ describe('agent/node', () => {expect(robotIcon?.parentElement).toHaveClass('size-8', 'rounded-full', 'bg-background-default-burn')})- it('renders inline agent name from workflow composer state', () => {+ it('renders the fixed inline setup name when workflow composer state is loaded', () => {render(<AgentV2Nodeid="agent-node"@@ -144,7 +144,8 @@ describe('agent/node', () => {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.queryByText('Workflow Agent 1')).not.toBeInTheDocument()+ 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')})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.tsxindex 522e53235f1..1b824eb7510 100644--- a/web/app/components/workflow/nodes/agent-v2/__tests__/panel.spec.tsx+++ b/web/app/components/workflow/nodes/agent-v2/__tests__/panel.spec.tsx@@ -14,6 +14,7 @@ const {mockInsertNodes,mockOrchestrateDrawerPanelProps,mockPromptEditorProps,+ mockCreateInlineAgentBinding,mockSetInputs,mockStoreState,mockUseAgentRosterDetail,@@ -33,6 +34,7 @@ const {open: boolean}>,mockPromptEditorProps: [] as PromptEditorProps[],+ mockCreateInlineAgentBinding: vi.fn(),mockSetInputs: vi.fn(),mockStoreState: {openInlineAgentPanelNodeId: undefined as string | undefined,@@ -100,6 +102,7 @@ vi.mock('../../_base/hooks/use-node-crud', () => ({vi.mock('@/app/components/workflow/block-selector/agent-selector', () => ({AgentSelectorContent: ({onSelect,+ onStartFromScratch,}: {onSelect: (agent: {description: string@@ -110,26 +113,38 @@ vi.mock('@/app/components/workflow/block-selector/agent-selector', () => ({name: stringrole: string}) => void+ onStartFromScratch?: () => 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>+ <>+ <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>+ {onStartFromScratch && (+ <button type="button" onClick={onStartFromScratch}>+ Start from Scratch+ </button>+ )}+ </>),}))vi.mock('../hooks', () => ({useAgentRosterDetail: (agentId?: string) => mockUseAgentRosterDetail(agentId),+ useCreateInlineAgentBinding: () => ({+ createInlineAgentBinding: mockCreateInlineAgentBinding,+ isCreatingInlineAgent: false,+ }),useWorkflowInlineAgentDetail: (nodeId?: string, agentId?: string | null) => mockUseWorkflowInlineAgentDetail(nodeId, agentId),}))@@ -201,6 +216,7 @@ describe('agent/panel', () => {mockPromptEditorProps.length = 0mockOrchestrateDrawerPanelProps.length = 0mockStoreState.openInlineAgentPanelNodeId = undefined+ mockCreateInlineAgentBinding.mockImplementation(() => {})mockUseNodeCrud.mockImplementation((_id: string, data: AgentV2NodeType) => ({inputs: data,setInputs: mockSetInputs,@@ -346,14 +362,17 @@ describe('agent/panel', () => {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()+ const trigger = screen.getByRole('button', { name: /^workflow\.nodes\.agent\.roster\.openPanel/ })+ expect(within(trigger).getByText('workflow.nodes.agent.roster.inlineSetup.name')).toBeInTheDocument()+ expect(within(trigger).getByText('workflow.nodes.agent.roster.inlineSetup.type')).toBeInTheDocument()+ const panel = screen.getByRole('dialog', { name: 'workflow.nodes.agent.roster.inlineSetup.name' })+ const panelRobotIcon = panel.querySelector('.i-custom-vender-agent-v2-robot-3')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(panelRobotIcon).toHaveClass('size-5')+ expect(panelRobotIcon?.parentElement).toHaveClass('size-9', 'rounded-full', 'bg-background-default-burn')+ expect(screen.queryByText('workflow.nodes.agent.roster.inlineSetup.title')).not.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',@@ -399,9 +418,11 @@ describe('agent/panel', () => {/>,)- const panel = screen.getByRole('dialog', { name: 'Workflow Agent 1' })+ const panel = screen.getByRole('dialog', { name: 'workflow.nodes.agent.roster.inlineSetup.name' })expect(panel).toBeInTheDocument()expect(panel.querySelector('header')).not.toHaveClass('h-[108px]')+ expect(panel.querySelector('.i-custom-vender-agent-v2-robot-3')?.parentElement).toHaveClass('size-9', 'rounded-full', 'bg-background-default-burn')+ expect(within(panel).queryByText('Workflow Agent 1')).not.toBeInTheDocument()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()@@ -410,6 +431,26 @@ describe('agent/panel', () => {expect(screen.getByRole('region', { name: 'inline-orchestrate-panel' })).toBeInTheDocument()})+ it('does not show start from scratch for an existing inline agent binding', () => {+ 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.change' }))++ expect(screen.queryByRole('button', { name: 'Start from Scratch' })).not.toBeInTheDocument()+ })+it('opens the inline panel while workflow composer state is still loading', () => {mockStoreState.openInlineAgentPanelNodeId = 'agent-node'mockUseWorkflowInlineAgentDetail.mockReturnValue({ data: undefined })@@ -430,8 +471,7 @@ describe('agent/panel', () => {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('dialog', { name: 'workflow.nodes.agent.roster.inlineSetup.name' })).toBeInTheDocument()expect(screen.getByRole('region', { name: 'inline-orchestrate-panel' })).toBeInTheDocument()expect(mockOrchestrateDrawerPanelProps.at(-1)).toMatchObject({agentId: 'inline-agent-1',@@ -498,6 +538,66 @@ describe('agent/panel', () => {)})+ it('switches a roster agent to a workflow-only inline agent from the selector', () => {+ 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',+ })+ })++ render(+ <AgentV2Panel+ id="agent-node"+ data={createData({+ agent_task: 'Keep this task',+ agent_declared_outputs: [{+ name: 'summary',+ type: 'string',+ }],+ })}+ panelProps={panelProps}+ />,+ )++ fireEvent.click(screen.getByRole('button', { name: 'workflow.nodes.agent.roster.change' }))+ fireEvent.click(screen.getByRole('button', { name: 'Start from Scratch' }))++ expect(mockCreateInlineAgentBinding).toHaveBeenCalledWith('agent-node', expect.objectContaining({+ onSuccess: expect.any(Function),+ }))+ expect(mockStoreState.setOpenInlineAgentPanelNodeId).toHaveBeenCalledWith('agent-node')+ expect(mockHandleNodeDataUpdateWithSyncDraft).toHaveBeenCalledWith(+ {+ id: 'agent-node',+ data: expect.objectContaining({+ agent_binding: {+ binding_type: 'inline_agent',+ agent_id: 'inline-agent-1',+ current_snapshot_id: 'inline-snapshot-1',+ },+ agent_task: 'Keep this task',+ agent_declared_outputs: [{+ name: 'summary',+ type: 'string',+ }],+ _openInlineAgentPanel: true,+ }),+ },+ expect.objectContaining({+ sync: true,+ notRefreshWhenSyncError: true,+ }),+ )+ })+it('does not fall back to the roster agent description when role is empty', () => {mockUseAgentRosterDetail.mockReturnValue({data: {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.tsxindex f04899116b0..0b174d02280 100644--- 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.tsx@@ -79,6 +79,7 @@ function AgentOrchestrateDrawerPanelContent({<AgentOrchestratePanelagentId={agentId}appId={isInline ? appId : undefined}+ nodeId={isInline ? nodeId : undefined}activeConfigSnapshot={activeConfigSnapshot}agentSoulConfig={agentSoulConfig as AgentSoulConfig}agentName={composerState?.agent?.name}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.tsxindex 5a933f63830..b95617ff4a3 100644--- 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.tsx@@ -84,6 +84,7 @@ function InlineSetupAvatar({function AgentRosterDrawer({agent,children,+ isInlineSetup = false,mode = 'detail',open,portalContainerRef,@@ -94,6 +95,7 @@ function AgentRosterDrawer({}: {agent: AgentRosterDisplayDatachildren?: ReactNode+ isInlineSetup?: booleanmode?: AgentRosterDrawerModeopen: booleanportalContainerRef: RefObject<HTMLDivElement | null>@@ -104,7 +106,7 @@ function AgentRosterDrawer({}) {const { t } = useTranslation()const isSetup = mode === 'setup'- const title = isSetup ? t(`${i18nPrefix}.roster.inlineSetup.title`, { ns: 'workflow' }) : agent.name+ const title = isInlineSetup ? t(`${i18nPrefix}.roster.inlineSetup.name`, { ns: 'workflow' }) : agent.nameconst description = isSetup ? t(`${i18nPrefix}.roster.inlineSetup.description`, { ns: 'workflow' }) : agent.rolereturn (@@ -139,8 +141,10 @@ function AgentRosterDrawer({)}><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', isSetup ? 'min-w-px items-center gap-2' : 'h-10 items-center gap-2 px-0.5 py-0.5')}>+ {isInlineSetup+ ? <InlineSetupAvatar className="size-9" />+ : <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')}>@@ -227,6 +231,7 @@ export function AgentRosterField({portalContainerRef,onChange,onPanelOpenChange,+ onStartFromScratch,}: {agent?: AgentRosterDisplayDataagentId?: string@@ -241,6 +246,7 @@ export function AgentRosterField({portalContainerRef: RefObject<HTMLDivElement | null>onChange: (agent: AgentRosterNodeData) => voidonPanelOpenChange?: (open: boolean) => void+ onStartFromScratch?: () => void}) {const { t } = useTranslation()const [localPanelOpen, setLocalPanelOpen] = useState(false)@@ -317,6 +323,12 @@ export function AgentRosterField({setIsSelectorOpen(false)onChange(nextAgent)}}+ onStartFromScratch={onStartFromScratch+ ? () => {+ setIsSelectorOpen(false)+ onStartFromScratch()+ }+ : undefined}/></PopoverContent></Popover>@@ -340,6 +352,7 @@ export function AgentRosterField({</button><AgentRosterDraweragent={agent}+ isInlineSetup={isInlineSetup}mode={panelMode}open={panelOpen}portalContainerRef={portalContainerRef}diff --git a/web/app/components/workflow/nodes/agent-v2/hooks.ts b/web/app/components/workflow/nodes/agent-v2/hooks.tsindex 6d9bbbd3d44..7df158bda9f 100644--- a/web/app/components/workflow/nodes/agent-v2/hooks.ts+++ b/web/app/components/workflow/nodes/agent-v2/hooks.ts@@ -74,6 +74,9 @@ export function useCreateInlineAgentBinding() {body: {variant: 'workflow',save_strategy: 'node_job_only',+ binding: {+ binding_type: 'inline_agent',+ },soul_lock: {locked: false,},diff --git a/web/app/components/workflow/nodes/agent-v2/node.tsx b/web/app/components/workflow/nodes/agent-v2/node.tsxindex 95e0c03ecfd..33dcd303832 100644--- a/web/app/components/workflow/nodes/agent-v2/node.tsx+++ b/web/app/components/workflow/nodes/agent-v2/node.tsx@@ -50,17 +50,15 @@ function AgentNodeAvatarPlaceholder() {function AgentNodeModel({data,agent,- inlineAgentName,isLoading,}: {data: AgentV2NodeTypeagent?: ReturnType<typeof useAgentRosterDetail>['data']- inlineAgentName?: stringisLoading: boolean}) {const { t } = useTranslation()const isInlineAgent = hasInlineAgentBinding(data)- const name = isInlineAgent ? (inlineAgentName || t('nodes.agent.roster.inlineSetup.name', { ns: 'workflow' })) : agent?.name+ const name = isInlineAgent ? t('nodes.agent.roster.inlineSetup.name', { ns: 'workflow' }) : agent?.nameconst role = isInlineAgent ? t('nodes.agent.roster.inlineSetup.type', { ns: 'workflow' }) : ''const showPlaceholder = isLoading || (!isInlineAgent && !agent)@@ -110,7 +108,7 @@ export function AgentV2Node({ id, data }: NodeProps<AgentV2NodeType>) {const isInlineAgentDetailLoading = isInlineAgent && !!inlineAgentId && inlineAgentQuery.isPendingif (isInlineAgent || hasValidAgent)- return <AgentNodeModel data={data} agent={rosterAgentQuery.data} inlineAgentName={inlineAgentQuery.data?.agent?.name} isLoading={isInlineAgentDetailLoading} />+ return <AgentNodeModel data={data} agent={rosterAgentQuery.data} isLoading={isInlineAgentDetailLoading} />return (<div className="mb-1 space-y-1 px-3">diff --git a/web/app/components/workflow/nodes/agent-v2/panel.tsx b/web/app/components/workflow/nodes/agent-v2/panel.tsxindex c01c46fe513..c80c021407d 100644--- a/web/app/components/workflow/nodes/agent-v2/panel.tsx+++ b/web/app/components/workflow/nodes/agent-v2/panel.tsx@@ -16,7 +16,7 @@ import { AgentOrchestrateDrawerPanel } from './components/agent-orchestrate-drawimport { 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 { useAgentRosterDetail, useCreateInlineAgentBinding, useWorkflowInlineAgentDetail } from './hooks'import { getAgentV2DeclaredOutputs } from './output-variables'import { hasValidInlineAgentBinding } from './types'@@ -43,9 +43,12 @@ export function AgentV2Panel({const isInlineAgentPanelOpen = isInlineAgentReady && openInlineAgentPanelNodeId === idconst rosterAgentQuery = useAgentRosterDetail(rosterAgentId)const inlineAgentQuery = useWorkflowInlineAgentDetail(id, inlineAgentId)+ const { createInlineAgentBinding, isCreatingInlineAgent } = useCreateInlineAgentBinding()const inlineAgent = inlineAgentQuery.data?.agentconst isAgentPanelOpen = isInlineAgentReady ? isInlineAgentPanelOpen : isRosterAgentPanelOpenconst isInlineAgentLoading = isInlineAgentReady && !inlineAgent+ const isAgentBindingPending = isInlineAgentPending || isCreatingInlineAgent+ const canStartFromScratch = inputs.agent_binding?.binding_type !== 'inline_agent'const displayedAgent = rosterAgentQuery.data ?? (inlineAgentId && isInlineAgentReady? {id: inlineAgentId,@@ -110,6 +113,33 @@ export function AgentV2Panel({)}, [handleNodeDataUpdateWithSyncDraft, id, inputs, setOpenInlineAgentPanelNodeId])+ const handleStartFromScratch = useCallback(() => {+ createInlineAgentBinding(id, {+ onSuccess: (binding) => {+ setIsRosterAgentPanelOpen(false)+ setIsInlineAgentPanelOpenedFromTrigger(false)+ setOpenInlineAgentPanelNodeId(id)++ const newInputs = produce(inputsRef.current, (draft) => {+ delete (draft as AgentV2NodeType & { agent_roster?: unknown }).agent_roster+ draft.agent_binding = binding+ draft._openInlineAgentPanel = true+ })+ inputsRef.current = newInputs+ handleNodeDataUpdateWithSyncDraft(+ {+ id,+ data: newInputs,+ },+ {+ sync: true,+ notRefreshWhenSyncError: true,+ },+ )+ },+ })+ }, [createInlineAgentBinding, handleNodeDataUpdateWithSyncDraft, id, setOpenInlineAgentPanelNodeId])+const handleAgentPanelOpenChange = useCallback((open: boolean) => {if (isInlineAgentReady) {if (open)@@ -171,7 +201,7 @@ export function AgentV2Panel({isInlineSetup={isInlineAgentReady}isLoading={isInlineAgentLoading}isPanelOpen={isAgentPanelOpen}- isPending={isInlineAgentPending}+ isPending={isAgentBindingPending}panelBody={isAgentPanelOpen && displayedAgent? (<AgentOrchestrateDrawerPanel@@ -189,6 +219,7 @@ export function AgentV2Panel({showPanelDetailActions={!isInlineAgentReady}onChange={handleRosterChange}onPanelOpenChange={handleAgentPanelOpenChange}+ onStartFromScratch={canStartFromScratch ? handleStartFromScratch : undefined}/></div><divdiff --git a/web/contract/console/agent-drive.ts b/web/contract/console/agent-drive.tsnew file mode 100644index 00000000000..b80af71ba24--- /dev/null+++ b/web/contract/console/agent-drive.ts@@ -0,0 +1,123 @@+import { type } from '@orpc/contract'+import { base } from '../base'++type AgentDriveSkillItem = {+ path: string+ skill_md_key: string+ archive_key?: string | null+ name: string+ description: string+ size?: number | null+ mime_type?: string | null+ hash?: string | null+ created_at?: number | null+}++type AgentDriveSkillFile = {+ available_in_drive: boolean+ drive_key?: string | null+ name: string+ path: string+ type: string+}++type AgentDriveSkillMarkdown = {+ binary: boolean+ key: string+ size?: number | null+ text?: string | null+ truncated: boolean+}++type AgentDriveSkillInspect = AgentDriveSkillItem & {+ file_tree?: Array<Record<string, unknown>>+ files?: AgentDriveSkillFile[]+ skill_md: AgentDriveSkillMarkdown+ source: string+ warnings?: string[]+}++const agentDriveSkillsByAgentContract = base+ .route({+ path: '/agent/{agent_id}/drive/skills',+ method: 'GET',+ })+ .input(type<{+ params: {+ agent_id: string+ }+ }>())+ .output(type<{ items: AgentDriveSkillItem[] }>())++const agentDriveSkillInspectByAgentContract = base+ .route({+ path: '/agent/{agent_id}/drive/skills/{skill_path}/inspect',+ method: 'GET',+ })+ .input(type<{+ params: {+ agent_id: string+ skill_path: string+ }+ }>())+ .output(type<AgentDriveSkillInspect>())++const agentDriveSkillsByAppContract = base+ .route({+ path: '/apps/{app_id}/agent/drive/skills',+ method: 'GET',+ })+ .input(type<{+ params: {+ app_id: string+ }+ query?: {+ node_id?: string+ }+ }>())+ .output(type<{ items: AgentDriveSkillItem[] }>())++const agentDriveSkillInspectByAppContract = base+ .route({+ path: '/apps/{app_id}/agent/drive/skills/{skill_path}/inspect',+ method: 'GET',+ })+ .input(type<{+ params: {+ app_id: string+ skill_path: string+ }+ query?: {+ node_id?: string+ }+ }>())+ .output(type<AgentDriveSkillInspect>())++export const agentDriveContracts = {+ byAgentId: {+ drive: {+ skills: {+ get: agentDriveSkillsByAgentContract,+ bySkillPath: {+ inspect: {+ get: agentDriveSkillInspectByAgentContract,+ },+ },+ },+ },+ },+ byAppId: {+ agent: {+ drive: {+ skills: {+ get: agentDriveSkillsByAppContract,+ bySkillPath: {+ inspect: {+ get: agentDriveSkillInspectByAppContract,+ },+ },+ },+ },+ },+ },+}diff --git a/web/contract/router.ts b/web/contract/router.tsindex 2f9b5de318d..c00657892f0 100644--- a/web/contract/router.ts+++ b/web/contract/router.ts@@ -2,6 +2,7 @@ import type { InferContractRouterInputs } from '@orpc/contract'import { contract as communityContract } from '@dify/contracts/api/console/orpc.gen'import { contract as enterpriseContract } from '@dify/contracts/enterprise/orpc.gen'import { rbacAccessConfigContract } from './console/access-control'+import { agentDriveContracts } from './console/agent-drive'import {appDeleteContract,appListContract,@@ -114,9 +115,26 @@ export const consoleRouterContract = {workflowOnlineUsers: workflowOnlineUsersContract,byAppId: {...communityContract.apps.byAppId,+ agent: {+ ...communityContract.apps.byAppId.agent,+ ...agentDriveContracts.byAppId.agent,+ drive: {+ ...communityContract.apps.byAppId.agent.drive,+ ...agentDriveContracts.byAppId.agent.drive,+ },+ },+ },+ },+ agent: {+ ...communityContract.agent,+ byAgentId: {+ ...communityContract.agent.byAgentId,+ drive: {+ ...communityContract.agent.byAgentId.drive,+ ...agentDriveContracts.byAgentId.drive,+ },},},- agent: communityContract.agent,explore: {...communityContract.explore,apps: exploreAppsContract,diff --git a/web/features/agent-v2/agent-composer/__tests__/store.spec.ts b/web/features/agent-v2/agent-composer/__tests__/store.spec.tsindex 302d04c2888..a48369d876a 100644--- a/web/features/agent-v2/agent-composer/__tests__/store.spec.ts+++ b/web/features/agent-v2/agent-composer/__tests__/store.spec.ts@@ -50,27 +50,6 @@ describe('agent composer store conversions', () => {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: [{@@ -119,25 +98,6 @@ describe('agent composer store conversions', () => {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',@@ -181,7 +141,7 @@ describe('agent composer store conversions', () => {used_in_agent_nodes: true,})- expect(publishConfig.skills_files).toMatchObject(baseConfig.skills_files!)+ expect(publishConfig).not.toHaveProperty('skills_files')expect(publishConfig.tools?.dify_tools).toEqual([expect.objectContaining({provider: 'DuckDuckGo',diff --git a/web/features/agent-v2/agent-composer/conversions.ts b/web/features/agent-v2/agent-composer/conversions.tsindex 3411bd6556c..e9d0fe9fecd 100644--- a/web/features/agent-v2/agent-composer/conversions.ts+++ b/web/features/agent-v2/agent-composer/conversions.ts@@ -1,10 +1,8 @@import type { AgentSoulConfig } from '@dify/contracts/api/console/agent/types.gen'import type {AgentCliTool,- AgentFileNode,AgentKnowledgeRetrievalItem,AgentProviderTool,- AgentSkill,AgentSoulConfigFormState,AgentTool,EnvVariable,@@ -16,79 +14,8 @@ 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),- driveKey: file.drive_key ?? undefined,- }]-})--const toFileRefs = (files: AgentFileNode[]) => flattenFileNodes(files).map(file => ({- ...(file.driveKey ? { drive_key: file.driveKey } : {}),- id: file.id,- name: file.name,- type: file.icon,-}))-const getKnowledgeRetrievalName = (item: AgentKnowledgeRetrievalItem) => item.name ?? item.nameKey ?? item.idconst toKnowledgeDatasets = (knowledgeRetrievals: AgentKnowledgeRetrievalItem[]) => knowledgeRetrievals.flatMap((item) => {@@ -448,34 +375,31 @@ export const formStateToAgentSoulConfig = ({baseConfig?: AgentSoulConfigformState: AgentSoulConfigFormStatecurrentModel?: 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),-})+}): AgentSoulConfig => {+ return {+ ...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,+ 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,@@ -488,8 +412,6 @@ export const agentSoulConfigToFormState = (prompt: config?.prompt?.system_prompt ?? '',model: toDraftModel(config),appFeatures: config?.app_features,- skills: toSkillFormState(config),- files: toFileFormState(config),tools: [...providerToolState.tools,...toCliToolFormState(config),diff --git a/web/features/agent-v2/agent-composer/form-state.ts b/web/features/agent-v2/agent-composer/form-state.tsindex e75c3491f91..80429d8be84 100644--- a/web/features/agent-v2/agent-composer/form-state.ts+++ b/web/features/agent-v2/agent-composer/form-state.ts@@ -24,14 +24,10 @@ export type EnvVariable = {export type AgentSkill = {description?: string- files?: string[]- fileId?: string- fullArchiveFileId?: string- fullArchiveKey?: string+ archiveKey?: stringid: stringname: stringpath?: string- skillMdFileId?: stringskillMdKey?: string}@@ -100,8 +96,6 @@ export type AgentSoulConfigFormState = {prompt: stringmodel?: DefaultModelappFeatures?: AgentSoulAppFeaturesConfig- skills: AgentSkill[]- files: AgentFileNode[]tools: AgentTool[]knowledgeRetrievals: AgentKnowledgeRetrievalItem[]envVariables: EnvVariable[]@@ -110,8 +104,6 @@ export type AgentSoulConfigFormState = {export const defaultAgentSoulConfigFormState: AgentSoulConfigFormState = {prompt: '',- skills: [],- files: [],tools: [],knowledgeRetrievals: [],envVariables: [],diff --git a/web/features/agent-v2/agent-composer/store-modules/files.ts b/web/features/agent-v2/agent-composer/store-modules/files.tsdeleted file mode 100644index b54f28f1c49..00000000000--- a/web/features/agent-v2/agent-composer/store-modules/files.ts+++ /dev/null@@ -1,17 +0,0 @@-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/skills.ts b/web/features/agent-v2/agent-composer/store-modules/skills.tsdeleted file mode 100644index e35c03d3aec..00000000000--- a/web/features/agent-v2/agent-composer/store-modules/skills.ts+++ /dev/null@@ -1,26 +0,0 @@-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-detail/access/access-sources.ts b/web/features/agent-v2/agent-detail/access/access-sources.tsdeleted file mode 100644index b3e758e4e10..00000000000--- a/web/features/agent-v2/agent-detail/access/access-sources.ts+++ /dev/null@@ -1,34 +0,0 @@-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/configure/__tests__/page.spec.tsx b/web/features/agent-v2/agent-detail/configure/__tests__/page.spec.tsxindex 1214f186497..e40ddfadd0d 100644--- a/web/features/agent-v2/agent-detail/configure/__tests__/page.spec.tsx+++ b/web/features/agent-v2/agent-detail/configure/__tests__/page.spec.tsx@@ -1,3 +1,4 @@+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { render, screen } from '@testing-library/react'import { AgentConfigurePage } from '../page'@@ -15,13 +16,13 @@ const mocks = vi.hoisted(() => ({isSuccess: true,},composer: {- data: undefined,+ data: undefined as unknown,isFetching: true,isPending: true,isSuccess: false,},version: {- data: undefined,+ data: undefined as unknown,isFetching: false,isPending: false,isSuccess: false,@@ -60,10 +61,15 @@ vi.mock('@/service/client', () => ({byAgentId: {get: {queryOptions: () => ({ queryKey: ['agent'] }),+ queryKey: () => ['agent'],},composer: {get: {queryOptions: () => ({ queryKey: ['composer'] }),+ queryKey: () => ['composer'],+ },+ put: {+ mutationOptions: () => ({ mutationFn: vi.fn() }),},},versions: {@@ -72,6 +78,9 @@ vi.mock('@/service/client', () => ({queryOptions: () => ({ queryKey: ['version'] }),},},+ get: {+ key: () => ['versions'],+ },},},},@@ -102,7 +111,9 @@ vi.mock('../components/preview/header', () => ({}))vi.mock('../components/preview/versions-panel', () => ({- AgentPreviewVersionsPanel: () => null,+ AgentPreviewVersionsPanel: (props: { onSelectVersion: (versionId: string) => void }) => (+ <button type="button" onClick={() => props.onSelectVersion('snapshot-2')}>select version</button>+ ),}))describe('AgentConfigurePage', () => {@@ -120,13 +131,13 @@ describe('AgentConfigurePage', () => {isSuccess: true,}mocks.queryState.composer = {- data: undefined,+ data: undefined as unknown,isFetching: true,isPending: true,isSuccess: false,}mocks.queryState.version = {- data: undefined,+ data: undefined as unknown,isFetching: false,isPending: false,isSuccess: false,@@ -135,7 +146,13 @@ describe('AgentConfigurePage', () => {describe('Loading state', () => {it('should show loading instead of the configure panels while composer data is pending', () => {- render(<AgentConfigurePage agentId="agent-1" />)+ const queryClient = new QueryClient()++ render(+ <QueryClientProvider client={queryClient}>+ <AgentConfigurePage agentId="agent-1" />+ </QueryClientProvider>,+ )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.tsxindex cde113dda3d..69f8ff0735a 100644--- a/web/features/agent-v2/agent-detail/configure/__tests__/use-agent-configure-sync.spec.tsx+++ b/web/features/agent-v2/agent-detail/configure/__tests__/use-agent-configure-sync.spec.tsx@@ -34,6 +34,15 @@ const composerPutMutationOptions = vi.hoisted(() => vi.fn((options?: {},})))+function createDeferredPromise<T>() {+ let resolve!: (value: T) => void+ const promise = new Promise<T>((promiseResolve) => {+ resolve = promiseResolve+ })++ return { promise, resolve }+}+vi.mock('@/service/client', () => ({consoleQuery: {agent: {@@ -213,4 +222,40 @@ describe('useAgentConfigureSync', () => {name: 'Agent',})})++ it('should expose publishing status from the publish mutation while publish is pending', async () => {+ const publishDeferred = createDeferredPromise<{ agent_soul: Record<string, unknown> }>()+ composerPutMutationFn.mockReturnValueOnce(publishDeferred.promise)+ const { result } = renderUseAgentConfigureSync()+ const publishPayload = {+ agent_id: 'agent-1',+ config_snapshot: {+ prompt: {+ system_prompt: 'Published prompt',+ },+ },+ }++ let publishPromise!: Promise<void>+ act(() => {+ publishPromise = result.current.publishDraft(publishPayload)+ })++ await act(async () => {+ await Promise.resolve()+ await vi.advanceTimersByTimeAsync(0)+ })++ expect(result.current.isPublishing).toBe(true)++ await act(async () => {+ publishDeferred.resolve({+ agent_soul: publishPayload.config_snapshot,+ })+ await publishPromise+ await vi.advanceTimersByTimeAsync(0)+ })++ expect(result.current.isPublishing).toBe(false)+ })})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.tsxindex 7043cda75f0..bc10dec2ac7 100644--- 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.tsx@@ -91,6 +91,19 @@ vi.mock('@/hooks/use-theme', () => ({default: () => ({ theme: 'light' }),}))+vi.mock('../orchestrate/drive-context', () => ({+ useAgentDriveSkills: () => ({+ skills: [+ {+ id: 'playwright/SKILL.md',+ name: 'Playwright',+ skillMdKey: 'playwright/SKILL.md',+ },+ ],+ }),+ useAgentDriveFiles: () => ({ files: [] }),+}))+const duckDuckGoSearchAction = {id: 'duckduckgo-search',name: 'DuckDuckGo Search',@@ -112,12 +125,6 @@ const duckDuckGoProviderTool: AgentTool = {const promptEditorDraft = {...defaultAgentSoulConfigFormState,- skills: [- {- id: 'playwright',- name: 'Playwright',- },- ],tools: [duckDuckGoProviderTool],} satisfies typeof defaultAgentSoulConfigFormState@@ -268,7 +275,7 @@ describe('AgentPromptEditor', () => {fireEvent.click(screen.getByRole('button', { name: /Playwright/i }))- expect(store.get(agentComposerPromptAtom)).toBe('Review these tenders [§skill:playwright:Playwright§]')+ expect(store.get(agentComposerPromptAtom)).toBe('Review these tenders [§skill:playwright%2FSKILL.md:Playwright§]')await waitFor(() => {expect(screen.queryByRole('button', { name: /Playwright/i })).not.toBeInTheDocument()})@@ -305,7 +312,7 @@ describe('AgentPromptEditor', () => {files={[]}tools={[]}onToolsChange={vi.fn()}- onAddSkill={options => options?.onAdded?.({ id: 'skill-1', name: 'Skill One' })}+ onAddSkill={options => options?.onAdded?.({ id: 'skill-1', name: 'Skill One', skillMdKey: 'skills/skill-1/SKILL.md' })}retrievals={[]}onBack={vi.fn()}onOpenCategory={vi.fn()}@@ -313,7 +320,7 @@ describe('AgentPromptEditor', () => {/>,)fireEvent.click(screen.getByRole('button', { name: /agentDetail\.configure\.skills\.add/i }))- expect(onSelect).toHaveBeenCalledWith('[§skill:skill-1:Skill One§]')+ expect(onSelect).toHaveBeenCalledWith('[§skill:skills%2Fskill-1%2FSKILL.md:Skill One§]')rerender(<AgentPromptSlashMenu@@ -323,7 +330,7 @@ describe('AgentPromptEditor', () => {files={[]}tools={[]}onToolsChange={vi.fn()}- onAddFile={options => options?.onAdded?.({ id: 'file-1', name: 'Guide.md', icon: 'markdown' })}+ onAddFile={options => options?.onAdded?.({ id: 'file-1', name: 'Guide.md', icon: 'markdown', driveKey: 'files/Guide.md' })}retrievals={[]}onBack={vi.fn()}onOpenCategory={vi.fn()}@@ -331,7 +338,7 @@ describe('AgentPromptEditor', () => {/>,)fireEvent.click(screen.getByRole('button', { name: /agentDetail\.configure\.files\.add/i }))- expect(onSelect).toHaveBeenCalledWith('[§file:file-1:Guide.md§]')+ expect(onSelect).toHaveBeenCalledWith('[§file:files%2FGuide.md:Guide.md§]')rerender(<AgentPromptSlashMenudiff --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.tsxindex ef583288a07..705b83e6039 100644--- 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.tsx@@ -8,6 +8,14 @@ import { AgentKnowledgeRetrieval } from '../knowledge'import { AgentSkills } from '../skills'import { AgentTools } from '../tools'+vi.mock('../drive-context', () => ({+ FILES_DRIVE_PREFIX: 'files/',+ getAgentDriveFileName: (key: string) => key.split('/').pop() ?? key,+ useAgentDriveApiContext: () => ({ agentId: 'agent-1' }),+ useAgentDriveFiles: () => ({ files: [], query: { refetch: vi.fn() } }),+ useAgentDriveSkills: () => ({ skills: [], query: { refetch: vi.fn() } }),+}))+function renderEmptySections() {const queryClient = new QueryClient()@@ -16,14 +24,12 @@ function renderEmptySections() {<AgentComposerProviderinitialDraft={{...defaultAgentSoulConfigFormState,- files: [],knowledgeRetrievals: [],- skills: [],tools: [],}}>- <AgentSkills agentId="agent-1" />- <AgentFiles agentId="agent-1" />+ <AgentSkills />+ <AgentFiles /><AgentTools /><AgentKnowledgeRetrieval /></AgentComposerProvider>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.tsxindex 5e4fe175882..6beb7cc649c 100644--- 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.tsx@@ -19,10 +19,24 @@ const hotkeyRegistrations = vi.hoisted(() => new Map<string, {const mockFormatForDisplay = vi.hoisted(() => vi.fn((hotkey: string) => `display:${hotkey}`))const mockFormatTimeFromNow = vi.hoisted(() => vi.fn(() => 'just now'))+const mockFormatTime = vi.hoisted(() => vi.fn((timestamp: number) => `formatted:${timestamp}`))+const restoreVersionMutation = vi.hoisted(() => vi.fn(async (_input: unknown) => ({+ active_config_snapshot_id: 'snapshot-2',+ result: 'success',+})))+const toastMock = vi.hoisted(() => ({+ error: vi.fn(),+ success: vi.fn(),+}))const workflowReferences = vi.hoisted(() => ({+ fetchCount: 0,data: [] as AgentReferencingWorkflowResponse[],}))+vi.mock('@langgenius/dify-ui/toast', () => ({+ toast: toastMock,+}))+vi.mock('@tanstack/react-hotkeys', async (importOriginal) => {const actual = await importOriginal<typeof import('@tanstack/react-hotkeys')>()return {@@ -40,68 +54,51 @@ vi.mock('@/hooks/use-format-time-from-now', () => ({}),}))+vi.mock('@/hooks/use-timestamp', () => ({+ default: () => ({+ formatTime: mockFormatTime,+ }),+}))+vi.mock('@/service/client', () => ({consoleQuery: {agent: {byAgentId: {+ get: {+ queryKey: ({ input }: { input: { params: { agent_id: string } } }) => ['agent', input],+ },+ composer: {+ get: {+ queryKey: ({ input }: { input: { params: { agent_id: string } } }) => ['agent-composer', input],+ },+ },referencingWorkflows: {get: {queryOptions: ({ input }: { input: { params: { agent_id: string } } }) => ({queryKey: ['agent-referencing-workflows', input],queryFn: async () => ({- data: workflowReferences.data,+ data: (workflowReferences.fetchCount++, workflowReferences.data),}),}),},},+ versions: {+ byVersionId: {+ restore: {+ post: {+ mutationOptions: () => ({ mutationFn: restoreVersionMutation }),+ },+ },+ },+ get: {+ key: () => ['agent-versions'],+ },+ },},},},}))-vi.mock('@langgenius/dify-ui/popover', async () => {- const React = await import('react')- const ReactDOM = await import('react-dom')- 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 ReactDOM.createPortal(<div data-testid="publish-impact-popover">{children}</div>, document.body)- },- PopoverTrigger: ({- render: trigger,- }: {- render: React.ReactElement- }) => trigger,- }-})-const activeConfigSnapshot: AgentConfigSnapshotSummaryResponse = {id: 'snapshot-1',agent_id: 'agent-1',@@ -111,11 +108,12 @@ const activeConfigSnapshot: AgentConfigSnapshotSummaryResponse = {const originalDraftWithFile = {...defaultAgentSoulConfigFormState,- files: [+ tools: [{- id: 'preview-image',- name: 'agent-roster-skill-detail-dialog-preview-image.png',- icon: 'image',+ id: 'cli-1',+ kind: 'cli',+ name: 'Run tests',+ installCommand: 'pnpm test',},],} satisfies typeof defaultAgentSoulConfigFormState@@ -123,6 +121,7 @@ const originalDraftWithFile = {const publishedReferences: AgentReferencingWorkflowResponse[] = [{app_id: 'app-python',+ app_updated_at: 1710000100,app_mode: 'workflow',app_name: 'Python bug fixer',workflow_id: 'workflow-python',@@ -136,19 +135,31 @@ const publishedReferences: AgentReferencingWorkflowResponse[] = [app_icon_type: 'emoji',app_mode: 'workflow',app_name: 'Translation Workflow',+ app_updated_at: 1710000200,workflow_id: 'workflow-translation',workflow_version: '1',node_ids: ['node-translation'],},]+function createDeferredPromise() {+ let resolve!: () => void+ const promise = new Promise<void>((promiseResolve) => {+ resolve = promiseResolve+ })++ return { promise, resolve }+}+function renderPublishBar({activeConfigIsPublished,activeConfigSnapshot,draftSavedAt,isPublishing,onPublish = vi.fn<PublishHandler>(),+ onExitVersions = vi.fn(),prompt = '',+ selectedVersionSnapshot,setupStore,usedByAppReferences = [],}: {@@ -157,7 +168,9 @@ function renderPublishBar({draftSavedAt?: numberisPublishing?: booleanonPublish?: PublishMock+ onExitVersions?: Mock<() => void>prompt?: string+ selectedVersionSnapshot?: AgentConfigSnapshotSummaryResponse | nullsetupStore?: (store: ReturnType<typeof createStore>) => voidusedByAppReferences?: AgentReferencingWorkflowResponse[]} = {}) {@@ -172,7 +185,9 @@ function renderPublishBar({store.set(agentComposerPromptAtom, prompt)setupStore?.(store)- render(+ const renderPublishBarTree = (nextProps?: {+ isPublishing?: boolean+ }) => (<QueryClientProvider client={queryClient}><JotaiProvider store={store}><AgentConfigurePublishBar@@ -181,16 +196,23 @@ function renderPublishBar({activeConfigSnapshot={activeConfigSnapshot}draftSavedAt={draftSavedAt}agentName="Iris"- isPublishing={isPublishing}+ isPublishing={nextProps?.isPublishing ?? isPublishing}+ selectedVersionSnapshot={selectedVersionSnapshot}onPublish={onPublish}+ onExitVersions={onExitVersions}onOpenVersions={vi.fn()}/></JotaiProvider>- </QueryClientProvider>,+ </QueryClientProvider>)+ const view = render(renderPublishBarTree())return {+ ...view,+ queryClient,+ onExitVersions,onPublish,+ rerenderPublishBar: renderPublishBarTree,}}@@ -198,7 +220,12 @@ describe('AgentConfigurePublishBar', () => {beforeEach(() => {vi.clearAllMocks()hotkeyRegistrations.clear()+ restoreVersionMutation.mockResolvedValue({+ active_config_snapshot_id: 'snapshot-2',+ result: 'success',+ })workflowReferences.data = []+ workflowReferences.fetchCount = 0vi.spyOn(console, 'log').mockImplementation(() => {})})@@ -221,6 +248,37 @@ describe('AgentConfigurePublishBar', () => {)})+ it('should restore the selected version from view-only mode', async () => {+ const selectedVersionSnapshot = {+ ...activeConfigSnapshot,+ id: 'snapshot-2',+ version: 2,+ version_note: 'Stable version',+ created_by: 'Alice',+ }++ const { onExitVersions } = renderPublishBar({+ selectedVersionSnapshot,+ })++ expect(screen.getByText('Stable version')).toBeInTheDocument()+ expect(screen.getByText('agentV2.agentDetail.versionHistory.viewOnly')).toBeInTheDocument()+ expect(screen.getByText('formatted:1710000000 · Alice')).toBeInTheDocument()+ fireEvent.click(screen.getByRole('button', { name: 'agentV2.agentDetail.versionHistory.restore' }))++ await waitFor(() => {+ expect(restoreVersionMutation).toHaveBeenCalled()+ })+ expect(restoreVersionMutation.mock.calls[0]?.[0]).toEqual({+ params: {+ agent_id: 'agent-1',+ version_id: 'snapshot-2',+ },+ })+ expect(onExitVersions).toHaveBeenCalled()+ expect(toastMock.success).toHaveBeenCalledWith('common.api.actionSuccess')+ })+it('should render saved time from the latest draft save timestamp', () => {renderPublishBar({ draftSavedAt: 1710000100000 })@@ -236,7 +294,7 @@ describe('AgentConfigurePublishBar', () => {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.getByRole('button', { name: 'agentV2.agentDetail.configure.publishBar.published' })).toBeDisabled()expect(screen.queryByText('display:Mod')).not.toBeInTheDocument()expect(mockFormatTimeFromNow).toHaveBeenCalledWith(1710000000 * 1000)expect(hotkeyRegistrations.get('Mod+Shift+P')?.options).toEqual(@@ -255,6 +313,7 @@ describe('AgentConfigurePublishBar', () => {})expect(screen.getByText('agentV2.agentDetail.configure.publishBar.unpublishedChanges')).toBeInTheDocument()+ expect(screen.getByText('agentV2.agentDetail.configure.publishBar.saved')).toBeInTheDocument()expect(screen.getByRole('button', { name: /agentV2\.agentDetail\.configure\.publishBar\.publishUpdate/ })).toBeInTheDocument()expect(hotkeyRegistrations.get('Mod+Shift+P')?.options).toEqual(expect.objectContaining({ enabled: true, ignoreInputs: false }),@@ -267,6 +326,9 @@ describe('AgentConfigurePublishBar', () => {agent_id: 'agent-1',}))})+ expect(screen.queryByRole('region', {+ name: /agentV2\.agentDetail\.configure\.publishImpact\.title/,+ })).not.toBeInTheDocument()})it('should publish the current draft payload from the unpublished changes state', async () => {@@ -299,7 +361,7 @@ describe('AgentConfigurePublishBar', () => {store.set(agentComposerOriginalDraftAtom, originalDraftWithFile)store.set(agentComposerDraftAtom, {...originalDraftWithFile,- files: [],+ tools: [],})},})@@ -335,63 +397,115 @@ describe('AgentConfigurePublishBar', () => {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.getByRole('button', { name: 'agentV2.agentDetail.configure.publishBar.publishing' })).toHaveAttribute('aria-busy', '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', async () => {+ it('should expand affected workflow details above the publish toolbar when clicking a publishable agent in use', async () => {const { onPublish } = renderPublishBar({activeConfigSnapshot,prompt: 'Updated system prompt',usedByAppReferences: publishedReferences,})- expect(screen.queryByTestId('publish-impact-popover')).not.toBeInTheDocument()- const publishBar = screen.getByText('agentV2.agentDetail.configure.publishBar.unpublishedChanges').closest('[aria-hidden]')- expect(publishBar).toHaveAttribute('aria-hidden', 'false')+ expect(screen.queryByRole('region', {+ name: /agentV2\.agentDetail\.configure\.publishImpact\.title/,+ })).not.toBeInTheDocument()+ await waitFor(() => {+ expect(workflowReferences.fetchCount).toBe(1)+ })- fireEvent.click(screen.getByRole('button', { name: /agentV2\.agentDetail\.configure\.publishBar\.publishUpdate/ }))+ const publishButton = screen.getByRole('button', { name: /agentV2\.agentDetail\.configure\.publishBar\.publishUpdate/ })+ fireEvent.click(publishButton)expect(onPublish).not.toHaveBeenCalled()- const impactPopover = await screen.findByTestId('publish-impact-popover')- expect(impactPopover).toBeInTheDocument()- expect(publishBar).toHaveAttribute('aria-hidden', 'false')- await waitFor(() => {- expect(publishBar).toHaveAttribute('aria-hidden', 'true')- expect(publishBar).toHaveClass('opacity-0')+ expect(publishButton).not.toHaveAttribute('aria-busy')+ const impactDetails = await screen.findByRole('region', {+ name: /agentV2\.agentDetail\.configure\.publishImpact\.title/,})+ expect(impactDetails).toBeInTheDocument()+ expect(workflowReferences.fetchCount).toBe(1)+ expect(screen.getAllByRole('button', { name: /agentV2\.agentDetail\.configure\.publishBar\.publishUpdate/ })).toHaveLength(1)+ expect(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.publishImpact.cancel' })).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.publishBar.versionHistory' })).toHaveClass('group-data-open/publish-bar:hidden')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')- expect(within(impactPopover).getByText('display:Mod')).toBeInTheDocument()- expect(within(impactPopover).getByText('display:Shift')).toBeInTheDocument()- expect(within(impactPopover).getByText('display:P')).toBeInTheDocument()+ expect(screen.getByRole('link', { name: /Python bug fixer/ })).toHaveAttribute('target', '_blank')+ expect(screen.getByRole('link', { name: /Python bug fixer/ })).toHaveAttribute('rel', 'noopener noreferrer')+ expect(within(impactDetails).getAllByText('just now')).toHaveLength(2)+ expect(screen.getByText('display:Mod')).toBeInTheDocument()+ expect(screen.getByText('display:Shift')).toBeInTheDocument()+ expect(screen.getByText('display:P')).toBeInTheDocument()})- it('should publish from the affected workflow popover action', async () => {- const { onPublish } = renderPublishBar({+ it('should publish from the fixed toolbar action after affected workflow details expand', async () => {+ const publishDeferred = createDeferredPromise()+ const onPublish = vi.fn<PublishHandler>(() => publishDeferred.promise)+ const { rerender, rerenderPublishBar } = renderPublishBar({activeConfigSnapshot,+ onPublish,prompt: 'Updated system prompt',usedByAppReferences: publishedReferences,})fireEvent.click(screen.getByRole('button', { name: /agentV2\.agentDetail\.configure\.publishBar\.publishUpdate/ }))- fireEvent.click(within(await screen.findByTestId('publish-impact-popover')).getByRole('button', {- name: /agentV2\.agentDetail\.configure\.publishBar\.publishUpdate/,- }))+ expect(await screen.findByRole('region', {+ name: /agentV2\.agentDetail\.configure\.publishImpact\.title/,+ })).toBeInTheDocument()+ fireEvent.click(screen.getByRole('button', { name: /agentV2\.agentDetail\.configure\.publishBar\.publishUpdate/ }))expect(onPublish).toHaveBeenCalledWith(expect.objectContaining({agent_id: 'agent-1',}))+ expect(screen.getByRole('region', {+ name: /agentV2\.agentDetail\.configure\.publishImpact\.title/,+ })).toBeInTheDocument()+ rerender(rerenderPublishBar({ isPublishing: true }))+ expect(await screen.findByRole('button', {+ name: 'agentV2.agentDetail.configure.publishBar.publishing',+ })).toHaveAttribute('aria-busy', 'true')++ await act(async () => {+ publishDeferred.resolve()+ await publishDeferred.promise+ })++ await waitFor(() => {+ expect(screen.queryByRole('region', {+ name: /agentV2\.agentDetail\.configure\.publishImpact\.title/,+ })).not.toBeInTheDocument()+ })+ })++ it('should collapse affected workflow details from the expanded footer cancel action', async () => {+ const { onPublish } = renderPublishBar({+ activeConfigSnapshot,+ prompt: 'Updated system prompt',+ usedByAppReferences: publishedReferences,+ })++ fireEvent.click(screen.getByRole('button', { name: /agentV2\.agentDetail\.configure\.publishBar\.publishUpdate/ }))+ expect(await screen.findByRole('region', {+ name: /agentV2\.agentDetail\.configure\.publishImpact\.title/,+ })).toBeInTheDocument()++ fireEvent.click(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.publishImpact.cancel' }))++ await waitFor(() => {+ expect(screen.queryByRole('region', {+ name: /agentV2\.agentDetail\.configure\.publishImpact\.title/,+ })).not.toBeInTheDocument()+ })+ expect(onPublish).not.toHaveBeenCalled()})- it('should open the affected workflow popover from the publish shortcut before publishing', async () => {+ it('should show affected workflow details from the publish shortcut before publishing', async () => {const { onPublish } = renderPublishBar({activeConfigSnapshot,prompt: 'Updated system prompt',@@ -404,7 +518,9 @@ describe('AgentConfigurePublishBar', () => {})expect(onPublish).not.toHaveBeenCalled()- expect(await screen.findByTestId('publish-impact-popover')).toBeInTheDocument()+ expect(await screen.findByRole('region', {+ name: /agentV2\.agentDetail\.configure\.publishImpact\.title/,+ })).toBeInTheDocument()await act(async () => {await hotkeyRegistrations.get('Mod+Shift+P')?.callback({ preventDefault: vi.fn() })@@ -414,4 +530,23 @@ describe('AgentConfigurePublishBar', () => {agent_id: 'agent-1',}))})++ it('should publish directly from the publish shortcut when no workflows reference the agent', async () => {+ const { onPublish } = renderPublishBar({+ activeConfigSnapshot,+ prompt: 'Updated system prompt',+ })+ const publishShortcut = hotkeyRegistrations.get('Mod+Shift+P')++ await act(async () => {+ await publishShortcut?.callback({ preventDefault: vi.fn() })+ })++ expect(screen.queryByRole('region', {+ name: /agentV2\.agentDetail\.configure\.publishImpact\.title/,+ })).not.toBeInTheDocument()+ expect(onPublish).toHaveBeenCalledWith(expect.objectContaining({+ agent_id: 'agent-1',+ }))+ })})diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/advanced/__tests__/index.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/advanced/__tests__/index.spec.tsxnew file mode 100644index 00000000000..c7b423ecf59--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/advanced/__tests__/index.spec.tsx@@ -0,0 +1,28 @@+import { fireEvent, render, screen } from '@testing-library/react'+import { AgentAdvancedSettings } from '../index'++vi.mock('../env', () => ({+ AgentEnvEditor: () => <div>advanced-env-editor</div>,+}))++vi.mock('../content-moderation', () => ({+ AgentContentModerationSettings: () => <div>advanced-content-moderation</div>,+}))++describe('AgentAdvancedSettings', () => {+ it('should render collapsed by default and expand from the section trigger', () => {+ render(<AgentAdvancedSettings />)++ const label = 'agentV2.agentDetail.configure.advancedSettings.label'+ const triggers = screen.getAllByRole('button', { name: label })++ expect(triggers[0]).not.toHaveAttribute('data-panel-open')+ expect(screen.queryByText('advanced-env-editor')).not.toBeInTheDocument()+ expect(screen.queryByText('advanced-content-moderation')).not.toBeInTheDocument()++ fireEvent.click(triggers[0]!)++ expect(screen.getByText('advanced-env-editor')).toBeInTheDocument()+ expect(screen.getByText('advanced-content-moderation')).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.tsxindex 532627f25dd..7a5578fbff1 100644--- 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.tsx@@ -14,6 +14,7 @@ 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'+import { useAgentOrchestrateReadOnly } from '../read-only-context'const defaultModerationConfig: ModerationConfig = {enabled: true,@@ -30,6 +31,7 @@ function AgentContentModerationSettingsContent() {const { t } = useTranslation()const locale = useLocale()const featuresStore = useFeaturesStore()+ const readOnly = useAgentOrchestrateReadOnly()const setAppFeatures = useSetAppFeatures()const { setShowModerationSettingModal } = useModalContext()const moderation = useFeatures(state => state.features.moderation)@@ -112,25 +114,27 @@ function AgentContentModerationSettingsContent() {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>- )}+ actions={!readOnly+ ? (+ <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>+ )+ : undefined}>{moderation?.enabled? (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.tsxindex 92b8950fdce..7c1aa1ce52d 100644--- 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.tsx@@ -15,6 +15,7 @@ export function AgentAdvancedSettings() {labelId="agent-configure-advanced-settings-label"panelId={advancedSettingsPanelId}description={t('agentDetail.configure.advancedSettings.description')}+ defaultOpen={false}rootClassName="gap-2 pt-1 pb-3"headerClassName="mb-0 pt-2"titleRowClassName="min-h-6"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.tsxindex 337d7be8e32..5eb42972cec 100644--- 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.tsx@@ -32,7 +32,7 @@ export function ConfigureSectionConfigurableItem({</span></div>{!readOnly && (- <div className="pointer-events-none flex shrink-0 items-center gap-1 opacity-0 transition-opacity group-focus-within:pointer-events-auto group-focus-within:opacity-100 group-hover:pointer-events-auto group-hover:opacity-100">+ <div className="hidden shrink-0 items-center gap-1 group-focus-within:flex group-hover:flex"><buttontype="button"aria-label={editAriaLabel}@@ -52,7 +52,7 @@ export function ConfigureSectionConfigurableItem({</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 transition-opacity group-focus-within:opacity-0 group-hover:opacity-0">+ <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>)}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.tsxindex 49b43817d82..22ab3e0946c 100644--- 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.tsx@@ -15,6 +15,7 @@ type ConfigureSectionBaseProps = {children: ReactNodeactions?: ReactNodedescription?: ReactNode+ defaultOpen?: booleanheadingLevel?: 'h3' | 'h4'panelId?: stringrootClassName?: string@@ -40,6 +41,7 @@ export function ConfigureSection({children,actions,description,+ defaultOpen = true,headingLevel = 'h3',panelId,tip,@@ -56,7 +58,7 @@ export function ConfigureSection({return (<CollapsibleRootrender={<section />}- defaultOpen+ defaultOpen={defaultOpen}className={rootClassName}aria-labelledby={labelId}>diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/drive-context.ts b/web/features/agent-v2/agent-detail/configure/components/orchestrate/drive-context.tsnew file mode 100644index 00000000000..d94a0632471--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/drive-context.ts@@ -0,0 +1,146 @@+'use client'++import type { AgentDriveItemResponse } from '@dify/contracts/api/console/agent/types.gen'+import type { AgentFileNode, AgentSkill } from '@/features/agent-v2/agent-composer/form-state'+import { useQuery } from '@tanstack/react-query'+import { createContext, use, useMemo } from 'react'+import { consoleQuery } from '@/service/client'+import { getDriveFileIconType } from './files/file-icon'++export type AgentDriveApiContext = {+ agentId: string+ workflow?: {+ appId: string+ nodeId: string+ }+}++export const FILES_DRIVE_PREFIX = 'files/'++const AgentDriveApiContext = createContext<AgentDriveApiContext | null>(null)++export const AgentDriveApiContextProvider = AgentDriveApiContext.Provider++const getAgentDriveFileName = (key: string) => {+ const normalizedKey = key.endsWith('/') ? key.slice(0, -1) : key+ return normalizedKey.split('/').pop() || normalizedKey+}++const toAgentSkill = (item: {+ archive_key?: string | null+ description: string+ name: string+ path: string+ skill_md_key: string+}): AgentSkill => ({+ id: item.skill_md_key,+ name: item.name,+ description: item.description || undefined,+ path: item.path,+ skillMdKey: item.skill_md_key,+ archiveKey: item.archive_key ?? undefined,+})++const toAgentFileNodeFromDriveItem = (item: {+ file_kind: string+ key: string+ mime_type?: string | null+}): AgentFileNode => ({+ id: item.key,+ name: getAgentDriveFileName(item.key),+ icon: getDriveFileIconType({+ fileKind: item.file_kind,+ fileName: getAgentDriveFileName(item.key),+ mimeType: item.mime_type,+ }),+ driveKey: item.key,+})++export const useAgentDriveApiContext = () => {+ const context = use(AgentDriveApiContext)+ if (!context)+ throw new Error('AgentDriveApiContextProvider is required for drive-backed UI.')++ return context+}++export const useAgentDriveSkills = () => {+ const apiContext = useAgentDriveApiContext()+ const agentSkillsQuery = useQuery({+ ...consoleQuery.agent.byAgentId.drive.skills.get.queryOptions({+ input: {+ params: {+ agent_id: apiContext.agentId,+ },+ },+ }),+ enabled: !apiContext.workflow,+ })+ const workflowSkillsQuery = useQuery({+ ...consoleQuery.apps.byAppId.agent.drive.skills.get.queryOptions({+ input: {+ params: {+ app_id: apiContext.workflow?.appId ?? '',+ },+ query: {+ node_id: apiContext.workflow?.nodeId,+ },+ },+ }),+ enabled: !!apiContext.workflow,+ })+ const query = apiContext.workflow ? workflowSkillsQuery : agentSkillsQuery+ const skills = useMemo(() => (query.data?.items ?? []).map(toAgentSkill), [query.data?.items])++ return {+ apiContext,+ query,+ skills,+ }+}++export const useAgentDriveFiles = ({+ prefix = FILES_DRIVE_PREFIX,+}: {+ prefix?: string+} = {}) => {+ const apiContext = useAgentDriveApiContext()+ const agentFilesQuery = useQuery({+ ...consoleQuery.agent.byAgentId.drive.files.get.queryOptions({+ input: {+ params: {+ agent_id: apiContext.agentId,+ },+ query: {+ prefix,+ },+ },+ }),+ enabled: !apiContext.workflow,+ })+ const workflowFilesQuery = useQuery({+ ...consoleQuery.apps.byAppId.agent.drive.files.get.queryOptions({+ input: {+ params: {+ app_id: apiContext.workflow?.appId ?? '',+ },+ query: {+ node_id: apiContext.workflow?.nodeId,+ prefix,+ },+ },+ }),+ enabled: !!apiContext.workflow,+ })+ const query = apiContext.workflow ? workflowFilesQuery : agentFilesQuery+ const files = useMemo(+ () => (query.data?.items ?? []).map((item: AgentDriveItemResponse) => toAgentFileNodeFromDriveItem(item)),+ [query.data?.items],+ )++ return {+ apiContext,+ query,+ files,+ }+}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.tsxindex 9961ba7d242..b8728fe9572 100644--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/__tests__/index.spec.tsx+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/__tests__/index.spec.tsx@@ -4,6 +4,7 @@ import { fireEvent, render, screen, waitFor, within } from '@testing-library/reaimport { 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 { AgentDriveApiContextProvider } from '../../drive-context'import { AgentOrchestrateReadOnlyContext } from '../../read-only-context'import { AgentFiles } from '../index'@@ -100,38 +101,10 @@ vi.mock('@/service/client', () => ({const agentFilesDraft = {...defaultAgentSoulConfigFormState,- files: [- {- id: 'preview-image',- name: 'agent-roster-skill-detail-dialog-preview-image.png',- icon: 'image',- driveKey: 'files/agent-roster-skill-detail-dialog-preview-image.png',- },- {- id: 'brief',- name: 'brief.md',- icon: 'markdown',- driveKey: 'files/brief.md',- },- ],} satisfies AgentSoulConfigFormStateconst agentSkillFilesDraft = {...defaultAgentSoulConfigFormState,- files: [- {- id: 'script',- name: 'run.py',- icon: 'file',- driveKey: 'files/run.py',- },- {- id: 'skill-md',- name: 'SKILL.md',- icon: 'markdown',- driveKey: 'files/SKILL.md',- },- ],} satisfies AgentSoulConfigFormStatefunction renderAgentFiles(initialDraft: AgentSoulConfigFormState = agentFilesDraft) {@@ -145,9 +118,11 @@ function renderAgentFiles(initialDraft: AgentSoulConfigFormState = agentFilesDrareturn render(<QueryClientProvider client={queryClient}>- <AgentComposerProvider initialDraft={initialDraft}>- <AgentFiles agentId="agent-1" />- </AgentComposerProvider>+ <AgentDriveApiContextProvider value={{ agentId: 'agent-1' }}>+ <AgentComposerProvider initialDraft={initialDraft}>+ <AgentFiles />+ </AgentComposerProvider>+ </AgentDriveApiContextProvider></QueryClientProvider>,)}@@ -163,11 +138,33 @@ function renderReadonlyAgentFiles() {return render(<QueryClientProvider client={queryClient}>- <AgentComposerProvider initialDraft={agentFilesDraft}>- <AgentOrchestrateReadOnlyContext value>- <AgentFiles agentId="agent-1" />- </AgentOrchestrateReadOnlyContext>- </AgentComposerProvider>+ <AgentDriveApiContextProvider value={{ agentId: 'agent-1' }}>+ <AgentComposerProvider initialDraft={agentFilesDraft}>+ <AgentOrchestrateReadOnlyContext value>+ <AgentFiles />+ </AgentOrchestrateReadOnlyContext>+ </AgentComposerProvider>+ </AgentDriveApiContextProvider>+ </QueryClientProvider>,+ )+}++function renderWorkflowAgentFiles(initialDraft: AgentSoulConfigFormState = agentFilesDraft) {+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: {+ retry: false,+ },+ },+ })++ return render(+ <QueryClientProvider client={queryClient}>+ <AgentDriveApiContextProvider value={{ agentId: 'agent-1', workflow: { appId: 'app-1', nodeId: 'node-1' } }}>+ <AgentComposerProvider initialDraft={initialDraft}>+ <AgentFiles />+ </AgentComposerProvider>+ </AgentDriveApiContextProvider></QueryClientProvider>,)}@@ -175,13 +172,31 @@ function renderReadonlyAgentFiles() {describe('AgentFiles', () => {beforeEach(() => {vi.clearAllMocks()+ const baseItems = [+ {+ file_kind: 'file',+ key: 'files/agent-roster-skill-detail-dialog-preview-image.png',+ mime_type: 'image/png',+ },+ {+ file_kind: 'file',+ key: 'files/brief.md',+ mime_type: 'text/markdown',+ },+ ]mocks.agentDriveFilesQueryOptions.mockImplementation(({ input }) => ({queryKey: ['agent-drive-files', input],- queryFn: () => new Promise(() => {}),+ initialData: { items: baseItems },+ queryFn: async () => ({+ items: baseItems,+ }),}))mocks.workflowAgentDriveFilesQueryOptions.mockImplementation(({ input }) => ({queryKey: ['workflow-agent-drive-files', input],- queryFn: () => new Promise(() => {}),+ initialData: { items: baseItems },+ queryFn: async () => ({+ items: baseItems,+ }),}))mocks.agentFilePreviewQueryOptions.mockImplementation(({ input }) => ({queryKey: ['agent-file-preview', input],@@ -264,6 +279,22 @@ describe('AgentFiles', () => {})})+ it('should list workflow-node drive files under the files prefix', () => {+ renderWorkflowAgentFiles()++ expect(mocks.workflowAgentDriveFilesQueryOptions).toHaveBeenCalledWith({+ input: {+ params: {+ app_id: 'app-1',+ },+ query: {+ node_id: 'node-1',+ prefix: 'files/',+ },+ },+ })+ })+it('should keep the file preview trigger focus ring inside the row bounds', () => {renderAgentFiles()@@ -300,6 +331,21 @@ describe('AgentFiles', () => {})it('should preview the clicked file when SKILL.md also exists', async () => {+ mocks.agentDriveFilesQueryOptions.mockImplementation(({ input }) => ({+ queryKey: ['agent-drive-files', input],+ initialData: {+ items: [+ { file_kind: 'file', key: 'files/run.py', mime_type: 'text/x-python' },+ { file_kind: 'file', key: 'files/SKILL.md', mime_type: 'text/markdown' },+ ],+ },+ queryFn: async () => ({+ items: [+ { file_kind: 'file', key: 'files/run.py', mime_type: 'text/x-python' },+ { file_kind: 'file', key: 'files/SKILL.md', mime_type: 'text/markdown' },+ ],+ }),+ }))renderAgentFiles(agentSkillFilesDraft)fireEvent.click(screen.getByRole('button', {@@ -322,6 +368,21 @@ describe('AgentFiles', () => {})it('should preview the selected file from the detail file tree', async () => {+ mocks.agentDriveFilesQueryOptions.mockImplementation(({ input }) => ({+ queryKey: ['agent-drive-files', input],+ initialData: {+ items: [+ { file_kind: 'file', key: 'files/run.py', mime_type: 'text/x-python' },+ { file_kind: 'file', key: 'files/SKILL.md', mime_type: 'text/markdown' },+ ],+ },+ queryFn: async () => ({+ items: [+ { file_kind: 'file', key: 'files/run.py', mime_type: 'text/x-python' },+ { file_kind: 'file', key: 'files/SKILL.md', mime_type: 'text/markdown' },+ ],+ }),+ }))renderAgentFiles(agentSkillFilesDraft)fireEvent.click(screen.getByRole('button', {@@ -368,13 +429,7 @@ describe('AgentFiles', () => {name: 'agent-roster-skill-detail-dialog-preview-image.png',}))- const image = await screen.findByRole('img', {- name: 'agent-roster-skill-detail-dialog-preview-image.png',- })-- expect(image).toHaveAttribute('src', 'https://signed.example/files/agent-roster-skill-detail-dialog-preview-image.png')- expect(screen.queryByRole('link', { name: /common\.operation\.download/ })).not.toBeInTheDocument()- expect(screen.queryByText('image preview should not render as text')).not.toBeInTheDocument()+ expect(screen.getByRole('dialog')).toBeInTheDocument()expect(mocks.agentFileDownloadQueryOptions).toHaveBeenCalledWith({input: {params: {@@ -411,10 +466,89 @@ describe('AgentFiles', () => {expect(screen.queryByText('Preview content for files/brief.md')).not.toBeInTheDocument()})+ it('should use workflow preview and download routes when workflow context is active', async () => {+ mocks.workflowAgentFilePreviewQueryOptions.mockImplementation(({ input }) => ({+ queryKey: ['workflow-agent-file-preview', input],+ queryFn: async () => ({+ binary: true,+ key: input.query.key,+ size: 12345,+ text: null,+ truncated: false,+ }),+ }))+ renderWorkflowAgentFiles()++ fireEvent.click(screen.getByRole('button', {+ name: 'brief.md',+ }))++ expect(mocks.workflowAgentFilePreviewQueryOptions).toHaveBeenCalledWith({+ input: {+ params: {+ app_id: 'app-1',+ },+ query: {+ node_id: 'node-1',+ key: 'files/brief.md',+ },+ },+ })+ expect(mocks.workflowAgentFileDownloadQueryOptions).toHaveBeenCalledWith({+ input: {+ params: {+ app_id: 'app-1',+ },+ query: {+ node_id: 'node-1',+ key: 'files/brief.md',+ },+ },+ })+ expect(await screen.findByRole('link', { name: 'common.operation.download' })).toHaveAttribute(+ 'href',+ 'https://signed.example/files/brief.md',+ )+ })+it('should commit an uploaded file to the Agent App drive before adding it to the composer draft', async () => {+ const driveFiles = [+ {+ file_kind: 'file',+ key: 'files/agent-roster-skill-detail-dialog-preview-image.png',+ mime_type: 'image/png',+ },+ {+ file_kind: 'file',+ key: 'files/brief.md',+ mime_type: 'text/markdown',+ },+ ]+ mocks.agentDriveFilesQueryOptions.mockImplementation(({ input }) => ({+ queryKey: ['agent-drive-files', input],+ initialData: { items: [...driveFiles] },+ queryFn: async () => ({ items: [...driveFiles] }),+ }))+ mocks.agentFileCommitMutationOptions.mockReturnValue({+ mutationFn: mocks.agentFileCommitMutationFn.mockImplementation(async () => {+ driveFiles.push({+ file_kind: 'file',+ key: 'files/uploaded.md',+ mime_type: 'text/markdown',+ })+ return {+ file: {+ drive_key: 'files/uploaded.md',+ file_id: 'drive-file-1',+ mime_type: 'text/markdown',+ name: 'uploaded.md',+ },+ }+ }),+ mutationKey: ['commit-agent-file'],+ })renderAgentFiles({...defaultAgentSoulConfigFormState,- files: [],})fireEvent.click(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.files.add' }))@@ -441,31 +575,188 @@ describe('AgentFiles', () => {expect.anything(),)})+ expect(await screen.findByRole('button', { name: 'uploaded.md' })).toBeInTheDocument()+ })++ it('should commit an uploaded file through workflow-node drive endpoints and refresh the list', async () => {+ const driveFiles = [+ {+ file_kind: 'file',+ key: 'files/agent-roster-skill-detail-dialog-preview-image.png',+ mime_type: 'image/png',+ },+ {+ file_kind: 'file',+ key: 'files/brief.md',+ mime_type: 'text/markdown',+ },+ ]+ mocks.workflowAgentDriveFilesQueryOptions.mockImplementation(({ input }) => ({+ queryKey: ['workflow-agent-drive-files', input],+ initialData: { items: [...driveFiles] },+ queryFn: async () => ({ items: [...driveFiles] }),+ }))+ mocks.workflowAgentFileCommitMutationOptions.mockReturnValue({+ mutationFn: mocks.workflowAgentFileCommitMutationFn.mockImplementation(async () => {+ driveFiles.push({+ file_kind: 'file',+ key: 'files/uploaded.md',+ mime_type: 'text/markdown',+ })+ return {+ file: {+ drive_key: 'files/uploaded.md',+ file_id: 'drive-file-1',+ mime_type: 'text/markdown',+ name: 'uploaded.md',+ },+ }+ }),+ mutationKey: ['commit-workflow-agent-file'],+ })+ renderWorkflowAgentFiles({+ ...defaultAgentSoulConfigFormState,+ })++ fireEvent.click(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.files.add' }))+ const input = document.querySelector('input[type="file"]')+ expect(input).toBeInstanceOf(HTMLInputElement)++ fireEvent.change(input!, {+ target: {+ files: [new File(['# Uploaded'], 'uploaded.md', { type: 'text/markdown' })],+ },+ })+ fireEvent.click(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.files.upload.action' }))++ await waitFor(() => {+ expect(mocks.workflowAgentFileCommitMutationFn).toHaveBeenCalledWith(+ {+ params: {+ app_id: 'app-1',+ },+ query: {+ node_id: 'node-1',+ },+ body: {+ upload_file_id: 'upload-file-1',+ },+ },+ expect.anything(),+ )+ })+ expect(await screen.findByRole('button', { name: 'uploaded.md' })).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', () => {+ it('should delete the file when the remove action is clicked', async () => {+ const driveFiles = [+ {+ file_kind: 'file',+ key: 'files/agent-roster-skill-detail-dialog-preview-image.png',+ mime_type: 'image/png',+ },+ {+ file_kind: 'file',+ key: 'files/brief.md',+ mime_type: 'text/markdown',+ },+ ]+ mocks.agentDriveFilesQueryOptions.mockImplementation(({ input }) => ({+ queryKey: ['agent-drive-files', input],+ initialData: { items: [...driveFiles] },+ queryFn: async () => ({ items: [...driveFiles] }),+ }))+ mocks.agentFileDeleteMutationOptions.mockReturnValue({+ mutationFn: mocks.agentFileDeleteMutationFn.mockImplementation(async () => {+ driveFiles.splice(0, 1)+ return { result: 'success' }+ }),+ mutationKey: ['delete-agent-file'],+ })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()+ await waitFor(() => {+ expect(mocks.agentFileDeleteMutationFn).toHaveBeenCalledWith(+ {+ params: {+ agent_id: 'agent-1',+ },+ query: {+ key: 'files/agent-roster-skill-detail-dialog-preview-image.png',+ },+ },+ expect.anything(),+ )+ })+ await waitFor(() => {+ expect(screen.queryByRole('button', { name: 'agent-roster-skill-detail-dialog-preview-image.png' })).not.toBeInTheDocument()+ })+ expect(screen.getByRole('button', { name: 'brief.md' })).toBeInTheDocument()})- it('should render the empty state after removing every file', () => {- renderAgentFiles()+ it('should delete a workflow-node file through workflow endpoints and refresh the list', async () => {+ const driveFiles = [+ {+ file_kind: 'file',+ key: 'files/agent-roster-skill-detail-dialog-preview-image.png',+ mime_type: 'image/png',+ },+ {+ file_kind: 'file',+ key: 'files/brief.md',+ mime_type: 'text/markdown',+ },+ ]+ mocks.workflowAgentDriveFilesQueryOptions.mockImplementation(({ input }) => ({+ queryKey: ['workflow-agent-drive-files', input],+ initialData: { items: [...driveFiles] },+ queryFn: async () => ({ items: [...driveFiles] }),+ }))+ mocks.workflowAgentFileDeleteMutationOptions.mockReturnValue({+ mutationFn: mocks.workflowAgentFileDeleteMutationFn.mockImplementation(async () => {+ driveFiles.splice(0, 1)+ return { result: 'success' }+ }),+ mutationKey: ['delete-workflow-agent-file'],+ })+ renderWorkflowAgentFiles()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/,++ await waitFor(() => {+ expect(mocks.workflowAgentFileDeleteMutationFn).toHaveBeenCalledWith(+ {+ params: {+ app_id: 'app-1',+ },+ query: {+ node_id: 'node-1',+ key: 'files/agent-roster-skill-detail-dialog-preview-image.png',+ },+ },+ expect.anything(),+ )+ })+ await waitFor(() => {+ expect(screen.queryByRole('button', { name: 'agent-roster-skill-detail-dialog-preview-image.png' })).not.toBeInTheDocument()+ })+ expect(screen.getByRole('button', { name: 'brief.md' })).toBeInTheDocument()+ })++ it('should render the empty state when the drive file query returns no items', () => {+ mocks.agentDriveFilesQueryOptions.mockImplementation(({ input }) => ({+ queryKey: ['agent-drive-files', input],+ initialData: { items: [] },+ queryFn: async () => ({ items: [] }),}))+ renderAgentFiles()expect(screen.getByText('agentV2.agentDetail.configure.files.empty.title')).toBeInTheDocument()})diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/api-context.ts b/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/api-context.tsdeleted file mode 100644index 886dd16841e..00000000000--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/api-context.ts+++ /dev/null@@ -1,7 +0,0 @@-export type AgentFileApiContext = {- agentId: string- workflow?: {- appId: string- nodeId: string- }-}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.tsxindex 4d61b51f9ec..da8ff756469 100644--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/index.tsx+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/index.tsx@@ -2,7 +2,7 @@import type { ReactNode } from 'react'import type { AgentOrchestrateAddActionOptions } from '../add-actions-context'-import type { AgentFileApiContext } from './api-context'+import type { AgentDriveApiContext } from '../drive-context'import type { AgentFileNode } from '@/features/agent-v2/agent-composer/form-state'import {Dialog,@@ -12,30 +12,19 @@ import {FileTreeGuide,} from '@langgenius/dify-ui/file-tree'import { useMutation, useQuery } from '@tanstack/react-query'-import { useAtom } from 'jotai'-import { useCallback, useMemo, useRef, useState } from 'react'+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 { FILES_DRIVE_PREFIX, useAgentDriveApiContext, useAgentDriveFiles } from '../drive-context'import { useAgentOrchestrateReadOnly } from '../read-only-context'import { AgentSkillDetailDialog } from '../skills/detail-dialog'-import { getDriveFileIconType } from './file-icon'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,- }))--const FILES_DRIVE_PREFIX = 'files/'-const getAgentFilePreviewKey = (file: AgentFileNode) => file.driveKey ?? file.idconst findAgentFileNode = (files: AgentFileNode[], fileId: string): AgentFileNode | undefined => {@@ -49,26 +38,6 @@ const findAgentFileNode = (files: AgentFileNode[], fileId: string): AgentFileNod}}-const getAgentDriveFileName = (key: string) => {- const normalizedKey = key.endsWith('/') ? key.slice(0, -1) : key- return normalizedKey.split('/').pop() || normalizedKey-}--const toAgentFileNodeFromDriveItem = (item: {- file_kind: string- key: string- mime_type?: string | null-}): AgentFileNode => ({- id: item.key,- name: getAgentDriveFileName(item.key),- icon: getDriveFileIconType({- fileKind: item.file_kind,- fileName: getAgentDriveFileName(item.key),- mimeType: item.mime_type,- }),- driveKey: item.key,-})-function AgentFileItem({children,depth,@@ -82,7 +51,7 @@ function AgentFileItem({depth: numberfile: AgentFileNodefiles: AgentFileNode[]- apiContext: AgentFileApiContext+ apiContext: AgentDriveApiContextonRemove: (fileId: string) => voidselected: boolean}) {@@ -217,68 +186,20 @@ function AgentFileItem({)}-export function AgentFiles({- agentId,- appId,- nodeId,-}: {- agentId: string- appId?: string- nodeId?: string-}) {+export function AgentFiles() {const { t } = useTranslation('agentV2')- const [draftFiles, setDraftFiles] = 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 apiContext: AgentFileApiContext = useMemo(() => appId && nodeId- ? {- agentId,- workflow: {- appId,- nodeId,- },- }- : { agentId }, [agentId, appId, nodeId])- const agentDriveFilesQuery = useQuery({- ...consoleQuery.agent.byAgentId.drive.files.get.queryOptions({- input: {- params: {- agent_id: agentId,- },- query: {- prefix: FILES_DRIVE_PREFIX,- },- },- }),- enabled: !apiContext.workflow,- })- const workflowDriveFilesQuery = useQuery({- ...consoleQuery.apps.byAppId.agent.drive.files.get.queryOptions({- input: {- params: {- app_id: appId ?? '',- },- query: {- node_id: nodeId,- prefix: FILES_DRIVE_PREFIX,- },- },- }),- enabled: !!apiContext.workflow,- })- const driveFilesQuery = apiContext.workflow ? workflowDriveFilesQuery : agentDriveFilesQuery+ const apiContext = useAgentDriveApiContext()+ const { query: driveFilesQuery, files } = useAgentDriveFiles({ prefix: FILES_DRIVE_PREFIX })const { mutate: deleteAgentFile } = useMutation(consoleQuery.agent.byAgentId.files.delete.mutationOptions())const { mutate: deleteWorkflowAgentFile } = useMutation(consoleQuery.apps.byAppId.agent.files.delete.mutationOptions())- const files = driveFilesQuery.isSuccess- ? (driveFilesQuery.data.items ?? []).map(toAgentFileNodeFromDriveItem)- : draftFilesconst removeFile = useCallback((fileId: string) => {const file = findAgentFileNode(files, fileId)const driveKey = file?.driveKey- setDraftFiles(removeFileNode(draftFiles, fileId))if (!driveKey)return@@ -306,18 +227,17 @@ export function AgentFiles({key: driveKey,},}, { onSuccess })- }, [apiContext, deleteAgentFile, deleteWorkflowAgentFile, draftFiles, driveFilesQuery, files, setDraftFiles])+ }, [apiContext, deleteAgentFile, deleteWorkflowAgentFile, driveFilesQuery, files])const handleOpenUpload = useCallback((options?: AgentOrchestrateAddActionOptions) => {promptAddCallbackRef.current = options?.onAddedsetIsUploadOpen(true)}, [])useRegisterAgentOrchestrateAddAction('files', handleOpenUpload)const handleUploaded = useCallback((file: AgentFileNode) => {- setDraftFiles([...draftFiles, file])void driveFilesQuery.refetch()promptAddCallbackRef.current?.(file)promptAddCallbackRef.current = undefined- }, [draftFiles, driveFilesQuery, setDraftFiles])+ }, [driveFilesQuery])const handleUploadOpenChange = useCallback((open: boolean) => {if (!open)promptAddCallbackRef.current = undefineddiff --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.tsxindex ac25c742af9..3abb5fdabba 100644--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/upload-dialog.tsx+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/upload-dialog.tsx@@ -1,7 +1,7 @@'use client'import type { FileResponse } from '@dify/contracts/api/console/files/types.gen'-import type { AgentFileApiContext } from './api-context'+import type { AgentDriveApiContext } from '../drive-context'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'@@ -137,7 +137,7 @@ export function AgentFileUploadDialog({onOpenChange,onUploaded,}: {- apiContext: AgentFileApiContext+ apiContext: AgentDriveApiContextopen: booleanonOpenChange: (open: boolean) => voidonUploaded: (file: AgentFileNode) => void@@ -220,8 +220,8 @@ export function AgentFileUploadDialog({}return (- <Dialog open={open} onOpenChange={handleOpenChange}>- <DialogContent>+ <Dialog open={open} onOpenChange={handleOpenChange} disablePointerDismissal>+ <DialogContent backdropProps={{ forceRender: true }} backdropClassName="fixed"><DialogCloseButton /><DialogTitle className="title-2xl-semi-bold text-text-primary">{t('agentDetail.configure.files.upload.title')}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.tsxindex 81c2653657a..cddbec00d68 100644--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/index.tsx+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/index.tsx@@ -5,9 +5,11 @@ 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 { useMemo } from 'react'import { useTranslation } from 'react-i18next'import { AgentOrchestrateAddActionsProvider } from './add-actions'import { AgentAdvancedSettings } from './advanced'+import { AgentDriveApiContextProvider } from './drive-context'import { AgentFiles } from './files'import { AgentOrchestrateHeader } from './header'import { AgentKnowledgeRetrieval } from './knowledge'@@ -21,6 +23,7 @@ import { AgentTools } from './tools'type AgentOrchestratePanelProps = {agentId: stringappId?: string+ nodeId?: stringactiveConfigIsPublished?: booleanactiveConfigSnapshot?: AgentConfigSnapshotSummaryResponse | nullagentSoulConfig?: AgentConfigSnapshotDetailResponse['config_snapshot']@@ -31,16 +34,19 @@ type AgentOrchestratePanelProps = {isPublishing?: booleanclassName?: stringreadOnly?: boolean+ selectedVersionSnapshot?: AgentConfigSnapshotSummaryResponse | nullshowHeader?: booleanshowPublishBar?: booleanonSelectModel: (model: DefaultModel) => voidonPublish: (payload: AgentConfigurePublishPayload) => void | Promise<void>+ onExitVersions?: () => voidonOpenVersions: () => void}export function AgentOrchestratePanel({agentId,appId,+ nodeId,activeConfigIsPublished,activeConfigSnapshot,agentSoulConfig,@@ -51,18 +57,29 @@ export function AgentOrchestratePanel({isPublishing,className,readOnly = false,+ selectedVersionSnapshot,showHeader = true,showPublishBar = true,onSelectModel,onPublish,+ onExitVersions,onOpenVersions,}: AgentOrchestratePanelProps) {const { t } = useTranslation('agentV2')const orchestrateHeadingId = 'agent-configure-orchestrate-heading'const orchestrateLabel = t('agentDetail.configure.orchestrate')+ const driveApiContext = useMemo(() => appId && nodeId+ ? {+ agentId,+ workflow: {+ appId,+ nodeId,+ },+ }+ : { agentId }, [agentId, appId, nodeId])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)}>+ <div className={cn('relative 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}>@@ -76,25 +93,25 @@ export function AgentOrchestratePanel({labelledBy={showHeader ? orchestrateHeadingId : undefined}slotClassNames={{viewport: 'overscroll-contain',- content: 'min-h-full px-4 py-3',+ content: cn('min-h-full px-4 py-3', showPublishBar && 'pb-20'),+ scrollbar: showPublishBar ? 'z-20' : undefined,}}>- <AgentOrchestrateAddActionsProvider>- <AgentModelField- currentModel={currentModel}- textGenerationModelList={textGenerationModelList}- onSelect={onSelectModel}- />- <AgentPromptEditor />- <AgentSkills agentId={agentId} />- <AgentFiles- agentId={agentId}- appId={appId}- />- <AgentTools />- <AgentKnowledgeRetrieval />- <AgentAdvancedSettings />- </AgentOrchestrateAddActionsProvider>+ <AgentDriveApiContextProvider value={driveApiContext}>+ <AgentOrchestrateAddActionsProvider>+ <AgentModelField+ currentModel={currentModel}+ textGenerationModelList={textGenerationModelList}+ onSelect={onSelectModel}+ />+ <AgentPromptEditor />+ <AgentSkills />+ <AgentFiles />+ <AgentTools />+ <AgentKnowledgeRetrieval />+ <AgentAdvancedSettings />+ </AgentOrchestrateAddActionsProvider>+ </AgentDriveApiContextProvider></ScrollArea></div></AgentOrchestrateReadOnlyContext>@@ -109,7 +126,9 @@ export function AgentOrchestratePanel({currentModel={currentModel}draftSavedAt={draftSavedAt}isPublishing={isPublishing}+ selectedVersionSnapshot={selectedVersionSnapshot}onPublish={onPublish}+ onExitVersions={onExitVersions}onOpenVersions={onOpenVersions}/>)}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.tsxindex cce4132779a..8f3e683002e 100644--- 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.tsx@@ -78,7 +78,7 @@ describe('AgentKnowledgeRetrieval', () => {})).not.toBeInTheDocument()})- it('should keep row actions focusable while visually hidden until hover or focus', () => {+ it('should keep row actions out of layout until hover or focus', () => {renderKnowledgeRetrieval()const editButton = screen.getByRole('button', {@@ -89,12 +89,10 @@ describe('AgentKnowledgeRetrieval', () => {})const actionGroup = editButton.parentElement- expect(actionGroup).toHaveClass('flex')- expect(actionGroup).not.toHaveClass('hidden')+ expect(actionGroup).toHaveClass('hidden')expect(actionGroup).toHaveClass(- 'opacity-0',- 'group-focus-within:opacity-100',- 'group-hover:opacity-100',+ 'group-focus-within:flex',+ 'group-hover:flex',)expect(removeButton).toHaveClass('hover:bg-state-destructive-hover',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.tsxindex 8e0d8b66586..8ca5b8f5efb 100644--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/index.tsx+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/index.tsx@@ -16,14 +16,13 @@ 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 { useAgentDriveFiles, useAgentDriveSkills } from '../drive-context'import { useAgentOrchestrateReadOnly } from '../read-only-context'import { replaceTrailingSlashWithToken } from './options'import { AgentPromptSlashMenu } from './slash'@@ -151,8 +150,8 @@ export function AgentPromptEditor() {const { t } = useTranslation('agentV2')const readOnly = useAgentOrchestrateReadOnly()const [value, setValue] = useAtom(agentComposerPromptAtom)- const skills = useAtomValue(agentComposerSkillsAtom)- const files = useAtomValue(agentComposerFilesAtom)+ const { skills } = useAgentDriveSkills()+ const { files } = useAgentDriveFiles()const [tools, setTools] = useAtom(agentComposerToolsAtom)const retrievals = useAtomValue(agentComposerKnowledgeRetrievalsAtom)const addActions = useAgentOrchestrateAddActions()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.tsxindex 449ae6f7288..9aee10696ef 100644--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/slash.tsx+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/slash.tsx@@ -53,6 +53,10 @@ const createReferenceToken = (kind: string, id: string, label?: string) => (`[§${kind}:${id}${label ? `:${label}` : ''}§]`)+const createDriveReferenceToken = (kind: 'skill' | 'file', driveKey: string, label: string) => (+ createReferenceToken(kind, encodeURIComponent(driveKey), label)+)+const isPromptReferenceItem = (item: AgentOrchestrateAddedItem): item is AgentFileNode | AgentSkill => ('id' in item && 'name' in item)@@ -87,8 +91,8 @@ export function AgentPromptSlashMenu({if (view === 'skills') {onAddSkill?.({onAdded: (item) => {- if (isPromptReferenceItem(item))- onSelect(createReferenceToken('skill', item.id, item.name))+ if (isPromptReferenceItem(item) && 'skillMdKey' in item && typeof item.skillMdKey === 'string')+ onSelect(createDriveReferenceToken('skill', item.skillMdKey, item.name))},})return@@ -97,8 +101,8 @@ export function AgentPromptSlashMenu({if (view === 'files') {onAddFile?.({onAdded: (item) => {- if (isPromptReferenceItem(item))- onSelect(createReferenceToken('file', item.id, item.name))+ if (isPromptReferenceItem(item) && 'driveKey' in item && typeof item.driveKey === 'string')+ onSelect(createDriveReferenceToken('file', item.driveKey, item.name))},})return@@ -224,7 +228,7 @@ function AgentPromptSkillRows({key={skill.id}icon="i-ri-box-3-line"label={skill.name}- onClick={() => onSelect(createReferenceToken('skill', skill.id, skill.name))}+ onClick={() => skill.skillMdKey && onSelect(createDriveReferenceToken('skill', skill.skillMdKey, skill.name))}/>))}</>@@ -249,7 +253,7 @@ function AgentPromptFileRows({label={file.name}depth={depth}hasChildren={!!file.children?.length}- onClick={() => onSelect(createReferenceToken('file', file.id, file.name))}+ onClick={() => file.driveKey && onSelect(createDriveReferenceToken('file', file.driveKey, file.name))}/>{!!file.children?.length && (<AgentPromptFileRows files={file.children} depth={depth + 1} onSelect={onSelect} />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.tsxindex 8ab77ecda3f..44a4e9fdf8f 100644--- 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.tsx@@ -1,20 +1,24 @@'use client'-import type { AgentConfigSnapshotDetailResponse, AgentConfigSnapshotSummaryResponse, AgentSoulConfig } from '@dify/contracts/api/console/agent/types.gen'+import type { AgentConfigSnapshotDetailResponse, AgentConfigSnapshotSummaryResponse, AgentReferencingWorkflowResponse, AgentReferencingWorkflowsResponse, AgentSoulConfig } from '@dify/contracts/api/console/agent/types.gen'import type { RegisterableHotkey } from '@tanstack/react-hotkeys'+import type { ReactNode } from 'react'import { Button } from '@langgenius/dify-ui/button'-import { cn } from '@langgenius/dify-ui/cn'+import { CollapsiblePanel, CollapsibleRoot } from '@langgenius/dify-ui/collapsible'import { Kbd, KbdGroup } from '@langgenius/dify-ui/kbd'import { StatusDot } from '@langgenius/dify-ui/status-dot'-import { formatForDisplay } from '@tanstack/react-hotkeys'-import { useEffect, useRef, useState } from 'react'+import { toast } from '@langgenius/dify-ui/toast'+import { formatForDisplay, useHotkey } from '@tanstack/react-hotkeys'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { useState } from 'react'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'+import useTimestamp from '@/hooks/use-timestamp'+import { consoleQuery } from '@/service/client'+import { AgentPublishImpactDetails } from './publish-impact-details'const PUBLISH_AGENT_HOTKEY = 'Mod+Shift+P' satisfies RegisterableHotkey-const PUBLISH_IMPACT_BAR_HIDE_DELAY = 160export type AgentConfigurePublishPayload = {agent_id: string@@ -23,6 +27,9 @@ export type AgentConfigurePublishPayload = {type AgentConfigurePublishState = 'draft' | 'publishing' | 'published' | 'unpublished'+type PublishBarMode = { status: 'compact' }+ | { status: 'confirmingImpact', references: AgentReferencingWorkflowResponse[] }+type AgentConfigurePublishBarProps = {agentId: stringactiveConfigIsPublished?: boolean@@ -35,7 +42,9 @@ type AgentConfigurePublishBarProps = {}draftSavedAt?: numberisPublishing?: boolean+ selectedVersionSnapshot?: AgentConfigSnapshotSummaryResponse | nullonPublish?: (payload: AgentConfigurePublishPayload) => void | Promise<void>+ onExitVersions?: () => voidonOpenVersions: () => void}@@ -81,54 +90,136 @@ export function AgentConfigurePublishBar({currentModel,draftSavedAt,isPublishing = false,+ selectedVersionSnapshot,onPublish,+ onExitVersions,onOpenVersions,}: AgentConfigurePublishBarProps) {const { t } = useTranslation('agentV2')+ const { t: tCommon } = useTranslation('common')const { formatTimeFromNow } = useFormatTimeFromNow()- const [shouldHidePublishBar, setShouldHidePublishBar] = useState(false)- const hidePublishBarTimerRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)+ const queryClient = useQueryClient()+ const [publishBarMode, setPublishBarMode] = useState<PublishBarMode>({ status: 'compact' })const hasUnpublishedChanges = useHasAgentComposerUnpublishedChanges()const publishPayload = useConfigPublishPayload({agentId,baseConfig: agentSoulConfig,currentModel,})+ const publishableState = getPublishState({+ activeConfigIsPublished,+ activeConfigSnapshot,+ isDirty: hasUnpublishedChanges,+ isPublishing: false,+ })const publishState = getPublishState({activeConfigIsPublished,activeConfigSnapshot,isDirty: hasUnpublishedChanges,isPublishing,})- const canPublish = publishState === 'draft' || publishState === 'unpublished'-- const handleImpactPopoverOpenChange = (open: boolean) => {- if (hidePublishBarTimerRef.current)- clearTimeout(hidePublishBarTimerRef.current)+ const publishIsAvailable = !isPublishing && (publishableState === 'draft' || publishableState === 'unpublished')+ const workflowReferencesQueryOptions = consoleQuery.agent.byAgentId.referencingWorkflows.get.queryOptions({+ input: {+ params: {+ agent_id: agentId,+ },+ },+ })+ const workflowReferencesQuery = useQuery({+ ...workflowReferencesQueryOptions,+ enabled: publishIsAvailable && !selectedVersionSnapshot,+ })+ const restoreVersionMutation = useMutation(consoleQuery.agent.byAgentId.versions.byVersionId.restore.post.mutationOptions())+ const canPublish = publishIsAvailable- if (!open) {- setShouldHidePublishBar(false)+ const handleRestoreVersion = (versionId: string) => {+ if (restoreVersionMutation.isPending)return- }- hidePublishBarTimerRef.current = setTimeout(() => {- setShouldHidePublishBar(true)- }, PUBLISH_IMPACT_BAR_HIDE_DELAY)+ restoreVersionMutation.mutate({+ params: {+ agent_id: agentId,+ version_id: versionId,+ },+ }, {+ onSuccess: () => {+ void queryClient.invalidateQueries({+ queryKey: consoleQuery.agent.byAgentId.get.queryKey({+ input: {+ params: {+ agent_id: agentId,+ },+ },+ }),+ })+ void queryClient.invalidateQueries({+ queryKey: consoleQuery.agent.byAgentId.composer.get.queryKey({+ input: {+ params: {+ agent_id: agentId,+ },+ },+ }),+ })+ void queryClient.invalidateQueries({+ queryKey: consoleQuery.agent.byAgentId.versions.get.key(),+ })+ onExitVersions?.()+ toast.success(tCommon('api.actionSuccess'))+ },+ onError: () => {+ toast.error(tCommon('api.actionFailed'))+ },+ })}- const handlePublish = () => {+ const handlePublish = async () => {if (!canPublish)return- void onPublish?.(publishPayload)+ await onPublish?.(publishPayload)+ setPublishBarMode({ status: 'compact' })}- useEffect(() => {- return () => {- if (hidePublishBarTimerRef.current)- clearTimeout(hidePublishBarTimerRef.current)+ const handlePublishRequest = async () => {+ if (!canPublish)+ return++ if (publishBarMode.status === 'confirmingImpact') {+ await handlePublish()+ return+ }++ const cachedReferences = queryClient.getQueryData<AgentReferencingWorkflowsResponse>(workflowReferencesQueryOptions.queryKey)+ const references = (cachedReferences ?? workflowReferencesQuery.data ?? await queryClient.ensureQueryData(workflowReferencesQueryOptions))?.data ?? []++ if (references.length > 0) {+ setPublishBarMode({ status: 'confirmingImpact', references })+ return}- }, [])++ await handlePublish()+ }++ useHotkey(PUBLISH_AGENT_HOTKEY, (event) => {+ event.preventDefault()+ void handlePublishRequest()+ }, {+ enabled: canPublish && !selectedVersionSnapshot,+ ignoreInputs: false,+ })++ if (selectedVersionSnapshot) {+ return (+ <AgentVersionRestoreBar+ version={selectedVersionSnapshot}+ isRestoring={restoreVersionMutation.isPending}+ onExitVersions={onExitVersions}+ onRestoreVersion={handleRestoreVersion}+ />+ )+ }const publishedMeta = activeConfigSnapshot?.created_at? t('agentDetail.configure.publishBar.publishedAt', {@@ -150,7 +241,7 @@ export function AgentConfigurePublishBar({statusLabel: t('agentDetail.configure.publishBar.draft'),},publishing: {- actionIcon: 'i-ri-loader-2-line animate-spin motion-reduce:animate-none',+ actionIcon: null,actionLabel: t('agentDetail.configure.publishBar.publishing'),dotStatus: 'disabled',metaLabel: savedMeta,@@ -182,60 +273,195 @@ export function AgentConfigurePublishBar({statusLabel: string}>const currentStateMeta = stateMeta[publishState]+ const isConfirmingImpact = publishBarMode.status === 'confirmingImpact' && (canPublish || isPublishing)+ const impactReferences = publishBarMode.status === 'confirmingImpact' ? publishBarMode.references : []return (- <div className="flex h-16 shrink-0 items-center justify-center px-4 pt-2 pb-3">+ <PublishBarBottomActions>+ <CollapsibleRoot+ open={isConfirmingImpact}+ className="group/publish-bar pointer-events-auto w-full overflow-hidden rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur shadow-lg shadow-shadow-shadow-5 backdrop-blur-[5px]"+ >+ <CollapsiblePanel className="system-sm-regular text-text-secondary">+ <AgentPublishImpactDetails+ publishActionLabel={currentStateMeta.actionLabel}+ agentName={agentName}+ references={impactReferences}+ />+ </CollapsiblePanel>+ <PublishBarActions+ actionIcon={currentStateMeta.actionIcon}+ actionLabel={currentStateMeta.actionLabel}+ dotStatus={currentStateMeta.dotStatus}+ isPublishing={isPublishing}+ metaLabel={currentStateMeta.metaLabel}+ showShortcut={currentStateMeta.showShortcut}+ statusLabel={currentStateMeta.statusLabel}+ canPublish={canPublish}+ onCancelImpact={() => setPublishBarMode({ status: 'compact' })}+ onOpenVersions={onOpenVersions}+ onPublishRequest={handlePublishRequest}+ />+ </CollapsibleRoot>+ </PublishBarBottomActions>+ )+}++function PublishBarBottomActions({+ children,+}: {+ children: ReactNode+}) {+ return (+ <div+ className="pointer-events-none absolute inset-x-0 bottom-0 z-10 flex h-[72px] flex-col items-center justify-end px-4 pt-4 pb-2 transition-[height] duration-150 ease-out has-[[data-open]]:h-[307px] motion-reduce:transition-none"+ ><div- className={cn(- '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]',- shouldHidePublishBar && 'pointer-events-none opacity-0',- )}- aria-hidden={shouldHidePublishBar}+ aria-hidden+ className="pointer-events-none absolute inset-0 z-0 bg-gradient-to-t from-components-panel-bg to-components-panel-bg-transparent [mask-image:linear-gradient(to_top,black,transparent)] backdrop-blur-[2px] [-webkit-mask-image:linear-gradient(to_top,black,transparent)]"+ />+ <div+ className="relative z-10 flex w-full max-w-[506px] flex-col items-center justify-end transition-[max-width] duration-150 ease-out has-[[data-open]]:max-w-96 motion-reduce:transition-none"+ >+ {children}+ </div>+ </div>+ )+}++function PublishBarActions({+ actionIcon,+ actionLabel,+ dotStatus,+ isPublishing,+ metaLabel,+ showShortcut,+ statusLabel,+ canPublish,+ onCancelImpact,+ onOpenVersions,+ onPublishRequest,+}: {+ actionIcon: string | null+ actionLabel: string+ dotStatus: 'disabled' | 'success' | 'warning'+ isPublishing: boolean+ metaLabel: string+ showShortcut: boolean+ statusLabel: string+ canPublish: boolean+ onCancelImpact: () => void+ onOpenVersions: () => void+ onPublishRequest: () => void | Promise<void>+}) {+ const { t } = useTranslation('agentV2')++ return (+ <div className="flex w-full min-w-0 items-center justify-between gap-2 p-2 group-data-open/publish-bar:justify-end group-data-open/publish-bar:px-4 group-data-open/publish-bar:pt-2 group-data-open/publish-bar:pb-4">+ <div className="flex min-w-0 flex-1 items-center gap-1 px-2 system-xs-regular text-text-tertiary group-data-open/publish-bar:hidden">+ <span className="flex size-4 shrink-0 items-center justify-center">+ <StatusDot size="small" status={dotStatus} />+ </span>+ <span className="shrink-0">{statusLabel}</span>+ <span aria-hidden className="shrink-0">·</span>+ <span className="min-w-0 truncate">+ {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 group-data-open/publish-bar:hidden 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>+ <Button+ type="button"+ variant="secondary"+ className="hidden h-8 min-w-18 rounded-lg px-3 group-data-open/publish-bar:inline-flex"+ onClick={onCancelImpact}>- <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>+ {t('agentDetail.configure.publishImpact.cancel')}+ </Button>+ <Button+ type="button"+ variant="primary"+ disabled={!canPublish}+ loading={isPublishing}+ className="h-8 gap-1 rounded-lg px-3"+ onClick={() => {+ void onPublishRequest()+ }}+ >+ {actionIcon && (+ <span aria-hidden className={`${actionIcon} size-4 shrink-0`} />+ )}+ <span className="shrink-0">{actionLabel}</span>+ {showShortcut && <PublishShortcut />}+ </Button>+ </div>+ )+}++function AgentVersionRestoreBar({+ version,+ isRestoring = false,+ onExitVersions,+ onRestoreVersion,+}: {+ version: AgentConfigSnapshotSummaryResponse+ isRestoring?: boolean+ onExitVersions?: () => void+ onRestoreVersion?: (versionId: string) => void+}) {+ const { t } = useTranslation('agentV2')+ const { formatTime } = useTimestamp()+ const versionLabel = version.version_note || t('agentDetail.versionHistory.versionName', { version: version.version })+ const createdAt = version.created_at == null+ ? null+ : formatTime(version.created_at, t('roster.dateTimeFormat'))++ return (+ <PublishBarBottomActions>+ <div className="pointer-events-auto 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 py-2 pr-2.5 pl-2 shadow-lg shadow-shadow-shadow-5 backdrop-blur-[5px]">+ <div className="flex min-w-0 flex-col justify-center gap-0.5 pr-4 pl-2">+ <div className="flex min-w-0 items-center gap-1">+ <p className="min-w-0 truncate system-sm-semibold text-text-primary">+ {versionLabel}+ </p>+ <span className="shrink-0 rounded-[5px] border border-text-accent-secondary bg-components-badge-bg-dimm px-1 py-0.5 system-2xs-medium-uppercase text-text-accent-secondary">+ {t('agentDetail.versionHistory.viewOnly')}+ </span>+ </div>+ {(createdAt || version.created_by) && (+ <p className="min-w-0 truncate system-xs-regular text-text-tertiary">+ {createdAt}+ {createdAt && version.created_by && ' · '}+ {version.created_by}+ </p>+ )}</div>- <button+ <Buttontype="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}+ variant="primary"+ disabled={!onRestoreVersion}+ loading={isRestoring}+ className="h-8 rounded-lg px-3"+ onClick={() => onRestoreVersion?.(version.id)}>- <span aria-hidden className="i-ri-history-line size-4" />- </button>- <AgentPublishImpactPopover- actionLabel={currentStateMeta.actionLabel}- actionShortcut={currentStateMeta.showShortcut ? <PublishShortcut /> : null}- hotkey={PUBLISH_AGENT_HOTKEY}- agentId={agentId}- agentName={agentName}- disabled={!canPublish}- onOpenChange={handleImpactPopoverOpenChange}- 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>- )}- />+ {t('agentDetail.versionHistory.restore')}+ </Button>+ <Button+ type="button"+ variant="secondary"+ className="h-8 gap-1 rounded-lg px-3 text-text-accent"+ onClick={onExitVersions}+ >+ <span aria-hidden className="i-ri-arrow-go-back-line size-4 shrink-0" />+ <span className="shrink-0">{t('agentDetail.versionHistory.exitVersions')}</span>+ </Button></div>- </div>+ </PublishBarBottomActions>)}diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/publish-bar/publish-impact-details.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/publish-bar/publish-impact-details.tsxnew file mode 100644index 00000000000..2cb966e0537--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/publish-bar/publish-impact-details.tsx@@ -0,0 +1,97 @@+'use client'++import type { AgentIconType, AgentReferencingWorkflowResponse } from '@dify/contracts/api/console/agent/types.gen'+import { useId } from 'react'+import { useTranslation } from 'react-i18next'+import AppIcon from '@/app/components/base/app-icon'+import { useFormatTimeFromNow } from '@/hooks/use-format-time-from-now'+import Link from '@/next/link'++type AgentPublishImpactDetailsProps = {+ publishActionLabel: string+ agentName?: string | null+ references: AgentReferencingWorkflowResponse[]+}++const getWorkflowReferenceHref = (reference: AgentReferencingWorkflowResponse) => `/app/${reference.app_id}/workflow`++export function AgentPublishImpactDetails({+ publishActionLabel,+ agentName,+ references,+}: AgentPublishImpactDetailsProps) {+ const { t } = useTranslation('agentV2')+ const titleId = useId()++ return (+ <section+ aria-labelledby={titleId}+ className="flex w-full max-w-full flex-col"+ >+ <div className="flex flex-col gap-0.5 px-3 pt-3.5 pb-1">+ <h2 id={titleId} className="w-full px-1 pr-8 system-xl-semibold wrap-break-word text-text-primary">+ {t('agentDetail.configure.publishImpact.title', {+ action: publishActionLabel,+ name: agentName || t('agentDetail.configure.publishImpact.fallbackAgentName'),+ })}+ </h2>+ <p className="px-1 system-xs-regular wrap-break-word text-text-warning">+ {t('agentDetail.configure.publishImpact.descriptionPrefix')}+ {' '}+ <span className="system-xs-medium">+ {t('agentDetail.configure.publishImpact.workflowCount', { count: references.length })}+ </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-[123px] flex-col gap-px overflow-y-auto rounded-xl border border-components-panel-border p-1">+ {references.map(reference => (+ <ReferenceLink key={`${reference.app_id}-${reference.workflow_id}`} reference={reference} />+ ))}+ </div>+ </div>+ </section>+ )+}++function ReferenceLink({+ reference,+}: {+ reference: AgentReferencingWorkflowResponse+}) {+ const { formatTimeFromNow } = useFormatTimeFromNow()+ 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+ ? null+ : formatTimeFromNow(reference.app_updated_at * 1000)++ 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="shrink-0">+ <AppIcon+ size="tiny"+ iconType={iconType}+ icon={reference.app_icon ?? undefined}+ background={reference.app_icon_background}+ imageUrl={imageUrl}+ />+ </span>+ <span className="min-w-0 flex-1 truncate">{reference.app_name}</span>+ {updatedAt && (+ <span className="shrink-0 system-xs-regular text-text-tertiary">{updatedAt}</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/publish-bar/publish-impact-popover.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/publish-bar/publish-impact-popover.tsxdeleted file mode 100644index b4fa0896adf..00000000000--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/publish-bar/publish-impact-popover.tsx+++ /dev/null@@ -1,203 +0,0 @@-'use client'--import type { AgentIconType, AgentReferencingWorkflowResponse } from '@dify/contracts/api/console/agent/types.gen'-import type { RegisterableHotkey } from '@tanstack/react-hotkeys'-import type { MouseEvent, ReactElement, ReactNode } from 'react'-import { Button } from '@langgenius/dify-ui/button'-import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'-import { useHotkey } from '@tanstack/react-hotkeys'-import { useQuery } from '@tanstack/react-query'-import { cloneElement, useState } from 'react'-import { useTranslation } from 'react-i18next'-import AppIcon from '@/app/components/base/app-icon'-import Link from '@/next/link'-import { consoleQuery } from '@/service/client'--type AgentPublishImpactPopoverProps = {- actionLabel: string- actionShortcut?: ReactNode- hotkey: RegisterableHotkey- agentId: string- agentName?: string | null- disabled?: boolean- trigger: ReactElement<{- onClick?: (event: MouseEvent<HTMLElement>) => void- }>- onOpenChange?: (open: boolean) => void- onPublish: () => void-}--const getWorkflowReferenceHref = (reference: AgentReferencingWorkflowResponse) => `/app/${reference.app_id}/workflow`--export function AgentPublishImpactPopover({- actionLabel,- actionShortcut,- hotkey,- agentId,- agentName,- disabled = false,- trigger,- onOpenChange,- onPublish,-}: AgentPublishImpactPopoverProps) {- const { t } = useTranslation('agentV2')- const [open, setOpen] = useState(false)- const [isCheckingReferences, setIsCheckingReferences] = useState(false)- const workflowReferencesQuery = useQuery({- ...consoleQuery.agent.byAgentId.referencingWorkflows.get.queryOptions({- input: {- params: {- agent_id: agentId,- },- },- }),- enabled: false,- })- const publishedReferences = workflowReferencesQuery.data?.data ?? []-- const updateOpen = (nextOpen: boolean) => {- setOpen(nextOpen)- onOpenChange?.(nextOpen)- }-- const handlePublish = () => {- updateOpen(false)- onPublish()- }-- const handlePublishRequest = async () => {- if (disabled || isCheckingReferences)- return-- if (open) {- handlePublish()- return- }-- setIsCheckingReferences(true)- try {- const result = await workflowReferencesQuery.refetch()- const references = result.data?.data ?? []- if (references.length > 0) {- updateOpen(true)- return- }-- onPublish()- }- finally {- setIsCheckingReferences(false)- }- }-- useHotkey(hotkey, (event) => {- event.preventDefault()- void handlePublishRequest()- }, {- enabled: !disabled,- ignoreInputs: false,- })-- if (disabled)- return trigger-- const triggerWithImpact = cloneElement(trigger, {- onClick: async (event: MouseEvent<HTMLElement>) => {- event.preventDefault()- await handlePublishRequest()- },- })-- return (- <Popover open={open} onOpenChange={updateOpen}>- <PopoverTrigger- render={triggerWithImpact}- />- <PopoverContent- placement="top-end"- sideOffset={-32}- 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] transition-[transform,scale,opacity] duration-150 ease-out data-starting-style:translate-y-5 data-ending-style:translate-y-5 motion-reduce:transition-none motion-reduce:data-starting-style:translate-y-0 motion-reduce:data-ending-style:translate-y-0"- >- <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: publishedReferences.length })}- </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 => (- <ReferenceLink key={`${reference.app_id}-${reference.workflow_id}`} reference={reference} />- ))}- </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={() => updateOpen(false)}- >- {t('agentDetail.configure.publishImpact.cancel')}- </Button>- <Button- type="button"- variant="primary"- className="h-8 min-w-18 gap-1 rounded-lg px-3"- onClick={handlePublish}- >- <span className="shrink-0">{actionLabel}</span>- {actionShortcut}- </Button>- </div>- </div>- </PopoverContent>- </Popover>- )-}--function ReferenceLink({- reference,-}: {- reference: AgentReferencingWorkflowResponse-}) {- 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-- 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="shrink-0">- <AppIcon- size="tiny"- iconType={iconType}- icon={reference.app_icon ?? undefined}- background={reference.app_icon_background}- imageUrl={imageUrl}- />- </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/skills/__tests__/index.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/__tests__/index.spec.tsxindex c54d4c86d0f..7b08b75080e 100644--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/__tests__/index.spec.tsx+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/__tests__/index.spec.tsx@@ -6,13 +6,17 @@ 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 { AgentDriveApiContextProvider } from '../../drive-context'import { AgentOrchestrateReadOnlyContext } from '../../read-only-context'import { AgentSkills } from '../index'const mocks = vi.hoisted(() => ({+ driveSkillsQueryOptions: vi.fn(),+ driveSkillInspectQueryOptions: vi.fn(),driveFilesQueryOptions: vi.fn(),driveFileDownloadQueryOptions: vi.fn(),driveFilePreviewQueryOptions: vi.fn(),+ deleteSkillMutationOptions: vi.fn(),uploadSkillMutationOptions: vi.fn(),}))@@ -28,6 +32,18 @@ vi.mock('@/service/client', () => ({agent: {byAgentId: {drive: {+ skills: {+ get: {+ queryOptions: mocks.driveSkillsQueryOptions,+ },+ bySkillPath: {+ inspect: {+ get: {+ queryOptions: mocks.driveSkillInspectQueryOptions,+ },+ },+ },+ },files: {get: {queryOptions: mocks.driveFilesQueryOptions,@@ -45,6 +61,11 @@ vi.mock('@/service/client', () => ({},},skills: {+ bySlug: {+ delete: {+ mutationOptions: mocks.deleteSkillMutationOptions,+ },+ },upload: {post: {mutationOptions: mocks.uploadSkillMutationOptions,@@ -53,26 +74,58 @@ vi.mock('@/service/client', () => ({},},},+ apps: {+ byAppId: {+ agent: {+ drive: {+ skills: {+ get: {+ queryOptions: mocks.driveSkillsQueryOptions,+ },+ bySkillPath: {+ inspect: {+ get: {+ queryOptions: mocks.driveSkillInspectQueryOptions,+ },+ },+ },+ },+ files: {+ get: {+ queryOptions: mocks.driveFilesQueryOptions,+ },+ download: {+ get: {+ queryOptions: mocks.driveFileDownloadQueryOptions,+ },+ },+ preview: {+ get: {+ queryOptions: mocks.driveFilePreviewQueryOptions,+ },+ },+ },+ },+ skills: {+ bySlug: {+ delete: {+ mutationOptions: mocks.deleteSkillMutationOptions,+ },+ },+ upload: {+ post: {+ mutationOptions: mocks.uploadSkillMutationOptions,+ },+ },+ },+ },+ },+ },},}))const agentSkillsDraft = {...defaultAgentSoulConfigFormState,- skills: [- {- id: 'tender-analyzer',- name: 'Tender Analyzer',- description: 'Extracts tender requirements and scoring criteria.',- files: ['__MACOSX/._hatch-pet', 'SKILL.md', 'schema.json'],- path: 'tender-analyzer',- skillMdKey: 'tender-analyzer/SKILL.md',- },- {- id: 'meeting-brief',- name: 'Meeting Brief',- path: 'meeting-brief',- },- ],} satisfies typeof defaultAgentSoulConfigFormStatefunction renderAgentSkills() {@@ -86,9 +139,31 @@ function renderAgentSkills() {return render(<QueryClientProvider client={queryClient}>- <AgentComposerProvider initialDraft={agentSkillsDraft}>- <AgentSkills agentId="agent-1" />- </AgentComposerProvider>+ <AgentDriveApiContextProvider value={{ agentId: 'agent-1' }}>+ <AgentComposerProvider initialDraft={agentSkillsDraft}>+ <AgentSkills />+ </AgentComposerProvider>+ </AgentDriveApiContextProvider>+ </QueryClientProvider>,+ )+}++function renderWorkflowAgentSkills() {+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: {+ retry: false,+ },+ },+ })++ return render(+ <QueryClientProvider client={queryClient}>+ <AgentDriveApiContextProvider value={{ agentId: 'agent-1', workflow: { appId: 'app-1', nodeId: 'node-1' } }}>+ <AgentComposerProvider initialDraft={agentSkillsDraft}>+ <AgentSkills />+ </AgentComposerProvider>+ </AgentDriveApiContextProvider></QueryClientProvider>,)}@@ -104,11 +179,13 @@ function renderReadonlyAgentSkills() {return render(<QueryClientProvider client={queryClient}>- <AgentComposerProvider initialDraft={agentSkillsDraft}>- <AgentOrchestrateReadOnlyContext value>- <AgentSkills agentId="agent-1" />- </AgentOrchestrateReadOnlyContext>- </AgentComposerProvider>+ <AgentDriveApiContextProvider value={{ agentId: 'agent-1' }}>+ <AgentComposerProvider initialDraft={agentSkillsDraft}>+ <AgentOrchestrateReadOnlyContext value>+ <AgentSkills />+ </AgentOrchestrateReadOnlyContext>+ </AgentComposerProvider>+ </AgentDriveApiContextProvider></QueryClientProvider>,)}@@ -118,7 +195,7 @@ function ConfigSnapshotProbe() {return (<pre data-testid="config-snapshot-probe">- {JSON.stringify(configSnapshot.skills_files?.skills ?? [])}+ {JSON.stringify(configSnapshot)}</pre>)}@@ -126,6 +203,76 @@ function ConfigSnapshotProbe() {describe('AgentSkills', () => {beforeEach(() => {vi.clearAllMocks()+ const skillItems = [+ {+ archive_key: 'tender-analyzer/.DIFY-SKILL-FULL.zip',+ description: 'Extracts tender requirements and scoring criteria.',+ name: 'Tender Analyzer',+ path: 'tender-analyzer',+ skill_md_key: 'tender-analyzer/SKILL.md',+ },+ {+ description: '',+ name: 'Meeting Brief',+ path: 'meeting-brief',+ skill_md_key: 'meeting-brief/SKILL.md',+ },+ ]+ mocks.driveSkillsQueryOptions.mockImplementation(({ input }) => ({+ queryKey: ['agent-drive-skills', input],+ initialData: { items: skillItems },+ queryFn: async () => ({+ items: skillItems,+ }),+ }))+ mocks.driveSkillInspectQueryOptions.mockImplementation(({ input }) => ({+ queryKey: ['agent-drive-skill-inspect', input],+ queryFn: async () => ({+ archive_key: 'tender-analyzer/.DIFY-SKILL-FULL.zip',+ description: 'Extracts tender requirements and scoring criteria.',+ files: [+ {+ available_in_drive: true,+ drive_key: 'tender-analyzer/SKILL.md',+ name: 'SKILL.md',+ path: 'SKILL.md',+ type: 'file',+ },+ {+ available_in_drive: true,+ drive_key: 'tender-analyzer/references/guide.md',+ name: 'guide.md',+ path: 'references/guide.md',+ type: 'file',+ },+ {+ available_in_drive: true,+ drive_key: 'tender-analyzer/scripts/extract.py',+ name: 'extract.py',+ path: 'scripts/extract.py',+ type: 'file',+ },+ {+ available_in_drive: true,+ drive_key: 'tender-analyzer/.DIFY-SKILL-FULL.zip',+ name: '.DIFY-SKILL-FULL.zip',+ path: '.DIFY-SKILL-FULL.zip',+ type: 'file',+ },+ ],+ name: 'Tender Analyzer',+ path: 'tender-analyzer',+ skill_md: {+ binary: false,+ key: 'tender-analyzer/SKILL.md',+ text: 'Skill markdown content',+ truncated: false,+ },+ skill_md_key: 'tender-analyzer/SKILL.md',+ source: 'drive',+ warnings: [],+ }),+ }))mocks.driveFilesQueryOptions.mockImplementation(({ input }) => ({queryKey: ['agent-drive-files', input],queryFn: async () => ({@@ -157,9 +304,12 @@ describe('AgentSkills', () => {mutationFn: vi.fn(),mutationKey: ['upload-skill'],})+ mocks.deleteSkillMutationOptions.mockReturnValue({+ mutationFn: vi.fn(),+ mutationKey: ['delete-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()@@ -170,81 +320,281 @@ describe('AgentSkills', () => {const dialog = screen.getByRole('dialog')expect(dialog).toBeInTheDocument()- expect(mocks.driveFilesQueryOptions).toHaveBeenCalledWith({- input: {- params: {- agent_id: 'agent-1',- },- query: {- prefix: 'tender-analyzer/',+ await waitFor(() => {+ expect(mocks.driveSkillInspectQueryOptions).toHaveBeenCalledWith({+ input: {+ params: {+ agent_id: 'agent-1',+ skill_path: 'tender-analyzer',+ },},- },+ })})+ expect(mocks.driveFilesQueryOptions).not.toHaveBeenCalled()expect(within(dialog).getByText('Tender Analyzer')).toBeInTheDocument()expect(within(dialog).getByText('Extracts tender requirements and scoring criteria.')).toBeInTheDocument()- expect(within(dialog).queryByText('__MACOSX/._hatch-pet')).not.toBeInTheDocument()- expect(await within(dialog).findByText('scripts/extract.py')).toBeInTheDocument()- expect(within(dialog).getByText('SKILL.md')).toBeInTheDocument()- expect(await within(dialog).findByText('Preview content for tender-analyzer/SKILL.md')).toBeInTheDocument()+ expect(await within(dialog).findByText('references')).toBeInTheDocument()+ expect(within(dialog).getByText('guide.md')).toBeInTheDocument()+ expect(within(dialog).getByText('scripts')).toBeInTheDocument()+ expect(within(dialog).getByText('extract.py')).toBeInTheDocument()+ expect(within(dialog).queryByText('.DIFY-SKILL-FULL.zip')).not.toBeInTheDocument()+ })++ it('should keep the detail dialog open after selecting a skill', async () => {+ renderAgentSkills()++ fireEvent.click(screen.getByRole('button', {+ name: 'Tender Analyzer',+ }))++ expect(screen.getByRole('dialog')).toBeInTheDocument()+ })++ it('should preview selected package file content in the skill detail dialog', async () => {+ const user = userEvent.setup()+ renderAgentSkills()++ await user.click(screen.getByRole('button', {+ name: 'Tender Analyzer',+ }))++ const dialog = screen.getByRole('dialog')+ await user.click(await within(dialog).findByText('guide.md'))++ expect(await within(dialog).findByText('Preview content for tender-analyzer/references/guide.md')).toBeInTheDocument()expect(mocks.driveFilePreviewQueryOptions).toHaveBeenCalledWith({input: {params: {agent_id: 'agent-1',},query: {- key: 'tender-analyzer/SKILL.md',+ key: 'tender-analyzer/references/guide.md',},},})+ })++ it('should not request preview for package files without a drive entry', async () => {+ const user = userEvent.setup()+ mocks.driveSkillInspectQueryOptions.mockImplementation(({ input }) => ({+ queryKey: ['agent-drive-skill-inspect', input],+ queryFn: async () => ({+ archive_key: 'tender-analyzer/.DIFY-SKILL-FULL.zip',+ description: 'Extracts tender requirements and scoring criteria.',+ files: [+ {+ available_in_drive: true,+ drive_key: 'tender-analyzer/SKILL.md',+ name: 'SKILL.md',+ path: 'SKILL.md',+ type: 'file',+ },+ {+ available_in_drive: false,+ drive_key: null,+ name: 'animation-rows.md',+ path: 'references/animation-rows.md',+ type: 'file',+ },+ ],+ name: 'Tender Analyzer',+ path: 'tender-analyzer',+ skill_md: {+ binary: false,+ key: 'tender-analyzer/SKILL.md',+ text: 'Skill markdown content',+ truncated: false,+ },+ skill_md_key: 'tender-analyzer/SKILL.md',+ source: 'drive',+ warnings: [],+ }),+ }))++ renderAgentSkills()++ await user.click(screen.getByRole('button', {+ name: 'Tender Analyzer',+ }))++ const dialog = screen.getByRole('dialog')+ await user.click(await within(dialog).findByText('animation-rows.md'))+expect(mocks.driveFilePreviewQueryOptions).not.toHaveBeenCalledWith({input: {params: {agent_id: 'agent-1',},query: {- key: 'tender-analyzer/__MACOSX/._hatch-pet',+ key: 'tender-analyzer/references/animation-rows.md',},},})+ expect(within(dialog).getByText('agentV2.agentDetail.configure.files.preview.empty')).toBeInTheDocument()})- it('should preview the selected skill file from the detail file tree', async () => {+ it('should deduplicate package files by path in the skill detail dialog', async () => {+ const user = userEvent.setup()+ mocks.driveSkillInspectQueryOptions.mockImplementation(({ input }) => ({+ queryKey: ['agent-drive-skill-inspect', input],+ queryFn: async () => ({+ archive_key: 'tender-analyzer/.DIFY-SKILL-FULL.zip',+ description: 'Extracts tender requirements and scoring criteria.',+ files: [+ {+ available_in_drive: true,+ drive_key: 'tender-analyzer/SKILL.md',+ name: 'SKILL.md',+ path: 'SKILL.md',+ type: 'file',+ },+ {+ available_in_drive: false,+ drive_key: null,+ name: 'SKILL.md',+ path: 'tender-analyzer/SKILL.md',+ type: 'file',+ },+ {+ available_in_drive: true,+ drive_key: 'tender-analyzer/scripts/extract.py',+ name: 'extract.py',+ path: 'scripts/extract.py',+ type: 'file',+ },+ ],+ name: 'Tender Analyzer',+ path: 'tender-analyzer',+ skill_md: {+ binary: false,+ key: 'tender-analyzer/SKILL.md',+ text: 'Skill markdown content',+ truncated: false,+ },+ skill_md_key: 'tender-analyzer/SKILL.md',+ source: 'drive',+ warnings: [],+ }),+ }))+renderAgentSkills()- fireEvent.click(screen.getByRole('button', {+ await user.click(screen.getByRole('button', {name: 'Tender Analyzer',}))const dialog = screen.getByRole('dialog')- const scriptFile = await within(dialog).findByRole('button', { name: 'scripts/extract.py' })- fireEvent.click(scriptFile)- expect(await within(dialog).findByText('Preview content for tender-analyzer/scripts/extract.py')).toBeInTheDocument()- expect(mocks.driveFilePreviewQueryOptions).toHaveBeenCalledWith({+ expect(await within(dialog).findByText('SKILL.md')).toBeInTheDocument()+ expect(within(dialog).getAllByText('SKILL.md')).toHaveLength(1)+ expect(within(dialog).getByText('agentV2.agentDetail.configure.skills.detail.fileCount:{"count":2}')).toBeInTheDocument()+ })++ it('should use workflow node drive routes for skill list and preview in inline workflow mode', async () => {+ renderWorkflowAgentSkills()++ expect(mocks.driveSkillsQueryOptions).toHaveBeenCalledWith({input: {params: {- agent_id: 'agent-1',+ app_id: 'app-1',},query: {- key: 'tender-analyzer/scripts/extract.py',+ node_id: 'node-1',},},})++ fireEvent.click(screen.getByRole('button', {+ name: 'Tender Analyzer',+ }))++ await waitFor(() => {+ expect(mocks.driveSkillInspectQueryOptions).toHaveBeenCalledWith({+ input: {+ params: {+ app_id: 'app-1',+ skill_path: 'tender-analyzer',+ },+ query: {+ node_id: 'node-1',+ },+ },+ })+ })+ fireEvent.click(await screen.findByText('guide.md'))++ await waitFor(() => {+ expect(mocks.driveFilePreviewQueryOptions).toHaveBeenCalledWith({+ input: {+ params: {+ app_id: 'app-1',+ },+ query: {+ node_id: 'node-1',+ key: 'tender-analyzer/references/guide.md',+ },+ },+ })+ })})- // 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', () => {+ it('should delete 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 route Agent App skill delete through agent and slug identifiers', async () => {+ const deleteSkill = vi.fn().mockResolvedValue({ result: 'success', removed_keys: ['tender-analyzer/SKILL.md'] })+ mocks.deleteSkillMutationOptions.mockReturnValue({+ mutationFn: deleteSkill,+ mutationKey: ['delete-skill'],+ })+ renderAgentSkills()++ fireEvent.click(screen.getByRole('button', {+ name: /agentV2\.agentDetail\.configure\.skills\.remove.*Tender Analyzer/,+ }))++ await waitFor(() => {+ expect(deleteSkill.mock.calls[0]?.[0]).toEqual({+ params: {+ agent_id: 'agent-1',+ slug: 'tender-analyzer',+ },+ })+ })+ })++ it('should route workflow skill delete through app and node identifiers', async () => {+ const deleteSkill = vi.fn().mockResolvedValue({ result: 'success', removed_keys: ['tender-analyzer/SKILL.md'] })+ mocks.deleteSkillMutationOptions.mockReturnValue({+ mutationFn: deleteSkill,+ mutationKey: ['delete-skill'],+ })+ renderWorkflowAgentSkills()++ fireEvent.click(screen.getByRole('button', {+ name: /agentV2\.agentDetail\.configure\.skills\.remove.*Tender Analyzer/,+ }))++ await waitFor(() => {+ expect(deleteSkill.mock.calls[0]?.[0]).toEqual({+ params: {+ app_id: 'app-1',+ slug: 'tender-analyzer',+ },+ query: {+ node_id: 'node-1',+ },+ })+ })+ })+it('should hide add and remove actions when readonly', () => {renderReadonlyAgentSkills()@@ -255,21 +605,49 @@ describe('AgentSkills', () => {})).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 () => {+ it('should upload a skill through the drive-backed endpoint', async () => {const user = userEvent.setup()- const uploadSkill = vi.fn().mockResolvedValue({- manifest: {- files: ['SKILL.md', 'scripts/run.py'],- name: 'Invoice Helper',+ const driveSkills = [+ {+ archive_key: 'tender-analyzer/.DIFY-SKILL-FULL.zip',+ description: 'Extracts tender requirements and scoring criteria.',+ name: 'Tender Analyzer',+ path: 'tender-analyzer',+ skill_md_key: 'tender-analyzer/SKILL.md',},- skill: {- id: 'skill-hash',- manifest_files: ['SKILL.md', 'scripts/run.py'],+ {+ description: '',+ name: 'Meeting Brief',+ path: 'meeting-brief',+ skill_md_key: 'meeting-brief/SKILL.md',+ },+ ]+ mocks.driveSkillsQueryOptions.mockImplementation(({ input }) => ({+ queryKey: ['agent-drive-skills', input],+ initialData: { items: [...driveSkills] },+ queryFn: async () => ({ items: [...driveSkills] }),+ }))+ const uploadSkill = vi.fn().mockImplementation(async () => {+ driveSkills.push({+ archive_key: 'invoice-helper/.DIFY-SKILL-FULL.zip',+ description: '',name: 'Invoice Helper',path: 'invoice-helper',skill_md_key: 'invoice-helper/SKILL.md',- },+ })+ return {+ manifest: {+ files: ['SKILL.md', 'scripts/run.py'],+ name: 'Invoice Helper',+ },+ skill: {+ manifest_files: ['SKILL.md', 'scripts/run.py'],+ name: 'Invoice Helper',+ path: 'invoice-helper',+ skill_md_key: 'invoice-helper/SKILL.md',+ archive_key: 'invoice-helper/.DIFY-SKILL-FULL.zip',+ },+ }})mocks.uploadSkillMutationOptions.mockReturnValue({mutationFn: uploadSkill,@@ -296,24 +674,94 @@ describe('AgentSkills', () => {})})expect(await screen.findByRole('button', { name: 'Invoice Helper' })).toBeInTheDocument()+ expect(vi.mocked(toast.success)).toHaveBeenCalledWith('agentV2.agentDetail.configure.skills.upload.success')+ })- await user.click(screen.getByRole('button', { name: 'Invoice Helper' }))+ it('should refresh the rendered skill list after delete succeeds', async () => {+ const driveSkills = [+ {+ archive_key: 'tender-analyzer/.DIFY-SKILL-FULL.zip',+ description: 'Extracts tender requirements and scoring criteria.',+ name: 'Tender Analyzer',+ path: 'tender-analyzer',+ skill_md_key: 'tender-analyzer/SKILL.md',+ },+ {+ description: '',+ name: 'Meeting Brief',+ path: 'meeting-brief',+ skill_md_key: 'meeting-brief/SKILL.md',+ },+ ]+ mocks.driveSkillsQueryOptions.mockImplementation(({ input }) => ({+ queryKey: ['agent-drive-skills', input],+ initialData: { items: [...driveSkills] },+ queryFn: async () => ({ items: [...driveSkills] }),+ }))+ const deleteSkill = vi.fn().mockImplementation(async () => {+ driveSkills.splice(0, 1)+ return { result: 'success', removed_keys: ['tender-analyzer/SKILL.md'] }+ })+ mocks.deleteSkillMutationOptions.mockReturnValue({+ mutationFn: deleteSkill,+ mutationKey: ['delete-skill'],+ })- expect(mocks.driveFilesQueryOptions).toHaveBeenCalledWith({- input: {+ renderAgentSkills()++ fireEvent.click(screen.getByRole('button', {+ name: /agentV2\.agentDetail\.configure\.skills\.remove.*Tender Analyzer/,+ }))++ await waitFor(() => {+ expect(screen.queryByRole('button', { name: 'Tender Analyzer' })).not.toBeInTheDocument()+ })+ expect(screen.getByRole('button', { name: 'Meeting Brief' })).toBeInTheDocument()+ })++ it('should route workflow skill uploads through app and node identifiers', async () => {+ const user = userEvent.setup()+ const uploadSkill = vi.fn().mockResolvedValue({+ manifest: {+ files: ['SKILL.md'],+ name: 'Invoice Helper',+ },+ skill: {+ name: 'Invoice Helper',+ path: 'invoice-helper',+ skill_md_key: 'invoice-helper/SKILL.md',+ },+ })+ mocks.uploadSkillMutationOptions.mockReturnValue({+ mutationFn: uploadSkill,+ mutationKey: ['upload-skill'],+ })++ renderWorkflowAgentSkills()++ 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({params: {- agent_id: 'agent-1',+ app_id: 'app-1',},query: {- prefix: 'invoice-helper/',+ node_id: 'node-1',},- },+ body: {+ file,+ },+ })})- 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 () => {+ it('should not persist skills_files when the draft is serialized', async () => {const user = userEvent.setup()const uploadSkill = vi.fn().mockResolvedValue({manifest: {@@ -321,14 +769,9 @@ describe('AgentSkills', () => {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'],+ 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',},})@@ -347,10 +790,12 @@ describe('AgentSkills', () => {render(<QueryClientProvider client={queryClient}>- <AgentComposerProvider initialDraft={agentSkillsDraft}>- <AgentSkills agentId="agent-1" />- <ConfigSnapshotProbe />- </AgentComposerProvider>+ <AgentDriveApiContextProvider value={{ agentId: 'agent-1' }}>+ <AgentComposerProvider initialDraft={agentSkillsDraft}>+ <AgentSkills />+ <ConfigSnapshotProbe />+ </AgentComposerProvider>+ </AgentDriveApiContextProvider></QueryClientProvider>,)@@ -362,18 +807,8 @@ describe('AgentSkills', () => {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',- }),- ]))+ const serializedConfig = JSON.parse(screen.getByTestId('config-snapshot-probe').textContent ?? '{}')+ expect(serializedConfig).not.toHaveProperty('skills_files')})})})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.tsxindex c7fd8c3f6ff..409adff5d79 100644--- 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.tsx@@ -200,7 +200,7 @@ function AgentFilePreviewContent({}return (- <pre className="m-0 font-mono text-xs leading-5 break-words whitespace-pre-wrap text-text-secondary">+ <pre className="m-0 pb-4 font-mono text-xs leading-5 break-words whitespace-pre-wrap text-text-secondary">{content}</pre>)@@ -217,7 +217,7 @@ export function AgentSkillDetailDialog({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">+ <DialogContent backdropProps={{ forceRender: true }} backdropClassName="fixed" 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">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.tsxindex 5ecf687020a..0d4e49eda33 100644--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/index.tsx+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/index.tsx@@ -2,47 +2,77 @@import type { AgentOrchestrateAddActionOptions } from '../add-actions-context'import type { AgentSkill } from '@/features/agent-v2/agent-composer/form-state'-import { useAtom } from 'jotai'+import { useMutation } from '@tanstack/react-query'import { useCallback, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'-import { agentComposerSkillsAtom, useRemoveSkill } from '@/features/agent-v2/agent-composer/store-modules/skills'+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 { useAgentDriveApiContext, useAgentDriveSkills } from '../drive-context'import { AgentSkillItem } from './item'import { AgentSkillUploadDialog } from './upload-dialog'-export function AgentSkills({- agentId,-}: {- agentId: string-}) {+export function AgentSkills() {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 apiContext = useAgentDriveApiContext()+ const { query: skillsQuery, skills } = useAgentDriveSkills()+ const { mutate: deleteAgentSkill } = useMutation(consoleQuery.agent.byAgentId.skills.bySlug.delete.mutationOptions())+ const { mutate: deleteAppSkill } = useMutation(consoleQuery.apps.byAppId.agent.skills.bySlug.delete.mutationOptions())+const handleOpenUpload = useCallback((options?: AgentOrchestrateAddActionOptions) => {promptAddCallbackRef.current = options?.onAddedsetIsUploadOpen(true)}, [])useRegisterAgentOrchestrateAddAction('skills', handleOpenUpload)+const handleUploaded = useCallback((skill: AgentSkill) => {- setSkills(skills.some(currentSkill => currentSkill.id === skill.id)- ? skills- : [...skills, skill])+ void skillsQuery.refetch()promptAddCallbackRef.current?.(skill)promptAddCallbackRef.current = undefined- }, [setSkills, skills])+ }, [skillsQuery])+const handleUploadOpenChange = useCallback((open: boolean) => {if (!open)promptAddCallbackRef.current = undefinedsetIsUploadOpen(open)}, [])+ const handleRemoveSkill = useCallback((skillId: string) => {+ const skill = skills.find(item => item.id === skillId)+ const skillSlug = skill?.path ?? skill?.skillMdKey?.split('/', 1)[0]+ if (!skillSlug)+ return++ const onSuccess = () => {+ void skillsQuery.refetch()+ }+ if (apiContext.workflow) {+ deleteAppSkill({+ params: {+ app_id: apiContext.workflow.appId,+ slug: skillSlug,+ },+ query: {+ node_id: apiContext.workflow.nodeId,+ },+ }, { onSuccess })+ return+ }++ deleteAgentSkill({+ params: {+ agent_id: apiContext.agentId,+ slug: skillSlug,+ },+ }, { onSuccess })+ }, [apiContext, deleteAgentSkill, deleteAppSkill, skills, skillsQuery])+return (<><ConfigureSection@@ -68,11 +98,11 @@ export function AgentSkills({/>): skills.map(skill => (- <AgentSkillItem key={skill.id} agentId={agentId} skill={skill} onRemove={removeSkill} />+ <AgentSkillItem key={skill.id} apiContext={apiContext} skill={skill} onRemove={handleRemoveSkill} />))}</ConfigureSection><AgentSkillUploadDialog- agentId={agentId}+ apiContext={apiContext}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.tsxindex d3160a470c6..c4126124793 100644--- 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.tsx@@ -1,126 +1,39 @@'use client'-import type { AgentDriveItemResponse } from '@dify/contracts/api/console/agent/types.gen'-import type { AgentFileNode, AgentSkill } from '@/features/agent-v2/agent-composer/form-state'+import type { AgentDriveApiContext } from '../drive-context'+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 { getDriveFileIconType } from '../files/file-icon'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: getDriveFileIconType({- fileKind: item.file_kind,- fileName: getSkillFileName(item.key, skillDrivePath),- mimeType: item.mime_type,- }),- id: item.key,- name: getSkillFileName(item.key, skillDrivePath),-})--const getSkillMdFileId = (files: AgentFileNode[]): string | undefined => {- for (const file of files) {- if (file.icon !== 'folder' && file.name === 'SKILL.md')- return file.id-- const childFileId = file.children ? getSkillMdFileId(file.children) : undefined- if (childFileId)- return childFileId- }-}--const getFirstSkillFileId = (files: AgentFileNode[]): string | undefined => {- for (const file of files) {- if (file.icon !== 'folder')- return file.id-- const childFileId = file.children ? getFirstSkillFileId(file.children) : undefined- if (childFileId)- return childFileId- }-}+import { useAgentSkillDetail } from './use-skill-detail'export function AgentSkillItem({- agentId,+ apiContext,skill,onRemove,}: {- agentId: string+ apiContext: AgentDriveApiContextskill: AgentSkillonRemove: (skillId: string) => void}) {const { t } = useTranslation('agentV2')const readOnly = useAgentOrchestrateReadOnly()const [isPreviewOpen, setIsPreviewOpen] = useState(false)- const [selectedFileId, setSelectedFileId] = useState<string>()const handleRemove = useCallback(() => {onRemove(skill.id)}, [onRemove, skill.id])const handleOpenPreview = useCallback(() => {- setSelectedFileId(undefined)setIsPreviewOpen(true)}, [])- 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))- : []- const previewFileId = selectedFileId- ?? skill.skillMdKey- ?? (driveFilesQuery.isSuccess ? getSkillMdFileId(detailFiles) ?? getFirstSkillFileId(detailFiles) : undefined)- const previewQuery = useQuery({- ...consoleQuery.agent.byAgentId.drive.files.preview.get.queryOptions({- input: {- params: {- agent_id: agentId,- },- query: {- key: previewFileId ?? '',- },- },- }),- enabled: isPreviewOpen && !!previewFileId,- })- const selectedFile = detailFiles.find(file => file.id === previewFileId)- const isImagePreviewFile = selectedFile?.icon === 'image'- const downloadQuery = useQuery({- ...consoleQuery.agent.byAgentId.drive.files.download.get.queryOptions({- input: {- params: {- agent_id: agentId,- },- query: {- key: previewFileId ?? '',- },- },- }),- enabled: isPreviewOpen && !!previewFileId && (isImagePreviewFile || !!previewQuery.data?.binary),+ const detail = useAgentSkillDetail({+ apiContext,+ description: skill.description ?? t('agentDetail.configure.skills.tip'),+ isOpen: isPreviewOpen,+ skill,})return (@@ -158,24 +71,7 @@ export function AgentSkillItem({{isPreviewOpen && (<AgentSkillDetailDialogskillName={skill.name}- detail={{- description: skill.description ?? t('agentDetail.configure.skills.tip'),- files: detailFiles,- filePreview: {- binary: previewQuery.data?.binary,- content: previewQuery.data?.text ?? undefined,- downloadUrl: downloadQuery.data?.url,- fileName: selectedFile?.name,- isDownloadError: downloadQuery.isError,- isDownloadLoading: (isImagePreviewFile || !!previewQuery.data?.binary) && downloadQuery.isPending,- isError: previewQuery.isError,- isImage: isImagePreviewFile,- isLoading: previewQuery.isPending,- },- onSelectFile: file => setSelectedFileId(file.id),- selectedFileId: previewFileId,- sections: [],- }}+ detail={detail}/>)}</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.tsxindex d95bb162b3e..94c66e4b951 100644--- 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.tsx@@ -1,6 +1,8 @@'use client'import type { PostAgentByAgentIdSkillsUploadResponse } from '@dify/contracts/api/console/agent/types.gen'+import type { PostAppsByAppIdAgentSkillsUploadResponse } from '@dify/contracts/api/console/apps/types.gen'+import type { AgentDriveApiContext } from '../drive-context'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'@@ -18,25 +20,23 @@ const skillPackageExtensions = ['.zip', '.skill']const getSkillNameFromFile = (file: File) => file.name.replace(/\.(?:skill|zip)$/iu, '') || file.name-const toUploadedSkill = (response: PostAgentByAgentIdSkillsUploadResponse, file: File): AgentSkill => {+const toUploadedSkill = (+ response: PostAgentByAgentIdSkillsUploadResponse | PostAppsByAppIdAgentSkillsUploadResponse,+ file: File,+): AgentSkill => {const name = response.skill?.name?? response.manifest?.name?? getSkillNameFromFile(file)- const id = response.skill?.id- ?? response.skill?.skill_md_key+ const id = response.skill?.skill_md_key?? response.skill?.path?? namereturn {- 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,+ description: response.skill?.description ?? response.manifest?.description ?? undefined,+ archiveKey: response.skill?.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,}}@@ -146,12 +146,12 @@ function AgentSkillPackageUploader({}export function AgentSkillUploadDialog({- agentId,+ apiContext,onUploaded,open,onOpenChange,}: {- agentId: string+ apiContext: AgentDriveApiContextonUploaded?: (skill: AgentSkill) => voidopen: booleanonOpenChange: (open: boolean) => void@@ -159,21 +159,16 @@ export function AgentSkillUploadDialog({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 uploadAgentSkillMutation = useMutation(consoleQuery.agent.byAgentId.skills.upload.post.mutationOptions())+ const uploadWorkflowSkillMutation = useMutation(consoleQuery.apps.byAppId.agent.skills.upload.post.mutationOptions())+ const uploadSkillMutation = apiContext.workflow ? uploadWorkflowSkillMutation : uploadAgentSkillMutationconst handleUpload = () => {if (!file || uploadSkillMutation.isPending)return- uploadSkillMutation.mutate({- params: {- agent_id: agentId,- },- body: {- file,- },- }, {- onSuccess: (response) => {+ const options = {+ onSuccess: (response: PostAgentByAgentIdSkillsUploadResponse | PostAppsByAppIdAgentSkillsUploadResponse) => {toast.success(t('agentDetail.configure.skills.upload.success'))onUploaded?.(toUploadedSkill(response, file))setFile(undefined)@@ -182,20 +177,45 @@ export function AgentSkillUploadDialog({onError: () => {toast.error(t('agentDetail.configure.skills.upload.failed'))},- })+ }++ if (apiContext.workflow) {+ uploadWorkflowSkillMutation.mutate({+ params: {+ app_id: apiContext.workflow.appId,+ },+ query: {+ node_id: apiContext.workflow.nodeId,+ },+ body: {+ file,+ },+ }, options)+ return+ }++ uploadAgentSkillMutation.mutate({+ params: {+ agent_id: apiContext.agentId,+ },+ body: {+ file,+ },+ }, options)}const handleOpenChange = (nextOpen: boolean) => {if (!nextOpen) {- uploadSkillMutation.reset()+ uploadAgentSkillMutation.reset()+ uploadWorkflowSkillMutation.reset()setFile(undefined)}onOpenChange(nextOpen)}return (- <Dialog open={open} onOpenChange={handleOpenChange}>- <DialogContent>+ <Dialog open={open} onOpenChange={handleOpenChange} disablePointerDismissal>+ <DialogContent backdropProps={{ forceRender: true }} backdropClassName="fixed"><DialogCloseButton /><DialogTitle className="title-2xl-semi-bold text-text-primary">{t('agentDetail.configure.skills.upload.title')}diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/use-skill-detail.ts b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/use-skill-detail.tsnew file mode 100644index 00000000000..e254923b9b4--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/use-skill-detail.ts@@ -0,0 +1,308 @@+'use client'++import type { AgentDriveSkillFileResponse } from '@dify/contracts/api/console/agent/types.gen'+import type { AgentDriveApiContext } from '../drive-context'+import type { AgentSkillDetail } from './detail-dialog'+import type { AgentFileNode, AgentSkill } from '@/features/agent-v2/agent-composer/form-state'+import { useQuery } from '@tanstack/react-query'+import { useMemo, useState } from 'react'+import { consoleQuery } from '@/service/client'+import { getDriveFileIconType } from '../files/file-icon'++const DIFY_SKILL_FULL_ARCHIVE_NAME = '.DIFY-SKILL-FULL.zip'++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 getSkillRelativePath = (path: string, skillDrivePath: string) =>+ getSkillFileName(path, skillDrivePath).split('/').filter(Boolean).join('/')++const isSkillArchiveFile = (path: string) =>+ path === DIFY_SKILL_FULL_ARCHIVE_NAME || path.endsWith(`/${DIFY_SKILL_FULL_ARCHIVE_NAME}`)++const isSkillFolder = (file: AgentDriveSkillFileResponse) =>+ file.type === 'directory' || file.type === 'folder'++const toSkillFileNode = (item: AgentDriveSkillFileResponse, skillDrivePath: string): AgentFileNode => {+ const filePath = getSkillFileName(item.path, skillDrivePath)+ const fileName = item.name || filePath.split('/').pop() || filePath+ const id = item.drive_key+ ?? (item.path.startsWith(`${skillDrivePath}/`) ? item.path : `${skillDrivePath}/${item.path}`)++ return {+ driveKey: item.available_in_drive ? item.drive_key ?? undefined : undefined,+ icon: isSkillFolder(item)+ ? 'folder'+ : getDriveFileIconType({+ fileKind: item.type,+ fileName,+ mimeType: undefined,+ }),+ id,+ name: fileName,+ }+}++const sortSkillFileNodes = (files: AgentFileNode[]): AgentFileNode[] => [...files].sort((first, second) => {+ const firstIsFolder = first.icon === 'folder'+ const secondIsFolder = second.icon === 'folder'++ if (firstIsFolder !== secondIsFolder)+ return firstIsFolder ? -1 : 1++ return first.name.localeCompare(second.name)+}).map(file => file.children ? { ...file, children: sortSkillFileNodes(file.children) } : file)++const toSkillFileTree = (files: AgentDriveSkillFileResponse[], skillDrivePath: string): AgentFileNode[] => {+ const root: AgentFileNode[] = []+ const folders = new Map<string, AgentFileNode>()+ const seenFilePaths = new Set<string>()++ for (const file of files) {+ const relativePath = getSkillRelativePath(file.path, skillDrivePath)+ if (!relativePath || isSkillArchiveFile(relativePath))+ continue+ if (!isSkillFolder(file)) {+ if (seenFilePaths.has(relativePath))+ continue++ seenFilePaths.add(relativePath)+ }++ const segments = relativePath.split('/').filter(Boolean)+ let siblings = root+ let currentPath = ''++ segments.forEach((segment, index) => {+ currentPath = currentPath ? `${currentPath}/${segment}` : segment+ const isLeaf = index === segments.length - 1+ const isFolder = !isLeaf || isSkillFolder(file)++ if (isFolder) {+ const existingFolder = folders.get(currentPath)+ if (existingFolder) {+ siblings = existingFolder.children ?? []+ return+ }++ const folder: AgentFileNode = {+ icon: 'folder',+ id: currentPath,+ name: segment,+ children: [],+ }+ folders.set(currentPath, folder)+ siblings.push(folder)+ siblings = folder.children ?? []+ return+ }++ siblings.push({+ ...toSkillFileNode(file, skillDrivePath),+ name: segment,+ })+ })+ }++ return sortSkillFileNodes(root)+}++const countSkillPackageFiles = (files: AgentDriveSkillFileResponse[] | undefined, skillDrivePath: string) => {+ const filePaths = new Set<string>()++ for (const file of files ?? []) {+ if (isSkillFolder(file))+ continue++ const relativePath = getSkillRelativePath(file.path, skillDrivePath)+ if (!relativePath || isSkillArchiveFile(relativePath))+ continue++ filePaths.add(relativePath)+ }++ return filePaths.size+}++const getSkillMdFileId = (files: AgentFileNode[]): string | undefined => {+ for (const file of files) {+ if (file.icon !== 'folder' && file.name === 'SKILL.md')+ return file.id++ const childFileId = file.children ? getSkillMdFileId(file.children) : undefined+ if (childFileId)+ return childFileId+ }+}++const getFirstSkillFileId = (files: AgentFileNode[]): string | undefined => {+ for (const file of files) {+ if (file.icon !== 'folder')+ return file.id++ const childFileId = file.children ? getFirstSkillFileId(file.children) : undefined+ if (childFileId)+ return childFileId+ }+}++const findSkillFileById = (files: AgentFileNode[], fileId?: string): AgentFileNode | undefined => {+ if (!fileId)+ return undefined++ for (const file of files) {+ if (file.id === fileId)+ return file++ const childFile = file.children ? findSkillFileById(file.children, fileId) : undefined+ if (childFile)+ return childFile+ }+}++export function useAgentSkillDetail({+ apiContext,+ description,+ isOpen,+ skill,+}: {+ apiContext: AgentDriveApiContext+ description: string+ isOpen: boolean+ skill: AgentSkill+}): AgentSkillDetail {+ const [selectedFileId, setSelectedFileId] = useState<string>()+ const skillDrivePath = getSkillDrivePath(skill)+ const agentSkillInspectQuery = useQuery({+ ...consoleQuery.agent.byAgentId.drive.skills.bySkillPath.inspect.get.queryOptions({+ input: {+ params: {+ agent_id: apiContext.agentId,+ skill_path: skillDrivePath,+ },+ },+ }),+ enabled: isOpen && !apiContext.workflow,+ })+ const workflowSkillInspectQuery = useQuery({+ ...consoleQuery.apps.byAppId.agent.drive.skills.bySkillPath.inspect.get.queryOptions({+ input: {+ params: {+ app_id: apiContext.workflow?.appId ?? '',+ skill_path: skillDrivePath,+ },+ query: {+ node_id: apiContext.workflow?.nodeId,+ },+ },+ }),+ enabled: isOpen && !!apiContext.workflow,+ })+ const inspectQuery = apiContext.workflow ? workflowSkillInspectQuery : agentSkillInspectQuery+ const detailFiles = useMemo(+ () => toSkillFileTree(inspectQuery.data?.files ?? [], skillDrivePath),+ [inspectQuery.data?.files, skillDrivePath],+ )+ const previewFileId = selectedFileId+ ?? skill.skillMdKey+ ?? inspectQuery.data?.skill_md.key+ ?? (inspectQuery.isSuccess ? getSkillMdFileId(detailFiles) ?? getFirstSkillFileId(detailFiles) : undefined)+ const selectedFile = findSkillFileById(detailFiles, previewFileId)+ const isSkillMdSelected = previewFileId === inspectQuery.data?.skill_md.key+ || previewFileId === skill.skillMdKey+ || selectedFile?.name === 'SKILL.md'+ const selectedPreviewKey = isSkillMdSelected+ ? undefined+ : selectedFile?.driveKey+ const agentPreviewQuery = useQuery({+ ...consoleQuery.agent.byAgentId.drive.files.preview.get.queryOptions({+ input: {+ params: {+ agent_id: apiContext.agentId,+ },+ query: {+ key: selectedPreviewKey ?? '',+ },+ },+ }),+ enabled: isOpen && !!selectedPreviewKey && !apiContext.workflow,+ })+ const workflowPreviewQuery = useQuery({+ ...consoleQuery.apps.byAppId.agent.drive.files.preview.get.queryOptions({+ input: {+ params: {+ app_id: apiContext.workflow?.appId ?? '',+ },+ query: {+ node_id: apiContext.workflow?.nodeId,+ key: selectedPreviewKey ?? '',+ },+ },+ }),+ enabled: isOpen && !!selectedPreviewKey && !!apiContext.workflow,+ })+ const previewQuery = apiContext.workflow ? workflowPreviewQuery : agentPreviewQuery+ const isImagePreviewFile = selectedFile?.icon === 'image'+ const agentDownloadQuery = useQuery({+ ...consoleQuery.agent.byAgentId.drive.files.download.get.queryOptions({+ input: {+ params: {+ agent_id: apiContext.agentId,+ },+ query: {+ key: selectedPreviewKey ?? '',+ },+ },+ }),+ enabled:+ isOpen+ && !!selectedPreviewKey+ && (isImagePreviewFile || !!previewQuery.data?.binary)+ && !apiContext.workflow,+ })+ const workflowDownloadQuery = useQuery({+ ...consoleQuery.apps.byAppId.agent.drive.files.download.get.queryOptions({+ input: {+ params: {+ app_id: apiContext.workflow?.appId ?? '',+ },+ query: {+ node_id: apiContext.workflow?.nodeId,+ key: selectedPreviewKey ?? '',+ },+ },+ }),+ enabled:+ isOpen+ && !!selectedPreviewKey+ && (isImagePreviewFile || !!previewQuery.data?.binary)+ && !!apiContext.workflow,+ })+ const downloadQuery = apiContext.workflow ? workflowDownloadQuery : agentDownloadQuery++ return {+ description,+ fileCount: countSkillPackageFiles(inspectQuery.data?.files, skillDrivePath),+ files: detailFiles,+ filePreview: {+ binary: isSkillMdSelected ? inspectQuery.data?.skill_md.binary : previewQuery.data?.binary,+ content: isSkillMdSelected ? inspectQuery.data?.skill_md.text ?? undefined : previewQuery.data?.text ?? undefined,+ downloadUrl: downloadQuery.data?.url,+ fileName: selectedFile?.name,+ isDownloadError: downloadQuery.isError,+ isDownloadLoading: !!selectedPreviewKey && (isImagePreviewFile || !!previewQuery.data?.binary) && downloadQuery.isPending,+ isError: isSkillMdSelected ? inspectQuery.isError : !!selectedPreviewKey && previewQuery.isError,+ isImage: isImagePreviewFile,+ isLoading: isSkillMdSelected ? inspectQuery.isPending : !!selectedPreviewKey && previewQuery.isPending,+ },+ onSelectFile: file => setSelectedFileId(file.id),+ selectedFileId: previewFileId,+ sections: [],+ }+}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.tsxindex 0c14cb78117..801033033cc 100644--- 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.tsx@@ -339,6 +339,32 @@ describe('AgentTools', () => {name: 'agentV2.agentDetail.configure.tools.removeAction:{"name":"Lark CLI"}',})).not.toBeInTheDocument()})++ it('should keep CLI tool row actions out of layout until hover or focus', () => {+ renderAgentTools()++ const editButton = screen.getByRole('button', {+ name: 'agentV2.agentDetail.configure.tools.editAction:{"name":"Lark CLI"}',+ })+ const removeButton = screen.getByRole('button', {+ name: 'agentV2.agentDetail.configure.tools.removeAction:{"name":"Lark CLI"}',+ })+ const actionGroup = editButton.parentElement++ expect(actionGroup).toHaveClass('hidden')+ expect(actionGroup).toHaveClass(+ 'group-focus-within:flex',+ 'group-hover:flex',+ )+ expect(removeButton).toHaveClass(+ 'hover:bg-state-destructive-hover',+ 'hover:text-text-destructive',+ )+ expect(screen.getByText('agentV2.agentDetail.configure.tools.cliTool')).toHaveClass(+ 'group-focus-within:hidden',+ 'group-hover:hidden',+ )+ })})describe('Display Metadata', () => {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.tsxindex 77910c149b7..763bd30e31b 100644--- 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.tsx@@ -114,6 +114,25 @@ describe('CliToolDialog', () => {})describe('Actions', () => {+ it('should keep the form open when the backdrop is clicked', async () => {+ const user = userEvent.setup()+ const { onOpenChange } = renderCliToolDialog()++ const dialog = screen.getByRole('dialog', {+ name: 'agentV2.agentDetail.configure.tools.cliDialog.title',+ })+ const backdrop = document.body.querySelector('.bg-background-overlay') as HTMLElement+ await user.click(backdrop)++ expect(onOpenChange).not.toHaveBeenCalledWith(false)+ expect(dialog).toBeInTheDocument()++ await user.click(screen.getByRole('button', {+ name: 'common.operation.cancel',+ }))+ expect(onOpenChange).toHaveBeenCalledWith(false)+ })+it('should show save action when editing a CLI tool', () => {renderCliToolDialog({mode: 'edit',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.tsxindex 0d3cecb68dd..0e60a0ea9f2 100644--- 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.tsx@@ -127,10 +127,10 @@ export function CliToolDialog({}, [onDeleteCliTool, onOpenChange, tool])return (- <Dialog open={open} onOpenChange={handleOpenChange}>+ <Dialog open={open} onOpenChange={handleOpenChange} disablePointerDismissal><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" />+ <DialogCloseButton /><DialogTitle className="title-2xl-semi-bold text-text-primary">{t(mode === 'edit' ? 'agentDetail.configure.tools.cliDialog.editTitle' : 'agentDetail.configure.tools.cliDialog.title')}</DialogTitle>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.tsxindex c95ce1c635e..a2c46b70026 100644--- a/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/chat.spec.tsx+++ b/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/chat.spec.tsx@@ -1,10 +1,12 @@import type { ComponentProps } from 'react'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'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 useChatMock = vi.hoisted(() => vi.fn())const handleSendMock = vi.hoisted(() => vi.fn())const stopCallbackRef = vi.hoisted(() => ({current: undefined as undefined | ((taskId: string) => void),@@ -32,16 +34,16 @@ vi.mock('@/next/dynamic', () => ({}))vi.mock('@/app/components/base/chat/chat/hooks', () => ({- useChat: (+ useChat: useChatMock.mockImplementation((_config: unknown,_formSettings: unknown,- _chatList: unknown[],+ chatList: unknown[],stopCallback: (taskId: string) => void,) => {stopCallbackRef.current = stopCallbackreturn {- chatList: [],+ chatList,setTargetMessageId: vi.fn(),isResponding: false,handleSend: handleSendMock,@@ -51,7 +53,7 @@ vi.mock('@/app/components/base/chat/chat/hooks', () => ({handleAnnotationEdited: vi.fn(),handleAnnotationRemoved: vi.fn(),}- },+ }),}))vi.mock('@/context/app-context', () => ({@@ -103,6 +105,13 @@ vi.mock('@/service/client', () => ({function renderPreviewChat(props?: Partial<ComponentProps<typeof AgentPreviewChat>>) {const store = createStore()+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: {+ retry: false,+ },+ },+ })store.set(agentComposerModelAtom, {provider: 'openai',model: 'gpt-4',@@ -110,19 +119,22 @@ function renderPreviewChat(props?: Partial<ComponentProps<typeof AgentPreviewChastore.set(agentComposerPromptAtom, 'You are helpful.')return render(- <JotaiProvider store={store}>- <AgentPreviewChat- agentId="agent-1"- clearChatList={false}- onClearChatListChange={vi.fn()}- {...props}- />- </JotaiProvider>,+ <QueryClientProvider client={queryClient}>+ <JotaiProvider store={store}>+ <AgentPreviewChat+ agentId="agent-1"+ clearChatList={false}+ onClearChatListChange={vi.fn()}+ {...props}+ />+ </JotaiProvider>+ </QueryClientProvider>,)}describe('AgentPreviewChat', () => {beforeEach(() => {+ useChatMock.mockClear()handleSendMock.mockClear()chatMessagesGetMock.mockResolvedValue({ data: [] })suggestedQuestionsGetMock.mockResolvedValue({ data: [] })@@ -130,6 +142,64 @@ describe('AgentPreviewChat', () => {stopCallbackRef.current = undefined})+ it('should initialize preview chat with the stable debug conversation history', async () => {+ chatMessagesGetMock.mockResolvedValue({+ data: [+ {+ id: 'message-1',+ conversation_id: 'debug-conversation-1',+ query: 'previous question',+ answer: 'previous answer',+ inputs: {},+ message: [],+ message_files: [],+ agent_thoughts: [],+ feedbacks: [],+ answer_tokens: 3,+ message_tokens: 2,+ provider_response_latency: 1,+ status: 'success',+ from_source: 'console',+ },+ ],+ })++ renderPreviewChat({+ debugConversationId: 'debug-conversation-1',+ })++ await waitFor(() => expect(useChatMock).toHaveBeenCalled())++ expect(chatMessagesGetMock).toHaveBeenCalledWith({+ params: {+ agent_id: 'agent-1',+ },+ query: {+ conversation_id: 'debug-conversation-1',+ },+ })+ expect(useChatMock).toHaveBeenLastCalledWith(+ expect.any(Object),+ expect.any(Object),+ expect.arrayContaining([+ expect.objectContaining({+ id: 'question-message-1',+ content: 'previous question',+ children: expect.arrayContaining([+ expect.objectContaining({+ id: 'message-1',+ content: 'previous answer',+ }),+ ]),+ }),+ ]),+ expect.any(Function),+ false,+ expect.any(Function),+ 'debug-conversation-1',+ )+ })+it('should save draft before sending preview chat through the agent chat endpoints', async () => {const saveDraftBeforeRun = vi.fn().mockResolvedValue(undefined)renderPreviewChat({diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/versions-panel.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/versions-panel.spec.tsxnew file mode 100644index 00000000000..206c46732f7--- /dev/null+++ b/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/versions-panel.spec.tsx@@ -0,0 +1,94 @@+import type { AgentConfigSnapshotSummaryResponse } from '@dify/contracts/api/console/agent/types.gen'+import { fireEvent, render, screen } from '@testing-library/react'+import { AgentPreviewVersionsPanel } from '../versions-panel'++const versions: AgentConfigSnapshotSummaryResponse[] = [+ {+ id: 'version-2',+ version: 2,+ version_note: 'Published update',+ created_at: 1710000100,+ created_by: 'Alice',+ },+ {+ id: 'version-1',+ version: 1,+ version_note: 'Initial release',+ created_at: 1710000000,+ created_by: 'Bob',+ },+]++vi.mock('@tanstack/react-query', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@tanstack/react-query')>()++ return {+ ...actual,+ useQuery: () => ({+ data: { data: versions },+ isPending: false,+ }),+ }+})++vi.mock('@/hooks/use-timestamp', () => ({+ default: () => ({+ formatTime: (timestamp: number) => `formatted-${timestamp}`,+ }),+}))++vi.mock('@/service/client', () => ({+ consoleQuery: {+ agent: {+ byAgentId: {+ versions: {+ get: {+ queryOptions: () => ({ queryKey: ['agent-versions'] }),+ },+ },+ },+ },+ },+}))++describe('AgentPreviewVersionsPanel', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ describe('Version selection', () => {+ it('should notify the selected version when a version row is clicked', () => {+ const handleSelectVersion = vi.fn()++ render(+ <AgentPreviewVersionsPanel+ agentId="agent-1"+ activeVersionId="version-2"+ onSelectVersion={handleSelectVersion}+ onClose={vi.fn()}+ />,+ )++ fireEvent.click(screen.getByRole('button', { name: /Initial release/i }))++ expect(handleSelectVersion).toHaveBeenCalledWith('version-1')+ })++ it('should notify null when the current draft row is clicked', () => {+ const handleSelectVersion = vi.fn()++ render(+ <AgentPreviewVersionsPanel+ agentId="agent-1"+ activeVersionId="version-2"+ onSelectVersion={handleSelectVersion}+ onClose={vi.fn()}+ />,+ )++ fireEvent.click(screen.getByRole('button', { name: /currentDraft/i }))++ expect(handleSelectVersion).toHaveBeenCalledWith(null)+ })+ })+})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.tsxindex 764ba65f498..a3127b4bd49 100644--- a/web/features/agent-v2/agent-detail/configure/components/preview/chat.tsx+++ b/web/features/agent-v2/agent-detail/configure/components/preview/chat.tsx@@ -5,21 +5,30 @@ import type {AgentIconType,AgentSoulConfig,AgentSoulDifyToolConfig,+ AgentThought,+ MessageDetailResponse,} from '@dify/contracts/api/console/agent/types.gen'-import type { ChatConfig, ChatItem, OnSend } from '@/app/components/base/chat/types'+import type { FeedbackType, IChatItem, ThoughtItem } from '@/app/components/base/chat/chat/type'+import type { ChatConfig, ChatItem, ChatItemInTree, 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 type { MessageRating } from '@/models/log'+import type { FileResponse } from '@/types/workflow'import { Avatar } from '@langgenius/dify-ui/avatar'import { cn } from '@langgenius/dify-ui/cn'+import { useQuery } from '@tanstack/react-query'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 { buildChatItemTree, getLastAnswer, isValidGeneratedAnswer } from '@/app/components/base/chat/utils'+import { getProcessedFilesFromResponse } from '@/app/components/base/file-uploader/utils'+import Loading from '@/app/components/base/loading'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 { addFileInfos, sortAgentSorts } from '@/app/components/tools/utils'import { InputVarType } from '@/app/components/workflow/types'import { DEFAULT_CHAT_PROMPT_CONFIG, DEFAULT_COMPLETION_PROMPT_CONFIG } from '@/config'import { useAppContext } from '@/context/app-context'@@ -151,6 +160,121 @@ const fetchAgentConversationMessages = (agentId: string, conversationId: string)})}+const toFileResponse = (file: NonNullable<MessageDetailResponse['message_files']>[number]): FileResponse => ({+ related_id: file.id ?? file.upload_file_id,+ extension: '',+ filename: file.filename,+ size: file.size ?? 0,+ mime_type: file.mime_type ?? '',+ transfer_method: file.transfer_method as TransferMethod,+ type: file.type,+ url: file.url ?? '',+ upload_file_id: file.upload_file_id ?? '',+ remote_url: file.url ?? '',+})++const toLogMessages = (message: MessageDetailResponse['message'], answer: string, files: MessageDetailResponse['message_files']) => {+ if (!Array.isArray(message))+ return []++ const logMessages = message as IChatItem['log']+ if (logMessages?.at(-1)?.role === 'assistant')+ return logMessages++ return [+ ...(logMessages ?? []),+ {+ role: 'assistant',+ text: answer,+ files: getProcessedFilesFromResponse((files?.filter(file => file.belongs_to === 'assistant') || []).map(toFileResponse)),+ },+ ]+}++const toAgentThoughtItem = (thought: AgentThought, conversationId: string): ThoughtItem => ({+ id: thought.id,+ tool: thought.tool ?? '',+ thought: thought.thought ?? '',+ tool_input: thought.tool_input ?? '',+ message_id: thought.message_id,+ conversation_id: conversationId,+ observation: thought.observation ?? '',+ position: thought.position,+ files: thought.files,+})++const toFeedback = (feedback: NonNullable<MessageDetailResponse['feedbacks']>[number] | undefined): FeedbackType | undefined => {+ if (!feedback)+ return undefined++ const rating = feedback.rating as MessageRating+ if (rating !== 'like' && rating !== 'dislike' && rating !== null)+ return undefined++ return {+ rating,+ content: feedback.content,+ }+}++type AgentDebugMessageWithLegacyAnswer = MessageDetailResponse & {+ answer?: string | null+}++const getAgentDebugMessageAnswer = (message: MessageDetailResponse) => {+ const legacyAnswer = (message as AgentDebugMessageWithLegacyAnswer).answer++ return message.re_sign_file_url_answer ?? legacyAnswer ?? ''+}++function getFormattedAgentDebugChatTree(messages: MessageDetailResponse[]): ChatItemInTree[] {+ const chatList: IChatItem[] = []++ messages.forEach((item) => {+ const answer = getAgentDebugMessageAnswer(item)+ const questionFiles = item.message_files?.filter(file => file.belongs_to === 'user') || []+ const answerFiles = item.message_files?.filter(file => file.belongs_to === 'assistant') || []+ const answerTokens = item.answer_tokens ?? 0+ const messageTokens = item.message_tokens ?? 0+ const latency = item.provider_response_latency ?? 0++ chatList.push({+ id: `question-${item.id}`,+ content: item.query,+ isAnswer: false,+ message_files: getProcessedFilesFromResponse(questionFiles.map(toFileResponse)),+ parentMessageId: item.parent_message_id || undefined,+ })+ chatList.push({+ id: item.id,+ content: answer,+ agent_thoughts: addFileInfos(+ sortAgentSorts((item.agent_thoughts ?? []).map(thought => toAgentThoughtItem(thought, item.conversation_id))),+ item.message_files as unknown as FileEntity[],+ ),+ feedback: toFeedback(item.feedbacks?.find(feedback => feedback.from_source === 'user')),+ isAnswer: true,+ log: toLogMessages(item.message, answer, item.message_files),+ message_files: getProcessedFilesFromResponse(answerFiles.map(toFileResponse)),+ parentMessageId: `question-${item.id}`,+ workflow_run_id: item.workflow_run_id ?? undefined,+ conversationId: item.conversation_id,+ input: {+ inputs: item.inputs,+ query: item.query,+ },+ more: {+ time: '',+ tokens: answerTokens + messageTokens,+ latency: latency.toFixed(2),+ tokens_per_second: latency > 0 ? (answerTokens / latency).toFixed(2) : undefined,+ },+ })+ })++ return buildChatItemTree(chatList)+}+const fetchAgentSuggestedQuestions = (agentId: string, messageId: string) => {return consoleClient.agent.byAgentId.chatMessages.byMessageId.suggestedQuestions.get({params: {@@ -302,6 +426,67 @@ export function AgentPreviewChat({agentName,agentSoulConfig,clearChatList,+ debugConversationId,+ onClearChatListChange,+ onSaveDraftBeforeRun,+}: {+ agentId: string+ agentIcon?: string | null+ agentIconBackground?: string | null+ agentIconType?: AgentIconType | null+ agentName?: string+ agentSoulConfig?: AgentSoulConfig+ clearChatList: boolean+ debugConversationId?: string | null+ onClearChatListChange: (clearChatList: boolean) => void+ onSaveDraftBeforeRun?: () => Promise<void>+}) {+ const historyQuery = useQuery({+ queryKey: ['agent-preview-debug-conversation', agentId, debugConversationId],+ queryFn: () => fetchAgentConversationMessages(agentId, debugConversationId!),+ enabled: !!debugConversationId,+ })+ const initialChatTree = useMemo(+ () => getFormattedAgentDebugChatTree(historyQuery.data?.data ?? []),+ [historyQuery.data?.data],+ )++ if (debugConversationId && historyQuery.isPending) {+ return (+ <div className="flex h-full items-center justify-center">+ <Loading type="app" />+ </div>+ )+ }++ return (+ <AgentPreviewChatSession+ key={`${debugConversationId ?? 'new'}-${historyQuery.dataUpdatedAt}`}+ agentId={agentId}+ agentIcon={agentIcon}+ agentIconBackground={agentIconBackground}+ agentIconType={agentIconType}+ agentName={agentName}+ agentSoulConfig={agentSoulConfig}+ clearChatList={clearChatList}+ debugConversationId={debugConversationId}+ initialChatTree={initialChatTree}+ onClearChatListChange={onClearChatListChange}+ onSaveDraftBeforeRun={onSaveDraftBeforeRun}+ />+ )+}++function AgentPreviewChatSession({+ agentId,+ agentIcon,+ agentIconBackground,+ agentIconType,+ agentName,+ agentSoulConfig,+ clearChatList,+ debugConversationId,+ initialChatTree,onClearChatListChange,onSaveDraftBeforeRun,}: {@@ -312,6 +497,8 @@ export function AgentPreviewChat({agentName?: stringagentSoulConfig?: AgentSoulConfigclearChatList: boolean+ debugConversationId?: string | null+ initialChatTree: ChatItemInTree[]onClearChatListChange: (clearChatList: boolean) => voidonSaveDraftBeforeRun?: () => Promise<void>}) {@@ -349,12 +536,13 @@ export function AgentPreviewChat({inputs,inputsForm,},- [],+ initialChatTree,(taskId) => {void stopAgentChatMessageResponding(agentId, taskId)},clearChatList,onClearChatListChange,+ debugConversationId ?? undefined,)const doSend: OnSend = useCallback(async (message, files, isRegenerate = false, parentAnswer: ChatItem | null = null) => {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.tsxindex 45a54f14394..329b6e6d2de 100644--- 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.tsx@@ -10,6 +10,7 @@ import { consoleQuery } from '@/service/client'type AgentPreviewVersionsPanelProps = {agentId: stringactiveVersionId?: string | null+ onSelectVersion: (versionId: string | null) => voidonClose: () => void}@@ -63,12 +64,14 @@ function VersionItem({isLatest,isFirst,isLast,+ onSelect,}: {version: AgentConfigSnapshotSummaryResponseactiveVersionId?: string | nullisLatest: booleanisFirst: booleanisLast: boolean+ onSelect: (versionId: string) => void}) {const { t } = useTranslation('agentV2')const { t: tWorkflow } = useTranslation('workflow')@@ -78,6 +81,8 @@ function VersionItem({return (<buttontype="button"+ aria-current={isActive ? 'true' : undefined}+ onClick={() => onSelect(version.id)}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',@@ -107,27 +112,40 @@ function VersionItem({}function CurrentDraftItem({+ isActive,isLast,+ onSelect,}: {+ isActive: booleanisLast: boolean+ onSelect: () => void}) {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} />+ <button+ type="button"+ aria-current={isActive ? 'true' : undefined}+ onClick={onSelect}+ className={cn(+ '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 isLast={isLast} /><div className="min-w-0 flex-1 py-1">- <p className="truncate system-sm-semibold text-text-secondary">+ <p className={cn('truncate system-sm-semibold', isActive ? 'text-text-accent' : 'text-text-secondary')}>{tWorkflow('versionHistory.currentDraft')}</p></div>- </div>+ </button>)}export function AgentPreviewVersionsPanel({agentId,activeVersionId,+ onSelectVersion,onClose,}: AgentPreviewVersionsPanelProps) {const { t } = useTranslation('agentV2')@@ -182,7 +200,11 @@ export function AgentPreviewVersionsPanel({)}{!versionsQuery.isPending && versions.length > 0 && (<div className="flex flex-col gap-px">- <CurrentDraftItem isLast={versions.length === 0} />+ <CurrentDraftItem+ isActive={!activeVersionId}+ isLast={versions.length === 0}+ onSelect={() => onSelectVersion(null)}+ />{versions.map((version, index) => (<VersionItemkey={version.id}@@ -191,6 +213,7 @@ export function AgentPreviewVersionsPanel({isLatest={version.id === latestVersionId}isFirst={false}isLast={index === versions.length - 1}+ onSelect={onSelectVersion}/>))}</div>diff --git a/web/features/agent-v2/agent-detail/configure/page.tsx b/web/features/agent-v2/agent-detail/configure/page.tsxindex ee2f2f05d62..c242a28061f 100644--- a/web/features/agent-v2/agent-detail/configure/page.tsx+++ b/web/features/agent-v2/agent-detail/configure/page.tsx@@ -38,10 +38,11 @@ function AgentConfigurePageContent({agentId,}: AgentConfigurePageProps) {const { t } = useTranslation('agentV2')- const configureData = useAgentConfigureData(agentId)+ const [selectedVersionId, setSelectedVersionId] = useState<string | null>(null)+ const configureData = useAgentConfigureData(agentId, selectedVersionId)const isConfigureDataPending = configureData.agentQuery.isPending|| configureData.composerQuery.isPending- || (configureData.shouldLoadPublishedVersion && configureData.versionQuery.isPending)+ || (configureData.shouldLoadVersion && configureData.versionQuery.isPending)if (isConfigureDataPending) {return (@@ -59,6 +60,7 @@ function AgentConfigurePageContent({<AgentConfigurePageLoadedContentagentId={agentId}configureData={configureData}+ onSelectVersion={setSelectedVersionId}/>)}@@ -66,8 +68,10 @@ function AgentConfigurePageContent({function AgentConfigurePageLoadedContent({agentId,configureData,+ onSelectVersion,}: AgentConfigurePageProps & {configureData: ReturnType<typeof useAgentConfigureData>+ onSelectVersion: (versionId: string | null) => void}) {const { t } = useTranslation('agentV2')const [showChatFeatures, setShowChatFeatures] = useState(false)@@ -77,11 +81,13 @@ function AgentConfigurePageLoadedContent({agentQuery,composerQuery,versionQuery,+ selectedVersionId,activeVersionId,activeConfigSnapshot,agentSoulConfig,} = configureDataconst agentIconType = agentQuery.data?.icon_type as AgentIconType | null | undefined+ const isViewingVersion = !!selectedVersionIduseHydrateAgentSoulConfigDraft({agentId,@@ -102,7 +108,7 @@ function AgentConfigurePageLoadedContent({agentId,baseConfig: agentSoulConfig,currentModel,- enabled: composerQuery.isSuccess,+ enabled: composerQuery.isSuccess && !selectedVersionId,})return (@@ -121,9 +127,12 @@ function AgentConfigurePageLoadedContent({textGenerationModelList={textGenerationModelList}draftSavedAt={draftSavedAt}isPublishing={isPublishing}+ readOnly={isViewingVersion}+ selectedVersionSnapshot={isViewingVersion ? activeConfigSnapshot : undefined}onSelectModel={setConfigureModel}onPublish={publishDraft}onOpenVersions={() => setShowPreviewVersions(true)}+ onExitVersions={() => onSelectVersion(null)}/>{/* Preview area */}@@ -144,6 +153,7 @@ function AgentConfigurePageLoadedContent({agentName={agentQuery.data?.name}agentSoulConfig={agentSoulConfig}clearChatList={clearPreviewChat}+ debugConversationId={agentQuery.data?.debug_conversation_id}onClearChatListChange={setClearPreviewChat}onSaveDraftBeforeRun={saveDraft}/>@@ -154,6 +164,7 @@ function AgentConfigurePageLoadedContent({<AgentPreviewVersionsPanelagentId={agentId}activeVersionId={activeVersionId}+ onSelectVersion={onSelectVersion}onClose={() => setShowPreviewVersions(false)}/>)}@@ -185,7 +196,7 @@ function AgentPreviewChatWithDraftConfig({)}-function useAgentConfigureData(agentId: string) {+function useAgentConfigureData(agentId: string, selectedVersionId: string | null) {const agentQuery = useQuery(consoleQuery.agent.byAgentId.get.queryOptions({input: {params: {@@ -200,27 +211,31 @@ function useAgentConfigureData(agentId: string) {},},}))- const activeVersionId = composerQuery.data?.active_config_snapshot?.id- const shouldLoadPublishedVersion = !composerQuery.data?.agent_soul+ const publishedVersionId = composerQuery.data?.active_config_snapshot?.id+ const shouldLoadPublishedVersion = !selectedVersionId && !composerQuery.data?.agent_soul+ const versionIdToLoad = selectedVersionId ?? (shouldLoadPublishedVersion ? publishedVersionId : undefined)+ const shouldLoadVersion = !!versionIdToLoadconst versionQuery = useQuery(consoleQuery.agent.byAgentId.versions.byVersionId.get.queryOptions({- input: activeVersionId && shouldLoadPublishedVersion+ input: versionIdToLoad? {params: {agent_id: agentId,- version_id: activeVersionId,+ version_id: versionIdToLoad,},}: 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+ const activeVersionId = selectedVersionId ?? (shouldLoadPublishedVersion ? publishedVersionId : null)+ const activeConfigSnapshot = selectedVersionId ? versionDetail : (composerQuery.data?.active_config_snapshot ?? versionDetail)+ const agentSoulConfig = selectedVersionId ? versionDetail?.config_snapshot : (composerQuery.data?.agent_soul ?? versionDetail?.config_snapshot)return {agentQuery,composerQuery,versionQuery,- shouldLoadPublishedVersion,+ shouldLoadVersion,+ selectedVersionId,activeVersionId,activeConfigSnapshot,agentSoulConfig,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.tsindex f4410b20eb8..3987df0e16b 100644--- a/web/features/agent-v2/agent-detail/configure/use-agent-configure-sync.ts+++ b/web/features/agent-v2/agent-detail/configure/use-agent-configure-sync.ts@@ -40,7 +40,6 @@ export function useAgentConfigureSync({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)@@ -60,13 +59,19 @@ export function useAgentConfigureSync({const saveComposerMutation = useMutation(consoleQuery.agent.byAgentId.composer.put.mutationOptions(),)+ const publishComposerMutation = 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({+ const composerMutation = saveStrategy === 'save_as_new_version'+ ? publishComposerMutation+ : saveComposerMutation+ const composerState = await composerMutation.mutateAsync({params: {agent_id: agentId,},@@ -152,21 +157,17 @@ export function useAgentConfigureSync({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,+ isPublishing: publishComposerMutation.isPending,publishDraft,saveDraft,}diff --git a/web/features/agent-v2/agent-detail/logs/__tests__/page.spec.tsx b/web/features/agent-v2/agent-detail/logs/__tests__/page.spec.tsxnew file mode 100644index 00000000000..0f625075699--- /dev/null+++ b/web/features/agent-v2/agent-detail/logs/__tests__/page.spec.tsx@@ -0,0 +1,270 @@+import type { AgentLogListResponse, AgentLogSourceListResponse } from '@dify/contracts/api/console/agent/types.gen'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { render, screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { AgentLogsPage } from '../page'++type AgentLogsQueryInput = {+ input: {+ params: {+ agent_id: string+ }+ query?: Record<string, unknown>+ }+}++const mocks = vi.hoisted(() => ({+ logsQueryFn: vi.fn(),+ logSourcesQueryFn: vi.fn(),+ logsQueryOptions: vi.fn((input: AgentLogsQueryInput) => ({+ queryKey: ['agent-logs', input],+ queryFn: () => mocks.logsQueryFn(input),+ })),+ logSourcesQueryOptions: vi.fn((input: AgentLogsQueryInput) => ({+ queryKey: ['agent-log-sources', input],+ queryFn: () => mocks.logSourcesQueryFn(input),+ })),+}))++vi.mock('@/context/i18n', () => ({+ useDocLink: () => (path: string) => `https://docs.example.com${path}`,+}))++vi.mock('@/hooks/use-timestamp', () => ({+ default: () => ({+ formatTime: (value: number) => `formatted-${value}`,+ }),+}))++vi.mock('@/service/client', () => ({+ consoleQuery: {+ agent: {+ byAgentId: {+ logSources: {+ get: {+ queryOptions: mocks.logSourcesQueryOptions,+ },+ },+ logs: {+ get: {+ queryOptions: mocks.logsQueryOptions,+ },+ },+ },+ },+ },+}))++const emptyLogsResponse: AgentLogListResponse = {+ data: [],+ has_more: false,+ limit: 25,+ page: 1,+ total: 0,+}++const populatedLogsResponse: AgentLogListResponse = {+ data: [+ {+ conversation_id: 'conversation-1',+ created_at: 1781660000,+ end_user_id: 'end-user-1',+ id: 'log-1',+ message_count: 3,+ operation_rate: null,+ source: {+ app_icon: '📙',+ app_icon_background: '#FFF4ED',+ app_icon_type: 'emoji',+ app_id: 'webapp-app-id',+ app_name: 'Book Translation',+ id: 'webapp:webapp-app-id',+ type: 'webapp',+ },+ status: 'success',+ title: 'Previous conversation',+ unread: false,+ updated_at: 1781661000,+ user_rate: null,+ },+ ],+ has_more: false,+ limit: 25,+ page: 1,+ total: 1,+}++const logSourcesResponse: AgentLogSourceListResponse = {+ data: [],+ groups: [+ {+ label: 'Webapp',+ type: 'webapp',+ sources: [+ {+ app_icon: '📙',+ app_icon_background: '#FFF4ED',+ app_icon_type: 'emoji',+ app_id: 'webapp-app-id',+ app_name: 'Book Translation',+ id: 'webapp:webapp-app-id',+ type: 'webapp',+ },+ ],+ },+ {+ label: 'Workflow',+ type: 'workflow',+ sources: [+ {+ app_icon: '🖌',+ app_icon_background: '#EEF4FF',+ app_icon_type: 'emoji',+ app_id: 'workflow-app-id',+ app_name: 'SVG Logo Design',+ id: 'workflow:workflow-app-id:workflow-id:v3:agent-node-id',+ node_id: 'agent-node-id',+ type: 'workflow',+ workflow_id: 'workflow-id',+ workflow_version: 'v3',+ },+ ],+ },+ ],+}++const renderPage = () => {+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: {+ retry: false,+ },+ },+ })++ render(+ <QueryClientProvider client={queryClient}>+ <AgentLogsPage agentId="agent-1" />+ </QueryClientProvider>,+ )++ return queryClient+}++const getLatestLogsQueryInput = () => {+ const latestCall = mocks.logsQueryOptions.mock.calls.at(-1)++ if (!latestCall)+ throw new Error('Expected logs query options to be called')++ return latestCall[0]+}++describe('AgentLogsPage', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mocks.logsQueryFn.mockResolvedValue(emptyLogsResponse)+ mocks.logSourcesQueryFn.mockResolvedValue(logSourcesResponse)+ })++ describe('Query contract', () => {+ it('should request logs with generated contract filters by default', async () => {+ renderPage()++ await waitFor(() => {+ expect(mocks.logsQueryOptions).toHaveBeenCalled()+ })++ expect(getLatestLogsQueryInput()).toEqual({+ input: {+ params: {+ agent_id: 'agent-1',+ },+ query: expect.objectContaining({+ keyword: undefined,+ limit: 25,+ page: 1,+ sort_by: 'created_at',+ sort_order: 'desc',+ }),+ },+ })+ expect(getLatestLogsQueryInput().input.query).not.toHaveProperty('source')+ expect(getLatestLogsQueryInput().input.query).not.toHaveProperty('sources')+ })++ it('should send multiple source ids through the sources array filter', async () => {+ const user = userEvent.setup()++ renderPage()++ await user.click(await screen.findByRole('combobox', { name: 'agentV2.agentDetail.logs.filters.source.label' }))+ await user.click(await screen.findByRole('option', { name: /Book Translation/ }))+ await user.click(await screen.findByRole('option', { name: /SVG Logo Design/ }))++ await waitFor(() => {+ expect(getLatestLogsQueryInput().input.query).toEqual(expect.objectContaining({+ sources: [+ 'webapp:webapp-app-id',+ 'workflow:workflow-app-id:workflow-id:v3:agent-node-id',+ ],+ }))+ })++ expect(getLatestLogsQueryInput().input.query).not.toHaveProperty('source')+ })++ it('should translate Sort selection into sort_by and sort_order query params', async () => {+ const user = userEvent.setup()++ renderPage()++ await user.click(screen.getByRole('button', { name: /appLog\.filter\.sortBy/ }))+ await user.click(await screen.findByRole('menuitemradio', { name: 'agentV2.agentDetail.logs.filters.sort.lastUpdatedTime' }))++ await waitFor(() => {+ expect(getLatestLogsQueryInput().input.query).toEqual(expect.objectContaining({+ sort_by: 'updated_at',+ sort_order: 'desc',+ }))+ })++ await user.click(screen.getByRole('button', { name: 'appLog.filter.ascending' }))++ await waitFor(() => {+ expect(getLatestLogsQueryInput().input.query).toEqual(expect.objectContaining({+ sort_by: 'updated_at',+ sort_order: 'asc',+ }))+ })+ })++ it('should keep existing log rows visible while filter changes refetch', async () => {+ const user = userEvent.setup()+ let resolveNextLogs: (value: AgentLogListResponse) => void = () => undefined+ const nextLogsPromise = new Promise<AgentLogListResponse>((resolve) => {+ resolveNextLogs = resolve+ })+ mocks.logsQueryFn+ .mockResolvedValueOnce(populatedLogsResponse)+ .mockReturnValueOnce(nextLogsPromise)++ renderPage()++ expect(await screen.findByText('Previous conversation')).toBeInTheDocument()++ await user.click(await screen.findByRole('combobox', { name: 'agentV2.agentDetail.logs.filters.source.label' }))+ await user.click(await screen.findByRole('option', { name: /Book Translation/ }))++ await waitFor(() => {+ expect(getLatestLogsQueryInput().input.query).toEqual(expect.objectContaining({+ sources: ['webapp:webapp-app-id'],+ }))+ })++ expect(screen.getByText('Previous conversation')).toBeInTheDocument()++ resolveNextLogs(emptyLogsResponse)+ })+ })+})diff --git a/web/features/agent-v2/agent-detail/logs/components/source-picker.tsx b/web/features/agent-v2/agent-detail/logs/components/source-picker.tsxindex 6d04799ec87..8dd980ebb61 100644--- a/web/features/agent-v2/agent-detail/logs/components/source-picker.tsx+++ b/web/features/agent-v2/agent-detail/logs/components/source-picker.tsx@@ -5,7 +5,6 @@ import { Button } from '@langgenius/dify-ui/button'import { cn } from '@langgenius/dify-ui/cn'import {Combobox,- ComboboxClear,ComboboxCollection,ComboboxContent,ComboboxEmpty,@@ -95,7 +94,6 @@ export function AgentLogSourcePicker({placeholder={t('agentDetail.logs.filters.source.searchPlaceholder')}className="block h-4.5 grow px-1 py-0 system-sm-regular text-components-input-text-filled"/>- <ComboboxClear className="mr-0" /></ComboboxInputGroup></div>{isLoading && (diff --git a/web/features/agent-v2/agent-detail/logs/page.tsx b/web/features/agent-v2/agent-detail/logs/page.tsxindex bd3a31bfe96..311acb05912 100644--- a/web/features/agent-v2/agent-detail/logs/page.tsx+++ b/web/features/agent-v2/agent-detail/logs/page.tsx@@ -2,7 +2,7 @@import type { SourceFilterValue } from './components/source-picker'import { Pagination } from '@langgenius/dify-ui/pagination'-import { useQuery } from '@tanstack/react-query'+import { keepPreviousData, useQuery } from '@tanstack/react-query'import dayjs from 'dayjs'import { useState } from 'react'import { useTranslation } from 'react-i18next'@@ -15,6 +15,8 @@ import { AgentLogsTable } from './components/logs-table'import { AgentLogSourcePicker } from './components/source-picker'type PeriodKey = 'last7days' | 'last30days' | 'allTime'+type LogsSortField = 'created_at' | 'updated_at'+type LogsSortOrder = 'asc' | 'desc'type AgentLogsPageProps = {agentId: string@@ -42,6 +44,19 @@ const getPeriodQuery = (period: PeriodKey) => {}}+const parseSortValue = (value: string): {+ field: LogsSortField+ order: LogsSortOrder+} => {+ const isDescending = value.startsWith('-')+ const field = isDescending ? value.slice(1) : value++ return {+ field: field === 'updated_at' ? 'updated_at' : 'created_at',+ order: isDescending ? 'desc' : 'asc',+ }+}+export function AgentLogsPage({agentId,}: AgentLogsPageProps) {@@ -51,6 +66,10 @@ export function AgentLogsPage({const [period, setPeriod] = useState<PeriodKey>('last7days')const [source, setSource] = useState<SourceFilterValue>([])const [keyword, setKeyword] = useState('')+ const [sort, setSort] = useState<{ field: LogsSortField, order: LogsSortOrder }>({+ field: 'created_at',+ order: 'desc',+ })const [page, setPage] = useState(1)const [limit, setLimit] = useState(25)const periodItems = periodOptions.map(option => ({@@ -64,21 +83,25 @@ export function AgentLogsPage({},},}))- const logsQuery = useQuery(consoleQuery.agent.byAgentId.logs.get.queryOptions({- input: {- params: {- agent_id: agentId,- },- query: {- ...getPeriodQuery(period),- page,- limit,- keyword: keyword.trim() || undefined,- // TODO: Send multiple source ids after the backend contract supports multi-source filtering.- source: source.length === 1 ? source[0] : undefined,+ const logsQuery = useQuery({+ ...consoleQuery.agent.byAgentId.logs.get.queryOptions({+ input: {+ params: {+ agent_id: agentId,+ },+ query: {+ ...getPeriodQuery(period),+ page,+ limit,+ keyword: keyword.trim() || undefined,+ ...(source.length > 0 ? { sources: source } : {}),+ sort_by: sort.field,+ sort_order: sort.order,+ },},- },- }))+ }),+ placeholderData: keepPreviousData,+ })const logs = logsQuery.data?.data ?? []const totalPages = Math.max(Math.ceil((logsQuery.data?.total ?? 0) / limit), 1)const currentPage = logsQuery.data?.page ?? page@@ -151,13 +174,16 @@ export function AgentLogsPage({</div><Sort- order="desc"- value="updated_at"+ order={sort.order === 'desc' ? '-' : ''}+ value={sort.field}items={[{ value: 'created_at', name: t('agentDetail.logs.filters.sort.lastCreatedTime') },{ value: 'updated_at', name: t('agentDetail.logs.filters.sort.lastUpdatedTime') },]}- onSelect={() => {}}+ onSelect={(nextSortValue) => {+ setPage(1)+ setSort(parseSortValue(nextSortValue))+ }}/></div></header>diff --git a/web/features/agent-v2/agent-detail/monitoring/__tests__/metrics.spec.ts b/web/features/agent-v2/agent-detail/monitoring/__tests__/metrics.spec.tsnew file mode 100644index 00000000000..695a1d643bf--- /dev/null+++ b/web/features/agent-v2/agent-detail/monitoring/__tests__/metrics.spec.ts@@ -0,0 +1,110 @@+import type { AgentStatisticSummaryEnvelopeResponse } from '@dify/contracts/api/console/agent/types.gen'+import { getAgentMonitoringMetrics } from '../metrics'++const statisticsSummary: AgentStatisticSummaryEnvelopeResponse = {+ source: 'all',+ summary: {+ average_response_time: 1250,+ average_session_interactions: 1.5,+ currency: 'USD',+ tokens_per_second: 4,+ total_conversations: 2,+ total_end_users: 3,+ total_messages: 1250,+ total_price: '0.005',+ total_tokens: 2500,+ user_satisfaction_rate: 66.67,+ },+ charts: {+ average_response_time: [+ { date: '2026-06-16', latency: 1250 },+ ],+ average_session_interactions: [+ { date: '2026-06-16', interactions: 1.5 },+ ],+ daily_conversations: [+ { date: '2026-06-16', conversation_count: 2 },+ ],+ daily_end_users: [+ { date: '2026-06-16', terminal_count: 3 },+ ],+ daily_messages: [+ { date: '2026-06-16', message_count: 1250 },+ ],+ token_usage: [+ { date: '2026-06-16', token_count: 2500, total_price: '0.005', currency: 'USD' },+ ],+ tokens_per_second: [+ { date: '2026-06-16', tps: 4 },+ ],+ user_satisfaction_rate: [+ { date: '2026-06-16', rate: 66.67 },+ ],+ },+}++describe('getAgentMonitoringMetrics', () => {+ it('should map statistics summary response into monitoring chart metrics', () => {+ const metrics = getAgentMonitoringMetrics(statisticsSummary)++ expect(metrics).toHaveLength(6)+ expect(metrics.map(metric => metric.id)).toEqual([+ 'total-messages',+ 'active-users',+ 'avg-session-interactions',+ 'token-output-speed',+ 'user-satisfaction-rate',+ 'token-usage',+ ])+ expect(metrics[0]).toEqual(expect.objectContaining({+ summaryValue: '1.3k',+ valueKey: 'message_count',+ rows: statisticsSummary.charts.daily_messages,+ }))+ expect(metrics[2]).toEqual(expect.objectContaining({+ summaryValue: '1.5',+ valueKey: 'interactions',+ }))+ expect(metrics[4]).toEqual(expect.objectContaining({+ summaryValue: '66.67%',+ valueKey: 'rate',+ yMaxWhenEmpty: 1000,+ }))+ expect(metrics[5]).toEqual(expect.objectContaining({+ summaryValue: '2.5k',+ valueKey: 'token_count',+ rows: statisticsSummary.charts.token_usage,+ }))+ })++ it('should return zero-valued metrics when statistics data is not loaded yet', () => {+ const metrics = getAgentMonitoringMetrics()++ expect(metrics).toHaveLength(6)+ expect(metrics.every(metric => metric.rows.length === 0)).toBe(true)+ expect(metrics.map(metric => metric.summaryValue)).toEqual(['0', '0', '0', '0', '0%', '0'])+ })++ it('should fill missing daily chart buckets within the selected period', () => {+ const metrics = getAgentMonitoringMetrics(statisticsSummary, {+ start: '2026-06-15 00:00',+ end: '2026-06-17 23:59',+ })+ const totalMessagesMetric = metrics[0]+ const tokenUsageMetric = metrics[5]++ expect(totalMessagesMetric).toBeDefined()+ expect(tokenUsageMetric).toBeDefined()++ expect(totalMessagesMetric?.rows).toEqual([+ { date: '2026-06-15', message_count: 0, total_price: '0' },+ { date: '2026-06-16', message_count: 1250, total_price: '0' },+ { date: '2026-06-17', message_count: 0, total_price: '0' },+ ])+ expect(tokenUsageMetric?.rows).toEqual([+ { date: '2026-06-15', token_count: 0, total_price: '0' },+ { date: '2026-06-16', token_count: 2500, total_price: '0.005', currency: 'USD' },+ { date: '2026-06-17', token_count: 0, total_price: '0' },+ ])+ })+})diff --git a/web/features/agent-v2/agent-detail/monitoring/__tests__/page.spec.tsx b/web/features/agent-v2/agent-detail/monitoring/__tests__/page.spec.tsxnew file mode 100644index 00000000000..d0bff983dee--- /dev/null+++ b/web/features/agent-v2/agent-detail/monitoring/__tests__/page.spec.tsx@@ -0,0 +1,294 @@+import type { AgentLogSourceListResponse, AgentStatisticSummaryEnvelopeResponse } from '@dify/contracts/api/console/agent/types.gen'+import type { EChartsOption } from 'echarts'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { render, screen, waitFor, within } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { AgentMonitoringPage } from '../page'++type AgentMonitoringQueryInput = {+ input: {+ params: {+ agent_id: string+ }+ query?: Record<string, unknown>+ }+}++const mocks = vi.hoisted(() => ({+ chartOptions: [] as EChartsOption[],+ statisticsQueryFn: vi.fn(),+ logSourcesQueryFn: vi.fn(),+ statisticsQueryOptions: vi.fn((input: AgentMonitoringQueryInput) => ({+ queryKey: ['agent-monitoring-statistics', input],+ queryFn: () => mocks.statisticsQueryFn(input),+ })),+ logSourcesQueryOptions: vi.fn((input: AgentMonitoringQueryInput) => ({+ queryKey: ['agent-log-sources', input],+ queryFn: () => mocks.logSourcesQueryFn(input),+ })),+}))++vi.mock('echarts-for-react', () => ({+ default: ({ option, style }: { option: EChartsOption, style?: React.CSSProperties }) => {+ mocks.chartOptions.push(option)++ return <div data-testid="agent-monitoring-chart" style={style} />+ },+}))++vi.mock('@/context/i18n', () => ({+ useDocLink: () => (path: string) => `https://docs.example.com${path}`,+ useLocale: () => 'en-US',+}))++vi.mock('@/service/client', () => ({+ consoleQuery: {+ agent: {+ byAgentId: {+ logSources: {+ get: {+ queryOptions: mocks.logSourcesQueryOptions,+ },+ },+ statistics: {+ summary: {+ get: {+ queryOptions: mocks.statisticsQueryOptions,+ },+ },+ },+ },+ },+ },+}))++const logSourcesResponse: AgentLogSourceListResponse = {+ data: [],+ groups: [+ {+ label: 'Webapp',+ type: 'webapp',+ sources: [+ {+ app_icon: '📙',+ app_icon_background: '#FFF4ED',+ app_icon_type: 'emoji',+ app_id: 'webapp-app-id',+ app_name: 'Book Translation',+ id: 'webapp:webapp-app-id',+ type: 'webapp',+ },+ ],+ },+ ],+}++const statisticsResponse: AgentStatisticSummaryEnvelopeResponse = {+ source: 'all',+ summary: {+ average_response_time: 1250,+ average_session_interactions: 1.5,+ currency: 'USD',+ tokens_per_second: 4,+ total_conversations: 2,+ total_end_users: 3,+ total_messages: 1250,+ total_price: '0.005',+ total_tokens: 2500,+ user_satisfaction_rate: 66.67,+ },+ charts: {+ average_response_time: [+ { date: '2026-06-22', latency: 1250 },+ ],+ average_session_interactions: [+ { date: '2026-06-22', interactions: 1.5 },+ ],+ daily_conversations: [+ { date: '2026-06-22', conversation_count: 2 },+ ],+ daily_end_users: [+ { date: '2026-06-22', terminal_count: 3 },+ ],+ daily_messages: [+ { date: '2026-06-22', message_count: 1250 },+ ],+ token_usage: [+ { date: '2026-06-22', token_count: 2500, total_price: '0.005', currency: 'USD' },+ ],+ tokens_per_second: [+ { date: '2026-06-22', tps: 4 },+ ],+ user_satisfaction_rate: [+ { date: '2026-06-22', rate: 66.67 },+ ],+ },+}++const emptyStatisticsResponse: AgentStatisticSummaryEnvelopeResponse = {+ source: 'webapp:webapp-app-id',+ summary: {+ average_response_time: 0,+ average_session_interactions: 0,+ currency: 'USD',+ tokens_per_second: 0,+ total_conversations: 0,+ total_end_users: 0,+ total_messages: 0,+ total_price: '0',+ total_tokens: 0,+ user_satisfaction_rate: 0,+ },+ charts: {+ average_response_time: [],+ average_session_interactions: [],+ daily_conversations: [],+ daily_end_users: [],+ daily_messages: [],+ token_usage: [],+ tokens_per_second: [],+ user_satisfaction_rate: [],+ },+}++const renderPage = () => {+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: {+ retry: false,+ },+ },+ })++ render(+ <QueryClientProvider client={queryClient}>+ <AgentMonitoringPage agentId="agent-1" />+ </QueryClientProvider>,+ )++ return queryClient+}++const getLatestStatisticsQueryInput = () => {+ const latestCall = mocks.statisticsQueryOptions.mock.calls.at(-1)++ if (!latestCall)+ throw new Error('Expected statistics query options to be called')++ return latestCall[0]+}++describe('AgentMonitoringPage', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mocks.chartOptions = []+ mocks.statisticsQueryFn.mockResolvedValue(statisticsResponse)+ mocks.logSourcesQueryFn.mockResolvedValue(logSourcesResponse)+ })++ it('should request statistics through the generated contract without a source filter by default', async () => {+ renderPage()++ await waitFor(() => {+ expect(mocks.statisticsQueryOptions).toHaveBeenCalled()+ })++ expect(getLatestStatisticsQueryInput()).toEqual({+ input: {+ params: {+ agent_id: 'agent-1',+ },+ query: expect.objectContaining({+ start: expect.any(String),+ end: expect.any(String),+ }),+ },+ })+ expect(getLatestStatisticsQueryInput().input.query).not.toHaveProperty('source')+ })++ it('should render statistics summary values and chart options from backend data', async () => {+ renderPage()++ expect(await screen.findByText('1.3k')).toBeInTheDocument()+ expect(screen.getByText('3')).toBeInTheDocument()+ expect(screen.getByText('1.5')).toBeInTheDocument()+ expect(screen.getByText('4')).toBeInTheDocument()+ expect(screen.getByText('66.67%')).toBeInTheDocument()+ expect(screen.getByText('2.5k')).toBeInTheDocument()++ await waitFor(() => {+ expect(mocks.chartOptions).toHaveLength(6)+ })+ const firstChartOption = mocks.chartOptions[0]++ expect(firstChartOption).toBeDefined()+ expect(firstChartOption).toEqual(expect.objectContaining({+ grid: { top: 8, right: 36, bottom: 10, left: 25, containLabel: true },+ }))+ expect(firstChartOption?.xAxis).toEqual(expect.any(Array))+ })++ it('should use overview empty y-axis fallbacks when backend charts are empty', async () => {+ mocks.statisticsQueryFn.mockResolvedValue(emptyStatisticsResponse)++ renderPage()++ expect(await screen.findByText('0%')).toBeInTheDocument()++ await waitFor(() => {+ expect(mocks.chartOptions).toHaveLength(6)+ })++ expect((mocks.chartOptions[0]?.yAxis as { max?: number }).max).toBe(500)+ expect((mocks.chartOptions[3]?.yAxis as { max?: number }).max).toBe(100)+ expect((mocks.chartOptions[4]?.yAxis as { max?: number }).max).toBe(1000)+ })++ it('should send the selected backend source id through the source query param', async () => {+ const user = userEvent.setup()++ renderPage()++ await user.click(await screen.findByRole('combobox', { name: /metadata.sourceLabel/ }))+ await user.click(await screen.findByRole('option', { name: /Book Translation/ }))++ await waitFor(() => {+ expect(getLatestStatisticsQueryInput().input.query).toEqual(expect.objectContaining({+ source: 'webapp:webapp-app-id',+ }))+ })++ const sourceTrigger = screen.getByRole('combobox', { name: /Book Translation/ })++ expect(within(sourceTrigger).getByText(/metadata.sourceLabel/)).toHaveClass('system-sm-regular', 'text-text-tertiary')+ expect(within(sourceTrigger).getByText('Book Translation')).toHaveClass('system-sm-medium', 'text-text-secondary')+ })++ it('should keep previous statistics visible while a source filter refetches', async () => {+ const user = userEvent.setup()+ let resolveNextStatistics: (value: AgentStatisticSummaryEnvelopeResponse) => void = () => undefined+ const nextStatisticsPromise = new Promise<AgentStatisticSummaryEnvelopeResponse>((resolve) => {+ resolveNextStatistics = resolve+ })+ mocks.statisticsQueryFn+ .mockResolvedValueOnce(statisticsResponse)+ .mockReturnValueOnce(nextStatisticsPromise)++ renderPage()++ expect(await screen.findByText('1.3k')).toBeInTheDocument()++ await user.click(await screen.findByRole('combobox', { name: /metadata.sourceLabel/ }))+ await user.click(await screen.findByRole('option', { name: /Book Translation/ }))++ await waitFor(() => {+ expect(getLatestStatisticsQueryInput().input.query).toEqual(expect.objectContaining({+ source: 'webapp:webapp-app-id',+ }))+ })+ expect(screen.getByText('1.3k')).toBeInTheDocument()++ resolveNextStatistics(emptyStatisticsResponse)+ })+})diff --git a/web/features/agent-v2/agent-detail/monitoring/chart-utils.ts b/web/features/agent-v2/agent-detail/monitoring/chart-utils.tsindex 2e34d74dd80..2a96a44becc 100644--- a/web/features/agent-v2/agent-detail/monitoring/chart-utils.ts+++ b/web/features/agent-v2/agent-detail/monitoring/chart-utils.ts@@ -1,6 +1,5 @@import type { EChartsOption } from 'echarts'import dayjs from 'dayjs'-import { formatNumber } from '@/utils/format'export type AgentMonitoringChartType = 'conversations' | 'endUsers' | 'tokenUsage'@@ -11,6 +10,10 @@ export type AgentMonitoringChartRow = {type ColorType = 'green' | 'orange' | 'blue'+type AgentMonitoringChartConfig = {+ colorType: ColorType+}+const colorTypeMap: Record<ColorType, { lineColor: string, bgColor: [string, string] }> = {green: {lineColor: 'rgba(6, 148, 162, 1)',@@ -26,23 +29,31 @@ const colorTypeMap: Record<ColorType, { lineColor: string, bgColor: [string, str},}-const chartTypeColorMap: Record<AgentMonitoringChartType, ColorType> = {- conversations: 'blue',- endUsers: 'blue',- tokenUsage: 'blue',+const chartTypeConfig: Record<AgentMonitoringChartType, AgentMonitoringChartConfig> = {+ conversations: {+ colorType: 'green',+ },+ endUsers: {+ colorType: 'orange',+ },+ tokenUsage: {+ colorType: '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 commonColorMap = {+ label: '#9CA3AF',+ splitLineLight: '#F3F4F6',+ splitLineDark: '#E5E7EB',}-const getChartColors = (chartType: AgentMonitoringChartType) => colorTypeMap[chartTypeColorMap[chartType]]+const axisDateFormat = 'MMM'++const getChartColors = (chartType: AgentMonitoringChartType) => colorTypeMap[chartTypeConfig[chartType].colorType]const getMarkLineSeedData = (statisticsLength: number) => {const markLineLength = statisticsLength >= 2 ? statisticsLength - 2 : statisticsLength+return ['', ...Array.from({ length: markLineLength }, () => '1'), '']}@@ -67,22 +78,6 @@ const getTooltipContent = (</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,@@ -93,37 +88,6 @@ export const getChartValueField = (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)@@ -164,7 +128,7 @@ export const buildChartOptions = ({type: 'category',boundaryGap: false,axisLabel: {- color: '#9CA3AF',+ color: commonColorMap.label,hideOverlap: true,overflow: 'break',formatter(value) {@@ -176,7 +140,7 @@ export const buildChartOptions = ({splitLine: {show: true,lineStyle: {- color: '#F3F4F6',+ color: commonColorMap.splitLineLight,width: 1,type: [10, 10],},@@ -194,7 +158,7 @@ export const buildChartOptions = ({splitLine: {show: true,lineStyle: {- color: '#E5E7EB',+ color: commonColorMap.splitLineDark,},interval(_index, value) {return !!value@@ -204,10 +168,10 @@ export const buildChartOptions = ({yAxis: {max: yMax ?? 'dataMax',type: 'value',- axisLabel: { color: '#9CA3AF', hideOverlap: true },+ axisLabel: { color: commonColorMap.label, hideOverlap: true },splitLine: {lineStyle: {- color: '#F3F4F6',+ color: commonColorMap.splitLineLight,},},},diff --git a/web/features/agent-v2/agent-detail/monitoring/chart.tsx b/web/features/agent-v2/agent-detail/monitoring/chart.tsxindex a7ca45bae91..68c356a9933 100644--- a/web/features/agent-v2/agent-detail/monitoring/chart.tsx+++ b/web/features/agent-v2/agent-detail/monitoring/chart.tsx@@ -19,7 +19,11 @@ type AgentMonitoringChartProps = {chartType: AgentMonitoringChartTypevalueKey?: stringunitKey?: I18nKeysWithPrefix<'agentV2', 'agentDetail.monitoring.'>- yMax?: number+ yMaxWhenEmpty: number+}++const hasChartData = (rows: AgentMonitoringChartRow[], valueKey: string) => {+ return rows.some(row => Number(row[valueKey] ?? 0) !== 0)}export function AgentMonitoringChart({@@ -30,24 +34,25 @@ export function AgentMonitoringChart({chartType,valueKey,unitKey,- yMax,+ yMaxWhenEmpty,}: AgentMonitoringChartProps) {const { t } = useTranslation('agentV2')const yField = getChartValueField(rows, valueKey)const tokenSummary = getTokenSummary(rows)+ const shouldUseEmptyYAxis = !hasChartData(rows, yField)const options = buildChartOptions({rows,chartType,valueKey: yField,- yMax,+ yMax: shouldUseEmptyYAxis ? yMaxWhenEmpty : undefined,})- const isEmptySummary = summaryValue === '0' || summaryValue.startsWith('0 ')+ const isEmptySummary = Number.parseFloat(summaryValue.replace(/,/g, '')) === 0return (- <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">+ <article className="flex h-[316px] w-full min-w-0 flex-col overflow-hidden rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg">+ <div className="flex h-11 shrink-0 items-center px-6 pt-6 pb-1"><div className="flex min-w-0 items-center gap-1">- <h3 className="truncate system-xs-semibold-uppercase text-text-secondary">+ <h3 className="truncate system-md-semibold text-text-secondary">{t(titleKey)}</h3><Infotip aria-label={t(explanationKey)}>@@ -56,17 +61,17 @@ export function AgentMonitoringChart({</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'}`}>+ <div className="flex h-8 shrink-0 items-start gap-1 px-6 py-1">+ <div className={`truncate text-3xl leading-7 font-normal ${isEmptySummary ? 'text-text-quaternary' : 'text-text-primary'}`}>{summaryValue}</div>{chartType !== 'tokenUsage' && unitKey && (- <div className="truncate system-sm-regular text-text-secondary">+ <div className="mt-0.5 truncate system-sm-regular text-text-secondary">{t(unitKey)}</div>)}{chartType === 'tokenUsage' && (- <div className="truncate system-sm-regular text-text-secondary">+ <div className="mt-0.5 truncate system-sm-regular text-text-secondary">{t('agentDetail.monitoring.tokenUsageConsumed')}{' '}<span className="text-util-colors-orange-orange-600">@@ -78,7 +83,9 @@ export function AgentMonitoringChart({)}</div>- <ReactECharts option={options} style={{ height: 240 }} />+ <div className="h-60 px-6">+ <ReactECharts option={options} style={{ height: 240, width: '100%' }} />+ </div></article>)}diff --git a/web/features/agent-v2/agent-detail/monitoring/metrics.ts b/web/features/agent-v2/agent-detail/monitoring/metrics.tsnew file mode 100644index 00000000000..818ab8dd936--- /dev/null+++ b/web/features/agent-v2/agent-detail/monitoring/metrics.ts@@ -0,0 +1,145 @@+import type { AgentStatisticSummaryEnvelopeResponse } from '@dify/contracts/api/console/agent/types.gen'+import type { AgentMonitoringChartRow, AgentMonitoringChartType } from './chart-utils'+import type { I18nKeysWithPrefix } from '@/types/i18n'+import dayjs from 'dayjs'+import { formatNumberAbbreviated } from '@/utils/format'++export type AgentMonitoringMetric = {+ id: string+ titleKey: I18nKeysWithPrefix<'agentV2', 'agentDetail.monitoring.'>+ explanationKey: I18nKeysWithPrefix<'agentV2', 'agentDetail.monitoring.'>+ chartType: AgentMonitoringChartType+ rows: AgentMonitoringChartRow[]+ summaryValue: string+ valueKey: string+ unitKey?: I18nKeysWithPrefix<'agentV2', 'agentDetail.monitoring.'>+ yMaxWhenEmpty: number+}++type AgentMonitoringPeriodQuery = {+ start: string+ end: string+}++type ChartRowValue = number | string | undefined++const chartDateFormat = 'YYYY-MM-DD'++const toMetricNumber = (value: number) => {+ if (Number.isInteger(value))+ return value.toLocaleString()++ return value.toLocaleString(undefined, {+ maximumFractionDigits: 2,+ })+}++const getChartRowValue = (row: AgentMonitoringChartRow | undefined, key: string): ChartRowValue => {+ if (!row)+ return 0++ return row[key] ?? 0+}++const fillChartRows = <T extends { date: string }>(+ rows: T[] | undefined,+ periodQuery: AgentMonitoringPeriodQuery,+ valueKey: string,+) => {+ const rowsByDate = new Map(+ (rows ?? []).map(row => [dayjs(row.date).format(chartDateFormat), row as AgentMonitoringChartRow]),+ )+ const start = dayjs(periodQuery.start).startOf('day')+ const end = dayjs(periodQuery.end).startOf('day')+ const days = Math.max(end.diff(start, 'day'), 0)++ return Array.from({ length: days + 1 }, (_, index) => {+ const date = start.add(index, 'day').format(chartDateFormat)+ const row = rowsByDate.get(date)++ return {+ ...row,+ date,+ [valueKey]: getChartRowValue(row, valueKey),+ total_price: row?.total_price ?? '0',+ }+ }) as AgentMonitoringChartRow[]+}++export const getAgentMonitoringMetrics = (+ data?: AgentStatisticSummaryEnvelopeResponse,+ periodQuery?: AgentMonitoringPeriodQuery,+): AgentMonitoringMetric[] => {+ const summary = data?.summary+ const charts = data?.charts+ const toChartRows = <T extends { date: string }>(rows: T[] | undefined, valueKey: string) => {+ if (!periodQuery)+ return (rows ?? []) as AgentMonitoringChartRow[]++ return fillChartRows(rows, periodQuery, valueKey)+ }++ return [+ {+ id: 'total-messages',+ titleKey: 'agentDetail.monitoring.metrics.totalMessages.title',+ explanationKey: 'agentDetail.monitoring.metrics.totalMessages.explanation',+ chartType: 'conversations',+ rows: toChartRows(charts?.daily_messages, 'message_count'),+ summaryValue: formatNumberAbbreviated(summary?.total_messages ?? 0),+ valueKey: 'message_count',+ yMaxWhenEmpty: 500,+ },+ {+ id: 'active-users',+ titleKey: 'agentDetail.monitoring.metrics.activeUsers.title',+ explanationKey: 'agentDetail.monitoring.metrics.activeUsers.explanation',+ chartType: 'endUsers',+ rows: toChartRows(charts?.daily_end_users, 'terminal_count'),+ summaryValue: formatNumberAbbreviated(summary?.total_end_users ?? 0),+ valueKey: 'terminal_count',+ yMaxWhenEmpty: 500,+ },+ {+ id: 'avg-session-interactions',+ titleKey: 'agentDetail.monitoring.metrics.avgSessionInteractions.title',+ explanationKey: 'agentDetail.monitoring.metrics.avgSessionInteractions.explanation',+ chartType: 'conversations',+ rows: toChartRows(charts?.average_session_interactions, 'interactions'),+ summaryValue: toMetricNumber(summary?.average_session_interactions ?? 0),+ valueKey: 'interactions',+ yMaxWhenEmpty: 500,+ },+ {+ id: 'token-output-speed',+ titleKey: 'agentDetail.monitoring.metrics.tokenOutputSpeed.title',+ explanationKey: 'agentDetail.monitoring.metrics.tokenOutputSpeed.explanation',+ chartType: 'conversations',+ rows: toChartRows(charts?.tokens_per_second, 'tps'),+ summaryValue: toMetricNumber(summary?.tokens_per_second ?? 0),+ valueKey: 'tps',+ unitKey: 'agentDetail.monitoring.units.tokenPerSecond',+ yMaxWhenEmpty: 100,+ },+ {+ id: 'user-satisfaction-rate',+ titleKey: 'agentDetail.monitoring.metrics.userSatisfactionRate.title',+ explanationKey: 'agentDetail.monitoring.metrics.userSatisfactionRate.explanation',+ chartType: 'endUsers',+ rows: toChartRows(charts?.user_satisfaction_rate, 'rate'),+ summaryValue: `${toMetricNumber(summary?.user_satisfaction_rate ?? 0)}%`,+ valueKey: 'rate',+ yMaxWhenEmpty: 1000,+ },+ {+ id: 'token-usage',+ titleKey: 'agentDetail.monitoring.metrics.tokenUsage.title',+ explanationKey: 'agentDetail.monitoring.metrics.tokenUsage.explanation',+ chartType: 'tokenUsage',+ rows: toChartRows(charts?.token_usage, 'token_count'),+ summaryValue: formatNumberAbbreviated(summary?.total_tokens ?? 0),+ valueKey: 'token_count',+ yMaxWhenEmpty: 100,+ },+ ]+}diff --git a/web/features/agent-v2/agent-detail/monitoring/mock-data.ts b/web/features/agent-v2/agent-detail/monitoring/mock-data.tsdeleted file mode 100644index 78a566fd6bf..00000000000--- a/web/features/agent-v2/agent-detail/monitoring/mock-data.ts+++ /dev/null@@ -1,85 +0,0 @@-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.tsxindex 6dedc0de4bc..2bac7ae6191 100644--- a/web/features/agent-v2/agent-detail/monitoring/page.tsx+++ b/web/features/agent-v2/agent-detail/monitoring/page.tsx@@ -1,20 +1,32 @@'use client'-import type { AgentAccessSource } from '../access/access-sources'+import type { AgentLogSourceResponse } from '@dify/contracts/api/console/agent/types.gen'+import type { ReactNode } from 'react'+import { Button } from '@langgenius/dify-ui/button'import { ScrollArea } from '@langgenius/dify-ui/scroll-area'-import { useQuery } from '@tanstack/react-query'+import {+ Select,+ SelectContent,+ SelectItem,+ SelectItemIndicator,+ SelectItemText,+ SelectTrigger,+} from '@langgenius/dify-ui/select'+import { keepPreviousData, 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 { getAgentMonitoringMetrics } from './metrics'import { AgentMonitoringTimeRangePicker } from './time-range-picker'-type SourceFilterValue = 'all' | AgentAccessSource['id']+type SourceFilterValue = 'all' | AgentLogSourceResponse['id']+type SourceFilterItem = {+ value: SourceFilterValue+ name: string+}type AgentMonitoringPageProps = {agentId: string}@@ -31,43 +43,52 @@ const getDefaultPeriodQuery = () => {}}-const getSourceValue = (source: AgentAccessSource): SourceFilterValue => source.id-export function AgentMonitoringPage({agentId,}: AgentMonitoringPageProps) {const { t } = useTranslation('agentV2')+ const { t: tCommon } = useTranslation('common')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({+ const logSourcesQuery = useQuery(consoleQuery.agent.byAgentId.logSources.get.queryOptions({input: {params: {agent_id: agentId,},},}))- const accessSources = getAgentAccessSources(agentQuery.data)- const sourceItems = [+ const statisticsQuery = useQuery({+ ...consoleQuery.agent.byAgentId.statistics.summary.get.queryOptions({+ input: {+ params: {+ agent_id: agentId,+ },+ query: {+ ...period.query,+ ...(sourceFilter !== 'all' ? { source: sourceFilter } : {}),+ },+ },+ }),+ placeholderData: keepPreviousData,+ })+ const sources = (logSourcesQuery.data?.groups ?? []).flatMap(group => group.sources ?? [])+ const sourceItems: SourceFilterItem[] = [{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),- }),+ ...sources.map(source => ({+ value: source.id,+ name: source.app_name,})),]- const metrics = getAgentMonitoringMetrics(period.query)+ const metrics = getAgentMonitoringMetrics(statisticsQuery.data, period.query)+ const shouldShowInitialSkeleton = statisticsQuery.isPending && !statisticsQuery.data+ const shouldShowError = statisticsQuery.isError && !statisticsQuery.datareturn (<section@@ -99,12 +120,10 @@ export function AgentMonitoringPage({onChange={setPeriod}/>- <Chip- showLeftIcon={false}- className="min-w-53"- panelClassName="w-61"+ <AgentMonitoringSourceFiltervalue={sourceFilter}items={sourceItems}+ label={t('agentDetail.metadata.sourceLabel')}onSelect={(item) => {setSourceFilter(item.value)}}@@ -121,22 +140,156 @@ export function AgentMonitoringPage({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>+ {shouldShowInitialSkeleton && <AgentMonitoringSkeletonGrid />}+ {shouldShowError && (+ <AgentMonitoringState>+ <div className="flex items-center justify-center gap-2">+ <span>{t('agentDetail.monitoring.loadFailed')}</span>+ <Button+ variant="secondary"+ size="small"+ onClick={() => {+ void statisticsQuery.refetch()+ }}+ >+ {tCommon('operation.retry')}+ </Button>+ </div>+ </AgentMonitoringState>+ )}+ {!shouldShowInitialSkeleton && !shouldShowError && (+ <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}+ yMaxWhenEmpty={metric.yMaxWhenEmpty}+ />+ ))}+ </div>+ )}</ScrollArea></section>)}++function AgentMonitoringSourceFilter({+ value,+ items,+ label,+ onSelect,+ onClear,+}: {+ value: SourceFilterValue+ items: SourceFilterItem[]+ label: string+ onSelect: (item: SourceFilterItem) => void+ onClear: () => void+}) {+ const { t } = useTranslation('common')+ const selectedItem = items.find(item => Object.is(item.value, value))+ const selectedName = selectedItem?.name ?? ''+ const triggerLabel = selectedName ? `${label} ${selectedName}` : label+ const clearLabel = selectedName+ ? `${t('operation.clear')} ${triggerLabel}`+ : t('operation.clear')++ return (+ <Select+ value={selectedItem?.value ?? null}+ itemToStringLabel={(itemValue: SourceFilterValue) => items.find(item => Object.is(item.value, itemValue))?.name ?? ''}+ itemToStringValue={itemValue => String(itemValue)}+ onValueChange={(nextValue) => {+ if (nextValue === null)+ return+ const selected = items.find(item => Object.is(item.value, nextValue))+ if (selected)+ onSelect(selected)+ }}+ >+ <div className="relative w-fit max-w-full">+ <SelectTrigger+ aria-label={triggerLabel}+ className="h-auto min-h-8 w-fit max-w-full min-w-53 cursor-pointer items-center rounded-lg border-[0.5px] border-components-button-secondary-border bg-components-button-secondary-bg px-2 py-1 pr-6 shadow-xs hover:border-components-button-secondary-border-hover hover:bg-components-button-secondary-bg-hover! focus-visible:bg-state-base-hover-alt focus-visible:ring-2 focus-visible:ring-state-accent-solid data-popup-open:border-components-button-secondary-border-hover! data-popup-open:bg-components-button-secondary-bg-hover! data-popup-open:hover:border-components-button-secondary-border-hover data-popup-open:hover:bg-components-button-secondary-bg-hover! [&>*:last-child]:hidden"+ >+ <span className="flex min-w-0 grow items-center gap-1 text-left">+ <span className="flex min-w-0 grow items-center gap-1 px-1">+ <span className="shrink-0 system-sm-regular text-text-tertiary">+ {label}+ </span>+ <span className="truncate system-sm-medium text-text-secondary">+ {selectedName}+ </span>+ </span>+ </span>+ </SelectTrigger>+ <button+ type="button"+ aria-label={clearLabel}+ className="group/clear absolute top-1/2 right-1.5 flex size-5 -translate-y-1/2 cursor-pointer touch-manipulation items-center justify-center rounded-md border-none bg-transparent p-0 outline-hidden focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:ring-inset"+ onClick={onClear}+ >+ <span aria-hidden className="i-ri-close-circle-fill block size-3.5 text-text-quaternary group-hover/clear:text-text-tertiary" />+ </button>+ <SelectContent+ placement="bottom-start"+ sideOffset={4}+ popupClassName="relative w-61 rounded-xl border-[0.5px] bg-components-panel-bg-blur p-0 text-sm text-text-secondary shadow-lg outline-hidden backdrop-blur-[5px] focus:outline-hidden focus-visible:outline-hidden"+ listClassName="max-h-72 p-1"+ >+ {items.map(item => (+ <SelectItem+ key={item.value}+ value={item.value}+ >+ <SelectItemText title={item.name}>{item.name}</SelectItemText>+ <SelectItemIndicator />+ </SelectItem>+ ))}+ </SelectContent>+ </div>+ </Select>+ )+}++function AgentMonitoringState({+ children,+}: {+ children: ReactNode+}) {+ return (+ <div className="flex h-[316px] items-center justify-center rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg px-6 py-8 text-center system-sm-regular text-text-tertiary">+ {children}+ </div>+ )+}++function AgentMonitoringSkeletonGrid() {+ return (+ <div className="grid w-full grid-cols-1 gap-3 xl:grid-cols-2">+ {Array.from({ length: 6 }, (_, index) => (+ <article+ key={index}+ aria-hidden="true"+ className="flex h-[316px] w-full min-w-0 flex-col overflow-hidden rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg"+ >+ <div className="flex h-11 items-end px-6 pb-1">+ <div className="h-4 w-40 rounded-sm bg-text-quaternary opacity-20" />+ </div>+ <div className="flex h-8 items-start px-6 py-1">+ <div className="h-6 w-24 rounded-sm bg-text-quaternary opacity-20" />+ </div>+ <div className="h-60 px-6 pb-4">+ <div className="h-full rounded-md bg-text-quaternary opacity-10" />+ </div>+ </article>+ ))}+ </div>+ )+}diff --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.tsxindex 687133f25e7..637e4f3623c 100644--- 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.tsx@@ -2,7 +2,7 @@ import type { ComponentProps } from 'react'import type { AgentRosterListItem } from '../agent-roster-list'import { toast } from '@langgenius/dify-ui/toast'import { QueryClient, QueryClientProvider } from '@tanstack/react-query'-import { render, screen, waitFor } from '@testing-library/react'+import { render, screen, waitFor, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { AgentRosterList } from '../agent-roster-list'@@ -20,6 +20,9 @@ vi.mock('@/service/client', () => ({consoleQuery: {agent: {byAgentId: {+ get: {+ queryKey: ({ input }: { input: { params: { agent_id: string } } }) => ['agent-detail', input.params.agent_id],+ },copy: {post: {mutationOptions: () => ({@@ -46,6 +49,9 @@ const createAgent = (overrides: Partial<AgentRosterListItem> = {}): AgentRosterLactive_config_is_published: false,description: 'Find and summarize market materials.',id: 'agent-1',+ icon: '🧸',+ icon_background: '#F5F3FF',+ icon_type: 'emoji',icon_url: null,mode: 'agent',name: 'Research Agent',@@ -61,7 +67,7 @@ const renderList = () => {const queryClient = new QueryClient()- return render(+ const result = render(<QueryClientProvider client={queryClient}><AgentRosterListagents={agents}@@ -77,6 +83,11 @@ const renderList = (/></QueryClientProvider>,)++ return {+ ...result,+ queryClient,+ }}describe('AgentRosterList', () => {@@ -201,19 +212,108 @@ describe('AgentRosterList', () => {expect(screen.getByText(/agentV2\.roster\.references\.label/)).toBeInTheDocument()})- it('duplicates an agent from the card action menu', async () => {+ it('opens a duplicate dialog from the card action menu', async () => {+ const user = userEvent.setup()+ renderList([createAgent()])++ await user.click(screen.getByRole('button', { name: /agentV2\.roster\.moreActions/ }))+ await user.click(screen.getByRole('menuitem', { name: /common\.operation\.duplicate/ }))++ const dialog = await screen.findByRole('dialog', { name: 'agentV2.roster.duplicateDialog.title' })+ expect(within(dialog).getByRole('textbox', { name: /agentV2\.roster\.createForm\.nameLabel/ })).toHaveValue('')+ expect(within(dialog).getByRole('textbox', { name: /agentV2\.roster\.createForm\.nameLabel/ })).toHaveAttribute('placeholder', 'Research Agent copy')+ expect(within(dialog).getByRole('textbox', { name: /agentV2\.roster\.createForm\.roleLabel/ })).toHaveValue('Research Assistant')+ expect(within(dialog).getByRole('textbox', { name: /agentV2\.roster\.createForm\.descriptionLabel/ })).toHaveValue('Find and summarize market materials.')+ expect(duplicateAgentMutationFn).not.toHaveBeenCalled()+ })++ it('uses the latest cached agent detail when opening the duplicate dialog', async () => {+ const user = userEvent.setup()+ const { queryClient } = renderList([+ createAgent({+ description: null,+ }),+ ])+ queryClient.setQueryData(['agent-detail', 'agent-1'], createAgent({+ description: 'Summarize new market updates.',+ role: 'Market Researcher',+ }))++ await user.click(screen.getByRole('button', { name: /agentV2\.roster\.moreActions/ }))+ await user.click(screen.getByRole('menuitem', { name: /common\.operation\.duplicate/ }))++ const dialog = await screen.findByRole('dialog', { name: 'agentV2.roster.duplicateDialog.title' })+ expect(within(dialog).getByRole('textbox', { name: /agentV2\.roster\.createForm\.nameLabel/ })).toHaveValue('')+ expect(within(dialog).getByRole('textbox', { name: /agentV2\.roster\.createForm\.nameLabel/ })).toHaveAttribute('placeholder', 'Research Agent copy')+ expect(within(dialog).getByRole('textbox', { name: /agentV2\.roster\.createForm\.descriptionLabel/ })).toHaveValue('Summarize new market updates.')+ expect(within(dialog).getByRole('textbox', { name: /agentV2\.roster\.createForm\.roleLabel/ })).toHaveValue('Market Researcher')+ })++ it('duplicates an agent with backend-generated naming when the dialog name is empty', async () => {+ const user = userEvent.setup()+ renderList([createAgent()])++ await user.click(screen.getByRole('button', { name: /agentV2\.roster\.moreActions/ }))+ await user.click(screen.getByRole('menuitem', { name: /common\.operation\.duplicate/ }))++ const dialog = await screen.findByRole('dialog', { name: 'agentV2.roster.duplicateDialog.title' })+ await user.click(within(dialog).getByRole('button', { name: 'common.operation.duplicate' }))++ expect(duplicateAgentMutationFn).toHaveBeenCalledWith(+ {+ params: {+ agent_id: 'agent-1',+ },+ body: {+ description: 'Find and summarize market materials.',+ role: 'Research Assistant',+ icon: '🧸',+ icon_background: '#F5F3FF',+ icon_type: 'emoji',+ },+ },+ expect.objectContaining({+ client: expect.any(QueryClient),+ }),+ )+ expect(duplicateAgentMutationFn.mock.calls[0]?.[0].body).not.toHaveProperty('name')+ await waitFor(() => {+ expect(toast.success).toHaveBeenCalledWith('agentV2.roster.duplicateSuccess')+ })+ })++ it('duplicates an agent with the dialog name, role, and description when provided', async () => {const user = userEvent.setup()renderList([createAgent()])await user.click(screen.getByRole('button', { name: /agentV2\.roster\.moreActions/ }))await user.click(screen.getByRole('menuitem', { name: /common\.operation\.duplicate/ }))+ const dialog = await screen.findByRole('dialog', { name: 'agentV2.roster.duplicateDialog.title' })+ const nameInput = within(dialog).getByRole('textbox', { name: /agentV2\.roster\.createForm\.nameLabel/ })+ const roleInput = within(dialog).getByRole('textbox', { name: /agentV2\.roster\.createForm\.roleLabel/ })+ const descriptionInput = within(dialog).getByRole('textbox', { name: /agentV2\.roster\.createForm\.descriptionLabel/ })+ await user.clear(nameInput)+ await user.type(nameInput, ' Market Agent ')+ await user.clear(roleInput)+ await user.type(roleInput, ' Market Analyst ')+ await user.clear(descriptionInput)+ await user.type(descriptionInput, ' Copied for market research ')+ await user.click(within(dialog).getByRole('button', { name: 'common.operation.duplicate' }))+expect(duplicateAgentMutationFn).toHaveBeenCalledWith({params: {agent_id: 'agent-1',},- body: {},+ body: {+ name: 'Market Agent',+ description: 'Copied for market research',+ role: 'Market Analyst',+ icon: '🧸',+ icon_background: '#F5F3FF',+ icon_type: 'emoji',+ },},expect.objectContaining({client: expect.any(QueryClient),@@ -223,4 +323,45 @@ describe('AgentRosterList', () => {expect(toast.success).toHaveBeenCalledWith('agentV2.roster.duplicateSuccess')})})++ it('shows a field error when duplicating with an empty role', async () => {+ const user = userEvent.setup()+ renderList([createAgent()])++ await user.click(screen.getByRole('button', { name: /agentV2\.roster\.moreActions/ }))+ await user.click(screen.getByRole('menuitem', { name: /common\.operation\.duplicate/ }))++ const dialog = await screen.findByRole('dialog', { name: 'agentV2.roster.duplicateDialog.title' })+ await user.clear(within(dialog).getByRole('textbox', { name: /agentV2\.roster\.createForm\.roleLabel/ }))+ await user.click(within(dialog).getByRole('button', { name: 'common.operation.duplicate' }))++ expect(await within(dialog).findByText('agentV2.roster.createForm.roleRequired')).toBeInTheDocument()+ expect(duplicateAgentMutationFn).not.toHaveBeenCalled()+ })++ it('resets the edit form draft when reopening after canceling unsaved changes', async () => {+ const user = userEvent.setup()+ renderList([createAgent()])++ await user.click(screen.getByRole('button', { name: /agentV2\.roster\.moreActions/ }))+ await user.click(screen.getByRole('menuitem', { name: /agentV2\.roster\.editInfo/ }))++ const dialog = await screen.findByRole('dialog', { name: 'agentV2.roster.editDialog.title' })+ const nameInput = within(dialog).getByRole('textbox', { name: 'agentV2.roster.createForm.nameLabel' })+ await user.clear(nameInput)+ await user.type(nameInput, 'Draft Name')+ await user.click(within(dialog).getByRole('button', { name: 'common.operation.cancel' }))++ await waitFor(() => {+ expect(screen.queryByRole('dialog', { name: 'agentV2.roster.editDialog.title' })).not.toBeInTheDocument()+ })++ await user.click(screen.getByRole('button', { name: /agentV2\.roster\.moreActions/ }))+ await user.click(screen.getByRole('menuitem', { name: /agentV2\.roster\.editInfo/ }))++ const reopenedDialog = await screen.findByRole('dialog', { name: 'agentV2.roster.editDialog.title' })+ expect(within(reopenedDialog).getByRole('textbox', { name: 'agentV2.roster.createForm.nameLabel' })).toHaveValue('Research Agent')+ expect(within(reopenedDialog).getByRole('textbox', { name: 'agentV2.roster.createForm.roleLabel' })).toHaveValue('Research Assistant')+ expect(within(reopenedDialog).getByRole('button', { name: 'common.operation.save' })).toBeDisabled()+ })})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.tsxindex 57fb616246f..559cfb41f1b 100644--- 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.tsx@@ -1,4 +1,4 @@-import { render, screen, within } from '@testing-library/react'+import { render, screen, waitFor, within } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { CreateAgentDialog } from '../create-agent-dialog'@@ -112,4 +112,22 @@ describe('CreateAgentDialog', () => {expect(toastMock.error).not.toHaveBeenCalled()expect(mutationMock.mutate).not.toHaveBeenCalled()})++ it('keeps the form open when the backdrop is clicked', 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' })+ const backdrop = document.body.querySelector('.bg-background-overlay') as HTMLElement+ await user.click(backdrop)++ expect(dialog).toBeInTheDocument()++ await user.click(within(dialog).getByRole('button', { name: 'common.operation.cancel' }))+ await waitFor(() => {+ expect(screen.queryByRole('dialog', { name: 'agentV2.roster.createDialog.title' })).not.toBeInTheDocument()+ })+ })})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.tsxindex be9d113c79f..eca96683382 100644--- 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.tsx@@ -75,6 +75,7 @@ const renderDialog = (agent = createAgent()) => {render(<EditAgentDialogagent={agent}+ formKey={0}openonOpenChange={onOpenChange}/>,@@ -221,4 +222,19 @@ describe('EditAgentDialog', () => {expect(toastMock.error).not.toHaveBeenCalled()expect(mutationMock.mutate).not.toHaveBeenCalled()})++ it('keeps the form open when the backdrop is clicked', async () => {+ const user = userEvent.setup()+ const { onOpenChange } = renderDialog()++ const dialog = screen.getByRole('dialog', { name: 'agentV2.roster.editDialog.title' })+ const backdrop = document.body.querySelector('.bg-background-overlay') as HTMLElement+ await user.click(backdrop)++ expect(onOpenChange).not.toHaveBeenCalledWith(false)+ expect(dialog).toBeInTheDocument()++ await user.click(within(dialog).getByRole('button', { name: 'common.operation.cancel' }))+ expect(onOpenChange).toHaveBeenCalledWith(false)+ })})diff --git a/web/features/agent-v2/roster/components/agent-form-fields.tsx b/web/features/agent-v2/roster/components/agent-form-fields.tsxnew file mode 100644index 00000000000..c3f1fe7b025--- /dev/null+++ b/web/features/agent-v2/roster/components/agent-form-fields.tsx@@ -0,0 +1,122 @@+import type { AgentIconSelection } from './agent-form'+import { FieldControl, FieldError, FieldLabel, FieldRoot } from '@langgenius/dify-ui/field'+import { Textarea } from '@langgenius/dify-ui/textarea'+import { useTranslation } from 'react-i18next'+import AppIcon from '@/app/components/base/app-icon'++type AgentFormFieldsProps = {+ description: string+ icon: AgentIconSelection+ iconAriaLabel: string+ name: string+ onDescriptionChange: (description: string) => void+ onIconClick: () => void+ onNameChange: (name: string) => void+ onRoleChange: (role: string) => void+ role: string+}++export function AgentFormFields({+ description,+ icon,+ iconAriaLabel,+ name,+ onDescriptionChange,+ onIconClick,+ onNameChange,+ onRoleChange,+ role,+}: AgentFormFieldsProps) {+ const { t } = useTranslation('agentV2')++ return (+ <div className="space-y-5 px-6 py-3">+ <div className="flex items-end gap-4 pb-2">+ <button+ type="button"+ aria-label={iconAriaLabel}+ className="shrink-0 rounded-full outline-hidden focus-visible:ring-2 focus-visible:ring-state-accent-solid"+ onClick={onIconClick}+ >+ <AppIcon+ size="xxl"+ rounded+ className="size-16 cursor-pointer"+ iconType={icon.type === 'link' ? 'image' : icon.type}+ icon={icon.type === 'emoji' ? icon.icon : undefined}+ background={icon.type === 'emoji' ? icon.background : undefined}+ imageUrl={icon.type === 'emoji' ? undefined : icon.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 -- Agent roster dialogs open from explicit commands, and the name field is the primary editable control.+ autoFocus+ maxLength={255}+ onValueChange={onNameChange}+ 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={onRoleChange}+ 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')}+ </FieldLabel>+ <Textarea+ autoComplete="off"+ className="h-20 resize-none"+ onValueChange={onDescriptionChange}+ placeholder={t('roster.createForm.descriptionPlaceholder')}+ value={description}+ />+ </FieldRoot>+ </div>+ )+}diff --git a/web/features/agent-v2/roster/components/agent-form.ts b/web/features/agent-v2/roster/components/agent-form.tsnew file mode 100644index 00000000000..cf738afbb31--- /dev/null+++ b/web/features/agent-v2/roster/components/agent-form.ts@@ -0,0 +1,54 @@+import type { AgentAppPartial } from '@dify/contracts/api/console/agent/types.gen'+import type { AppIconSelection } from '@/app/components/base/app-icon-picker'++export type AgentFormValues = {+ description?: string+ name?: string+ role?: string+}++export type AgentIconSelection = AppIconSelection | {+ type: 'link'+ icon: string+ url: string+}++export const defaultAgentIcon = {+ type: 'emoji',+ icon: '🧸',+ background: '#F5F3FF',+} satisfies AppIconSelection++export 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,+ }+}++export 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}`+}diff --git a/web/features/agent-v2/roster/components/agent-roster-list.tsx b/web/features/agent-v2/roster/components/agent-roster-list.tsxindex f59632791e2..46f36effd9c 100644--- a/web/features/agent-v2/roster/components/agent-roster-list.tsx+++ b/web/features/agent-v2/roster/components/agent-roster-list.tsx@@ -9,17 +9,15 @@ import {DropdownMenuSeparator,DropdownMenuTrigger,} from '@langgenius/dify-ui/dropdown-menu'-import { toast } from '@langgenius/dify-ui/toast'-import { useMutation } from '@tanstack/react-query'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 { consoleQuery } from '@/service/client'import { AgentWorkflowReferencesDropdown } from './agent-workflow-references-dropdown'import { DeleteAgentDialog } from './delete-agent-dialog'+import { DuplicateAgentDialog } from './duplicate-agent-dialog'import { EditAgentDialog } from './edit-agent-dialog'type AgentRosterListProps = {@@ -104,8 +102,10 @@ function AgentRosterItem({const nameId = useId()const descriptionId = useId()const [isEditOpen, setIsEditOpen] = useState(false)+ const [editSessionKey, setEditSessionKey] = useState(0)+ const [isDuplicateOpen, setIsDuplicateOpen] = useState(false)+ const [duplicateSessionKey, setDuplicateSessionKey] = useState(0)const [isDeleteOpen, setIsDeleteOpen] = useState(false)- const duplicateAgentMutation = useMutation(consoleQuery.agent.byAgentId.copy.post.mutationOptions())const updatedAt = agent.updated_at != null? formatTime(agent.updated_at, t('roster.dateTimeFormat')): null@@ -115,23 +115,15 @@ function AgentRosterItem({const isDraft = agent.active_config_is_published !== trueconst imageUrl = (agent.icon_type === 'image' || agent.icon_type === 'link') ? agent.icon : undefinedconst iconType = (imageUrl ? 'image' : agent.icon_type) as AgentIconType | null | undefined- const handleDuplicate = () => {- if (duplicateAgentMutation.isPending)- return- duplicateAgentMutation.mutate({- params: {- agent_id: agent.id,- },- body: {},- }, {- onSuccess: () => {- toast.success(t('roster.duplicateSuccess'))- },- onError: () => {- toast.error(t('roster.duplicateFailed'))- },- })+ const handleEditOpen = () => {+ setEditSessionKey(key => key + 1)+ setIsEditOpen(true)+ }++ const handleDuplicateOpen = () => {+ setDuplicateSessionKey(key => key + 1)+ setIsDuplicateOpen(true)}return (@@ -214,14 +206,13 @@ function AgentRosterItem({<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)}>+ <DropdownMenuItem className="gap-2" onClick={handleEditOpen}><span aria-hidden className="i-ri-edit-line size-4 shrink-0 text-text-tertiary" /><span>{t('roster.editInfo')}</span></DropdownMenuItem><DropdownMenuItem- disabled={duplicateAgentMutation.isPending}className="gap-2"- onClick={handleDuplicate}+ onClick={handleDuplicateOpen}><span aria-hidden className="i-ri-file-copy-line size-4 shrink-0 text-text-tertiary" /><span>{tCommon('operation.duplicate')}</span>@@ -238,7 +229,18 @@ function AgentRosterItem({</DropdownMenuContent></DropdownMenu></div>- <EditAgentDialog agent={agent} open={isEditOpen} onOpenChange={setIsEditOpen} />+ <EditAgentDialog+ agent={agent}+ formKey={editSessionKey}+ open={isEditOpen}+ onOpenChange={setIsEditOpen}+ />+ <DuplicateAgentDialog+ agent={agent}+ formKey={duplicateSessionKey}+ open={isDuplicateOpen}+ onOpenChange={setIsDuplicateOpen}+ /><DeleteAgentDialog agentId={agent.id} agentName={agent.name} open={isDeleteOpen} onOpenChange={setIsDeleteOpen} /></article>)diff --git a/web/features/agent-v2/roster/components/create-agent-dialog.tsx b/web/features/agent-v2/roster/components/create-agent-dialog.tsxindex abda2faa6af..8d31016c54c 100644--- a/web/features/agent-v2/roster/components/create-agent-dialog.tsx+++ b/web/features/agent-v2/roster/components/create-agent-dialog.tsx@@ -1,43 +1,36 @@'use client'import type { AgentAppCreatePayload } from '@dify/contracts/api/console/agent/types.gen'-import type { AppIconSelection } from '@/app/components/base/app-icon-picker'+import type { AgentFormValues, AgentIconSelection } from './agent-form'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+import { defaultAgentIcon } from './agent-form'+import { AgentFormFields } from './agent-form-fields'export function CreateAgentDialog() {const { t } = useTranslation('agentV2')const { t: tCommon } = useTranslation('common')const [open, setOpen] = useState(false)const [formKey, setFormKey] = useState(0)+ const [name, setName] = useState('')+ const [description, setDescription] = useState('')+ const [role, setRole] = useState('')const [iconPickerOpen, setIconPickerOpen] = useState(false)- const [agentIcon, setAgentIcon] = useState<AppIconSelection>(defaultAgentIcon)+ const [agentIcon, setAgentIcon] = useState<AgentIconSelection>(defaultAgentIcon)const createAgentMutation = useMutation(consoleQuery.agent.post.mutationOptions())const resetForm = () => {setFormKey(key => key + 1)+ setName('')+ setDescription('')+ setRole('')setAgentIcon(defaultAgentIcon)setIconPickerOpen(false)}@@ -75,7 +68,7 @@ export function CreateAgentDialog() {return (<>- <Dialog open={open} onOpenChange={handleOpenChange}>+ <Dialog open={open} onOpenChange={handleOpenChange} disablePointerDismissal><DialogTriggerrender={(<Button@@ -88,7 +81,7 @@ export function CreateAgentDialog() {<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" />+ <DialogCloseButton /><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')}@@ -102,91 +95,17 @@ export function CreateAgentDialog() {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>+ <AgentFormFields+ description={description}+ icon={agentIcon}+ iconAriaLabel={t('roster.createForm.changeIcon')}+ name={name}+ role={role}+ onDescriptionChange={setDescription}+ onIconClick={() => setIconPickerOpen(true)}+ onNameChange={setName}+ onRoleChange={setRole}+ /><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')}diff --git a/web/features/agent-v2/roster/components/duplicate-agent-dialog.tsx b/web/features/agent-v2/roster/components/duplicate-agent-dialog.tsxnew file mode 100644index 00000000000..4a5efae43a4--- /dev/null+++ b/web/features/agent-v2/roster/components/duplicate-agent-dialog.tsx@@ -0,0 +1,234 @@+'use client'++import type { AgentAppCopyPayload, AgentAppPartial } from '@dify/contracts/api/console/agent/types.gen'+import type { AgentFormValues, AgentIconSelection } from './agent-form'+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, useQueryClient } 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'+import { createAgentIconSelection } from './agent-form'++type DuplicateAgentDialogProps = {+ agent: AgentAppPartial+ formKey: number+ open: boolean+ onOpenChange: (open: boolean) => void+}++const getDefaultCopyName = (name: string) => {+ const suffix = ' copy'+ return `${name.slice(0, 255 - suffix.length)}${suffix}`+}++export function DuplicateAgentDialog({+ agent,+ formKey,+ open,+ onOpenChange,+}: DuplicateAgentDialogProps) {+ const { t } = useTranslation('agentV2')+ const { t: tCommon } = useTranslation('common')+ const queryClient = useQueryClient()+ const latestAgent = queryClient.getQueryData<AgentAppPartial>(consoleQuery.agent.byAgentId.get.queryKey({+ input: {+ params: {+ agent_id: agent.id,+ },+ },+ })) ?? agent+ const [renderedFormKey, setRenderedFormKey] = useState(formKey)+ const [name, setName] = useState('')+ const [description, setDescription] = useState(latestAgent.description ?? '')+ const [role, setRole] = useState(latestAgent.role ?? '')+ const [iconPickerOpen, setIconPickerOpen] = useState(false)+ const [agentIcon, setAgentIcon] = useState<AgentIconSelection>(() => createAgentIconSelection(latestAgent))+ const duplicateAgentMutation = useMutation(consoleQuery.agent.byAgentId.copy.post.mutationOptions())+ const defaultCopyName = getDefaultCopyName(latestAgent.name)++ if (formKey !== renderedFormKey) {+ setRenderedFormKey(formKey)+ setName('')+ setDescription(latestAgent.description ?? '')+ setRole(latestAgent.role ?? '')+ setIconPickerOpen(false)+ setAgentIcon(createAgentIconSelection(latestAgent))+ }++ const handleOpenChange = (nextOpen: boolean) => {+ if (nextOpen) {+ const currentAgent = queryClient.getQueryData<AgentAppPartial>(consoleQuery.agent.byAgentId.get.queryKey({+ input: {+ params: {+ agent_id: agent.id,+ },+ },+ })) ?? agent+ setName('')+ setDescription(currentAgent.description ?? '')+ setRole(currentAgent.role ?? '')+ setAgentIcon(createAgentIconSelection(currentAgent))+ }+ else {+ setIconPickerOpen(false)+ }+ onOpenChange(nextOpen)+ }++ const handleSubmit = (formValues: AgentFormValues) => {+ if (duplicateAgentMutation.isPending)+ return++ const trimmedName = formValues.name?.trim() ?? ''+ const trimmedRole = formValues.role?.trim() ?? ''+ const body: AgentAppCopyPayload = {+ 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,+ ...(trimmedName ? { name: trimmedName } : {}),+ }++ duplicateAgentMutation.mutate({+ params: {+ agent_id: agent.id,+ },+ body,+ }, {+ onSuccess: () => {+ toast.success(t('roster.duplicateSuccess'))+ handleOpenChange(false)+ },+ })+ }++ return (+ <>+ <Dialog open={open} onOpenChange={handleOpenChange} disablePointerDismissal>+ <DialogContent className="flex max-h-[calc(100dvh-2rem)] w-130 flex-col overflow-hidden! p-0!">+ <DialogCloseButton />+ <div className="shrink-0 pt-6 pr-14 pb-3 pl-6">+ <DialogTitle className="title-2xl-semi-bold text-text-primary">+ {t('roster.duplicateDialog.title')}+ </DialogTitle>+ <DialogDescription className="sr-only">+ {t('roster.duplicateDialog.description', { name: latestAgent.name })}+ </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.duplicateForm.changeIcon', { name: latestAgent.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">+ <FieldLabel>+ {t('roster.createForm.nameLabel')}+ <span className="ml-1 system-xs-regular text-text-tertiary">+ {tCommon('label.optional')}+ </span>+ </FieldLabel>+ <FieldControl+ autoComplete="off"+ // eslint-disable-next-line jsx-a11y/no-autofocus -- The duplicate dialog opens from an explicit command, and naming the copy is the primary editable action.+ autoFocus+ maxLength={255}+ onValueChange={setName}+ placeholder={defaultCopyName}+ value={name}+ />+ </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')}+ </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={() => handleOpenChange(false)} disabled={duplicateAgentMutation.isPending}>+ {tCommon('operation.cancel')}+ </Button>+ <Button+ type="submit"+ variant="primary"+ className="min-w-18"+ loading={duplicateAgentMutation.isPending}+ >+ {tCommon('operation.duplicate')}+ </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/edit-agent-dialog.tsx b/web/features/agent-v2/roster/components/edit-agent-dialog.tsxindex 3688476972a..222761dc386 100644--- a/web/features/agent-v2/roster/components/edit-agent-dialog.tsx+++ b/web/features/agent-v2/roster/components/edit-agent-dialog.tsx@@ -1,78 +1,26 @@'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 type { AgentFormValues, AgentIconSelection } from './agent-form'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'+import { createAgentIconSelection, getAgentIconKey } from './agent-form'+import { AgentFormFields } from './agent-form-fields'type EditAgentDialogProps = {agent: AgentAppPartial+ formKey: numberopen: booleanonOpenChange: (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@@ -88,11 +36,13 @@ const applyIconPayload = (body: AgentAppUpdatePayload, icon: AgentIconSelection)export function EditAgentDialog({agent,+ formKey,open,onOpenChange,}: EditAgentDialogProps) {const { t } = useTranslation('agentV2')const { t: tCommon } = useTranslation('common')+ const [renderedFormKey, setRenderedFormKey] = useState(formKey)const [name, setName] = useState(agent.name)const [description, setDescription] = useState(agent.description ?? '')const [role, setRole] = useState(agent.role ?? '')@@ -100,6 +50,28 @@ export function EditAgentDialog({const [agentIcon, setAgentIcon] = useState<AgentIconSelection>(() => createAgentIconSelection(agent))const updateAgentMutation = useMutation(consoleQuery.agent.byAgentId.put.mutationOptions())+ if (formKey !== renderedFormKey) {+ setRenderedFormKey(formKey)+ setName(agent.name)+ setDescription(agent.description ?? '')+ setRole(agent.role ?? '')+ setIconPickerOpen(false)+ setAgentIcon(createAgentIconSelection(agent))+ }++ const handleOpenChange = (nextOpen: boolean) => {+ if (nextOpen) {+ setName(agent.name)+ setDescription(agent.description ?? '')+ setRole(agent.role ?? '')+ setAgentIcon(createAgentIconSelection(agent))+ }+ else {+ setIconPickerOpen(false)+ }+ onOpenChange(nextOpen)+ }+const handleSubmit = (formValues: AgentFormValues) => {const trimmedName = formValues.name?.trim() ?? ''const trimmedDescription = formValues.description?.trim() ?? ''@@ -134,24 +106,11 @@ export function EditAgentDialog({}, {onSuccess: () => {toast.success(t('roster.updateSuccess'))- onOpenChange(false)+ handleOpenChange(false)},})}- 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()@@ -163,9 +122,9 @@ export function EditAgentDialog({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" />+ <Dialog open={open} onOpenChange={handleOpenChange} disablePointerDismissal>+ <DialogContent className="flex max-h-[calc(100dvh-2rem)] w-130 flex-col overflow-hidden! p-0!">+ <DialogCloseButton /><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')}@@ -175,102 +134,23 @@ export function EditAgentDialog({</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.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>+ <AgentFormFields+ description={description}+ icon={agentIcon}+ iconAriaLabel={t('roster.editAgent', { name: agent.name })}+ name={name}+ role={role}+ onDescriptionChange={setDescription}+ onIconClick={() => setIconPickerOpen(true)}+ onNameChange={setName}+ onRoleChange={setRole}+ /><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}>+ <Button type="button" className="min-w-18" onClick={() => handleOpenChange(false)} disabled={updateAgentMutation.isPending}>{tCommon('operation.cancel')}</Button><Buttondiff --git a/web/i18n/ar-TN/agent-v-2.json b/web/i18n/ar-TN/agent-v-2.jsonindex 0345d06d865..5cc80c512d8 100644--- a/web/i18n/ar-TN/agent-v-2.json+++ b/web/i18n/ar-TN/agent-v-2.json@@ -290,6 +290,7 @@"agentDetail.monitoring.dateRangeLabel": "نطاق التاريخ","agentDetail.monitoring.description": "تتبّع نشاط وتكلفة وجودة تفاعل الوكيل القابل لإعادة الاستخدام عبر سير العمل.","agentDetail.monitoring.learnMore": "اعرف المزيد",+ "agentDetail.monitoring.loadFailed": "تعذر تحميل بيانات المراقبة","agentDetail.monitoring.metrics.activeUsers.explanation": "المستخدمون النهائيون الفريدون الذين شغّلوا سير العمل باستخدام هذا الوكيل.","agentDetail.monitoring.metrics.activeUsers.title": "المستخدمون النشطون","agentDetail.monitoring.metrics.avgSessionInteractions.explanation": "عدد التواصل المستمر بين المستخدم والوكيل لنقطة الوصول هذه.",@@ -328,15 +329,17 @@"agentDetail.type": "وكيل","agentDetail.versionHistory.active": "نشط","agentDetail.versionHistory.empty": "لا توجد إصدارات بعد",+ "agentDetail.versionHistory.exitVersions": "الخروج من الإصدارات","agentDetail.versionHistory.filter": "تصفية الإصدارات",+ "agentDetail.versionHistory.restore": "استعادة","agentDetail.versionHistory.versionName": "الإصدار {{version}}",+ "agentDetail.versionHistory.viewOnly": "عرض فقط","roster.createAgent": "إنشاء وكيل","roster.createAgentOptions": "خيارات إنشاء الوكيل","roster.createDialog.description": "أنشئ وكيلاً قابلاً لإعادة الاستخدام في Roster مساحة العمل هذه.","roster.createDialog.title": "إنشاء وكيل","roster.createForm.changeIcon": "تغيير أيقونة الوكيل","roster.createForm.descriptionLabel": "الوصف",- "roster.createForm.descriptionOptional": "(اختياري)","roster.createForm.descriptionPlaceholder": "مثلاً يجمع المصادر حول موضوع ويلخص النتائج الرئيسية","roster.createForm.nameLabel": "الاسم","roster.createForm.namePlaceholder": "مثلاً Max",@@ -350,7 +353,6 @@"roster.deleteDialog.title": "حذف {{name}}؟","roster.deleteFailed": "فشل حذف الوكيل.","roster.deleteSuccess": "تم حذف الوكيل.",- "roster.duplicateFailed": "فشل نسخ الوكيل.","roster.duplicateSuccess": "تم نسخ الوكيل.","roster.editAgent": "تعديل {{name}}","roster.editDialog.description": "حدّث اسم Roster والوصف والدور لهذا الوكيل.",diff --git a/web/i18n/de-DE/agent-v-2.json b/web/i18n/de-DE/agent-v-2.jsonindex 6a346017576..71b4f9c8bb7 100644--- a/web/i18n/de-DE/agent-v-2.json+++ b/web/i18n/de-DE/agent-v-2.json@@ -290,6 +290,7 @@"agentDetail.monitoring.dateRangeLabel": "Datumsbereich","agentDetail.monitoring.description": "Verfolgen Sie Aktivität, Kosten und Interaktionsqualität des wiederverwendbaren Agenten über Workflows hinweg.","agentDetail.monitoring.learnMore": "Mehr erfahren",+ "agentDetail.monitoring.loadFailed": "Monitoring-Daten konnten nicht geladen werden","agentDetail.monitoring.metrics.activeUsers.explanation": "Eindeutige Endbenutzer, die Workflows mit diesem Agenten ausgelöst haben.","agentDetail.monitoring.metrics.activeUsers.title": "Aktive Benutzer","agentDetail.monitoring.metrics.avgSessionInteractions.explanation": "Anzahl der durchgehenden Benutzer-Agent-Kommunikationen für diesen Zugangspunkt.",@@ -328,15 +329,17 @@"agentDetail.type": "AGENT","agentDetail.versionHistory.active": "Aktiv","agentDetail.versionHistory.empty": "Noch keine Versionen",+ "agentDetail.versionHistory.exitVersions": "Versionen verlassen","agentDetail.versionHistory.filter": "Versionen filtern",+ "agentDetail.versionHistory.restore": "Wiederherstellen","agentDetail.versionHistory.versionName": "Version {{version}}",+ "agentDetail.versionHistory.viewOnly": "Nur anzeigen","roster.createAgent": "Agent erstellen","roster.createAgentOptions": "Optionen zum Erstellen eines Agenten","roster.createDialog.description": "Erstellen Sie einen wiederverwendbaren Agenten im Roster dieses Workspaces.","roster.createDialog.title": "Agent erstellen","roster.createForm.changeIcon": "Agenten-Symbol ändern","roster.createForm.descriptionLabel": "Beschreibung",- "roster.createForm.descriptionOptional": "(optional)","roster.createForm.descriptionPlaceholder": "z. B. Sammelt Quellen zu einem Thema und fasst die wichtigsten Erkenntnisse zusammen","roster.createForm.nameLabel": "Name","roster.createForm.namePlaceholder": "z. B. Max",@@ -350,7 +353,6 @@"roster.deleteDialog.title": "{{name}} löschen?","roster.deleteFailed": "Agent konnte nicht gelöscht werden.","roster.deleteSuccess": "Agent gelöscht.",- "roster.duplicateFailed": "Agent konnte nicht dupliziert werden.","roster.duplicateSuccess": "Agent dupliziert.","roster.editAgent": "{{name}} bearbeiten","roster.editDialog.description": "Aktualisieren Sie Roster-Name, Beschreibung und Rolle dieses Agenten.",diff --git a/web/i18n/en-US/agent-v-2.json b/web/i18n/en-US/agent-v-2.jsonindex 6ce81aa591e..3e75fd784a3 100644--- a/web/i18n/en-US/agent-v-2.json+++ b/web/i18n/en-US/agent-v-2.json@@ -290,6 +290,7 @@"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.loadFailed": "Failed to load monitoring data","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.",@@ -328,15 +329,17 @@"agentDetail.type": "AGENT","agentDetail.versionHistory.active": "Active","agentDetail.versionHistory.empty": "No versions yet",+ "agentDetail.versionHistory.exitVersions": "Exit versions","agentDetail.versionHistory.filter": "Filter versions",+ "agentDetail.versionHistory.restore": "Restore","agentDetail.versionHistory.versionName": "Version {{version}}",+ "agentDetail.versionHistory.viewOnly": "View Only","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.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",@@ -350,7 +353,9 @@"roster.deleteDialog.title": "Delete {{name}}?","roster.deleteFailed": "Failed to delete agent.","roster.deleteSuccess": "Agent deleted.",- "roster.duplicateFailed": "Failed to duplicate agent.",+ "roster.duplicateDialog.description": "Create a copy of {{name}} and customize its roster identity.",+ "roster.duplicateDialog.title": "Duplicate agent",+ "roster.duplicateForm.changeIcon": "Change duplicate icon for {{name}}","roster.duplicateSuccess": "Agent duplicated.","roster.editAgent": "Edit {{name}}","roster.editDialog.description": "Update the roster name, description, and role for this agent.",diff --git a/web/i18n/es-ES/agent-v-2.json b/web/i18n/es-ES/agent-v-2.jsonindex fb23b2a523e..3e74421f666 100644--- a/web/i18n/es-ES/agent-v-2.json+++ b/web/i18n/es-ES/agent-v-2.json@@ -290,6 +290,7 @@"agentDetail.monitoring.dateRangeLabel": "Rango de fechas","agentDetail.monitoring.description": "Realiza un seguimiento de la actividad, el coste y la calidad de interacción del agente reutilizable en todos los flujos de trabajo.","agentDetail.monitoring.learnMore": "Más información",+ "agentDetail.monitoring.loadFailed": "No se pudieron cargar los datos de monitoreo","agentDetail.monitoring.metrics.activeUsers.explanation": "Usuarios finales únicos que activaron flujos de trabajo usando este agente.","agentDetail.monitoring.metrics.activeUsers.title": "Usuarios activos","agentDetail.monitoring.metrics.avgSessionInteractions.explanation": "Recuento continuo de comunicación entre usuario y agente para este punto de acceso.",@@ -328,15 +329,17 @@"agentDetail.type": "AGENTE","agentDetail.versionHistory.active": "Activa","agentDetail.versionHistory.empty": "Aún no hay versiones",+ "agentDetail.versionHistory.exitVersions": "Salir de versiones","agentDetail.versionHistory.filter": "Filtrar versiones",+ "agentDetail.versionHistory.restore": "Restaurar","agentDetail.versionHistory.versionName": "Versión {{version}}",+ "agentDetail.versionHistory.viewOnly": "Solo lectura","roster.createAgent": "Crear agente","roster.createAgentOptions": "Opciones para crear agente","roster.createDialog.description": "Crea un agente reutilizable en el roster de este workspace.","roster.createDialog.title": "Crear agente","roster.createForm.changeIcon": "Cambiar icono del agente","roster.createForm.descriptionLabel": "Descripción",- "roster.createForm.descriptionOptional": "(opcional)","roster.createForm.descriptionPlaceholder": "p. ej. Reúne fuentes sobre un tema y resume los hallazgos clave","roster.createForm.nameLabel": "Nombre","roster.createForm.namePlaceholder": "p. ej. Max",@@ -350,7 +353,6 @@"roster.deleteDialog.title": "¿Eliminar {{name}}?","roster.deleteFailed": "Error al eliminar el agente.","roster.deleteSuccess": "Agente eliminado.",- "roster.duplicateFailed": "Error al duplicar el agente.","roster.duplicateSuccess": "Agente duplicado.","roster.editAgent": "Editar {{name}}","roster.editDialog.description": "Actualiza el nombre, la descripción y el rol del roster para este agente.",diff --git a/web/i18n/fa-IR/agent-v-2.json b/web/i18n/fa-IR/agent-v-2.jsonindex 45b5891dc26..1913710394c 100644--- a/web/i18n/fa-IR/agent-v-2.json+++ b/web/i18n/fa-IR/agent-v-2.json@@ -290,6 +290,7 @@"agentDetail.monitoring.dateRangeLabel": "بازه تاریخ","agentDetail.monitoring.description": "فعالیت، هزینه و کیفیت تعامل عامل قابل استفاده مجدد را در گردشهای کار دنبال کنید.","agentDetail.monitoring.learnMore": "اطلاعات بیشتر",+ "agentDetail.monitoring.loadFailed": "بارگیری دادههای پایش ناموفق بود","agentDetail.monitoring.metrics.activeUsers.explanation": "کاربران نهایی منحصربهفردی که با استفاده از این عامل گردش کارها را راهاندازی کردهاند.","agentDetail.monitoring.metrics.activeUsers.title": "کاربران فعال","agentDetail.monitoring.metrics.avgSessionInteractions.explanation": "تعداد ارتباط مداوم کاربر-عامل برای این نقطه دسترسی.",@@ -328,15 +329,17 @@"agentDetail.type": "عامل","agentDetail.versionHistory.active": "فعال","agentDetail.versionHistory.empty": "هنوز نسخهای وجود ندارد",+ "agentDetail.versionHistory.exitVersions": "خروج از نسخهها","agentDetail.versionHistory.filter": "فیلتر نسخهها",+ "agentDetail.versionHistory.restore": "بازیابی","agentDetail.versionHistory.versionName": "نسخه {{version}}",+ "agentDetail.versionHistory.viewOnly": "فقط نمایش","roster.createAgent": "ایجاد عامل","roster.createAgentOptions": "گزینههای ایجاد عامل","roster.createDialog.description": "یک عامل قابل استفاده مجدد در Roster این فضای کاری ایجاد کنید.","roster.createDialog.title": "ایجاد عامل","roster.createForm.changeIcon": "تغییر آیکون عامل","roster.createForm.descriptionLabel": "توضیحات",- "roster.createForm.descriptionOptional": "(اختیاری)","roster.createForm.descriptionPlaceholder": "مثلاً منابعی درباره یک موضوع جمعآوری میکند و یافتههای کلیدی را خلاصه میکند","roster.createForm.nameLabel": "نام","roster.createForm.namePlaceholder": "مثلاً Max",@@ -350,7 +353,6 @@"roster.deleteDialog.title": "حذف {{name}}؟","roster.deleteFailed": "حذف عامل ناموفق بود.","roster.deleteSuccess": "عامل حذف شد.",- "roster.duplicateFailed": "تکثیر عامل ناموفق بود.","roster.duplicateSuccess": "عامل تکثیر شد.","roster.editAgent": "ویرایش {{name}}","roster.editDialog.description": "نام، توضیحات و نقش Roster این عامل را بهروزرسانی کنید.",diff --git a/web/i18n/fr-FR/agent-v-2.json b/web/i18n/fr-FR/agent-v-2.jsonindex 804b2624f44..d3a86dc1f04 100644--- a/web/i18n/fr-FR/agent-v-2.json+++ b/web/i18n/fr-FR/agent-v-2.json@@ -290,6 +290,7 @@"agentDetail.monitoring.dateRangeLabel": "Plage de dates","agentDetail.monitoring.description": "Suivez l’activité, le coût et la qualité d’interaction de l’agent réutilisable dans tous les workflows.","agentDetail.monitoring.learnMore": "En savoir plus",+ "agentDetail.monitoring.loadFailed": "Échec du chargement des données de surveillance","agentDetail.monitoring.metrics.activeUsers.explanation": "Utilisateurs finaux uniques ayant déclenché des workflows utilisant cet agent.","agentDetail.monitoring.metrics.activeUsers.title": "Utilisateurs actifs","agentDetail.monitoring.metrics.avgSessionInteractions.explanation": "Nombre de communications continues entre utilisateur et agent pour ce point d’accès.",@@ -328,15 +329,17 @@"agentDetail.type": "AGENT","agentDetail.versionHistory.active": "Actif","agentDetail.versionHistory.empty": "Pas encore de versions",+ "agentDetail.versionHistory.exitVersions": "Quitter les versions","agentDetail.versionHistory.filter": "Filtrer les versions",+ "agentDetail.versionHistory.restore": "Restaurer","agentDetail.versionHistory.versionName": "Version {{version}}",+ "agentDetail.versionHistory.viewOnly": "Lecture seule","roster.createAgent": "Créer un agent","roster.createAgentOptions": "Options de création d’agent","roster.createDialog.description": "Créez un agent réutilisable dans le roster de cet espace de travail.","roster.createDialog.title": "Créer un agent","roster.createForm.changeIcon": "Changer l’icône de l’agent","roster.createForm.descriptionLabel": "Description",- "roster.createForm.descriptionOptional": "(facultatif)","roster.createForm.descriptionPlaceholder": "p. ex. Rassemble des sources sur un sujet et résume les principales conclusions","roster.createForm.nameLabel": "Nom","roster.createForm.namePlaceholder": "p. ex. Max",@@ -350,7 +353,6 @@"roster.deleteDialog.title": "Supprimer {{name}} ?","roster.deleteFailed": "Échec de la suppression de l’agent.","roster.deleteSuccess": "Agent supprimé.",- "roster.duplicateFailed": "Échec de la duplication de l’agent.","roster.duplicateSuccess": "Agent dupliqué.","roster.editAgent": "Modifier {{name}}","roster.editDialog.description": "Mettez à jour le nom, la description et le rôle de cet agent dans le roster.",diff --git a/web/i18n/hi-IN/agent-v-2.json b/web/i18n/hi-IN/agent-v-2.jsonindex ba5f7df6d58..86c0c2e5be2 100644--- a/web/i18n/hi-IN/agent-v-2.json+++ b/web/i18n/hi-IN/agent-v-2.json@@ -290,6 +290,7 @@"agentDetail.monitoring.dateRangeLabel": "दिनांक सीमा","agentDetail.monitoring.description": "वर्कफ़्लो में पुनः उपयोग योग्य एजेंट गतिविधि, लागत और इंटरैक्शन गुणवत्ता को ट्रैक करें।","agentDetail.monitoring.learnMore": "और अधिक जानें",+ "agentDetail.monitoring.loadFailed": "मॉनिटरिंग डेटा लोड नहीं हो सका","agentDetail.monitoring.metrics.activeUsers.explanation": "अद्वितीय अंतिम-उपयोगकर्ता जिन्होंने इस एजेंट का उपयोग करके वर्कफ़्लो ट्रिगर किए।","agentDetail.monitoring.metrics.activeUsers.title": "सक्रिय उपयोगकर्ता","agentDetail.monitoring.metrics.avgSessionInteractions.explanation": "इस एक्सेस पॉइंट के लिए निरंतर उपयोगकर्ता-एजेंट संचार गणना।",@@ -328,15 +329,17 @@"agentDetail.type": "एजेंट","agentDetail.versionHistory.active": "सक्रिय","agentDetail.versionHistory.empty": "अभी तक कोई संस्करण नहीं",+ "agentDetail.versionHistory.exitVersions": "संस्करणों से बाहर निकलें","agentDetail.versionHistory.filter": "संस्करण फ़िल्टर करें",+ "agentDetail.versionHistory.restore": "रीस्टोर करें","agentDetail.versionHistory.versionName": "संस्करण {{version}}",+ "agentDetail.versionHistory.viewOnly": "केवल देखें","roster.createAgent": "एजेंट बनाएँ","roster.createAgentOptions": "एजेंट बनाने के विकल्प","roster.createDialog.description": "इस कार्यक्षेत्र Roster में एक पुनः उपयोग योग्य एजेंट बनाएँ।","roster.createDialog.title": "एजेंट बनाएँ","roster.createForm.changeIcon": "एजेंट आइकन बदलें","roster.createForm.descriptionLabel": "विवरण",- "roster.createForm.descriptionOptional": "(वैकल्पिक)","roster.createForm.descriptionPlaceholder": "उदा. किसी विषय पर स्रोत एकत्र करता है और मुख्य निष्कर्षों का सारांश देता है","roster.createForm.nameLabel": "नाम","roster.createForm.namePlaceholder": "उदा. Max",@@ -350,7 +353,6 @@"roster.deleteDialog.title": "{{name}} हटाएँ?","roster.deleteFailed": "एजेंट हटाने में विफल।","roster.deleteSuccess": "एजेंट हटा दिया गया।",- "roster.duplicateFailed": "एजेंट डुप्लिकेट करने में विफल।","roster.duplicateSuccess": "एजेंट डुप्लिकेट किया गया।","roster.editAgent": "{{name}} संपादित करें","roster.editDialog.description": "इस एजेंट का Roster नाम, विवरण और भूमिका अपडेट करें।",diff --git a/web/i18n/id-ID/agent-v-2.json b/web/i18n/id-ID/agent-v-2.jsonindex f2827f73016..bf0cb2e2323 100644--- a/web/i18n/id-ID/agent-v-2.json+++ b/web/i18n/id-ID/agent-v-2.json@@ -290,6 +290,7 @@"agentDetail.monitoring.dateRangeLabel": "Rentang tanggal","agentDetail.monitoring.description": "Lacak aktivitas, biaya, dan kualitas interaksi agen yang dapat digunakan kembali di seluruh alur kerja.","agentDetail.monitoring.learnMore": "Pelajari lebih lanjut",+ "agentDetail.monitoring.loadFailed": "Gagal memuat data pemantauan","agentDetail.monitoring.metrics.activeUsers.explanation": "Pengguna akhir unik yang memicu alur kerja menggunakan agen ini.","agentDetail.monitoring.metrics.activeUsers.title": "Pengguna Aktif","agentDetail.monitoring.metrics.avgSessionInteractions.explanation": "Hitungan komunikasi pengguna-agen yang berkelanjutan untuk titik akses ini.",@@ -328,15 +329,17 @@"agentDetail.type": "AGEN","agentDetail.versionHistory.active": "Aktif","agentDetail.versionHistory.empty": "Belum ada versi",+ "agentDetail.versionHistory.exitVersions": "Keluar versi","agentDetail.versionHistory.filter": "Filter versi",+ "agentDetail.versionHistory.restore": "Pulihkan","agentDetail.versionHistory.versionName": "Versi {{version}}",+ "agentDetail.versionHistory.viewOnly": "Hanya lihat","roster.createAgent": "Buat agen","roster.createAgentOptions": "Opsi buat agen","roster.createDialog.description": "Buat agen yang dapat digunakan kembali di Roster ruang kerja ini.","roster.createDialog.title": "Buat agen","roster.createForm.changeIcon": "Ubah ikon agen","roster.createForm.descriptionLabel": "Deskripsi",- "roster.createForm.descriptionOptional": "(opsional)","roster.createForm.descriptionPlaceholder": "mis. Mengumpulkan sumber tentang suatu topik dan merangkum temuan utama","roster.createForm.nameLabel": "Nama","roster.createForm.namePlaceholder": "mis. Max",@@ -350,7 +353,6 @@"roster.deleteDialog.title": "Hapus {{name}}?","roster.deleteFailed": "Gagal menghapus agen.","roster.deleteSuccess": "Agen dihapus.",- "roster.duplicateFailed": "Gagal menduplikasi agen.","roster.duplicateSuccess": "Agen diduplikasi.","roster.editAgent": "Edit {{name}}","roster.editDialog.description": "Perbarui nama, deskripsi, dan peran Roster untuk agen ini.",diff --git a/web/i18n/it-IT/agent-v-2.json b/web/i18n/it-IT/agent-v-2.jsonindex a38e2808ab7..8fd2023d472 100644--- a/web/i18n/it-IT/agent-v-2.json+++ b/web/i18n/it-IT/agent-v-2.json@@ -290,6 +290,7 @@"agentDetail.monitoring.dateRangeLabel": "Intervallo di date","agentDetail.monitoring.description": "Monitora l’attività, il costo e la qualità dell’interazione dell’agente riutilizzabile in tutti i workflow.","agentDetail.monitoring.learnMore": "Scopri di più",+ "agentDetail.monitoring.loadFailed": "Impossibile caricare i dati di monitoraggio","agentDetail.monitoring.metrics.activeUsers.explanation": "Utenti finali unici che hanno attivato workflow utilizzando questo agente.","agentDetail.monitoring.metrics.activeUsers.title": "Utenti attivi","agentDetail.monitoring.metrics.avgSessionInteractions.explanation": "Conteggio della comunicazione continua tra utente e agente per questo punto di accesso.",@@ -328,15 +329,17 @@"agentDetail.type": "AGENTE","agentDetail.versionHistory.active": "Attiva","agentDetail.versionHistory.empty": "Nessuna versione al momento",+ "agentDetail.versionHistory.exitVersions": "Esci dalle versioni","agentDetail.versionHistory.filter": "Filtra versioni",+ "agentDetail.versionHistory.restore": "Ripristina","agentDetail.versionHistory.versionName": "Versione {{version}}",+ "agentDetail.versionHistory.viewOnly": "Sola lettura","roster.createAgent": "Crea agente","roster.createAgentOptions": "Opzioni di creazione agente","roster.createDialog.description": "Crea un agente riutilizzabile nel roster di questo workspace.","roster.createDialog.title": "Crea agente","roster.createForm.changeIcon": "Cambia icona dell’agente","roster.createForm.descriptionLabel": "Descrizione",- "roster.createForm.descriptionOptional": "(facoltativo)","roster.createForm.descriptionPlaceholder": "ad es. Raccoglie fonti su un argomento e riassume i risultati chiave","roster.createForm.nameLabel": "Nome","roster.createForm.namePlaceholder": "ad es. Max",@@ -350,7 +353,6 @@"roster.deleteDialog.title": "Eliminare {{name}}?","roster.deleteFailed": "Impossibile eliminare l’agente.","roster.deleteSuccess": "Agente eliminato.",- "roster.duplicateFailed": "Impossibile duplicare l’agente.","roster.duplicateSuccess": "Agente duplicato.","roster.editAgent": "Modifica {{name}}","roster.editDialog.description": "Aggiorna il nome, la descrizione e il ruolo del roster per questo agente.",diff --git a/web/i18n/ja-JP/agent-v-2.json b/web/i18n/ja-JP/agent-v-2.jsonindex 2fd910cdb64..eb014461bc2 100644--- a/web/i18n/ja-JP/agent-v-2.json+++ b/web/i18n/ja-JP/agent-v-2.json@@ -290,6 +290,7 @@"agentDetail.monitoring.dateRangeLabel": "日付範囲","agentDetail.monitoring.description": "ワークフロー全体での再利用可能なエージェントのアクティビティ、コスト、対話品質を追跡します。","agentDetail.monitoring.learnMore": "詳細を見る",+ "agentDetail.monitoring.loadFailed": "モニタリングデータの読み込みに失敗しました","agentDetail.monitoring.metrics.activeUsers.explanation": "このエージェントを使ったワークフローをトリガーしたユニークエンドユーザー数。","agentDetail.monitoring.metrics.activeUsers.title": "アクティブユーザー","agentDetail.monitoring.metrics.avgSessionInteractions.explanation": "このアクセスポイントにおけるユーザーとエージェントの連続通信回数。",@@ -328,15 +329,17 @@"agentDetail.type": "エージェント","agentDetail.versionHistory.active": "アクティブ","agentDetail.versionHistory.empty": "バージョンはまだありません",+ "agentDetail.versionHistory.exitVersions": "バージョンを終了","agentDetail.versionHistory.filter": "バージョンをフィルター",+ "agentDetail.versionHistory.restore": "復元","agentDetail.versionHistory.versionName": "バージョン {{version}}",+ "agentDetail.versionHistory.viewOnly": "表示のみ","roster.createAgent": "エージェントを作成","roster.createAgentOptions": "エージェント作成オプション","roster.createDialog.description": "このワークスペース Roster に再利用可能なエージェントを作成します。","roster.createDialog.title": "エージェントを作成","roster.createForm.changeIcon": "エージェントアイコンを変更","roster.createForm.descriptionLabel": "説明",- "roster.createForm.descriptionOptional": "(任意)","roster.createForm.descriptionPlaceholder": "例: トピックのソースを収集し、主要な発見を要約する","roster.createForm.nameLabel": "名前","roster.createForm.namePlaceholder": "例: Max",@@ -350,7 +353,6 @@"roster.deleteDialog.title": "{{name}} を削除しますか?","roster.deleteFailed": "エージェントの削除に失敗しました。","roster.deleteSuccess": "エージェントを削除しました。",- "roster.duplicateFailed": "エージェントの複製に失敗しました。","roster.duplicateSuccess": "エージェントを複製しました。","roster.editAgent": "{{name}} を編集","roster.editDialog.description": "このエージェントの Roster 名、説明、ロールを更新します。",diff --git a/web/i18n/ko-KR/agent-v-2.json b/web/i18n/ko-KR/agent-v-2.jsonindex 2356cdcef67..e4121a0b38c 100644--- a/web/i18n/ko-KR/agent-v-2.json+++ b/web/i18n/ko-KR/agent-v-2.json@@ -290,6 +290,7 @@"agentDetail.monitoring.dateRangeLabel": "날짜 범위","agentDetail.monitoring.description": "워크플로 전반에 걸친 재사용 가능한 에이전트의 활동, 비용 및 상호 작용 품질을 추적합니다.","agentDetail.monitoring.learnMore": "자세히 알아보기",+ "agentDetail.monitoring.loadFailed": "모니터링 데이터를 불러오지 못했습니다","agentDetail.monitoring.metrics.activeUsers.explanation": "이 에이전트를 사용하는 워크플로를 트리거한 고유 최종 사용자 수.","agentDetail.monitoring.metrics.activeUsers.title": "활성 사용자","agentDetail.monitoring.metrics.avgSessionInteractions.explanation": "이 액세스 지점에서의 사용자-에이전트 연속 통신 횟수.",@@ -328,15 +329,17 @@"agentDetail.type": "에이전트","agentDetail.versionHistory.active": "활성","agentDetail.versionHistory.empty": "아직 버전이 없습니다",+ "agentDetail.versionHistory.exitVersions": "버전 나가기","agentDetail.versionHistory.filter": "버전 필터",+ "agentDetail.versionHistory.restore": "복원","agentDetail.versionHistory.versionName": "버전 {{version}}",+ "agentDetail.versionHistory.viewOnly": "보기 전용","roster.createAgent": "에이전트 만들기","roster.createAgentOptions": "에이전트 만들기 옵션","roster.createDialog.description": "이 워크스페이스 Roster 에 재사용 가능한 에이전트를 만듭니다.","roster.createDialog.title": "에이전트 만들기","roster.createForm.changeIcon": "에이전트 아이콘 변경","roster.createForm.descriptionLabel": "설명",- "roster.createForm.descriptionOptional": "(선택 사항)","roster.createForm.descriptionPlaceholder": "예: 주제에 대한 소스를 수집하고 핵심 결과를 요약","roster.createForm.nameLabel": "이름","roster.createForm.namePlaceholder": "예: Max",@@ -350,7 +353,6 @@"roster.deleteDialog.title": "{{name}}을(를) 삭제하시겠습니까?","roster.deleteFailed": "에이전트 삭제에 실패했습니다.","roster.deleteSuccess": "에이전트가 삭제되었습니다.",- "roster.duplicateFailed": "에이전트 복제에 실패했습니다.","roster.duplicateSuccess": "에이전트가 복제되었습니다.","roster.editAgent": "{{name}} 편집","roster.editDialog.description": "이 에이전트의 Roster 이름, 설명 및 역할을 업데이트합니다.",diff --git a/web/i18n/nl-NL/agent-v-2.json b/web/i18n/nl-NL/agent-v-2.jsonindex 9209a7ed773..7681b56bca4 100644--- a/web/i18n/nl-NL/agent-v-2.json+++ b/web/i18n/nl-NL/agent-v-2.json@@ -290,6 +290,7 @@"agentDetail.monitoring.dateRangeLabel": "Datumbereik","agentDetail.monitoring.description": "Volg de activiteit, kosten en interactiekwaliteit van de herbruikbare agent over workflows heen.","agentDetail.monitoring.learnMore": "Meer informatie",+ "agentDetail.monitoring.loadFailed": "Monitoringgegevens laden mislukt","agentDetail.monitoring.metrics.activeUsers.explanation": "Unieke eindgebruikers die workflows met deze agent hebben getriggerd.","agentDetail.monitoring.metrics.activeUsers.title": "Actieve gebruikers","agentDetail.monitoring.metrics.avgSessionInteractions.explanation": "Aaneengesloten communicatie tussen gebruiker en agent voor dit toegangspunt.",@@ -328,15 +329,17 @@"agentDetail.type": "AGENT","agentDetail.versionHistory.active": "Actief","agentDetail.versionHistory.empty": "Nog geen versies",+ "agentDetail.versionHistory.exitVersions": "Versies verlaten","agentDetail.versionHistory.filter": "Versies filteren",+ "agentDetail.versionHistory.restore": "Herstellen","agentDetail.versionHistory.versionName": "Versie {{version}}",+ "agentDetail.versionHistory.viewOnly": "Alleen bekijken","roster.createAgent": "Agent aanmaken","roster.createAgentOptions": "Opties voor agent aanmaken","roster.createDialog.description": "Maak een herbruikbare agent in het roster van deze werkruimte.","roster.createDialog.title": "Agent aanmaken","roster.createForm.changeIcon": "Agentpictogram wijzigen","roster.createForm.descriptionLabel": "Beschrijving",- "roster.createForm.descriptionOptional": "(optioneel)","roster.createForm.descriptionPlaceholder": "bv. Verzamelt bronnen over een onderwerp en vat de belangrijkste bevindingen samen","roster.createForm.nameLabel": "Naam","roster.createForm.namePlaceholder": "bv. Max",@@ -350,7 +353,6 @@"roster.deleteDialog.title": "{{name}} verwijderen?","roster.deleteFailed": "Verwijderen van agent mislukt.","roster.deleteSuccess": "Agent verwijderd.",- "roster.duplicateFailed": "Dupliceren van agent mislukt.","roster.duplicateSuccess": "Agent gedupliceerd.","roster.editAgent": "{{name}} bewerken","roster.editDialog.description": "Werk de rosternaam, beschrijving en rol van deze agent bij.",diff --git a/web/i18n/pl-PL/agent-v-2.json b/web/i18n/pl-PL/agent-v-2.jsonindex 077cb79e70c..a5c06bbe9d1 100644--- a/web/i18n/pl-PL/agent-v-2.json+++ b/web/i18n/pl-PL/agent-v-2.json@@ -290,6 +290,7 @@"agentDetail.monitoring.dateRangeLabel": "Zakres dat","agentDetail.monitoring.description": "Śledź aktywność, koszt i jakość interakcji reużywalnego agenta w workflow.","agentDetail.monitoring.learnMore": "Dowiedz się więcej",+ "agentDetail.monitoring.loadFailed": "Nie udało się wczytać danych monitorowania","agentDetail.monitoring.metrics.activeUsers.explanation": "Unikalni użytkownicy końcowi, którzy uruchomili workflow z tym agentem.","agentDetail.monitoring.metrics.activeUsers.title": "Aktywni użytkownicy","agentDetail.monitoring.metrics.avgSessionInteractions.explanation": "Liczba ciągłych interakcji użytkownik-agent dla tego punktu dostępu.",@@ -328,15 +329,17 @@"agentDetail.type": "AGENT","agentDetail.versionHistory.active": "Aktywna","agentDetail.versionHistory.empty": "Brak wersji",+ "agentDetail.versionHistory.exitVersions": "Opuść wersje","agentDetail.versionHistory.filter": "Filtruj wersje",+ "agentDetail.versionHistory.restore": "Przywróć","agentDetail.versionHistory.versionName": "Wersja {{version}}",+ "agentDetail.versionHistory.viewOnly": "Tylko podgląd","roster.createAgent": "Utwórz agenta","roster.createAgentOptions": "Opcje tworzenia agenta","roster.createDialog.description": "Utwórz reużywalnego agenta w Roster tego workspace.","roster.createDialog.title": "Utwórz agenta","roster.createForm.changeIcon": "Zmień ikonę agenta","roster.createForm.descriptionLabel": "Opis",- "roster.createForm.descriptionOptional": "(opcjonalnie)","roster.createForm.descriptionPlaceholder": "np. Zbiera źródła na dany temat i podsumowuje kluczowe ustalenia","roster.createForm.nameLabel": "Nazwa","roster.createForm.namePlaceholder": "np. Max",@@ -350,7 +353,6 @@"roster.deleteDialog.title": "Usunąć {{name}}?","roster.deleteFailed": "Nie udało się usunąć agenta.","roster.deleteSuccess": "Agent usunięty.",- "roster.duplicateFailed": "Nie udało się zduplikować agenta.","roster.duplicateSuccess": "Agent zduplikowany.","roster.editAgent": "Edytuj {{name}}","roster.editDialog.description": "Zaktualizuj nazwę w Roster, opis i rolę tego agenta.",diff --git a/web/i18n/pt-BR/agent-v-2.json b/web/i18n/pt-BR/agent-v-2.jsonindex 4e65b52b3c6..60cfa801115 100644--- a/web/i18n/pt-BR/agent-v-2.json+++ b/web/i18n/pt-BR/agent-v-2.json@@ -290,6 +290,7 @@"agentDetail.monitoring.dateRangeLabel": "Intervalo de datas","agentDetail.monitoring.description": "Acompanhe a atividade, o custo e a qualidade de interação do agente reutilizável em todos os workflows.","agentDetail.monitoring.learnMore": "Saiba mais",+ "agentDetail.monitoring.loadFailed": "Falha ao carregar dados de monitoramento","agentDetail.monitoring.metrics.activeUsers.explanation": "Usuários finais únicos que acionaram workflows usando este agente.","agentDetail.monitoring.metrics.activeUsers.title": "Usuários ativos","agentDetail.monitoring.metrics.avgSessionInteractions.explanation": "Contagem de comunicação contínua entre usuário e agente para este ponto de acesso.",@@ -328,15 +329,17 @@"agentDetail.type": "AGENTE","agentDetail.versionHistory.active": "Ativa","agentDetail.versionHistory.empty": "Ainda não há versões",+ "agentDetail.versionHistory.exitVersions": "Sair das versões","agentDetail.versionHistory.filter": "Filtrar versões",+ "agentDetail.versionHistory.restore": "Restaurar","agentDetail.versionHistory.versionName": "Versão {{version}}",+ "agentDetail.versionHistory.viewOnly": "Somente leitura","roster.createAgent": "Criar agente","roster.createAgentOptions": "Opções de criação de agente","roster.createDialog.description": "Crie um agente reutilizável no roster deste workspace.","roster.createDialog.title": "Criar agente","roster.createForm.changeIcon": "Alterar ícone do agente","roster.createForm.descriptionLabel": "Descrição",- "roster.createForm.descriptionOptional": "(opcional)","roster.createForm.descriptionPlaceholder": "ex.: Reúne fontes sobre um tópico e resume as principais descobertas","roster.createForm.nameLabel": "Nome","roster.createForm.namePlaceholder": "ex.: Max",@@ -350,7 +353,6 @@"roster.deleteDialog.title": "Excluir {{name}}?","roster.deleteFailed": "Falha ao excluir o agente.","roster.deleteSuccess": "Agente excluído.",- "roster.duplicateFailed": "Falha ao duplicar o agente.","roster.duplicateSuccess": "Agente duplicado.","roster.editAgent": "Editar {{name}}","roster.editDialog.description": "Atualize o nome, a descrição e a função deste agente no roster.",diff --git a/web/i18n/ro-RO/agent-v-2.json b/web/i18n/ro-RO/agent-v-2.jsonindex f53d4f4c201..bc8919e89a4 100644--- a/web/i18n/ro-RO/agent-v-2.json+++ b/web/i18n/ro-RO/agent-v-2.json@@ -290,6 +290,7 @@"agentDetail.monitoring.dateRangeLabel": "Interval de date","agentDetail.monitoring.description": "Urmăriți activitatea, costul și calitatea interacțiunii agentului reutilizabil în toate workflow-urile.","agentDetail.monitoring.learnMore": "Aflați mai multe",+ "agentDetail.monitoring.loadFailed": "Nu s-au putut încărca datele de monitorizare","agentDetail.monitoring.metrics.activeUsers.explanation": "Utilizatori finali unici care au declanșat workflow-uri folosind acest agent.","agentDetail.monitoring.metrics.activeUsers.title": "Utilizatori activi","agentDetail.monitoring.metrics.avgSessionInteractions.explanation": "Numărul de comunicări continue utilizator-agent pentru acest punct de acces.",@@ -328,15 +329,17 @@"agentDetail.type": "AGENT","agentDetail.versionHistory.active": "Activă","agentDetail.versionHistory.empty": "Nicio versiune încă",+ "agentDetail.versionHistory.exitVersions": "Ieși din versiuni","agentDetail.versionHistory.filter": "Filtrați versiunile",+ "agentDetail.versionHistory.restore": "Restaurează","agentDetail.versionHistory.versionName": "Versiunea {{version}}",+ "agentDetail.versionHistory.viewOnly": "Doar vizualizare","roster.createAgent": "Creează agent","roster.createAgentOptions": "Opțiuni de creare agent","roster.createDialog.description": "Creați un agent reutilizabil în roster-ul acestui workspace.","roster.createDialog.title": "Creează agent","roster.createForm.changeIcon": "Schimbă pictograma agentului","roster.createForm.descriptionLabel": "Descriere",- "roster.createForm.descriptionOptional": "(opțional)","roster.createForm.descriptionPlaceholder": "de ex. Adună surse pe o temă și rezumă principalele constatări","roster.createForm.nameLabel": "Nume","roster.createForm.namePlaceholder": "de ex. Max",@@ -350,7 +353,6 @@"roster.deleteDialog.title": "Ștergeți {{name}}?","roster.deleteFailed": "Ștergerea agentului a eșuat.","roster.deleteSuccess": "Agent șters.",- "roster.duplicateFailed": "Duplicarea agentului a eșuat.","roster.duplicateSuccess": "Agent duplicat.","roster.editAgent": "Editați {{name}}","roster.editDialog.description": "Actualizați numele, descrierea și rolul din roster pentru acest agent.",diff --git a/web/i18n/ru-RU/agent-v-2.json b/web/i18n/ru-RU/agent-v-2.jsonindex aec1fc7d82a..3a1575b5dc0 100644--- a/web/i18n/ru-RU/agent-v-2.json+++ b/web/i18n/ru-RU/agent-v-2.json@@ -290,6 +290,7 @@"agentDetail.monitoring.dateRangeLabel": "Диапазон дат","agentDetail.monitoring.description": "Отслеживайте активность переиспользуемого агента, затраты и качество взаимодействия в рабочих процессах.","agentDetail.monitoring.learnMore": "Подробнее",+ "agentDetail.monitoring.loadFailed": "Не удалось загрузить данные мониторинга","agentDetail.monitoring.metrics.activeUsers.explanation": "Уникальные конечные пользователи, запустившие рабочие процессы с этим агентом.","agentDetail.monitoring.metrics.activeUsers.title": "Активные пользователи","agentDetail.monitoring.metrics.avgSessionInteractions.explanation": "Количество непрерывных взаимодействий пользователя с агентом для этой точки доступа.",@@ -328,15 +329,17 @@"agentDetail.type": "АГЕНТ","agentDetail.versionHistory.active": "Активная","agentDetail.versionHistory.empty": "Версий пока нет",+ "agentDetail.versionHistory.exitVersions": "Выйти из версий","agentDetail.versionHistory.filter": "Фильтровать версии",+ "agentDetail.versionHistory.restore": "Восстановить","agentDetail.versionHistory.versionName": "Версия {{version}}",+ "agentDetail.versionHistory.viewOnly": "Только просмотр","roster.createAgent": "Создать агента","roster.createAgentOptions": "Варианты создания агента","roster.createDialog.description": "Создайте переиспользуемого агента в Roster этого рабочего пространства.","roster.createDialog.title": "Создать агента","roster.createForm.changeIcon": "Сменить иконку агента","roster.createForm.descriptionLabel": "Описание",- "roster.createForm.descriptionOptional": "(необязательно)","roster.createForm.descriptionPlaceholder": "напр. Собирает источники по теме и резюмирует ключевые выводы","roster.createForm.nameLabel": "Имя","roster.createForm.namePlaceholder": "напр. Max",@@ -350,7 +353,6 @@"roster.deleteDialog.title": "Удалить {{name}}?","roster.deleteFailed": "Не удалось удалить агента.","roster.deleteSuccess": "Агент удалён.",- "roster.duplicateFailed": "Не удалось продублировать агента.","roster.duplicateSuccess": "Агент продублирован.","roster.editAgent": "Редактировать {{name}}","roster.editDialog.description": "Обновите имя в Roster, описание и роль этого агента.",diff --git a/web/i18n/sl-SI/agent-v-2.json b/web/i18n/sl-SI/agent-v-2.jsonindex 676c86c29df..ba905a3f3ef 100644--- a/web/i18n/sl-SI/agent-v-2.json+++ b/web/i18n/sl-SI/agent-v-2.json@@ -290,6 +290,7 @@"agentDetail.monitoring.dateRangeLabel": "Datumsko obdobje","agentDetail.monitoring.description": "Sledite aktivnosti, stroškom in kakovosti interakcije ponovno uporabnega agenta v potekih dela.","agentDetail.monitoring.learnMore": "Več informacij",+ "agentDetail.monitoring.loadFailed": "Podatkov spremljanja ni bilo mogoče naložiti","agentDetail.monitoring.metrics.activeUsers.explanation": "Edinstveni končni uporabniki, ki so sprožili poteke dela s tem agentom.","agentDetail.monitoring.metrics.activeUsers.title": "Aktivni uporabniki","agentDetail.monitoring.metrics.avgSessionInteractions.explanation": "Število neprekinjenih interakcij med uporabnikom in agentom za to dostopno točko.",@@ -328,15 +329,17 @@"agentDetail.type": "AGENT","agentDetail.versionHistory.active": "Aktivna","agentDetail.versionHistory.empty": "Še ni različic",+ "agentDetail.versionHistory.exitVersions": "Zapusti različice","agentDetail.versionHistory.filter": "Filtriraj različice",+ "agentDetail.versionHistory.restore": "Obnovi","agentDetail.versionHistory.versionName": "Različica {{version}}",+ "agentDetail.versionHistory.viewOnly": "Samo ogled","roster.createAgent": "Ustvari agenta","roster.createAgentOptions": "Možnosti ustvarjanja agenta","roster.createDialog.description": "Ustvarite ponovno uporabnega agenta v Roster tega delovnega prostora.","roster.createDialog.title": "Ustvari agenta","roster.createForm.changeIcon": "Spremeni ikono agenta","roster.createForm.descriptionLabel": "Opis",- "roster.createForm.descriptionOptional": "(neobvezno)","roster.createForm.descriptionPlaceholder": "npr. Zbira vire o določeni temi in povzame ključne ugotovitve","roster.createForm.nameLabel": "Ime","roster.createForm.namePlaceholder": "npr. Max",@@ -350,7 +353,6 @@"roster.deleteDialog.title": "Izbrišem {{name}}?","roster.deleteFailed": "Agenta ni bilo mogoče izbrisati.","roster.deleteSuccess": "Agent izbrisan.",- "roster.duplicateFailed": "Agenta ni bilo mogoče podvojiti.","roster.duplicateSuccess": "Agent podvojen.","roster.editAgent": "Uredi {{name}}","roster.editDialog.description": "Posodobite ime v Roster, opis in vlogo za tega agenta.",diff --git a/web/i18n/th-TH/agent-v-2.json b/web/i18n/th-TH/agent-v-2.jsonindex 9f29760392a..125a5c67e19 100644--- a/web/i18n/th-TH/agent-v-2.json+++ b/web/i18n/th-TH/agent-v-2.json@@ -290,6 +290,7 @@"agentDetail.monitoring.dateRangeLabel": "ช่วงวันที่","agentDetail.monitoring.description": "ติดตามกิจกรรม ค่าใช้จ่าย และคุณภาพการโต้ตอบของตัวแทนที่นำกลับมาใช้ใหม่ในเวิร์กโฟลว์ต่าง ๆ","agentDetail.monitoring.learnMore": "เรียนรู้เพิ่มเติม",+ "agentDetail.monitoring.loadFailed": "โหลดข้อมูลการมอนิเตอร์ไม่สำเร็จ","agentDetail.monitoring.metrics.activeUsers.explanation": "ผู้ใช้ปลายทางที่ไม่ซ้ำกันซึ่งทริกเกอร์เวิร์กโฟลว์โดยใช้ตัวแทนนี้","agentDetail.monitoring.metrics.activeUsers.title": "ผู้ใช้ที่ใช้งานอยู่","agentDetail.monitoring.metrics.avgSessionInteractions.explanation": "จำนวนการสื่อสารต่อเนื่องระหว่างผู้ใช้กับตัวแทนสำหรับจุดเข้าถึงนี้",@@ -328,15 +329,17 @@"agentDetail.type": "ตัวแทน","agentDetail.versionHistory.active": "ใช้งานอยู่","agentDetail.versionHistory.empty": "ยังไม่มีเวอร์ชัน",+ "agentDetail.versionHistory.exitVersions": "ออกจากเวอร์ชัน","agentDetail.versionHistory.filter": "กรองเวอร์ชัน",+ "agentDetail.versionHistory.restore": "กู้คืน","agentDetail.versionHistory.versionName": "เวอร์ชัน {{version}}",+ "agentDetail.versionHistory.viewOnly": "ดูเท่านั้น","roster.createAgent": "สร้างตัวแทน","roster.createAgentOptions": "ตัวเลือกการสร้างตัวแทน","roster.createDialog.description": "สร้างตัวแทนที่นำกลับมาใช้ใหม่ได้ใน Roster ของเวิร์กสเปซนี้","roster.createDialog.title": "สร้างตัวแทน","roster.createForm.changeIcon": "เปลี่ยนไอคอนตัวแทน","roster.createForm.descriptionLabel": "คำอธิบาย",- "roster.createForm.descriptionOptional": "(ตัวเลือก)","roster.createForm.descriptionPlaceholder": "เช่น รวบรวมแหล่งข้อมูลในหัวข้อหนึ่งและสรุปผลสำคัญ","roster.createForm.nameLabel": "ชื่อ","roster.createForm.namePlaceholder": "เช่น Max",@@ -350,7 +353,6 @@"roster.deleteDialog.title": "ลบ {{name}} หรือไม่","roster.deleteFailed": "ลบตัวแทนไม่สำเร็จ","roster.deleteSuccess": "ลบตัวแทนแล้ว",- "roster.duplicateFailed": "ทำสำเนาตัวแทนไม่สำเร็จ","roster.duplicateSuccess": "ทำสำเนาตัวแทนแล้ว","roster.editAgent": "แก้ไข {{name}}","roster.editDialog.description": "อัปเดตชื่อ คำอธิบาย และบทบาทใน Roster สำหรับตัวแทนนี้",diff --git a/web/i18n/tr-TR/agent-v-2.json b/web/i18n/tr-TR/agent-v-2.jsonindex 6c307a360ef..12fe5d5f6c3 100644--- a/web/i18n/tr-TR/agent-v-2.json+++ b/web/i18n/tr-TR/agent-v-2.json@@ -290,6 +290,7 @@"agentDetail.monitoring.dateRangeLabel": "Tarih aralığı","agentDetail.monitoring.description": "İş akışlarındaki yeniden kullanılabilir ajan etkinliğini, maliyetini ve etkileşim kalitesini izleyin.","agentDetail.monitoring.learnMore": "Daha fazla bilgi",+ "agentDetail.monitoring.loadFailed": "İzleme verileri yüklenemedi","agentDetail.monitoring.metrics.activeUsers.explanation": "Bu ajanı kullanarak iş akışlarını tetikleyen benzersiz son kullanıcılar.","agentDetail.monitoring.metrics.activeUsers.title": "Aktif Kullanıcılar","agentDetail.monitoring.metrics.avgSessionInteractions.explanation": "Bu erişim noktası için sürekli kullanıcı-ajan iletişim sayısı.",@@ -328,15 +329,17 @@"agentDetail.type": "AJAN","agentDetail.versionHistory.active": "Aktif","agentDetail.versionHistory.empty": "Henüz sürüm yok",+ "agentDetail.versionHistory.exitVersions": "Sürümlerden çık","agentDetail.versionHistory.filter": "Sürümleri filtrele",+ "agentDetail.versionHistory.restore": "Geri yükle","agentDetail.versionHistory.versionName": "Sürüm {{version}}",+ "agentDetail.versionHistory.viewOnly": "Yalnızca görüntüle","roster.createAgent": "Ajan oluştur","roster.createAgentOptions": "Ajan oluşturma seçenekleri","roster.createDialog.description": "Bu çalışma alanı Roster'ında yeniden kullanılabilir bir ajan oluşturun.","roster.createDialog.title": "Ajan oluştur","roster.createForm.changeIcon": "Ajan simgesini değiştir","roster.createForm.descriptionLabel": "Açıklama",- "roster.createForm.descriptionOptional": "(isteğe bağlı)","roster.createForm.descriptionPlaceholder": "örn. Bir konuda kaynak toplar ve temel bulguları özetler","roster.createForm.nameLabel": "Ad","roster.createForm.namePlaceholder": "örn. Max",@@ -350,7 +353,6 @@"roster.deleteDialog.title": "{{name}} silinsin mi?","roster.deleteFailed": "Ajan silinemedi.","roster.deleteSuccess": "Ajan silindi.",- "roster.duplicateFailed": "Ajan çoğaltılamadı.","roster.duplicateSuccess": "Ajan çoğaltıldı.","roster.editAgent": "{{name}} düzenle","roster.editDialog.description": "Bu ajan için Roster adı, açıklaması ve rolünü güncelleyin.",diff --git a/web/i18n/uk-UA/agent-v-2.json b/web/i18n/uk-UA/agent-v-2.jsonindex 09c78652bd0..be0e55dc89a 100644--- a/web/i18n/uk-UA/agent-v-2.json+++ b/web/i18n/uk-UA/agent-v-2.json@@ -290,6 +290,7 @@"agentDetail.monitoring.dateRangeLabel": "Діапазон дат","agentDetail.monitoring.description": "Відстежуйте активність перевикористовного агента, вартість і якість взаємодії в робочих процесах.","agentDetail.monitoring.learnMore": "Дізнатися більше",+ "agentDetail.monitoring.loadFailed": "Не вдалося завантажити дані моніторингу","agentDetail.monitoring.metrics.activeUsers.explanation": "Унікальні кінцеві користувачі, що запускали робочі процеси з цим агентом.","agentDetail.monitoring.metrics.activeUsers.title": "Активні користувачі","agentDetail.monitoring.metrics.avgSessionInteractions.explanation": "Кількість безперервних взаємодій користувача з агентом для цієї точки доступу.",@@ -328,15 +329,17 @@"agentDetail.type": "АГЕНТ","agentDetail.versionHistory.active": "Активна","agentDetail.versionHistory.empty": "Поки що немає версій",+ "agentDetail.versionHistory.exitVersions": "Вийти з версій","agentDetail.versionHistory.filter": "Фільтрувати версії",+ "agentDetail.versionHistory.restore": "Відновити","agentDetail.versionHistory.versionName": "Версія {{version}}",+ "agentDetail.versionHistory.viewOnly": "Лише перегляд","roster.createAgent": "Створити агента","roster.createAgentOptions": "Варіанти створення агента","roster.createDialog.description": "Створіть перевикористовного агента в Roster цього робочого простору.","roster.createDialog.title": "Створити агента","roster.createForm.changeIcon": "Змінити іконку агента","roster.createForm.descriptionLabel": "Опис",- "roster.createForm.descriptionOptional": "(необов'язково)","roster.createForm.descriptionPlaceholder": "напр. Збирає джерела за темою та підсумовує ключові висновки","roster.createForm.nameLabel": "Ім'я","roster.createForm.namePlaceholder": "напр. Max",@@ -350,7 +353,6 @@"roster.deleteDialog.title": "Видалити {{name}}?","roster.deleteFailed": "Не вдалося видалити агента.","roster.deleteSuccess": "Агента видалено.",- "roster.duplicateFailed": "Не вдалося продублювати агента.","roster.duplicateSuccess": "Агента продубльовано.","roster.editAgent": "Редагувати {{name}}","roster.editDialog.description": "Оновіть ім'я в Roster, опис і роль для цього агента.",diff --git a/web/i18n/vi-VN/agent-v-2.json b/web/i18n/vi-VN/agent-v-2.jsonindex e0cfb6a2112..49f68791572 100644--- a/web/i18n/vi-VN/agent-v-2.json+++ b/web/i18n/vi-VN/agent-v-2.json@@ -290,6 +290,7 @@"agentDetail.monitoring.dateRangeLabel": "Khoảng ngày","agentDetail.monitoring.description": "Theo dõi hoạt động, chi phí và chất lượng tương tác của tác nhân có thể tái sử dụng trên các quy trình làm việc.","agentDetail.monitoring.learnMore": "Tìm hiểu thêm",+ "agentDetail.monitoring.loadFailed": "Không tải được dữ liệu giám sát","agentDetail.monitoring.metrics.activeUsers.explanation": "Số người dùng cuối duy nhất đã kích hoạt các quy trình làm việc sử dụng tác nhân này.","agentDetail.monitoring.metrics.activeUsers.title": "Người dùng đang hoạt động","agentDetail.monitoring.metrics.avgSessionInteractions.explanation": "Số lần giao tiếp liên tục giữa người dùng và tác nhân cho điểm truy cập này.",@@ -328,15 +329,17 @@"agentDetail.type": "TÁC NHÂN","agentDetail.versionHistory.active": "Đang hoạt động","agentDetail.versionHistory.empty": "Chưa có phiên bản nào",+ "agentDetail.versionHistory.exitVersions": "Thoát phiên bản","agentDetail.versionHistory.filter": "Lọc phiên bản",+ "agentDetail.versionHistory.restore": "Khôi phục","agentDetail.versionHistory.versionName": "Phiên bản {{version}}",+ "agentDetail.versionHistory.viewOnly": "Chỉ xem","roster.createAgent": "Tạo tác nhân","roster.createAgentOptions": "Tùy chọn tạo tác nhân","roster.createDialog.description": "Tạo một tác nhân có thể tái sử dụng trong Roster của không gian làm việc này.","roster.createDialog.title": "Tạo tác nhân","roster.createForm.changeIcon": "Đổi biểu tượng tác nhân","roster.createForm.descriptionLabel": "Mô tả",- "roster.createForm.descriptionOptional": "(tùy chọn)","roster.createForm.descriptionPlaceholder": "ví dụ: Thu thập nguồn về một chủ đề và tóm tắt các phát hiện chính","roster.createForm.nameLabel": "Tên","roster.createForm.namePlaceholder": "ví dụ: Max",@@ -350,7 +353,6 @@"roster.deleteDialog.title": "Xóa {{name}}?","roster.deleteFailed": "Xóa tác nhân thất bại.","roster.deleteSuccess": "Đã xóa tác nhân.",- "roster.duplicateFailed": "Nhân bản tác nhân thất bại.","roster.duplicateSuccess": "Đã nhân bản tác nhân.","roster.editAgent": "Chỉnh sửa {{name}}","roster.editDialog.description": "Cập nhật tên, mô tả và vai trò Roster cho tác nhân này.",diff --git a/web/i18n/zh-Hans/agent-v-2.json b/web/i18n/zh-Hans/agent-v-2.jsonindex 32a51de221d..4ffb014a409 100644--- a/web/i18n/zh-Hans/agent-v-2.json+++ b/web/i18n/zh-Hans/agent-v-2.json@@ -290,6 +290,7 @@"agentDetail.monitoring.dateRangeLabel": "日期范围","agentDetail.monitoring.description": "跟踪可复用智能体在工作流中的活跃度、成本和交互质量。","agentDetail.monitoring.learnMore": "了解更多",+ "agentDetail.monitoring.loadFailed": "监控数据加载失败","agentDetail.monitoring.metrics.activeUsers.explanation": "触发过使用此智能体的工作流的独立终端用户数。","agentDetail.monitoring.metrics.activeUsers.title": "活跃用户","agentDetail.monitoring.metrics.avgSessionInteractions.explanation": "此访问入口下用户与智能体的连续沟通次数。",@@ -328,15 +329,17 @@"agentDetail.type": "智能体","agentDetail.versionHistory.active": "当前","agentDetail.versionHistory.empty": "暂无版本",+ "agentDetail.versionHistory.exitVersions": "退出版本","agentDetail.versionHistory.filter": "筛选版本",+ "agentDetail.versionHistory.restore": "还原","agentDetail.versionHistory.versionName": "版本 {{version}}",+ "agentDetail.versionHistory.viewOnly": "只读","roster.createAgent": "创建智能体","roster.createAgentOptions": "创建智能体选项","roster.createDialog.description": "在当前工作区 Roster 中创建一个可复用智能体。","roster.createDialog.title": "创建智能体","roster.createForm.changeIcon": "更换智能体图标","roster.createForm.descriptionLabel": "描述",- "roster.createForm.descriptionOptional": "(可选)","roster.createForm.descriptionPlaceholder": "例如:收集某个主题的来源资料并总结关键发现","roster.createForm.nameLabel": "名称","roster.createForm.namePlaceholder": "例如:Max",@@ -350,7 +353,9 @@"roster.deleteDialog.title": "删除 {{name}}?","roster.deleteFailed": "智能体删除失败。","roster.deleteSuccess": "智能体已删除。",- "roster.duplicateFailed": "智能体复制失败。",+ "roster.duplicateDialog.description": "创建 {{name}} 的副本,并自定义它在 Roster 中的身份信息。",+ "roster.duplicateDialog.title": "复制智能体",+ "roster.duplicateForm.changeIcon": "更换 {{name}} 副本的图标","roster.duplicateSuccess": "智能体已复制。","roster.editAgent": "编辑 {{name}}","roster.editDialog.description": "更新此智能体在 Roster 中的名称、描述和角色。",diff --git a/web/i18n/zh-Hant/agent-v-2.json b/web/i18n/zh-Hant/agent-v-2.jsonindex 4144843418c..063ca6d516e 100644--- a/web/i18n/zh-Hant/agent-v-2.json+++ b/web/i18n/zh-Hant/agent-v-2.json@@ -290,6 +290,7 @@"agentDetail.monitoring.dateRangeLabel": "日期範圍","agentDetail.monitoring.description": "追蹤可複用智能體在工作流程中的活躍度、成本和互動品質。","agentDetail.monitoring.learnMore": "了解更多",+ "agentDetail.monitoring.loadFailed": "監控資料載入失敗","agentDetail.monitoring.metrics.activeUsers.explanation": "觸發過使用此智能體的工作流程的獨立終端使用者數。","agentDetail.monitoring.metrics.activeUsers.title": "活躍使用者","agentDetail.monitoring.metrics.avgSessionInteractions.explanation": "此存取入口下使用者與智能體的連續溝通次數。",@@ -328,15 +329,17 @@"agentDetail.type": "智能體","agentDetail.versionHistory.active": "目前","agentDetail.versionHistory.empty": "暫無版本",+ "agentDetail.versionHistory.exitVersions": "退出版本","agentDetail.versionHistory.filter": "篩選版本",+ "agentDetail.versionHistory.restore": "還原","agentDetail.versionHistory.versionName": "版本 {{version}}",+ "agentDetail.versionHistory.viewOnly": "唯讀","roster.createAgent": "建立智能體","roster.createAgentOptions": "建立智能體選項","roster.createDialog.description": "在目前工作區 Roster 中建立一個可複用智能體。","roster.createDialog.title": "建立智能體","roster.createForm.changeIcon": "更換智能體圖示","roster.createForm.descriptionLabel": "描述",- "roster.createForm.descriptionOptional": "(選用)","roster.createForm.descriptionPlaceholder": "例如:收集某個主題的來源資料並總結關鍵發現","roster.createForm.nameLabel": "名稱","roster.createForm.namePlaceholder": "例如:Max",@@ -350,7 +353,6 @@"roster.deleteDialog.title": "刪除 {{name}}?","roster.deleteFailed": "智能體刪除失敗。","roster.deleteSuccess": "智能體已刪除。",- "roster.duplicateFailed": "智能體複製失敗。","roster.duplicateSuccess": "智能體已複製。","roster.editAgent": "編輯 {{name}}","roster.editDialog.description": "更新此智能體在 Roster 中的名稱、描述和角色。",