Skip to content

armgit / dify

Public Imported from GitHub
0

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

feat(agent-v2): sync nightly updates to main (2026-06-25) (#37915)

盐粒 Yanli52c106b5320f
diff --git a/api/clients/agent_backend/request_builder.py b/api/clients/agent_backend/request_builder.py
index 6eadd4ce3d8..fb45a783031 100644
--- a/api/clients/agent_backend/request_builder.py
+++ b/api/clients/agent_backend/request_builder.py
@@ -78,11 +78,22 @@ 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
+def _shell_layer_deps() -> dict[str, str]:
+ return {"execution_context": DIFY_EXECUTION_CONTEXT_LAYER_ID}
+
+
+def _drive_layer_deps() -> dict[str, str]:
+ return {"shell": DIFY_SHELL_LAYER_ID}
+
+
+def _shell_config_with_drive_ref(
+ shell_config: DifyShellLayerConfig | None,
+ drive_config: DifyDriveLayerConfig | None,
+) -> DifyShellLayerConfig:
+ config = shell_config or DifyShellLayerConfig()
+ if drive_config is None:
+ return config
+ return config.model_copy(update={"agent_stub_drive_ref": drive_config.drive_ref})
class AgentBackendModelConfig(BaseModel):
@@ -263,14 +274,29 @@ class AgentBackendRunRequestBuilder:
]
)
+ include_shell = run_input.include_shell or run_input.drive_config is not None
+ if include_shell:
+ # Sandboxed bash workspace (dify.shell). It enters before drive so
+ # drive can materialize mentioned targets with `dify-agent drive pull`
+ # in the same shell-visible filesystem used by model commands.
+ layers.append(
+ RunLayerSpec(
+ name=DIFY_SHELL_LAYER_ID,
+ type=DIFY_SHELL_LAYER_TYPE_ID,
+ deps=_shell_layer_deps(),
+ metadata=run_input.metadata,
+ config=_shell_config_with_drive_ref(run_input.shell_config, run_input.drive_config),
+ )
+ )
+
if run_input.drive_config is not None:
- # Drive Skills & Files declaration (dify.drive): a config-only index;
- # the agent pulls listed entries through the back proxy by drive_ref.
+ # Drive Skills & Files declaration (dify.drive): the catalog plus
+ # prompt-mentioned entries eagerly pulled through the shell layer.
layers.append(
RunLayerSpec(
name=DIFY_DRIVE_LAYER_ID,
type=DIFY_DRIVE_LAYER_TYPE_ID,
- deps={"execution_context": DIFY_EXECUTION_CONTEXT_LAYER_ID},
+ deps=_drive_layer_deps(),
metadata=run_input.metadata,
config=run_input.drive_config,
)
@@ -312,7 +338,7 @@ class AgentBackendRunRequestBuilder:
)
)
- if run_input.knowledge is not None and run_input.knowledge.dataset_ids:
+ if run_input.knowledge is not None and run_input.knowledge.sets:
layers.append(
RunLayerSpec(
name=DIFY_KNOWLEDGE_BASE_LAYER_ID,
@@ -336,21 +362,6 @@ 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, 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=_shell_layer_deps(include_drive=run_input.drive_config is not None),
- metadata=run_input.metadata,
- config=run_input.shell_config or DifyShellLayerConfig(),
- )
- )
-
if run_input.output is not None:
layers.append(
RunLayerSpec(
@@ -445,7 +456,7 @@ class AgentBackendRunRequestBuilder:
name=WORKFLOW_NODE_JOB_PROMPT_LAYER_ID,
type=PLAIN_PROMPT_LAYER_TYPE_ID,
metadata={**run_input.metadata, "origin": "workflow_node_job"},
- config=PromptLayerConfig(prefix=run_input.workflow_node_job_prompt),
+ config=PromptLayerConfig(user=run_input.workflow_node_job_prompt),
),
RunLayerSpec(
name=WORKFLOW_USER_PROMPT_LAYER_ID,
@@ -462,14 +473,29 @@ class AgentBackendRunRequestBuilder:
]
)
+ include_shell = run_input.include_shell or run_input.drive_config is not None
+ if include_shell:
+ # Sandboxed bash workspace (dify.shell). It enters before drive so
+ # drive can materialize mentioned targets with `dify-agent drive pull`
+ # in the same shell-visible filesystem used by model commands.
+ layers.append(
+ RunLayerSpec(
+ name=DIFY_SHELL_LAYER_ID,
+ type=DIFY_SHELL_LAYER_TYPE_ID,
+ deps=_shell_layer_deps(),
+ metadata=run_input.metadata,
+ config=_shell_config_with_drive_ref(run_input.shell_config, run_input.drive_config),
+ )
+ )
+
if run_input.drive_config is not None:
- # Drive Skills & Files declaration (dify.drive): a config-only index;
- # the agent pulls listed entries through the back proxy by drive_ref.
+ # Drive Skills & Files declaration (dify.drive): the catalog plus
+ # prompt-mentioned entries eagerly pulled through the shell layer.
layers.append(
RunLayerSpec(
name=DIFY_DRIVE_LAYER_ID,
type=DIFY_DRIVE_LAYER_TYPE_ID,
- deps={"execution_context": DIFY_EXECUTION_CONTEXT_LAYER_ID},
+ deps=_drive_layer_deps(),
metadata=run_input.metadata,
config=run_input.drive_config,
)
@@ -513,7 +539,7 @@ class AgentBackendRunRequestBuilder:
)
)
- if run_input.knowledge is not None and run_input.knowledge.dataset_ids:
+ if run_input.knowledge is not None and run_input.knowledge.sets:
layers.append(
RunLayerSpec(
name=DIFY_KNOWLEDGE_BASE_LAYER_ID,
@@ -537,21 +563,6 @@ 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, 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=_shell_layer_deps(include_drive=run_input.drive_config is not None),
- metadata=run_input.metadata,
- config=run_input.shell_config or DifyShellLayerConfig(),
- )
- )
-
if run_input.output is not None:
layers.append(
RunLayerSpec(
diff --git a/api/configs/extra/agent_backend_config.py b/api/configs/extra/agent_backend_config.py
index 0d65d3de97e..58228cbfb02 100644
--- a/api/configs/extra/agent_backend_config.py
+++ b/api/configs/extra/agent_backend_config.py
@@ -36,8 +36,8 @@ class AgentBackendConfig(BaseSettings):
description=(
"Inject the dify.drive layer (Skills & Files drive manifest declaration) "
"into Agent runs. The declaration is an index only — the agent backend "
- "pulls the actual SKILL.md / files through the back proxy. Keep it off "
- "until the agent backend registers the dify.drive layer type."
+ "pulls the actual SKILL.md / files through the back proxy. Set this to "
+ "false only when temporarily rolling back the drive integration."
),
- default=False,
+ default=True,
)
diff --git a/api/controllers/console/agent/app_helpers.py b/api/controllers/console/agent/app_helpers.py
index 51adc1e136e..7af38b0164d 100644
--- a/api/controllers/console/agent/app_helpers.py
+++ b/api/controllers/console/agent/app_helpers.py
@@ -6,5 +6,15 @@ from services.agent.roster_service import AgentRosterService
def resolve_agent_app_model(*, tenant_id: str, agent_id: UUID) -> App:
- """Resolve the hidden Agent App backing an Agent Console resource."""
+ """Resolve a roster Agent's public Agent App."""
return AgentRosterService(db.session).get_agent_app_model(tenant_id=tenant_id, agent_id=str(agent_id))
+
+
+def resolve_agent_runtime_app_model(*, tenant_id: str, agent_id: UUID) -> App:
+ """Resolve the App that backs an Agent runtime surface.
+
+ This accepts both roster Agent Apps and workflow-only inline Agents with a
+ hidden backing App.
+ """
+
+ return AgentRosterService(db.session).get_agent_runtime_app_model(tenant_id=tenant_id, agent_id=str(agent_id))
diff --git a/api/controllers/console/agent/composer.py b/api/controllers/console/agent/composer.py
index b54cf4b6daf..7413be95d75 100644
--- a/api/controllers/console/agent/composer.py
+++ b/api/controllers/console/agent/composer.py
@@ -1,10 +1,10 @@
from uuid import UUID
+from flask import request
from flask_restx import Resource
-from controllers.common.schema import register_response_schema_models, register_schema_models
+from controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_models
from controllers.console import console_ns
-from controllers.console.agent.app_helpers import resolve_agent_app_model
from controllers.console.app.wraps import get_app_model
from controllers.console.wraps import (
RBACPermission,
@@ -28,9 +28,15 @@ from libs.login import login_required
from models.model import App, AppMode
from services.agent.composer_service import AgentComposerService
from services.agent.composer_validator import ComposerConfigValidator
-from services.entities.agent_entities import ComposerSavePayload, WorkflowComposerCopyFromRosterPayload
+from services.entities.agent_entities import (
+ ComposerSavePayload,
+ WorkflowAgentComposerQuery,
+ WorkflowComposerCopyFromRosterPayload,
+)
-register_schema_models(console_ns, ComposerSavePayload, WorkflowComposerCopyFromRosterPayload)
+register_schema_models(
+ console_ns, ComposerSavePayload, WorkflowAgentComposerQuery, WorkflowComposerCopyFromRosterPayload
+)
register_response_schema_models(
console_ns,
AgentAppComposerResponse,
@@ -41,27 +47,26 @@ register_response_schema_models(
)
-def _resolve_agent_app_id(*, tenant_id: str, agent_id: UUID) -> str:
- return resolve_agent_app_model(tenant_id=tenant_id, agent_id=agent_id).id
-
-
@console_ns.route("/apps/<uuid:app_id>/workflows/draft/nodes/<string:node_id>/agent-composer")
class WorkflowAgentComposerApi(Resource):
@console_ns.response(
200, "Workflow agent composer state", console_ns.models[WorkflowAgentComposerResponse.__name__]
)
+ @console_ns.doc(params=query_params_from_model(WorkflowAgentComposerQuery))
@setup_required
@login_required
@account_initialization_required
@get_app_model(mode=[AppMode.WORKFLOW, AppMode.ADVANCED_CHAT])
@with_current_tenant_id
def get(self, tenant_id: str, app_model: App, node_id: str):
+ query = WorkflowAgentComposerQuery.model_validate(request.args.to_dict(flat=True))
return dump_response(
WorkflowAgentComposerResponse,
AgentComposerService.load_workflow_composer(
tenant_id=tenant_id,
app_id=app_model.id,
node_id=node_id,
+ snapshot_id=query.snapshot_id,
),
)
@@ -137,6 +142,7 @@ class WorkflowAgentComposerValidateApi(Resource):
def post(self, tenant_id: str, app_model: App, node_id: str):
payload = ComposerSavePayload.model_validate(console_ns.payload or {})
ComposerConfigValidator.validate_publish_payload(payload)
+ AgentComposerService.validate_knowledge_datasets(tenant_id=tenant_id, agent_soul=payload.agent_soul)
findings = AgentComposerService.collect_validation_findings(
tenant_id=tenant_id,
payload=payload,
@@ -228,10 +234,9 @@ class AgentComposerApi(Resource):
@account_initialization_required
@with_current_tenant_id
def get(self, tenant_id: str, agent_id: UUID):
- app_id = _resolve_agent_app_id(tenant_id=tenant_id, agent_id=agent_id)
return dump_response(
AgentAppComposerResponse,
- AgentComposerService.load_agent_app_composer(tenant_id=tenant_id, app_id=app_id),
+ AgentComposerService.load_agent_composer(tenant_id=tenant_id, agent_id=str(agent_id)),
)
@console_ns.expect(console_ns.models[ComposerSavePayload.__name__])
@@ -244,13 +249,12 @@ class AgentComposerApi(Resource):
@with_current_user_id
@with_current_tenant_id
def put(self, tenant_id: str, account_id: str, agent_id: UUID):
- app_id = _resolve_agent_app_id(tenant_id=tenant_id, agent_id=agent_id)
payload = ComposerSavePayload.model_validate(console_ns.payload or {})
return dump_response(
AgentAppComposerResponse,
- AgentComposerService.save_agent_app_composer(
+ AgentComposerService.save_agent_composer(
tenant_id=tenant_id,
- app_id=app_id,
+ agent_id=str(agent_id),
account_id=account_id,
payload=payload,
),
@@ -268,9 +272,10 @@ class AgentComposerValidateApi(Resource):
@account_initialization_required
@with_current_tenant_id
def post(self, tenant_id: str, agent_id: UUID):
- _resolve_agent_app_id(tenant_id=tenant_id, agent_id=agent_id)
+ AgentComposerService.load_agent_composer(tenant_id=tenant_id, agent_id=str(agent_id))
payload = ComposerSavePayload.model_validate(console_ns.payload or {})
ComposerConfigValidator.validate_publish_payload(payload)
+ AgentComposerService.validate_knowledge_datasets(tenant_id=tenant_id, agent_soul=payload.agent_soul)
findings = AgentComposerService.collect_validation_findings(
tenant_id=tenant_id,
payload=payload,
@@ -290,12 +295,11 @@ class AgentComposerCandidatesApi(Resource):
@with_current_user_id
@with_current_tenant_id
def get(self, tenant_id: str, current_user_id: str, agent_id: UUID):
- app_id = _resolve_agent_app_id(tenant_id=tenant_id, agent_id=agent_id)
return dump_response(
AgentComposerCandidatesResponse,
AgentComposerService.get_agent_app_candidates(
tenant_id=tenant_id,
- app_id=app_id,
+ agent_id=str(agent_id),
user_id=current_user_id,
),
)
diff --git a/api/controllers/console/agent/roster.py b/api/controllers/console/agent/roster.py
index ac3f7ef4824..3b33dc68c72 100644
--- a/api/controllers/console/agent/roster.py
+++ b/api/controllers/console/agent/roster.py
@@ -7,7 +7,7 @@ from sqlalchemy import func, select
from controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_models
from controllers.console import console_ns
-from controllers.console.agent.app_helpers import resolve_agent_app_model
+from controllers.console.agent.app_helpers import resolve_agent_app_model, resolve_agent_runtime_app_model
from controllers.console.apikey import ApiKeyItem, ApiKeyList, BaseApiKeyListResource, BaseApiKeyResource
from controllers.console.app.app import (
AppDetailWithSite as GenericAppDetailWithSite,
@@ -54,8 +54,10 @@ from libs.datetime_utils import parse_time_range
from libs.helper import dump_response
from libs.login import login_required
from models import Account
+from models.agent import Agent, AgentStatus
from models.enums import ApiTokenType
from models.model import ApiToken, App, IconType
+from services.agent.composer_service import AgentComposerService
from services.agent.errors import AgentNotFoundError
from services.agent.observability_service import (
AgentLogQueryParams,
@@ -65,7 +67,7 @@ from services.agent.observability_service import (
from services.agent.roster_service import AgentRosterService
from services.app_service import AppListParams, AppService, CreateAppParams
from services.enterprise.enterprise_service import EnterpriseService
-from services.entities.agent_entities import RosterListQuery
+from services.entities.agent_entities import ComposerSavePayload, RosterListQuery
from services.feature_service import FeatureService
@@ -232,6 +234,8 @@ class AgentStatisticsQuery(BaseModel):
class AgentAppPartial(GenericAppPartial):
app_id: str | None = None
+ backing_app_id: str | None = None
+ hidden_app_backed: bool = False
debug_conversation_id: str | None = None
role: str | None = None
active_config_is_published: bool = False
@@ -241,6 +245,8 @@ class AgentAppPartial(GenericAppPartial):
class AgentAppDetailWithSite(GenericAppDetailWithSite):
app_id: str | None = None
+ backing_app_id: str | None = None
+ hidden_app_backed: bool = False
debug_conversation_id: str | None = None
role: str | None = None
active_config_is_published: bool = False
@@ -250,6 +256,36 @@ class AgentDebugConversationRefreshResponse(BaseModel):
debug_conversation_id: str
+class AgentPublishPayload(BaseModel):
+ version_note: str | None = Field(default=None, description="Optional note for this published Agent version")
+
+
+class AgentPublishResponse(BaseModel):
+ result: str
+ active_config_snapshot_id: str
+ active_config_snapshot: dict[str, object] | None = None
+ draft: dict[str, object] | None = None
+
+
+class AgentBuildDraftCheckoutPayload(BaseModel):
+ force: bool = Field(default=False, description="Overwrite the existing current-user build draft")
+
+
+class AgentBuildDraftResponse(BaseModel):
+ variant: str
+ draft: dict[str, object]
+ agent_soul: dict[str, object]
+
+
+class AgentBuildDraftApplyResponse(BaseModel):
+ result: str
+ draft: dict[str, object]
+
+
+class AgentSimpleResultResponse(BaseModel):
+ result: str
+
+
class AgentAppPagination(GenericAppPagination):
data: list[AgentAppPartial] = Field( # type: ignore[assignment] # pyrefly: ignore[bad-override-mutable-attribute]
validation_alias=AliasChoices("items", "data")
@@ -261,6 +297,9 @@ register_schema_models(
AgentAppCreatePayload,
AgentAppUpdatePayload,
AgentAppCopyPayload,
+ AgentPublishPayload,
+ AgentBuildDraftCheckoutPayload,
+ ComposerSavePayload,
AgentApiStatusPayload,
AgentInviteOptionsQuery,
AgentLogsQuery,
@@ -277,6 +316,10 @@ register_response_schema_models(
AgentAppDetailWithSite,
AgentAppPartial,
AgentDebugConversationRefreshResponse,
+ AgentPublishResponse,
+ AgentBuildDraftResponse,
+ AgentBuildDraftApplyResponse,
+ AgentSimpleResultResponse,
AgentConfigSnapshotDetailResponse,
AgentConfigSnapshotListResponse,
AgentConfigSnapshotRestoreResponse,
@@ -294,7 +337,7 @@ def _agent_roster_service() -> AgentRosterService:
return AgentRosterService(db.session)
-def _serialize_agent_app_detail(app_model, *, current_user: Account) -> dict:
+def _serialize_agent_app_detail(app_model, *, current_user: Account, agent_id: str | None = None) -> dict:
"""Serialize an Agent App detail using roster-only DTOs.
`/agent` responses are roster-shaped rather than raw app-shaped: `id`
@@ -311,11 +354,23 @@ def _serialize_agent_app_detail(app_model, *, current_user: Account) -> dict:
roster_service = _agent_roster_service()
payload = AgentAppDetailWithSite.model_validate(app_model, from_attributes=True).model_dump(mode="json")
- agent = roster_service.get_app_backing_agent(tenant_id=app_model.tenant_id, app_id=str(app_model.id))
+ agent = (
+ db.session.scalar(
+ select(Agent).where(
+ Agent.tenant_id == app_model.tenant_id,
+ Agent.id == agent_id,
+ Agent.status == AgentStatus.ACTIVE,
+ )
+ )
+ if agent_id
+ else roster_service.get_app_backing_agent(tenant_id=app_model.tenant_id, app_id=str(app_model.id))
+ )
if not agent:
raise AgentNotFoundError()
payload.pop("bound_agent_id", None)
- payload["app_id"] = str(app_model.id)
+ payload["app_id"] = agent.app_id
+ payload["backing_app_id"] = roster_service.runtime_backing_app_id(agent)
+ payload["hidden_app_backed"] = bool(agent.backing_app_id and agent.backing_app_id != agent.app_id)
payload["id"] = agent.id
payload["debug_conversation_id"] = roster_service.get_or_create_agent_app_debug_conversation_id(
tenant_id=app_model.tenant_id,
@@ -365,6 +420,8 @@ def _serialize_agent_app_pagination(app_pagination, *, tenant_id: str, current_u
agent = agents_by_app_id.get(app_id)
if agent:
item["app_id"] = app_id
+ item["backing_app_id"] = agent.backing_app_id or app_id
+ item["hidden_app_backed"] = False
item["id"] = agent.id
item["debug_conversation_id"] = debug_conversation_ids_by_agent_id.get(agent.id)
item["role"] = agent.role or ""
@@ -516,8 +573,8 @@ class AgentAppApi(Resource):
@with_current_user
@with_current_tenant_id
def get(self, tenant_id: str, current_user: Account, agent_id: UUID):
- app_model = _resolve_agent_app_model(tenant_id=tenant_id, agent_id=agent_id)
- return _serialize_agent_app_detail(app_model, current_user=current_user)
+ app_model = resolve_agent_runtime_app_model(tenant_id=tenant_id, agent_id=agent_id)
+ return _serialize_agent_app_detail(app_model, current_user=current_user, agent_id=str(agent_id))
@console_ns.expect(console_ns.models[AgentAppUpdatePayload.__name__])
@console_ns.response(200, "Agent app updated successfully", console_ns.models[AgentAppDetailWithSite.__name__])
@@ -583,6 +640,112 @@ class AgentDebugConversationRefreshApi(Resource):
)
+@console_ns.route("/agent/<uuid:agent_id>/publish")
+class AgentPublishApi(Resource):
+ @console_ns.expect(console_ns.models[AgentPublishPayload.__name__])
+ @console_ns.response(200, "Agent draft published", console_ns.models[AgentPublishResponse.__name__])
+ @console_ns.response(403, "Insufficient permissions")
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @edit_permission_required
+ @with_current_user
+ @with_current_tenant_id
+ def post(self, tenant_id: str, current_user: Account, agent_id: UUID):
+ args = AgentPublishPayload.model_validate(console_ns.payload or {})
+ return AgentComposerService.publish_agent_app_draft(
+ tenant_id=tenant_id,
+ agent_id=str(agent_id),
+ account_id=current_user.id,
+ version_note=args.version_note,
+ )
+
+
+@console_ns.route("/agent/<uuid:agent_id>/build-draft/checkout")
+class AgentBuildDraftCheckoutApi(Resource):
+ @console_ns.expect(console_ns.models[AgentBuildDraftCheckoutPayload.__name__])
+ @console_ns.response(200, "Agent build draft checked out", console_ns.models[AgentBuildDraftResponse.__name__])
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @edit_permission_required
+ @with_current_user
+ @with_current_tenant_id
+ def post(self, tenant_id: str, current_user: Account, agent_id: UUID):
+ args = AgentBuildDraftCheckoutPayload.model_validate(console_ns.payload or {})
+ return AgentComposerService.checkout_agent_app_build_draft(
+ tenant_id=tenant_id,
+ agent_id=str(agent_id),
+ account_id=current_user.id,
+ force=args.force,
+ )
+
+
+@console_ns.route("/agent/<uuid:agent_id>/build-draft")
+class AgentBuildDraftApi(Resource):
+ @console_ns.response(200, "Agent build draft", console_ns.models[AgentBuildDraftResponse.__name__])
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @edit_permission_required
+ @with_current_user
+ @with_current_tenant_id
+ def get(self, tenant_id: str, current_user: Account, agent_id: UUID):
+ return AgentComposerService.load_agent_app_build_draft(
+ tenant_id=tenant_id,
+ agent_id=str(agent_id),
+ account_id=current_user.id,
+ )
+
+ @console_ns.expect(console_ns.models[ComposerSavePayload.__name__])
+ @console_ns.response(200, "Agent build draft saved", console_ns.models[AgentBuildDraftResponse.__name__])
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @edit_permission_required
+ @with_current_user
+ @with_current_tenant_id
+ def put(self, tenant_id: str, current_user: Account, agent_id: UUID):
+ payload = ComposerSavePayload.model_validate(console_ns.payload or {})
+ return AgentComposerService.save_agent_app_build_draft(
+ tenant_id=tenant_id,
+ agent_id=str(agent_id),
+ account_id=current_user.id,
+ payload=payload,
+ )
+
+ @console_ns.response(200, "Agent build draft discarded", console_ns.models[AgentSimpleResultResponse.__name__])
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @edit_permission_required
+ @with_current_user
+ @with_current_tenant_id
+ def delete(self, tenant_id: str, current_user: Account, agent_id: UUID):
+ return AgentComposerService.discard_agent_app_build_draft(
+ tenant_id=tenant_id,
+ agent_id=str(agent_id),
+ account_id=current_user.id,
+ )
+
+
+@console_ns.route("/agent/<uuid:agent_id>/build-draft/apply")
+class AgentBuildDraftApplyApi(Resource):
+ @console_ns.response(200, "Agent build draft applied", console_ns.models[AgentBuildDraftApplyResponse.__name__])
+ @setup_required
+ @login_required
+ @account_initialization_required
+ @edit_permission_required
+ @with_current_user
+ @with_current_tenant_id
+ def post(self, tenant_id: str, current_user: Account, agent_id: UUID):
+ return AgentComposerService.apply_agent_app_build_draft(
+ tenant_id=tenant_id,
+ agent_id=str(agent_id),
+ account_id=current_user.id,
+ )
+
+
@console_ns.route("/agent/<uuid:agent_id>/copy")
class AgentAppCopyApi(Resource):
@console_ns.expect(console_ns.models[AgentAppCopyPayload.__name__])
@@ -712,7 +875,7 @@ class AgentLogsApi(Resource):
@with_current_user
@with_current_tenant_id
def get(self, tenant_id: str, current_user: Account, agent_id: UUID):
- app_model = _resolve_agent_app_model(tenant_id=tenant_id, agent_id=agent_id)
+ app_model = resolve_agent_runtime_app_model(tenant_id=tenant_id, agent_id=agent_id)
query_data: dict[str, object] = dict(request.args.to_dict(flat=True))
query_data["sources"] = _multi_query_values("sources", "source")
query_data["statuses"] = _multi_query_values("statuses", "status")
@@ -749,7 +912,7 @@ class AgentLogMessagesApi(Resource):
@with_current_user
@with_current_tenant_id
def get(self, tenant_id: str, current_user: Account, agent_id: UUID, conversation_id: UUID):
- app_model = _resolve_agent_app_model(tenant_id=tenant_id, agent_id=agent_id)
+ app_model = resolve_agent_runtime_app_model(tenant_id=tenant_id, agent_id=agent_id)
query_data: dict[str, object] = dict(request.args.to_dict(flat=True))
query_data["sources"] = _multi_query_values("sources", "source")
query_data["statuses"] = _multi_query_values("statuses", "status")
@@ -786,7 +949,7 @@ class AgentLogSourcesApi(Resource):
@with_current_user
@with_current_tenant_id
def get(self, tenant_id: str, current_user: Account, agent_id: UUID):
- app_model = _resolve_agent_app_model(tenant_id=tenant_id, agent_id=agent_id)
+ app_model = resolve_agent_runtime_app_model(tenant_id=tenant_id, agent_id=agent_id)
payload = _agent_observability_service().list_log_sources(app=app_model, agent_id=str(agent_id))
return dump_response(AgentLogSourceListResponse, payload)
@@ -805,7 +968,7 @@ class AgentStatisticsSummaryApi(Resource):
@with_current_user
@with_current_tenant_id
def get(self, tenant_id: str, current_user: Account, agent_id: UUID):
- app_model = _resolve_agent_app_model(tenant_id=tenant_id, agent_id=agent_id)
+ app_model = resolve_agent_runtime_app_model(tenant_id=tenant_id, agent_id=agent_id)
query = AgentStatisticsQuery.model_validate(request.args.to_dict(flat=True))
timezone = current_user.timezone or "UTC"
start, end = _parse_observability_time_range(query.start, query.end, current_user)
diff --git a/api/controllers/console/app/agent.py b/api/controllers/console/app/agent.py
index 86a3c473547..99164b4755a 100644
--- a/api/controllers/console/app/agent.py
+++ b/api/controllers/console/app/agent.py
@@ -13,7 +13,7 @@ from controllers.common.schema import (
register_schema_models,
)
from controllers.console import console_ns
-from controllers.console.agent.app_helpers import resolve_agent_app_model
+from controllers.console.agent.app_helpers import resolve_agent_runtime_app_model
from controllers.console.app.wraps import get_app_model
from controllers.console.wraps import (
RBACPermission,
@@ -351,7 +351,7 @@ class AgentSkillUploadByAgentApi(Resource):
@with_current_user
@with_current_tenant_id
def post(self, tenant_id: str, current_user: Account, agent_id: UUID):
- app_model = resolve_agent_app_model(tenant_id=tenant_id, agent_id=agent_id)
+ app_model = resolve_agent_runtime_app_model(tenant_id=tenant_id, agent_id=agent_id)
return _upload_skill_for_app(current_user=current_user, app_model=app_model)
@@ -394,7 +394,7 @@ class AgentDriveFilesByAgentApi(Resource):
@with_current_user
@with_current_tenant_id
def post(self, tenant_id: str, current_user: Account, agent_id: UUID):
- app_model = resolve_agent_app_model(tenant_id=tenant_id, agent_id=agent_id)
+ app_model = resolve_agent_runtime_app_model(tenant_id=tenant_id, agent_id=agent_id)
return _commit_drive_file_for_app(current_user=current_user, app_model=app_model, allow_node_id=False)
@console_ns.doc("delete_agent_drive_file_by_agent")
@@ -407,7 +407,7 @@ class AgentDriveFilesByAgentApi(Resource):
@with_current_user
@with_current_tenant_id
def delete(self, tenant_id: str, current_user: Account, agent_id: UUID):
- app_model = resolve_agent_app_model(tenant_id=tenant_id, agent_id=agent_id)
+ app_model = resolve_agent_runtime_app_model(tenant_id=tenant_id, agent_id=agent_id)
return _delete_drive_file_for_app(current_user=current_user, app_model=app_model, allow_node_id=False)
@@ -454,7 +454,7 @@ class AgentSkillByAgentApi(Resource):
@with_current_user
@with_current_tenant_id
def delete(self, tenant_id: str, current_user: Account, agent_id: UUID, slug: str):
- app_model = resolve_agent_app_model(tenant_id=tenant_id, agent_id=agent_id)
+ app_model = resolve_agent_runtime_app_model(tenant_id=tenant_id, agent_id=agent_id)
return _delete_skill_for_app(current_user=current_user, app_model=app_model, slug=slug, allow_node_id=False)
@@ -494,7 +494,7 @@ class AgentSkillInferToolsByAgentApi(Resource):
@account_initialization_required
@with_current_tenant_id
def post(self, tenant_id: str, agent_id: UUID, slug: str):
- app_model = resolve_agent_app_model(tenant_id=tenant_id, agent_id=agent_id)
+ app_model = resolve_agent_runtime_app_model(tenant_id=tenant_id, agent_id=agent_id)
return _infer_skill_tools_for_app(app_model=app_model, slug=slug)
diff --git a/api/controllers/console/app/agent_app_feature.py b/api/controllers/console/app/agent_app_feature.py
index 358e552beb0..be6b9b28543 100644
--- a/api/controllers/console/app/agent_app_feature.py
+++ b/api/controllers/console/app/agent_app_feature.py
@@ -17,7 +17,7 @@ from pydantic import BaseModel, Field
from controllers.common.fields import SimpleResultResponse
from controllers.common.schema import register_response_schema_models, register_schema_models
from controllers.console import console_ns
-from controllers.console.agent.app_helpers import resolve_agent_app_model
+from controllers.console.agent.app_helpers import resolve_agent_runtime_app_model
from controllers.console.wraps import (
RBACPermission,
RBACResourceScope,
@@ -87,7 +87,7 @@ class AgentAppFeatureConfigResource(Resource):
@with_current_user
@with_current_tenant_id
def post(self, tenant_id: str, current_user: Account, agent_id: UUID):
- app_model = resolve_agent_app_model(tenant_id=tenant_id, agent_id=agent_id)
+ app_model = resolve_agent_runtime_app_model(tenant_id=tenant_id, agent_id=agent_id)
args = AgentAppFeaturesPayload.model_validate(console_ns.payload or {})
new_app_model_config = AgentAppFeatureConfigService.update_features(
diff --git a/api/controllers/console/app/agent_app_sandbox.py b/api/controllers/console/app/agent_app_sandbox.py
index f9bda13c63a..9d92c078bd4 100644
--- a/api/controllers/console/app/agent_app_sandbox.py
+++ b/api/controllers/console/app/agent_app_sandbox.py
@@ -22,7 +22,7 @@ from controllers.common.schema import (
register_schema_models,
)
from controllers.console import console_ns
-from controllers.console.agent.app_helpers import resolve_agent_app_model
+from controllers.console.agent.app_helpers import resolve_agent_runtime_app_model
from controllers.console.app.wraps import get_app_model
from controllers.console.wraps import account_initialization_required, setup_required, with_current_tenant_id
from fields.base import ResponseModel
@@ -144,7 +144,7 @@ class AgentAppSandboxListResource(Resource):
@account_initialization_required
@with_current_tenant_id
def get(self, tenant_id: str, agent_id: UUID):
- app_model = resolve_agent_app_model(tenant_id=tenant_id, agent_id=agent_id)
+ app_model = resolve_agent_runtime_app_model(tenant_id=tenant_id, agent_id=agent_id)
query = query_params_from_request(AgentSandboxListQuery)
try:
result = AgentAppSandboxService().list_files(
@@ -169,7 +169,7 @@ class AgentAppSandboxReadResource(Resource):
@account_initialization_required
@with_current_tenant_id
def get(self, tenant_id: str, agent_id: UUID):
- app_model = resolve_agent_app_model(tenant_id=tenant_id, agent_id=agent_id)
+ app_model = resolve_agent_runtime_app_model(tenant_id=tenant_id, agent_id=agent_id)
query = query_params_from_request(AgentSandboxFileQuery)
try:
result = AgentAppSandboxService().read_file(
@@ -194,7 +194,7 @@ class AgentAppSandboxUploadResource(Resource):
@account_initialization_required
@with_current_tenant_id
def post(self, tenant_id: str, agent_id: UUID):
- app_model = resolve_agent_app_model(tenant_id=tenant_id, agent_id=agent_id)
+ app_model = resolve_agent_runtime_app_model(tenant_id=tenant_id, agent_id=agent_id)
payload = AgentSandboxUploadPayload.model_validate(request.get_json(silent=True) or {})
try:
result = AgentAppSandboxService().upload_file(
diff --git a/api/controllers/console/app/agent_drive_inspector.py b/api/controllers/console/app/agent_drive_inspector.py
index bd639955d9c..473e7364b3e 100644
--- a/api/controllers/console/app/agent_drive_inspector.py
+++ b/api/controllers/console/app/agent_drive_inspector.py
@@ -25,7 +25,7 @@ from controllers.common.schema import (
register_response_schema_models,
)
from controllers.console import console_ns
-from controllers.console.agent.app_helpers import resolve_agent_app_model
+from controllers.console.agent.app_helpers import resolve_agent_runtime_app_model
from controllers.console.app.wraps import get_app_model
from controllers.console.wraps import account_initialization_required, setup_required, with_current_tenant_id
from fields.base import ResponseModel
@@ -182,7 +182,7 @@ class AgentDriveListByAgentApi(Resource):
@with_current_tenant_id
def get(self, tenant_id: str, agent_id: UUID):
query = query_params_from_request(AgentDriveListByAgentQuery)
- resolve_agent_app_model(tenant_id=tenant_id, agent_id=agent_id)
+ resolve_agent_runtime_app_model(tenant_id=tenant_id, agent_id=agent_id)
try:
items = AgentDriveService().manifest(tenant_id=tenant_id, agent_id=str(agent_id), prefix=query.prefix)
except AgentDriveError as exc:
@@ -201,7 +201,7 @@ class AgentDriveSkillListByAgentApi(Resource):
@account_initialization_required
@with_current_tenant_id
def get(self, tenant_id: str, agent_id: UUID):
- resolve_agent_app_model(tenant_id=tenant_id, agent_id=agent_id)
+ resolve_agent_runtime_app_model(tenant_id=tenant_id, agent_id=agent_id)
try:
items = AgentDriveService().list_skills(tenant_id=tenant_id, agent_id=str(agent_id))
except AgentDriveError as exc:
@@ -220,7 +220,7 @@ class AgentDriveSkillInspectByAgentApi(Resource):
@account_initialization_required
@with_current_tenant_id
def get(self, tenant_id: str, agent_id: UUID, skill_path: str):
- resolve_agent_app_model(tenant_id=tenant_id, agent_id=agent_id)
+ resolve_agent_runtime_app_model(tenant_id=tenant_id, agent_id=agent_id)
try:
return _json_response(
AgentDriveService().inspect_skill(
@@ -245,7 +245,7 @@ class AgentDrivePreviewByAgentApi(Resource):
@with_current_tenant_id
def get(self, tenant_id: str, agent_id: UUID):
query = query_params_from_request(AgentDriveFileByAgentQuery)
- resolve_agent_app_model(tenant_id=tenant_id, agent_id=agent_id)
+ resolve_agent_runtime_app_model(tenant_id=tenant_id, agent_id=agent_id)
try:
return AgentDriveService().preview(tenant_id=tenant_id, agent_id=str(agent_id), key=query.key)
except AgentDriveError as exc:
@@ -264,7 +264,7 @@ class AgentDriveDownloadByAgentApi(Resource):
@with_current_tenant_id
def get(self, tenant_id: str, agent_id: UUID):
query = query_params_from_request(AgentDriveFileByAgentQuery)
- resolve_agent_app_model(tenant_id=tenant_id, agent_id=agent_id)
+ resolve_agent_runtime_app_model(tenant_id=tenant_id, agent_id=agent_id)
try:
url = AgentDriveService().download_url(tenant_id=tenant_id, agent_id=str(agent_id), key=query.key)
except AgentDriveError as exc:
diff --git a/api/controllers/console/app/app.py b/api/controllers/console/app/app.py
index 7ed527d6876..4c703ad73f6 100644
--- a/api/controllers/console/app/app.py
+++ b/api/controllers/console/app/app.py
@@ -331,7 +331,7 @@ class ModelConfig(ResponseModel):
return to_timestamp(value)
-class Site(ResponseModel):
+class AppDetailSiteResponse(ResponseModel):
access_token: str | None = Field(default=None, validation_alias="code")
code: str | None = None
title: str | None = None
@@ -462,7 +462,7 @@ class AppDetailWithSite(AppDetail):
api_base_url: str | None = None
max_active_requests: int | None = None
deleted_tools: list[DeletedTool] = Field(default_factory=list)
- site: Site | None = None
+ site: AppDetailSiteResponse | None = None
# For Agent App type: the roster Agent backing this app (None otherwise).
bound_agent_id: str | None = None
# For Agent App responses exposed through /agent.
@@ -547,7 +547,7 @@ register_schema_models(
WorkflowPartial,
ModelConfigPartial,
ModelConfig,
- Site,
+ AppDetailSiteResponse,
DeletedTool,
AppDetail,
AppExportResponse,
diff --git a/api/controllers/console/app/completion.py b/api/controllers/console/app/completion.py
index 545fad34cde..16c1a2f570b 100644
--- a/api/controllers/console/app/completion.py
+++ b/api/controllers/console/app/completion.py
@@ -11,7 +11,7 @@ import services
from controllers.common.fields import GeneratedAppResponse, SimpleResultResponse
from controllers.common.schema import register_response_schema_models, register_schema_models
from controllers.console import console_ns
-from controllers.console.agent.app_helpers import resolve_agent_app_model
+from controllers.console.agent.app_helpers import resolve_agent_runtime_app_model
from controllers.console.app.error import (
AppUnavailableError,
CompletionRequestError,
@@ -93,6 +93,10 @@ class ChatMessagePayload(BaseMessagePayload):
query: str = Field(..., description="User query")
conversation_id: str | None = Field(default=None, description="Conversation ID")
parent_message_id: str | None = Field(default=None, description="Parent message ID")
+ draft_type: Literal["draft", "debug_build"] = Field(
+ default="draft",
+ description="Agent App debug config source. Use debug_build while the Agent is in build mode.",
+ )
@field_validator("conversation_id", "parent_message_id")
@classmethod
@@ -218,7 +222,7 @@ class AgentChatMessageApi(Resource):
@with_current_user
@with_current_tenant_id
def post(self, current_tenant_id: str, current_user: Account, agent_id: UUID):
- app_model = resolve_agent_app_model(tenant_id=current_tenant_id, agent_id=agent_id)
+ app_model = resolve_agent_runtime_app_model(tenant_id=current_tenant_id, agent_id=agent_id)
return _create_chat_message(
current_tenant_id=current_tenant_id,
current_user=current_user,
@@ -254,7 +258,7 @@ class AgentChatMessageStopApi(Resource):
@with_current_user_id
@with_current_tenant_id
def post(self, current_tenant_id: str, current_user_id: str, agent_id: UUID, task_id: str):
- app_model = resolve_agent_app_model(tenant_id=current_tenant_id, agent_id=agent_id)
+ app_model = resolve_agent_runtime_app_model(tenant_id=current_tenant_id, agent_id=agent_id)
return _stop_chat_message(current_user_id=current_user_id, app_model=app_model, task_id=task_id)
diff --git a/api/controllers/console/app/message.py b/api/controllers/console/app/message.py
index f987ecca745..3e24dbdcff0 100644
--- a/api/controllers/console/app/message.py
+++ b/api/controllers/console/app/message.py
@@ -13,7 +13,7 @@ from controllers.common.controller_schemas import MessageFeedbackPayload as _Mes
from controllers.common.fields import SimpleResultResponse, TextFileResponse
from controllers.common.schema import query_params_from_model, register_response_schema_models, register_schema_models
from controllers.console import console_ns
-from controllers.console.agent.app_helpers import resolve_agent_app_model
+from controllers.console.agent.app_helpers import resolve_agent_runtime_app_model
from controllers.console.app.error import (
CompletionRequestError,
ProviderModelCurrentlyNotSupportError,
@@ -214,7 +214,7 @@ class AgentChatMessageListApi(Resource):
@with_current_user
@with_current_tenant_id
def get(self, current_tenant_id: str, current_user: Account, agent_id: UUID):
- app_model = resolve_agent_app_model(tenant_id=current_tenant_id, agent_id=agent_id)
+ app_model = resolve_agent_runtime_app_model(tenant_id=current_tenant_id, agent_id=agent_id)
return _list_chat_messages(app_model=app_model, current_user=current_user)
@@ -250,7 +250,7 @@ class AgentMessageFeedbackApi(Resource):
@with_current_user
@with_current_tenant_id
def post(self, current_tenant_id: str, current_user: Account, agent_id: UUID):
- app_model = resolve_agent_app_model(tenant_id=current_tenant_id, agent_id=agent_id)
+ app_model = resolve_agent_runtime_app_model(tenant_id=current_tenant_id, agent_id=agent_id)
return _update_message_feedback(current_user=current_user, app_model=app_model)
@@ -315,7 +315,7 @@ class AgentMessageSuggestedQuestionApi(Resource):
@with_current_user
@with_current_tenant_id
def get(self, current_tenant_id: str, current_user: Account, agent_id: UUID, message_id: UUID):
- app_model = resolve_agent_app_model(tenant_id=current_tenant_id, agent_id=agent_id)
+ app_model = resolve_agent_runtime_app_model(tenant_id=current_tenant_id, agent_id=agent_id)
return _get_message_suggested_questions(current_user=current_user, app_model=app_model, message_id=message_id)
@@ -393,7 +393,7 @@ class AgentMessageApi(Resource):
@account_initialization_required
@with_current_tenant_id
def get(self, current_tenant_id: str, agent_id: UUID, message_id: UUID):
- app_model = resolve_agent_app_model(tenant_id=current_tenant_id, agent_id=agent_id)
+ app_model = resolve_agent_runtime_app_model(tenant_id=current_tenant_id, agent_id=agent_id)
return _get_message_detail(app_model=app_model, message_id=message_id)
diff --git a/api/controllers/files/__init__.py b/api/controllers/files/__init__.py
index f8976b86b9f..5d26308e430 100644
--- a/api/controllers/files/__init__.py
+++ b/api/controllers/files/__init__.py
@@ -14,11 +14,12 @@ api = ExternalApi(
files_ns = Namespace("files", description="File operations", path="/")
-from . import image_preview, tool_files, upload
+from . import agent_drive_archive, image_preview, tool_files, upload
api.add_namespace(files_ns)
__all__ = [
+ "agent_drive_archive",
"api",
"bp",
"files_ns",
diff --git a/api/controllers/files/agent_drive_archive.py b/api/controllers/files/agent_drive_archive.py
new file mode 100644
index 00000000000..afa6ac79483
--- /dev/null
+++ b/api/controllers/files/agent_drive_archive.py
@@ -0,0 +1,67 @@
+from urllib.parse import quote
+
+from flask import Response, request
+from flask_restx import Resource
+from pydantic import BaseModel, Field
+from werkzeug.exceptions import Forbidden, NotFound
+
+from controllers.common.file_response import enforce_download_for_html
+from controllers.common.schema import register_schema_models
+from controllers.files import files_ns
+from models.agent import AgentDriveFileKind
+from services.agent_drive_service import AgentDriveError, AgentDriveService
+
+
+class AgentDriveArchiveMemberQuery(BaseModel):
+ tenant_id: str = Field(..., description="Tenant ID")
+ agent_id: str = Field(..., description="Agent ID")
+ key: str = Field(..., description="Virtual drive key")
+ archive_file_kind: AgentDriveFileKind = Field(..., description="Archive file kind")
+ archive_file_id: str = Field(..., description="Archive file id")
+ member_path: str = Field(..., description="Zip member path")
+ timestamp: str = Field(..., description="Unix timestamp")
+ nonce: str = Field(..., description="Random nonce")
+ sign: str = Field(..., description="HMAC signature")
+ as_attachment: bool = Field(default=False, description="Download as attachment")
+
+
+register_schema_models(files_ns, AgentDriveArchiveMemberQuery)
+
+
+@files_ns.route("/agent-drive/archive-member")
+class AgentDriveArchiveMemberApi(Resource):
+ @files_ns.doc("get_agent_drive_archive_member")
+ @files_ns.doc(description="Download a lazily resolved Agent Skill archive member by signed parameters")
+ def get(self):
+ args = AgentDriveArchiveMemberQuery.model_validate(request.args.to_dict(flat=True))
+ if not AgentDriveService.verify_archive_member_signature(
+ tenant_id=args.tenant_id,
+ agent_id=args.agent_id,
+ key=args.key,
+ archive_file_kind=args.archive_file_kind,
+ archive_file_id=args.archive_file_id,
+ member_path=args.member_path,
+ timestamp=args.timestamp,
+ nonce=args.nonce,
+ sign=args.sign,
+ ):
+ raise Forbidden("Invalid request.")
+ try:
+ payload, mime_type, filename = AgentDriveService().load_archive_member_for_signed_request(
+ tenant_id=args.tenant_id,
+ agent_id=args.agent_id,
+ key=args.key,
+ archive_file_kind=args.archive_file_kind,
+ archive_file_id=args.archive_file_id,
+ member_path=args.member_path,
+ )
+ except AgentDriveError as exc:
+ raise NotFound(exc.message) from exc
+
+ response = Response(payload, mimetype=mime_type, direct_passthrough=True, headers={})
+ response.headers["Content-Length"] = str(len(payload))
+ if args.as_attachment and filename:
+ encoded_filename = quote(filename)
+ response.headers["Content-Disposition"] = f"attachment; filename*=UTF-8''{encoded_filename}"
+ enforce_download_for_html(response, mime_type=mime_type, filename=filename, extension="")
+ return response
diff --git a/api/core/app/apps/agent_app/app_generator.py b/api/core/app/apps/agent_app/app_generator.py
index f816b1fa477..4f2c546fb7b 100644
--- a/api/core/app/apps/agent_app/app_generator.py
+++ b/api/core/app/apps/agent_app/app_generator.py
@@ -16,7 +16,7 @@ from collections.abc import Generator, Mapping
from typing import Any
from flask import Flask, current_app
-from sqlalchemy import select
+from sqlalchemy import and_, or_, select
from clients.agent_backend import AgentBackendRunEventAdapter
from clients.agent_backend.factory import create_agent_backend_run_client
@@ -42,7 +42,15 @@ from core.app.llm.model_access import build_dify_model_access
from core.ops.ops_trace_manager import TraceQueueManager
from extensions.ext_database import db
from models import Account, App, EndUser, Message
-from models.agent import Agent, AgentConfigSnapshot, AgentScope, AgentSource, AgentStatus
+from models.agent import (
+ Agent,
+ AgentConfigDraft,
+ AgentConfigDraftType,
+ AgentConfigSnapshot,
+ AgentScope,
+ AgentSource,
+ AgentStatus,
+)
from models.agent_config_entities import AgentSoulConfig
from services.conversation_service import ConversationService
@@ -73,10 +81,15 @@ class AgentAppGenerator(MessageBasedAppGenerator):
inputs = args["inputs"]
# Resolve the bound roster Agent + its current Agent Soul snapshot.
- agent, snapshot, agent_soul = self._resolve_agent(app_model)
+ agent, agent_config_id, agent_soul = self._resolve_agent(
+ app_model,
+ invoke_from=invoke_from,
+ draft_type=args.get("draft_type"),
+ user=user,
+ )
runtime_session_snapshot_id = self._runtime_session_snapshot_id(
invoke_from=invoke_from,
- snapshot_id=snapshot.id,
+ snapshot_id=agent_config_id,
)
conversation = None
@@ -123,7 +136,7 @@ class AgentAppGenerator(MessageBasedAppGenerator):
call_depth=0,
trace_manager=trace_manager,
agent_id=agent.id,
- agent_config_snapshot_id=snapshot.id,
+ agent_config_snapshot_id=agent_config_id,
agent_runtime_session_snapshot_id=runtime_session_snapshot_id,
)
@@ -179,7 +192,12 @@ class AgentAppGenerator(MessageBasedAppGenerator):
persisted to the conversation. Live streaming to a reconnected client is
out of scope here — the message is persisted and can be re-fetched.
"""
- agent, snapshot, agent_soul = self._resolve_agent(app_model)
+ agent, agent_config_id, agent_soul = self._resolve_agent(
+ app_model,
+ invoke_from=invoke_from,
+ draft_type="draft",
+ user=user,
+ )
conversation = ConversationService.get_conversation(
app_model=app_model, conversation_id=conversation_id, user=user
)
@@ -226,7 +244,7 @@ class AgentAppGenerator(MessageBasedAppGenerator):
call_depth=0,
trace_manager=trace_manager,
agent_id=agent.id,
- agent_config_snapshot_id=snapshot.id,
+ agent_config_snapshot_id=agent_config_id,
)
conversation, message = self._init_generate_records(application_generate_entity, conversation)
@@ -421,50 +439,135 @@ class AgentAppGenerator(MessageBasedAppGenerator):
return False, query
- def _resolve_agent(self, app_model: App) -> tuple[Agent, AgentConfigSnapshot, AgentSoulConfig]:
+ def _resolve_agent(
+ self,
+ app_model: App,
+ *,
+ invoke_from: InvokeFrom,
+ draft_type: Any,
+ user: Account | EndUser,
+ ) -> tuple[Agent, str, AgentSoulConfig]:
agent = db.session.scalar(
- select(Agent).where(
- Agent.app_id == app_model.id,
- Agent.scope == AgentScope.ROSTER,
- Agent.source == AgentSource.AGENT_APP,
+ select(Agent)
+ .where(
+ Agent.tenant_id == app_model.tenant_id,
Agent.status == AgentStatus.ACTIVE,
+ or_(
+ and_(
+ Agent.app_id == app_model.id,
+ Agent.scope == AgentScope.ROSTER,
+ Agent.source == AgentSource.AGENT_APP,
+ ),
+ Agent.backing_app_id == app_model.id,
+ ),
)
+ .order_by(Agent.created_at.desc())
+ .limit(1)
)
if agent is None:
raise AgentAppGeneratorError("Agent App has no bound Agent")
- return self._resolve_agent_by_id(
- tenant_id=app_model.tenant_id, agent_id=agent.id, snapshot_id=agent.active_config_snapshot_id
+ if invoke_from == InvokeFrom.DEBUGGER:
+ draft = self._resolve_debug_draft(
+ tenant_id=app_model.tenant_id,
+ agent=agent,
+ draft_type=draft_type,
+ account_id=user.id if isinstance(user, Account) else None,
+ )
+ agent_soul = AgentSoulConfig.model_validate(draft.config_snapshot_dict)
+ return agent, draft.id, agent_soul
+ _, snapshot, agent_soul = self._resolve_agent_by_id(
+ tenant_id=app_model.tenant_id,
+ agent_id=agent.id,
+ snapshot_id=agent.active_config_snapshot_id,
)
+ return agent, snapshot.id, agent_soul
@staticmethod
def _runtime_session_snapshot_id(*, invoke_from: InvokeFrom, snapshot_id: str) -> str | None:
"""Return the session scope snapshot id for Agent App runtime state.
- Console preview/debug chat is an editing workspace: saving Agent Soul
- creates replacement snapshots, but the user expects the same preview
- conversation to keep context while trying prompt changes. Use a stable
- NULL snapshot scope for debugger runs so each turn can use the latest
- Agent Soul while reusing the conversation history. Published/web/API
- runs keep snapshot-scoped sessions for reproducible runtime state.
+ Console preview/debug chat uses a stable Agent draft row id; build mode
+ uses the current user's build-draft row id. Published/web/API runs use
+ immutable published snapshot ids. This keeps runtime session continuity
+ inside one editable surface without mixing draft/build/published state.
"""
- if invoke_from == InvokeFrom.DEBUGGER:
- return None
return snapshot_id
+ @staticmethod
+ def _resolve_debug_draft(
+ *, tenant_id: str, agent: Agent, draft_type: Any, account_id: str | None
+ ) -> AgentConfigDraft:
+ effective_draft_type = (
+ AgentConfigDraftType.DEBUG_BUILD
+ if draft_type == AgentConfigDraftType.DEBUG_BUILD.value
+ else AgentConfigDraftType.DRAFT
+ )
+ stmt = select(AgentConfigDraft).where(
+ AgentConfigDraft.tenant_id == tenant_id,
+ AgentConfigDraft.agent_id == agent.id,
+ AgentConfigDraft.draft_type == effective_draft_type,
+ )
+ if effective_draft_type == AgentConfigDraftType.DEBUG_BUILD:
+ if not account_id:
+ raise AgentAppGeneratorError("Build draft requires an account user")
+ stmt = stmt.where(AgentConfigDraft.account_id == account_id)
+ else:
+ stmt = stmt.where(AgentConfigDraft.account_id.is_(None))
+ draft = db.session.scalar(stmt.order_by(AgentConfigDraft.updated_at.desc()).limit(1))
+ if draft is not None:
+ return draft
+ if effective_draft_type == AgentConfigDraftType.DEBUG_BUILD:
+ raise AgentAppGeneratorError("Agent build draft not found")
+ _, snapshot, agent_soul = AgentAppGenerator._resolve_agent_by_id(
+ tenant_id=tenant_id,
+ agent_id=agent.id,
+ snapshot_id=agent.active_config_snapshot_id,
+ )
+ draft = AgentConfigDraft(
+ tenant_id=tenant_id,
+ agent_id=agent.id,
+ draft_type=AgentConfigDraftType.DRAFT,
+ account_id=None,
+ draft_owner_key="",
+ base_snapshot_id=snapshot.id,
+ config_snapshot=agent_soul,
+ created_by=agent.created_by,
+ updated_by=agent.updated_by,
+ )
+ db.session.add(draft)
+ db.session.flush()
+ return draft
+
@staticmethod
def _resolve_agent_by_id(
*, tenant_id: str, agent_id: str, snapshot_id: str | None
- ) -> tuple[Agent, AgentConfigSnapshot, AgentSoulConfig]:
+ ) -> tuple[Agent, AgentConfigSnapshot | AgentConfigDraft, AgentSoulConfig]:
agent = db.session.scalar(select(Agent).where(Agent.id == agent_id, Agent.tenant_id == tenant_id))
if agent is None:
raise AgentAppGeneratorError("Agent not found")
if not snapshot_id:
raise AgentAppGeneratorError("Agent has no published version")
- snapshot = db.session.scalar(select(AgentConfigSnapshot).where(AgentConfigSnapshot.id == snapshot_id))
- if snapshot is None:
+ snapshot = db.session.scalar(
+ select(AgentConfigSnapshot).where(
+ AgentConfigSnapshot.tenant_id == tenant_id,
+ AgentConfigSnapshot.agent_id == agent_id,
+ AgentConfigSnapshot.id == snapshot_id,
+ )
+ )
+ if snapshot is not None:
+ agent_soul = AgentSoulConfig.model_validate(snapshot.config_snapshot_dict)
+ return agent, snapshot, agent_soul
+ draft = db.session.scalar(
+ select(AgentConfigDraft).where(
+ AgentConfigDraft.tenant_id == tenant_id,
+ AgentConfigDraft.agent_id == agent_id,
+ AgentConfigDraft.id == snapshot_id,
+ )
+ )
+ if draft is None:
raise AgentAppGeneratorError("Agent published version not found")
- agent_soul = AgentSoulConfig.model_validate(snapshot.config_snapshot_dict)
- return agent, snapshot, agent_soul
+ agent_soul = AgentSoulConfig.model_validate(draft.config_snapshot_dict)
+ return agent, draft, agent_soul
__all__ = ["AgentAppGenerator", "AgentAppGeneratorError"]
diff --git a/api/core/workflow/nodes/agent_v2/agent_node.py b/api/core/workflow/nodes/agent_v2/agent_node.py
index 8adb27240c7..1268cde65bd 100644
--- a/api/core/workflow/nodes/agent_v2/agent_node.py
+++ b/api/core/workflow/nodes/agent_v2/agent_node.py
@@ -31,6 +31,7 @@ from graphon.enums import BuiltinNodeTypes, WorkflowNodeExecutionMetadataKey, Wo
from graphon.node_events import NodeEventBase, NodeRunResult, PauseRequestedEvent, StreamCompletedEvent
from graphon.nodes.base.node import Node
from models.agent_config_entities import AgentSoulConfig, WorkflowNodeJobConfig
+from services.agent.prompt_mentions import extract_workflow_node_output_selectors
from .ask_human_hitl import AskHumanFormBuildError, build_ask_human_pause_reason
from .ask_human_resume import build_deferred_tool_results, resolve_ask_human_form
@@ -688,5 +689,20 @@ class DifyAgentNode(Node[DifyAgentNodeData]):
node_id: str,
node_data: DifyAgentNodeData,
) -> Mapping[str, Sequence[str]]:
- del graph_config, node_id, node_data
- return {}
+ """Reuse frontend workflow-marker parsing for graph variable loading.
+
+ This follows the same marker parser used by publish sync and runtime
+ request building, including reserved-prefix exclusion.
+ """
+ del graph_config
+
+ agent_task = (
+ node_data.get("agent_task") if isinstance(node_data, Mapping) else getattr(node_data, "agent_task", None)
+ )
+ if not isinstance(agent_task, str):
+ return {}
+
+ return {
+ f"{node_id}.{'.'.join(selector)}": list(selector)
+ for selector in extract_workflow_node_output_selectors(agent_task)
+ }
diff --git a/api/core/workflow/nodes/agent_v2/runtime_feature_manifest.py b/api/core/workflow/nodes/agent_v2/runtime_feature_manifest.py
index fa7b28cbb0a..8fd2783f61f 100644
--- a/api/core/workflow/nodes/agent_v2/runtime_feature_manifest.py
+++ b/api/core/workflow/nodes/agent_v2/runtime_feature_manifest.py
@@ -3,6 +3,7 @@ from __future__ import annotations
from typing import Any
from models.agent_config_entities import AgentSoulConfig
+from services.agent.knowledge_datasets import list_agent_soul_knowledge_dataset_ids
SUPPORTED_AGENT_BACKEND_FEATURES = frozenset(
{
@@ -48,9 +49,7 @@ def build_runtime_feature_manifest(agent_soul: AgentSoulConfig) -> dict[str, Any
)
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["knowledge"] = "supported_by_knowledge_layer" if agent_soul.knowledge.sets else "not_configured"
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"
@@ -66,14 +65,14 @@ def build_runtime_feature_manifest(agent_soul: AgentSoulConfig) -> dict[str, Any
def list_configured_knowledge_dataset_ids(agent_soul: AgentSoulConfig) -> list[str]:
- """Return the normalized knowledge dataset ids that can produce a runtime layer.
+ """Return normalized dataset ids selected by Agent v2 knowledge sets.
``build_runtime_feature_manifest()`` and ``build_knowledge_layer_config()``
- must stay aligned: both decide knowledge support from this effective,
- non-blank dataset-id set rather than from raw
- ``agent_soul.knowledge.datasets`` entries.
+ stay aligned on the set-based contract: DTO validation rejects blank dataset
+ ids before runtime, so this helper only flattens configured set datasets for
+ metadata/diagnostic surfaces that still need a dataset-id summary.
"""
- return [dataset_id for dataset in agent_soul.knowledge.datasets if (dataset_id := (dataset.id or "").strip())]
+ return list_agent_soul_knowledge_dataset_ids(agent_soul)
def _get_nested(value: dict[str, Any], path: str) -> Any:
diff --git a/api/core/workflow/nodes/agent_v2/runtime_request_builder.py b/api/core/workflow/nodes/agent_v2/runtime_request_builder.py
index e5a541ed350..f4a81bdcc54 100644
--- a/api/core/workflow/nodes/agent_v2/runtime_request_builder.py
+++ b/api/core/workflow/nodes/agent_v2/runtime_request_builder.py
@@ -1,10 +1,12 @@
from __future__ import annotations
+import json
from collections.abc import Mapping, Sequence
from dataclasses import dataclass
from typing import Any, Literal, Protocol, assert_never, cast
from agenton.compositor import CompositorSessionSnapshot
+from dify_agent.agent_stub.protocol import AgentStubFileMapping
from dify_agent.layers.ask_human import DifyAskHumanLayerConfig
from dify_agent.layers.drive import (
DifyDriveLayerConfig,
@@ -15,7 +17,16 @@ from dify_agent.layers.execution_context import (
DifyExecutionContextLayerConfig,
DifyExecutionContextUserFrom,
)
-from dify_agent.layers.knowledge import DifyKnowledgeBaseLayerConfig, DifyKnowledgeRetrievalConfig
+from dify_agent.layers.knowledge import (
+ DifyKnowledgeBaseLayerConfig,
+ DifyKnowledgeDatasetConfig,
+ DifyKnowledgeMetadataFilteringConfig,
+ DifyKnowledgeModelConfig,
+ DifyKnowledgeQueryConfig,
+ DifyKnowledgeRerankingModelConfig,
+ DifyKnowledgeRetrievalConfig,
+ DifyKnowledgeSetConfig,
+)
from dify_agent.layers.shell import (
DifyShellCliToolConfig,
DifyShellEnvVarConfig,
@@ -24,7 +35,7 @@ from dify_agent.layers.shell import (
DifyShellSecretRefConfig,
)
from dify_agent.protocol import CreateRunRequest, DeferredToolResultsPayload
-from pydantic import BaseModel
+from pydantic import BaseModel, ValidationError
from clients.agent_backend import (
AgentBackendModelConfig,
@@ -36,11 +47,13 @@ from clients.agent_backend import (
from configs import dify_config
from core.app.entities.app_invoke_entities import DifyRunContext, InvokeFrom
from core.workflow.system_variables import SystemVariableKey, get_system_text
-from graphon.file import FileTransferMethod
+from graphon.file import File, FileTransferMethod
from graphon.variables.segments import Segment
from models.agent import Agent, AgentConfigSnapshot, WorkflowAgentNodeBinding
from models.agent_config_entities import (
- AgentKnowledgeQueryConfig,
+ AgentKnowledgeMetadataFilteringConfig,
+ AgentKnowledgeModelConfig,
+ AgentKnowledgeRetrievalConfig,
AgentSoulConfig,
DeclaredArrayItem,
DeclaredOutputChildConfig,
@@ -58,13 +71,16 @@ from services.agent.prompt_mentions import (
build_node_job_mention_resolver,
build_soul_mention_resolver,
expand_prompt_mentions,
+ extract_workflow_node_output_selectors,
+ normalize_previous_node_output_selector,
parse_prompt_mentions,
+ workflow_previous_node_output_refs_from_selectors,
)
from services.agent_drive_service import AgentDriveService, decode_drive_mention_ref
from .output_failure_orchestrator import retry_idempotency_key
from .plugin_tools_builder import WorkflowAgentPluginToolsBuilder, WorkflowAgentPluginToolsBuildError
-from .runtime_feature_manifest import build_runtime_feature_manifest, list_configured_knowledge_dataset_ids
+from .runtime_feature_manifest import build_runtime_feature_manifest
_DENIED_PERMISSION_STATUSES = frozenset({"unauthorized", "denied", "forbidden", "invalid", "unavailable"})
_DANGEROUS_FLAG_KEYS = ("dangerous", "dangerous_command", "requires_confirmation")
@@ -74,6 +90,13 @@ _DANGEROUS_ACK_KEYS = (
"risk_accepted",
"approved",
)
+type AgentStubFileTransferMethod = Literal["local_file", "tool_file", "datasource_file", "remote_url"]
+_AGENT_STUB_FILE_TRANSFER_METHODS: Mapping[FileTransferMethod, AgentStubFileTransferMethod] = {
+ FileTransferMethod.LOCAL_FILE: "local_file",
+ FileTransferMethod.TOOL_FILE: "tool_file",
+ FileTransferMethod.DATASOURCE_FILE: "datasource_file",
+ FileTransferMethod.REMOTE_URL: "remote_url",
+}
class WorkflowAgentRuntimeRequestBuildError(ValueError):
@@ -126,6 +149,9 @@ class WorkflowAgentRuntimeRequest:
class WorkflowAgentRuntimeRequestBuilder:
"""Build public Dify Agent run requests from workflow Agent v2 runtime state."""
+ _WORKFLOW_USER_PROMPT_FALLBACK = "Use the current workflow context."
+ _WORKFLOW_JOB_PROMPT_FALLBACK = "Use the workflow user prompt for this run."
+
def __init__(
self,
*,
@@ -147,15 +173,13 @@ class WorkflowAgentRuntimeRequestBuilder:
)
metadata = self._build_metadata(context, agent_soul, node_job)
- workflow_context_prompt = self._build_workflow_context_prompt(context, node_job)
- # ENG-616: expand slash-menu mention tokens into model-readable names.
- # node_output mentions expand to their reference name only — the value
- # stays in the Workflow context block (user_prompt) below.
- workflow_job_prompt = (
- 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."
+ effective_node_job = node_job.model_copy(
+ update={"previous_node_output_refs": self._effective_previous_node_output_refs(node_job)}
)
- user_prompt = workflow_context_prompt.strip() or "Use the current workflow context."
+ workflow_task_prompt = self._build_workflow_task_prompt(context, effective_node_job)
+ workflow_context_prompt = self._build_workflow_context_prompt(context, effective_node_job)
+ workflow_job_prompt = workflow_task_prompt or self._WORKFLOW_JOB_PROMPT_FALLBACK
+ user_prompt = workflow_context_prompt or self._WORKFLOW_USER_PROMPT_FALLBACK
credentials = self._credentials_provider.fetch(agent_soul.model.model_provider, agent_soul.model.model)
try:
tools_layer = self._plugin_tools_builder.build(
@@ -310,15 +334,19 @@ class WorkflowAgentRuntimeRequestBuilder:
context: WorkflowAgentRuntimeBuildContext,
node_job: WorkflowNodeJobConfig,
) -> str:
- lines = ["Workflow context loaded for this run:"]
+ lines: list[str] = []
query = get_system_text(context.variable_pool, SystemVariableKey.QUERY)
- if query:
- lines.append(f"- User query: {query}")
-
resolved_outputs = self._resolve_previous_node_outputs(
context.variable_pool,
node_job.previous_node_output_refs,
)
+ if not query and not resolved_outputs:
+ return ""
+
+ lines.append("Workflow context loaded for this run:")
+ if query:
+ lines.append(f"- User query: {query}")
+
if resolved_outputs:
lines.append("- Previous node outputs:")
for item in resolved_outputs:
@@ -327,6 +355,31 @@ class WorkflowAgentRuntimeRequestBuilder:
lines.append("The above workflow context is run-specific. Do not treat it as Agent Soul or persistent memory.")
return "\n".join(lines)
+ def _build_workflow_task_prompt(
+ self,
+ context: WorkflowAgentRuntimeBuildContext,
+ node_job: WorkflowNodeJobConfig,
+ ) -> str:
+ del context
+ return expand_prompt_mentions(node_job.workflow_prompt, build_node_job_mention_resolver(node_job)).strip()
+
+ def _effective_previous_node_output_refs(
+ self,
+ node_job: WorkflowNodeJobConfig,
+ ) -> list[WorkflowPreviousNodeOutputRef]:
+ """Derive effective refs from the current frontend task markers.
+
+ The task text is the source of truth for previous-node context. When
+ the prompt has no frontend markers, stale persisted refs are discarded
+ instead of being carried forward into workflow context.
+ """
+ if not node_job.workflow_prompt:
+ return list(node_job.previous_node_output_refs)
+
+ return workflow_previous_node_output_refs_from_selectors(
+ extract_workflow_node_output_selectors(node_job.workflow_prompt)
+ )
+
def _resolve_previous_node_outputs(
self,
variable_pool: VariablePoolReader,
@@ -334,7 +387,7 @@ class WorkflowAgentRuntimeRequestBuilder:
) -> list[dict[str, Any]]:
resolved: list[dict[str, Any]] = []
for ref in refs:
- selector = self._selector_from_ref(ref)
+ selector = normalize_previous_node_output_selector(ref)
if not selector:
raise WorkflowAgentRuntimeRequestBuildError(
"invalid_previous_node_output_ref",
@@ -355,25 +408,73 @@ class WorkflowAgentRuntimeRequestBuilder:
)
return resolved
- @staticmethod
- def _selector_from_ref(ref: WorkflowPreviousNodeOutputRef) -> list[str] | None:
- for key in ("selector", "variable_selector", "value_selector"):
- value = ref.get(key)
- if isinstance(value, list) and all(isinstance(item, str) for item in value):
- return value
- node_id = ref.get("node_id")
- output_name = ref.get("output") or ref.get("name") or ref.get("variable") or ref.get("key")
- if isinstance(node_id, str) and isinstance(output_name, str):
- return [node_id, output_name]
- return None
-
@staticmethod
def _summarize_value(value: Any) -> str:
+ prompt_payload, used_download_mapping = WorkflowAgentRuntimeRequestBuilder._resolve_prompt_payload_value(value)
+ if used_download_mapping:
+ return json.dumps(prompt_payload, ensure_ascii=False, separators=(",", ":"))
+
text = str(value)
if len(text) > 2000:
return text[:2000] + "...[truncated]"
return text
+ @classmethod
+ def _resolve_prompt_payload_value(cls, value: Any) -> tuple[Any, bool]:
+ # File-valued workflow context must surface as Agent Stub download
+ # mappings so the model can materialize those inputs with
+ # `dify-agent file download --mapping ...` inside the sandbox.
+ download_mapping = cls._agent_stub_download_mapping(value)
+ if download_mapping is not None:
+ return download_mapping, True
+
+ if isinstance(value, list | tuple):
+ changed = False
+ resolved_items: list[Any] = []
+ for item in value:
+ resolved_item, item_changed = cls._resolve_prompt_payload_value(item)
+ resolved_items.append(resolved_item)
+ changed = changed or item_changed
+ return resolved_items, changed
+
+ if isinstance(value, Mapping):
+ changed = False
+ resolved_items_by_key: dict[str, Any] = {}
+ for key, item in value.items():
+ resolved_item, item_changed = cls._resolve_prompt_payload_value(item)
+ resolved_items_by_key[str(key)] = resolved_item
+ changed = changed or item_changed
+ return resolved_items_by_key, changed
+
+ return value, False
+
+ @staticmethod
+ def _agent_stub_download_mapping(value: Any) -> dict[str, Any] | None:
+ try:
+ if isinstance(value, File):
+ transfer_method = _AGENT_STUB_FILE_TRANSFER_METHODS.get(value.transfer_method)
+ if transfer_method is None:
+ return None
+ if value.transfer_method == FileTransferMethod.REMOTE_URL:
+ url = value.remote_url
+ if not isinstance(url, str) or not url:
+ return None
+ mapping = AgentStubFileMapping(transfer_method=transfer_method, url=url)
+ else:
+ reference = value.reference
+ if not isinstance(reference, str) or not reference:
+ return None
+ mapping = AgentStubFileMapping(transfer_method=transfer_method, reference=reference)
+ return mapping.model_dump(mode="json", exclude_none=True)
+
+ if isinstance(value, Mapping):
+ mapping = AgentStubFileMapping.model_validate(value)
+ return mapping.model_dump(mode="json", exclude_none=True)
+ except ValidationError:
+ return None
+
+ return None
+
@staticmethod
def _build_output_config(declared_outputs: Sequence[DeclaredOutputConfig]) -> AgentBackendOutputConfig | None:
"""Build the structured-output layer config sent to Agent backend.
@@ -547,42 +648,84 @@ def build_shell_layer_config(agent_soul: AgentSoulConfig) -> DifyShellLayerConfi
def build_knowledge_layer_config(agent_soul: AgentSoulConfig) -> DifyKnowledgeBaseLayerConfig | None:
- """Map Agent Soul knowledge config into the fixed Dify knowledge-base layer.
-
- Normalization intentionally matches the current dify-agent runtime contract:
+ """Map Agent Soul knowledge sets into one Dify knowledge-base layer.
- - blank or missing dataset ids are ignored;
- - if no valid dataset ids remain, no knowledge layer is injected;
- - retrieval mode is always forced to ``multiple`` in this first wiring pass;
- - ``top_k`` falls back to a stable runtime default when the soul omits it;
- - ``score_threshold`` is only forwarded when the product config explicitly
- enables it, otherwise the layer keeps the disabled/default ``0.0`` value;
- - metadata filtering stays at the layer DTO default (disabled).
+ Agent Soul DTO validation owns malformed set rejection. Runtime mapping is
+ intentionally lossless: every configured set is forwarded with its query
+ policy, dataset refs, retrieval controls, and metadata-filtering controls.
+ ``score_threshold=None`` means disabled threshold filtering and maps to the
+ inner retrieval request's ``0.0`` default through the Agent backend DTO.
"""
- dataset_ids = list_configured_knowledge_dataset_ids(agent_soul)
- if not dataset_ids:
+ if not agent_soul.knowledge.sets:
return None
- query_config = agent_soul.knowledge.query_config
return DifyKnowledgeBaseLayerConfig(
- dataset_ids=dataset_ids,
- retrieval=DifyKnowledgeRetrievalConfig(
- mode="multiple",
- top_k=_knowledge_top_k(query_config),
- score_threshold=_knowledge_score_threshold(query_config),
- ),
+ sets=[
+ DifyKnowledgeSetConfig(
+ id=knowledge_set.id,
+ name=knowledge_set.name,
+ description=knowledge_set.description,
+ datasets=[
+ DifyKnowledgeDatasetConfig(
+ id=dataset.id or "",
+ name=dataset.name,
+ description=dataset.description,
+ )
+ for dataset in knowledge_set.datasets
+ ],
+ query=DifyKnowledgeQueryConfig(
+ mode=cast(Literal["user_query", "generated_query"], knowledge_set.query.mode.value),
+ value=knowledge_set.query.value,
+ ),
+ retrieval=_knowledge_retrieval_config(knowledge_set.retrieval),
+ metadata_filtering=_knowledge_metadata_filtering_config(knowledge_set.metadata_filtering),
+ )
+ for knowledge_set in agent_soul.knowledge.sets
+ ],
)
-def _knowledge_top_k(query_config: AgentKnowledgeQueryConfig) -> int:
- top_k = query_config.top_k
- return top_k if isinstance(top_k, int) and top_k >= 1 else 4
+def _knowledge_retrieval_config(retrieval: AgentKnowledgeRetrievalConfig) -> DifyKnowledgeRetrievalConfig:
+ return DifyKnowledgeRetrievalConfig(
+ mode=retrieval.mode,
+ top_k=retrieval.top_k,
+ score_threshold=retrieval.score_threshold or 0.0,
+ reranking_mode=retrieval.reranking_mode,
+ reranking_enable=retrieval.reranking_enable,
+ reranking_model=DifyKnowledgeRerankingModelConfig(
+ provider=retrieval.reranking_model.provider,
+ model=retrieval.reranking_model.model,
+ )
+ if retrieval.reranking_model is not None
+ else None,
+ weights=cast(dict[str, Any], retrieval.weights.model_dump(mode="json", exclude_none=True))
+ if retrieval.weights is not None
+ else None,
+ model=_knowledge_model_config(retrieval.model),
+ )
-def _knowledge_score_threshold(query_config: AgentKnowledgeQueryConfig) -> float:
- if query_config.score_threshold_enabled and query_config.score_threshold is not None:
- return query_config.score_threshold
- return 0.0
+def _knowledge_metadata_filtering_config(
+ metadata_filtering: AgentKnowledgeMetadataFilteringConfig,
+) -> DifyKnowledgeMetadataFilteringConfig:
+ return DifyKnowledgeMetadataFilteringConfig(
+ mode=metadata_filtering.mode,
+ model_config=_knowledge_model_config(metadata_filtering.metadata_model_config),
+ conditions=cast(Any, metadata_filtering.conditions.model_dump(mode="json"))
+ if metadata_filtering.conditions is not None
+ else None,
+ )
+
+
+def _knowledge_model_config(model: AgentKnowledgeModelConfig | None) -> DifyKnowledgeModelConfig | None:
+ if model is None:
+ return None
+ return DifyKnowledgeModelConfig(
+ provider=model.provider,
+ name=model.name,
+ mode=model.mode,
+ completion_params=model.completion_params,
+ )
def build_ask_human_layer_config(agent_soul: AgentSoulConfig) -> DifyAskHumanLayerConfig | None:
diff --git a/api/core/workflow/nodes/agent_v2/validators.py b/api/core/workflow/nodes/agent_v2/validators.py
index 2eabac10dd6..7b915fe02be 100644
--- a/api/core/workflow/nodes/agent_v2/validators.py
+++ b/api/core/workflow/nodes/agent_v2/validators.py
@@ -18,6 +18,7 @@ from models.agent_config_entities import (
)
from models.model import UploadFile
from models.workflow import Workflow
+from services.agent.knowledge_datasets import list_missing_tenant_knowledge_dataset_ids
from .entities import DifyAgentNodeData
@@ -146,6 +147,7 @@ class WorkflowAgentNodeValidator:
)
cls._validate_agent_soul_env(binding=binding, agent_soul=agent_soul)
cls._validate_agent_soul_tools(binding=binding, agent_soul=agent_soul)
+ cls._validate_agent_soul_knowledge(binding=binding, agent_soul=agent_soul)
node_job = WorkflowNodeJobConfig.model_validate(binding.node_job_config_dict)
cls.validate_node_job(session=session, binding=binding, node_job=node_job, topology=topology)
@@ -364,6 +366,24 @@ class WorkflowAgentNodeValidator:
)
cli_tool_names.add(normalized_name)
+ @classmethod
+ def _validate_agent_soul_knowledge(
+ cls,
+ *,
+ binding: WorkflowAgentNodeBinding,
+ agent_soul: AgentSoulConfig,
+ ) -> None:
+ """Validate knowledge set dataset rows against the publishing tenant."""
+ missing_ids = list_missing_tenant_knowledge_dataset_ids(
+ tenant_id=binding.tenant_id,
+ agent_soul=agent_soul,
+ )
+ if missing_ids:
+ raise WorkflowAgentNodeValidationError(
+ f"Workflow Agent node {binding.node_id} references missing or out-of-scope knowledge datasets: "
+ f"{', '.join(missing_ids)}."
+ )
+
@classmethod
def _validate_agent_soul_env(
cls,
diff --git a/api/fields/agent_fields.py b/api/fields/agent_fields.py
index e60a6b01426..e045ee39afc 100644
--- a/api/fields/agent_fields.py
+++ b/api/fields/agent_fields.py
@@ -6,6 +6,7 @@ from pydantic import Field, field_validator
from fields.base import ResponseModel
from libs.helper import to_timestamp
from models.agent import (
+ AgentConfigDraftType,
AgentConfigRevisionOperation,
AgentIconType,
AgentKind,
@@ -47,6 +48,18 @@ class AgentConfigSnapshotSummaryResponse(ResponseModel):
created_at: int | None = None
+class AgentConfigDraftSummaryResponse(ResponseModel):
+ id: str
+ agent_id: str
+ draft_type: AgentConfigDraftType
+ account_id: str | None = None
+ base_snapshot_id: str | None = None
+ created_by: str | None = None
+ updated_by: str | None = None
+ created_at: int | None = None
+ updated_at: int | None = None
+
+
class AgentPublishedReferenceResponse(ResponseModel):
app_id: str
app_name: str
@@ -72,6 +85,8 @@ class AgentRosterResponse(ResponseModel):
scope: AgentScope
source: AgentSource
app_id: str | None = None
+ backing_app_id: str | None = None
+ hidden_app_backed: bool = False
workflow_id: str | None = None
workflow_node_id: str | None = None
active_config_snapshot_id: str | None = None
@@ -292,14 +307,24 @@ class AgentConfigSnapshotListResponse(ResponseModel):
class AgentConfigSnapshotRestoreResponse(ResponseModel):
result: Literal["success"]
active_config_snapshot_id: str
+ draft_config_id: str | None = None
+ restored_version_id: str | None = None
class AgentComposerAgentResponse(ResponseModel):
id: str
name: str
description: str
+ role: str | None = None
+ icon_type: str | None = None
+ icon: str | None = None
+ icon_background: str | None = None
scope: AgentScope
+ source: AgentSource | None = None
status: AgentStatus
+ app_id: str | None = None
+ backing_app_id: str | None = None
+ hidden_app_backed: bool = False
active_config_snapshot_id: str | None = None
@@ -343,6 +368,9 @@ class WorkflowAgentComposerResponse(ResponseModel):
impact_summary: AgentComposerImpactResponse | None = None
validation: "ComposerValidationFindingsResponse | None" = None
app_id: str | None = None
+ backing_app_id: str | None = None
+ hidden_app_backed: bool = False
+ chat_endpoint: str | None = None
workflow_id: str | None = None
node_id: str | None = None
@@ -350,10 +378,15 @@ class WorkflowAgentComposerResponse(ResponseModel):
class AgentAppComposerResponse(ResponseModel):
variant: Literal[ComposerVariant.AGENT_APP]
agent: AgentComposerAgentResponse
- active_config_snapshot: AgentConfigSnapshotSummaryResponse
+ active_config_snapshot: AgentConfigSnapshotSummaryResponse | None = None
+ draft: AgentConfigDraftSummaryResponse | None = None
agent_soul: AgentSoulConfig
save_options: list[ComposerSaveStrategy]
validation: "ComposerValidationFindingsResponse | None" = None
+ app_id: str | None = None
+ backing_app_id: str | None = None
+ hidden_app_backed: bool = False
+ chat_endpoint: str | None = None
class ComposerValidationWarningResponse(ResponseModel):
@@ -400,10 +433,22 @@ class AgentComposerNodeJobCandidatesResponse(ResponseModel):
human_contacts: list[AgentHumanContactConfig] = Field(default_factory=list)
+class AgentComposerKnowledgeDatasetCandidateResponse(AgentKnowledgeDatasetConfig):
+ missing: bool = False
+
+
+class AgentComposerKnowledgeSetCandidateResponse(ResponseModel):
+ id: str
+ name: str
+ description: str | None = None
+ datasets: list[AgentComposerKnowledgeDatasetCandidateResponse] = Field(default_factory=list)
+ missing_dataset_ids: list[str] = Field(default_factory=list)
+
+
class AgentComposerSoulCandidatesResponse(ResponseModel):
dify_tools: list[AgentComposerDifyToolCandidateResponse] = Field(default_factory=list)
cli_tools: list[AgentCliToolConfig] = Field(default_factory=list)
- knowledge_datasets: list[AgentKnowledgeDatasetConfig] = Field(default_factory=list)
+ knowledge_sets: list[AgentComposerKnowledgeSetCandidateResponse] = Field(default_factory=list)
human_contacts: list[AgentHumanContactConfig] = Field(default_factory=list)
diff --git a/api/migrations/versions/2026_05_25_1143-97e2e1a644e8_add_workflow_version_to_workflow_agent_.py b/api/migrations/versions/2026_05_25_1143-97e2e1a644e8_add_workflow_version_to_workflow_agent_.py
index 7348e19b3cc..8078c83fa14 100644
--- a/api/migrations/versions/2026_05_25_1143-97e2e1a644e8_add_workflow_version_to_workflow_agent_.py
+++ b/api/migrations/versions/2026_05_25_1143-97e2e1a644e8_add_workflow_version_to_workflow_agent_.py
@@ -1,16 +1,5 @@
"""add workflow_version to workflow_agent_node_bindings
-Restores the stage 1 §5.3 unique key
-``(tenant_id, workflow_id, workflow_version, node_id)`` so draft and published
-workflow bindings can coexist at the same workflow_id once we want to track
-them per workflow version. ``workflow_version`` mirrors ``workflows.version``
-("draft" or a published version string).
-
-Because the New Agent Experience feature is pre-release, this table is empty
-in every environment that matters; the ``server_default='draft'`` only exists
-to keep developer-local rows valid during the alter and is dropped immediately
-afterward so application code must specify ``workflow_version`` explicitly.
-
Revision ID: 97e2e1a644e8
Revises: f8b6b7e9c421
Create Date: 2026-05-25 11:43:37.611300
@@ -33,10 +22,8 @@ def upgrade():
'workflow_version',
sa.String(length=255),
nullable=False,
- server_default='draft',
)
)
- batch_op.alter_column('workflow_version', server_default=None)
batch_op.drop_constraint(
batch_op.f('workflow_agent_node_binding_node_unique'), type_='unique'
)
diff --git a/api/migrations/versions/2026_06_12_1100-0b2f2c8a9d1e_add_agent_role.py b/api/migrations/versions/2026_06_12_1100-0b2f2c8a9d1e_add_agent_role.py
index 900f7da06fc..ee30abaa45b 100644
--- a/api/migrations/versions/2026_06_12_1100-0b2f2c8a9d1e_add_agent_role.py
+++ b/api/migrations/versions/2026_06_12_1100-0b2f2c8a9d1e_add_agent_role.py
@@ -18,8 +18,7 @@ depends_on = None
def upgrade():
with op.batch_alter_table("agents", schema=None) as batch_op:
- batch_op.add_column(sa.Column("role", sa.String(length=255), nullable=False, server_default=""))
- batch_op.alter_column("role", server_default=None)
+ batch_op.add_column(sa.Column("role", sa.String(length=255), nullable=False))
def downgrade():
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.py
index 3398c2eb018..9dc85d2a89b 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,15 +6,9 @@ Create Date: 2026-06-18 23:00:00.000000
"""
-from __future__ import annotations
-
-import json
-from typing import Any
-
-from alembic import op
import sqlalchemy as sa
+from alembic import op
from sqlalchemy.dialects import mysql
-from sqlalchemy.engine.mock import MockConnection
# revision identifiers, used by Alembic.
revision = "b2515f9d4c2a"
@@ -37,46 +31,9 @@ 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 snapshot
diff --git a/api/migrations/versions/2026_06_24_2015-e4f5a6b7c8d9_add_agent_config_drafts.py b/api/migrations/versions/2026_06_24_2015-e4f5a6b7c8d9_add_agent_config_drafts.py
new file mode 100644
index 00000000000..f67fc55bb90
--- /dev/null
+++ b/api/migrations/versions/2026_06_24_2015-e4f5a6b7c8d9_add_agent_config_drafts.py
@@ -0,0 +1,56 @@
+"""add agent config drafts
+
+Revision ID: e4f5a6b7c8d9
+Revises: a6f1c9d2e8b4
+Create Date: 2026-06-24 20:15:00.000000
+
+"""
+
+import sqlalchemy as sa
+from alembic import op
+
+import models
+
+# revision identifiers, used by Alembic.
+revision = "e4f5a6b7c8d9"
+down_revision = "a6f1c9d2e8b4"
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+ op.create_table(
+ "agent_config_drafts",
+ sa.Column("id", models.types.StringUUID(), nullable=False),
+ sa.Column("tenant_id", models.types.StringUUID(), nullable=False),
+ sa.Column("agent_id", models.types.StringUUID(), nullable=False),
+ sa.Column("draft_type", sa.String(length=32), nullable=False),
+ sa.Column("account_id", models.types.StringUUID(), nullable=True),
+ sa.Column("draft_owner_key", sa.String(length=255), nullable=False),
+ sa.Column("base_snapshot_id", models.types.StringUUID(), nullable=True),
+ sa.Column("config_snapshot", models.types.LongText(), nullable=False),
+ sa.Column("created_by", models.types.StringUUID(), nullable=True),
+ sa.Column("updated_by", models.types.StringUUID(), nullable=True),
+ sa.Column("created_at", sa.DateTime(), server_default=sa.func.current_timestamp(), nullable=False),
+ sa.Column("updated_at", sa.DateTime(), server_default=sa.func.current_timestamp(), nullable=False),
+ sa.PrimaryKeyConstraint("id", name=op.f("agent_config_draft_pkey")),
+ sa.UniqueConstraint(
+ "tenant_id",
+ "agent_id",
+ "draft_type",
+ "draft_owner_key",
+ name=op.f("agent_config_draft_agent_type_account_unique"),
+ ),
+ )
+ op.create_index("agent_config_draft_tenant_agent_idx", "agent_config_drafts", ["tenant_id", "agent_id"])
+ op.create_index(
+ "agent_config_draft_base_snapshot_idx",
+ "agent_config_drafts",
+ ["tenant_id", "base_snapshot_id"],
+ )
+
+
+def downgrade():
+ op.drop_index("agent_config_draft_base_snapshot_idx", table_name="agent_config_drafts")
+ op.drop_index("agent_config_draft_tenant_agent_idx", table_name="agent_config_drafts")
+ op.drop_table("agent_config_drafts")
diff --git a/api/migrations/versions/2026_06_25_1100-a2b3c4d5e6f7_add_agent_backing_app_id.py b/api/migrations/versions/2026_06_25_1100-a2b3c4d5e6f7_add_agent_backing_app_id.py
new file mode 100644
index 00000000000..be19ecf7ed9
--- /dev/null
+++ b/api/migrations/versions/2026_06_25_1100-a2b3c4d5e6f7_add_agent_backing_app_id.py
@@ -0,0 +1,30 @@
+"""add agent backing app id
+
+Revision ID: a2b3c4d5e6f7
+Revises: e4f5a6b7c8d9
+Create Date: 2026-06-25 11:00:00.000000
+
+"""
+
+import sqlalchemy as sa
+from alembic import op
+
+import models
+
+# revision identifiers, used by Alembic.
+revision = "a2b3c4d5e6f7"
+down_revision = "e4f5a6b7c8d9"
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+ with op.batch_alter_table("agents", schema=None) as batch_op:
+ batch_op.add_column(sa.Column("backing_app_id", models.types.StringUUID(), nullable=True))
+ op.create_index("agent_tenant_backing_app_id_idx", "agents", ["tenant_id", "backing_app_id"])
+
+
+def downgrade():
+ op.drop_index("agent_tenant_backing_app_id_idx", table_name="agents")
+ with op.batch_alter_table("agents", schema=None) as batch_op:
+ batch_op.drop_column("backing_app_id")
diff --git a/api/migrations/versions/2026_06_26_1000-c3d4e5f6a7b8_add_agent_active_config_is_published.py b/api/migrations/versions/2026_06_26_1000-c3d4e5f6a7b8_add_agent_active_config_is_published.py
new file mode 100644
index 00000000000..5040287ca2e
--- /dev/null
+++ b/api/migrations/versions/2026_06_26_1000-c3d4e5f6a7b8_add_agent_active_config_is_published.py
@@ -0,0 +1,37 @@
+"""add agent active config is published
+
+Revision ID: c3d4e5f6a7b8
+Revises: a2b3c4d5e6f7
+Create Date: 2026-06-26 10:00:00.000000
+
+"""
+
+import sqlalchemy as sa
+from alembic import op
+
+# revision identifiers, used by Alembic.
+revision = "c3d4e5f6a7b8"
+down_revision = "a2b3c4d5e6f7"
+branch_labels = None
+depends_on = None
+
+
+def upgrade():
+ with op.batch_alter_table("agents", schema=None) as batch_op:
+ batch_op.add_column(
+ sa.Column(
+ "active_config_is_published",
+ sa.Boolean(),
+ server_default=sa.text("false"),
+ nullable=False,
+ comment=(
+ "Whether the normal shared Agent draft has been published into the active config snapshot. "
+ "User-scoped debug drafts do not affect this flag."
+ ),
+ )
+ )
+
+
+def downgrade():
+ with op.batch_alter_table("agents", schema=None) as batch_op:
+ batch_op.drop_column("active_config_is_published")
diff --git a/api/models/__init__.py b/api/models/__init__.py
index 9992de982c4..ac90eef0962 100644
--- a/api/models/__init__.py
+++ b/api/models/__init__.py
@@ -10,6 +10,8 @@ from .account import (
)
from .agent import (
Agent,
+ AgentConfigDraft,
+ AgentConfigDraftType,
AgentConfigRevision,
AgentConfigRevisionOperation,
AgentConfigSnapshot,
@@ -154,6 +156,8 @@ __all__ = [
"AccountStatus",
"AccountTrialAppRecord",
"Agent",
+ "AgentConfigDraft",
+ "AgentConfigDraftType",
"AgentConfigRevision",
"AgentConfigRevisionOperation",
"AgentConfigSnapshot",
diff --git a/api/models/agent.py b/api/models/agent.py
index 46044edd5e7..f91a05266ee 100644
--- a/api/models/agent.py
+++ b/api/models/agent.py
@@ -85,6 +85,17 @@ class AgentConfigRevisionOperation(StrEnum):
SAVE_TO_ROSTER = "save_to_roster"
# Switches the Agent's current published config back to an existing version.
RESTORE_VERSION = "restore_version"
+ # Publishes the editable Agent Soul draft as a new immutable version.
+ PUBLISH_DRAFT = "publish_draft"
+
+
+class AgentConfigDraftType(StrEnum):
+ """Editable Agent Soul draft workspace type."""
+
+ # Shared Agent Console draft edited by users before publishing.
+ DRAFT = "draft"
+ # Per-editor build draft mutated during debug/build mode.
+ DEBUG_BUILD = "debug_build"
class WorkflowAgentBindingType(StrEnum):
@@ -134,6 +145,7 @@ class Agent(DefaultFieldsMixin, Base):
Index("agent_tenant_scope_idx", "tenant_id", "scope"),
Index("agent_tenant_workflow_id_idx", "tenant_id", "workflow_id"),
Index("agent_tenant_app_id_idx", "tenant_id", "app_id"),
+ Index("agent_tenant_backing_app_id_idx", "tenant_id", "backing_app_id"),
Index("agent_active_config_snapshot_id_idx", "active_config_snapshot_id"),
Index(
"agent_tenant_invitable_idx",
@@ -162,12 +174,30 @@ class Agent(DefaultFieldsMixin, Base):
scope: Mapped[AgentScope] = mapped_column(EnumText(AgentScope, length=32), nullable=False)
source: Mapped[AgentSource] = mapped_column(EnumText(AgentSource, length=32), nullable=False)
app_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True)
+ backing_app_id: Mapped[str | None] = mapped_column(
+ StringUUID,
+ nullable=True,
+ comment=(
+ "Runtime Agent App used for chat/log/monitoring. For workflow-only agents, "
+ "app_id remains the parent workflow app id and this points to the hidden backing app."
+ ),
+ )
workflow_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True)
workflow_node_id: Mapped[str | None] = mapped_column(String(255), nullable=True)
active_config_snapshot_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True)
active_config_has_model: Mapped[bool] = mapped_column(
sa.Boolean, nullable=False, default=False, server_default=sa.text("false")
)
+ active_config_is_published: Mapped[bool] = mapped_column(
+ sa.Boolean,
+ nullable=False,
+ default=False,
+ server_default=sa.text("false"),
+ comment=(
+ "Whether the normal shared Agent draft has been published into the active config snapshot. "
+ "User-scoped debug drafts do not affect this flag."
+ ),
+ )
status: Mapped[AgentStatus] = mapped_column(
EnumText(AgentStatus, length=32), nullable=False, default=AgentStatus.ACTIVE
)
@@ -210,6 +240,44 @@ class AgentDebugConversation(DefaultFieldsMixin, Base):
conversation_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
+class AgentConfigDraft(DefaultFieldsMixin, Base):
+ """Editable Agent Soul draft separated from immutable published snapshots."""
+
+ __tablename__ = "agent_config_drafts"
+ __table_args__ = (
+ sa.PrimaryKeyConstraint("id", name="agent_config_draft_pkey"),
+ UniqueConstraint(
+ "tenant_id",
+ "agent_id",
+ "draft_type",
+ "draft_owner_key",
+ name="agent_config_draft_agent_type_account_unique",
+ ),
+ Index("agent_config_draft_tenant_agent_idx", "tenant_id", "agent_id"),
+ Index("agent_config_draft_base_snapshot_idx", "tenant_id", "base_snapshot_id"),
+ )
+
+ tenant_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
+ agent_id: Mapped[str] = mapped_column(StringUUID, nullable=False)
+ draft_type: Mapped[AgentConfigDraftType] = mapped_column(EnumText(AgentConfigDraftType, length=32), nullable=False)
+ account_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True)
+ draft_owner_key: Mapped[str] = mapped_column(String(255), nullable=False, default="")
+ base_snapshot_id: Mapped[str | None] = mapped_column(StringUUID, nullable=True)
+ config_snapshot: Mapped[Any] = mapped_column(JSONModelColumn(AgentSoulConfig), nullable=False)
+ created_by: Mapped[str | None] = mapped_column(StringUUID, nullable=True)
+ updated_by: Mapped[str | None] = mapped_column(StringUUID, nullable=True)
+
+ @property
+ def config_snapshot_dict(self) -> dict[str, Any]:
+ if not self.config_snapshot:
+ return {}
+ if hasattr(self.config_snapshot, "model_dump"):
+ return self.config_snapshot.model_dump(mode="json")
+ if isinstance(self.config_snapshot, str):
+ return json.loads(self.config_snapshot)
+ return dict(self.config_snapshot)
+
+
class AgentConfigSnapshot(DefaultFieldsMixin, Base):
"""Immutable Agent Soul snapshot.
@@ -355,9 +423,9 @@ class AgentRuntimeSession(DefaultFieldsMixin, Base):
agent_config_snapshot_id / composition_layer_specs`` columns are set.
- Agent App conversations: ``owner_type = conversation``; the
``conversation_id`` column is set and the workflow columns stay NULL.
- Published/web/API runs scope runtime state by ``agent_config_snapshot_id``;
- console debugger runs may keep it NULL so prompt-only draft saves can reuse
- the same preview conversation state while executing the latest Agent Soul.
+ Runtime state is scoped by ``agent_config_snapshot_id``. For published
+ web/API runs this points to an immutable AgentConfigSnapshot; for console
+ debugger/build runs it points to the editable AgentConfigDraft row.
The snapshot is runtime state returned by Agent backend, kept separate from
Agent Soul snapshots and workflow node-job config.
diff --git a/api/models/agent_config_entities.py b/api/models/agent_config_entities.py
index 2503ba66f06..c1faa5a6975 100644
--- a/api/models/agent_config_entities.py
+++ b/api/models/agent_config_entities.py
@@ -2,10 +2,11 @@ from __future__ import annotations
import re
from enum import StrEnum
-from typing import Annotated, Any, Final, Literal
+from typing import Annotated, Any, Final, Literal, Self
from pydantic import BaseModel, ConfigDict, Field, WithJsonSchema, field_validator, model_validator
+from core.rag.entities.metadata_entities import ConditionValue, SupportedComparisonOperator
from core.workflow.file_reference import is_canonical_file_reference
from graphon.file import FileTransferMethod
@@ -161,6 +162,11 @@ class AgentSkillRefConfig(AgentFlexibleConfig):
manifest_files: list[str] | None = None
+class AgentSoulFilesConfig(BaseModel):
+ skills: list[AgentSkillRefConfig] = Field(default_factory=list)
+ files: list[AgentFileRefConfig] = Field(default_factory=list)
+
+
class AgentPermissionConfig(BaseModel):
model_config = ConfigDict(extra="ignore")
@@ -236,17 +242,161 @@ class AgentCliToolConfig(AgentFlexibleConfig):
inferred_from: str | None = Field(default=None, max_length=255)
-class AgentKnowledgeDatasetConfig(AgentFlexibleConfig):
+class AgentKnowledgeDatasetConfig(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
id: str | None = Field(default=None, max_length=255)
name: str | None = Field(default=None, max_length=255)
description: str | None = None
-class AgentKnowledgeQueryConfig(AgentFlexibleConfig):
- query: str | None = None
+class AgentKnowledgeQueryConfig(BaseModel):
+ """Per-set query policy for Agent v2 knowledge retrieval.
+
+ Agent v2 stores knowledge as explicit ``knowledge.sets`` rather than the
+ legacy flat ``datasets`` / ``query_mode`` / ``query_config`` shape. Each
+ set owns its own query policy, so ``user_query`` must carry an explicit
+ ``value`` while ``generated_query`` leaves that value empty.
+ """
+
+ model_config = ConfigDict(extra="forbid")
+
+ mode: AgentKnowledgeQueryMode
+ value: str | None = None
+
+ @model_validator(mode="after")
+ def validate_query(self) -> Self:
+ if self.mode == AgentKnowledgeQueryMode.USER_QUERY and not (self.value or "").strip():
+ raise ValueError("knowledge query.value is required for user_query mode")
+ return self
+
+
+class AgentKnowledgeModelConfig(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ provider: str = Field(min_length=1, max_length=255)
+ name: str = Field(min_length=1, max_length=255)
+ mode: str = Field(min_length=1, max_length=64)
+ completion_params: dict[str, Any] = Field(default_factory=dict)
+
+
+class AgentKnowledgeRerankingModelConfig(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ provider: str = Field(min_length=1, max_length=255)
+ model: str = Field(min_length=1, max_length=255)
+
+
+class AgentKnowledgeWeightedScoreConfig(AgentFlexibleConfig):
+ weight_type: str | None = Field(default=None, max_length=64)
+ vector_setting: dict[str, Any] | None = None
+ keyword_setting: dict[str, Any] | None = None
+
+
+class AgentKnowledgeRetrievalConfig(BaseModel):
+ """Per-set retrieval policy for Agent v2 knowledge retrieval.
+
+ Retrieval settings now live on each knowledge set instead of one shared
+ flat config. A set may use either ``multiple`` retrieval with ``top_k`` or
+ ``single`` retrieval with a required model config.
+ """
+
+ model_config = ConfigDict(extra="forbid")
+
+ mode: Literal["single", "multiple"]
top_k: int | None = Field(default=None, ge=1)
score_threshold: float | None = Field(default=None, ge=0, le=1)
- score_threshold_enabled: bool | None = None
+ reranking_mode: str = "reranking_model"
+ reranking_enable: bool = True
+ reranking_model: AgentKnowledgeRerankingModelConfig | None = None
+ weights: AgentKnowledgeWeightedScoreConfig | None = None
+ model: AgentKnowledgeModelConfig | None = None
+
+ @model_validator(mode="after")
+ def validate_mode_fields(self) -> Self:
+ if self.mode == "multiple" and self.top_k is None:
+ raise ValueError("knowledge retrieval.top_k is required for multiple mode")
+ if self.mode == "single" and self.model is None:
+ raise ValueError("knowledge retrieval.model is required for single mode")
+ return self
+
+
+class AgentKnowledgeMetadataCondition(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ name: str = Field(min_length=1, max_length=255)
+ comparison_operator: SupportedComparisonOperator
+ value: ConditionValue = None
+
+
+class AgentKnowledgeMetadataConditions(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ logical_operator: Literal["and", "or"] = "and"
+ conditions: list[AgentKnowledgeMetadataCondition] = Field(default_factory=list)
+
+
+class AgentKnowledgeMetadataFilteringConfig(BaseModel):
+ """Per-set metadata filtering policy.
+
+ The Python attribute uses ``metadata_model_config`` for clarity because the
+ model belongs to metadata filtering specifically, while the external API and
+ generated schema keep the historical ``model_config`` field name via alias.
+ """
+
+ model_config = ConfigDict(extra="forbid", populate_by_name=True)
+
+ mode: Literal["disabled", "automatic", "manual"] = "disabled"
+ # Internal name is explicit; wire format remains ``model_config``.
+ metadata_model_config: AgentKnowledgeModelConfig | None = Field(default=None, alias="model_config")
+ conditions: AgentKnowledgeMetadataConditions | None = None
+
+ @model_validator(mode="after")
+ def validate_mode_fields(self) -> Self:
+ if self.mode == "automatic" and self.metadata_model_config is None:
+ raise ValueError("metadata_filtering.model_config is required for automatic mode")
+ if self.mode == "manual" and (self.conditions is None or not self.conditions.conditions):
+ raise ValueError("metadata_filtering.conditions is required for manual mode")
+ return self
+
+
+class AgentKnowledgeSetConfig(BaseModel):
+ """One explicit knowledge set in Agent v2.
+
+ ``knowledge.sets`` replaces the old flat knowledge config. Each set owns
+ its datasets plus query, retrieval, and metadata policies. An individual
+ set must contain at least one dataset id even though the overall knowledge
+ section may be empty, which is how callers express "no knowledge layer".
+ """
+
+ model_config = ConfigDict(extra="forbid")
+
+ id: str = Field(min_length=1, max_length=255)
+ name: str = Field(min_length=1, max_length=255)
+ description: str | None = None
+ datasets: list[AgentKnowledgeDatasetConfig]
+ query: AgentKnowledgeQueryConfig
+ retrieval: AgentKnowledgeRetrievalConfig
+ metadata_filtering: AgentKnowledgeMetadataFilteringConfig = Field(
+ default_factory=AgentKnowledgeMetadataFilteringConfig
+ )
+
+ @field_validator("id", "name")
+ @classmethod
+ def validate_non_blank_identity(cls, value: str) -> str:
+ normalized = value.strip()
+ if not normalized:
+ raise ValueError("knowledge set id and name must not be blank")
+ return normalized
+
+ @model_validator(mode="after")
+ def validate_datasets(self) -> Self:
+ dataset_ids = [(dataset.id or "").strip() for dataset in self.datasets]
+ if not dataset_ids or any(not dataset_id for dataset_id in dataset_ids):
+ raise ValueError("knowledge set requires at least one dataset id")
+ if len(dataset_ids) != len(set(dataset_ids)):
+ raise ValueError("knowledge set dataset ids must be unique")
+ return self
class AgentHumanContactConfig(AgentFlexibleConfig):
@@ -453,9 +603,28 @@ class AgentSoulToolsConfig(BaseModel):
class AgentSoulKnowledgeConfig(BaseModel):
- datasets: list[AgentKnowledgeDatasetConfig] = Field(default_factory=list)
- query_mode: AgentKnowledgeQueryMode | None = None
- query_config: AgentKnowledgeQueryConfig = Field(default_factory=AgentKnowledgeQueryConfig)
+ """Top-level Agent v2 knowledge config.
+
+ Agent v2 models knowledge as explicit sets instead of one flat
+ ``datasets`` / ``query_mode`` / ``query_config`` block. An empty ``sets``
+ list means no knowledge layer should be emitted at runtime, while set-name
+ uniqueness stays case-insensitive because runtime selection addresses sets
+ by name.
+ """
+
+ model_config = ConfigDict(extra="forbid")
+
+ sets: list[AgentKnowledgeSetConfig] = Field(default_factory=list)
+
+ @model_validator(mode="after")
+ def validate_unique_sets(self) -> Self:
+ set_ids = [item.id.strip() for item in self.sets]
+ if len(set_ids) != len(set(set_ids)):
+ raise ValueError("knowledge set ids must be unique")
+ set_names = [item.name.strip().lower() for item in self.sets]
+ if len(set_names) != len(set(set_names)):
+ raise ValueError("knowledge set names must be unique")
+ return self
class AgentSoulHumanConfig(BaseModel):
@@ -513,6 +682,7 @@ class AgentSoulConfig(BaseModel):
knowledge: AgentSoulKnowledgeConfig = Field(default_factory=AgentSoulKnowledgeConfig)
human: AgentSoulHumanConfig = Field(default_factory=AgentSoulHumanConfig)
env: AgentSoulEnvConfig = Field(default_factory=AgentSoulEnvConfig)
+ files: AgentSoulFilesConfig = Field(default_factory=AgentSoulFilesConfig)
sandbox: AgentSoulSandboxConfig = Field(default_factory=AgentSoulSandboxConfig)
memory: AgentSoulMemoryConfig = Field(default_factory=AgentSoulMemoryConfig)
model: AgentSoulModelConfig | None = None
diff --git a/api/models/model.py b/api/models/model.py
index 05399b07c5f..ac26f0cd80b 100644
--- a/api/models/model.py
+++ b/api/models/model.py
@@ -487,9 +487,15 @@ class App(Base):
agent = db.session.scalar(
select(Agent).where(
- Agent.app_id == self.id,
- Agent.scope == AgentScope.ROSTER,
- Agent.source == AgentSource.AGENT_APP,
+ Agent.tenant_id == self.tenant_id,
+ sa.or_(
+ sa.and_(
+ Agent.app_id == self.id,
+ Agent.scope == AgentScope.ROSTER,
+ Agent.source == AgentSource.AGENT_APP,
+ ),
+ Agent.backing_app_id == self.id,
+ ),
Agent.status == AgentStatus.ACTIVE,
)
)
diff --git a/api/openapi/markdown/console-openapi.md b/api/openapi/markdown/console-openapi.md
index 0debde6c238..2c86c4f70b1 100644
--- a/api/openapi/markdown/console-openapi.md
+++ b/api/openapi/markdown/console-openapi.md
@@ -465,6 +465,83 @@ Check if activation token is valid
| ---- | ----------- |
| 204 | Agent service API key deleted |
+### [DELETE] /agent/{agent_id}/build-draft
+#### Parameters
+
+| Name | Located in | Description | Required | Schema |
+| ---- | ---------- | ----------- | -------- | ------ |
+| agent_id | path | | Yes | string (uuid) |
+
+#### Responses
+
+| Code | Description | Schema |
+| ---- | ----------- | ------ |
+| 200 | Agent build draft discarded | **application/json**: [AgentSimpleResultResponse](#agentsimpleresultresponse)<br> |
+
+### [GET] /agent/{agent_id}/build-draft
+#### Parameters
+
+| Name | Located in | Description | Required | Schema |
+| ---- | ---------- | ----------- | -------- | ------ |
+| agent_id | path | | Yes | string (uuid) |
+
+#### Responses
+
+| Code | Description | Schema |
+| ---- | ----------- | ------ |
+| 200 | Agent build draft | **application/json**: [AgentBuildDraftResponse](#agentbuilddraftresponse)<br> |
+
+### [PUT] /agent/{agent_id}/build-draft
+#### Parameters
+
+| Name | Located in | Description | Required | Schema |
+| ---- | ---------- | ----------- | -------- | ------ |
+| agent_id | path | | Yes | string (uuid) |
+
+#### Request Body
+
+| Required | Schema |
+| -------- | ------ |
+| Yes | **application/json**: [ComposerSavePayload](#composersavepayload)<br> |
+
+#### Responses
+
+| Code | Description | Schema |
+| ---- | ----------- | ------ |
+| 200 | Agent build draft saved | **application/json**: [AgentBuildDraftResponse](#agentbuilddraftresponse)<br> |
+
+### [POST] /agent/{agent_id}/build-draft/apply
+#### Parameters
+
+| Name | Located in | Description | Required | Schema |
+| ---- | ---------- | ----------- | -------- | ------ |
+| agent_id | path | | Yes | string (uuid) |
+
+#### Responses
+
+| Code | Description | Schema |
+| ---- | ----------- | ------ |
+| 200 | Agent build draft applied | **application/json**: [AgentBuildDraftApplyResponse](#agentbuilddraftapplyresponse)<br> |
+
+### [POST] /agent/{agent_id}/build-draft/checkout
+#### Parameters
+
+| Name | Located in | Description | Required | Schema |
+| ---- | ---------- | ----------- | -------- | ------ |
+| agent_id | path | | Yes | string (uuid) |
+
+#### Request Body
+
+| Required | Schema |
+| -------- | ------ |
+| Yes | **application/json**: [AgentBuildDraftCheckoutPayload](#agentbuilddraftcheckoutpayload)<br> |
+
+#### Responses
+
+| Code | Description | Schema |
+| ---- | ----------- | ------ |
+| 200 | Agent build draft checked out | **application/json**: [AgentBuildDraftResponse](#agentbuilddraftresponse)<br> |
+
### [GET] /agent/{agent_id}/chat-messages
Get Agent App chat messages for a conversation with pagination
@@ -856,6 +933,26 @@ Get Agent App message details by ID
| 200 | Message retrieved successfully | **application/json**: [MessageDetailResponse](#messagedetailresponse)<br> |
| 404 | Agent or message not found | |
+### [POST] /agent/{agent_id}/publish
+#### Parameters
+
+| Name | Located in | Description | Required | Schema |
+| ---- | ---------- | ----------- | -------- | ------ |
+| agent_id | path | | Yes | string (uuid) |
+
+#### Request Body
+
+| Required | Schema |
+| -------- | ------ |
+| Yes | **application/json**: [AgentPublishPayload](#agentpublishpayload)<br> |
+
+#### Responses
+
+| Code | Description | Schema |
+| ---- | ----------- | ------ |
+| 200 | Agent draft published | **application/json**: [AgentPublishResponse](#agentpublishresponse)<br> |
+| 403 | Insufficient permissions | |
+
### [GET] /agent/{agent_id}/referencing-workflows
List workflow apps that reference this Agent App's bound Agent (read-only)
@@ -3767,6 +3864,7 @@ Submit human input form preview for workflow
| Name | Located in | Description | Required | Schema |
| ---- | ---------- | ----------- | -------- | ------ |
+| snapshot_id | query | | No | string |
| app_id | path | | Yes | string (uuid) |
| node_id | path | | Yes | string |
@@ -12173,9 +12271,14 @@ Default namespace
| Name | Type | Description | Required |
| ---- | ---- | ----------- | -------- |
-| active_config_snapshot | [AgentConfigSnapshotSummaryResponse](#agentconfigsnapshotsummaryresponse) | | Yes |
+| active_config_snapshot | [AgentConfigSnapshotSummaryResponse](#agentconfigsnapshotsummaryresponse) | | No |
| agent | [AgentComposerAgentResponse](#agentcomposeragentresponse) | | Yes |
| agent_soul | [AgentSoulConfig](#agentsoulconfig) | | Yes |
+| app_id | string | | No |
+| backing_app_id | string | | No |
+| chat_endpoint | string | | No |
+| draft | [AgentConfigDraftSummaryResponse](#agentconfigdraftsummaryresponse) | | No |
+| hidden_app_backed | boolean | | No |
| save_options | [ [ComposerSaveStrategy](#composersavestrategy) ] | | Yes |
| validation | [ComposerValidationFindingsResponse](#composervalidationfindingsresponse) | | No |
| variant | string | | Yes |
@@ -12210,6 +12313,7 @@ Default namespace
| active_config_is_published | boolean | | No |
| api_base_url | string | | No |
| app_id | string | | No |
+| backing_app_id | string | | No |
| bound_agent_id | string | | No |
| created_at | integer | | No |
| created_by | string | | No |
@@ -12218,6 +12322,7 @@ Default namespace
| description | string | | No |
| enable_api | boolean | | Yes |
| enable_site | boolean | | Yes |
+| hidden_app_backed | boolean | | No |
| icon | string | | No |
| icon_background | string | | No |
| icon_type | string | | No |
@@ -12230,7 +12335,7 @@ Default namespace
| name | string | | Yes |
| permission_keys | [ string ] | | No |
| role | string | | No |
-| site | [Site](#site) | | No |
+| site | [AppDetailSiteResponse](#appdetailsiteresponse) | | No |
| tags | [ [Tag](#tag) ] | | No |
| tracing | [JSONValue](#jsonvalue) | | No |
| updated_at | integer | | No |
@@ -12273,6 +12378,7 @@ default (the config form sends the full desired feature state on save).
| active_config_is_published | boolean | | No |
| app_id | string | | No |
| author_name | string | | No |
+| backing_app_id | string | | No |
| bound_agent_id | string | | No |
| create_user_name | string | | No |
| created_at | integer | | No |
@@ -12280,6 +12386,7 @@ default (the config form sends the full desired feature state on save).
| debug_conversation_id | string | | No |
| description | string | | No |
| has_draft_trigger | boolean | | No |
+| hidden_app_backed | boolean | | No |
| icon | string | | No |
| icon_background | string | | No |
| icon_type | string | | No |
@@ -12338,6 +12445,27 @@ default (the config form sends the full desired feature state on save).
| date | string | | Yes |
| interactions | number | | Yes |
+#### AgentBuildDraftApplyResponse
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| draft | object | | Yes |
+| result | string | | Yes |
+
+#### AgentBuildDraftCheckoutPayload
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| force | boolean | Overwrite the existing current-user build draft | No |
+
+#### AgentBuildDraftResponse
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| agent_soul | object | | Yes |
+| draft | object | | Yes |
+| variant | string | | Yes |
+
#### AgentCliToolAuthorizationStatus
Authorization state for Agent-scoped CLI tools.
@@ -12400,10 +12528,18 @@ Risk marker for CLI tool bootstrap commands.
| Name | Type | Description | Required |
| ---- | ---- | ----------- | -------- |
| active_config_snapshot_id | string | | No |
+| app_id | string | | No |
+| backing_app_id | string | | No |
| description | string | | Yes |
+| hidden_app_backed | boolean | | No |
+| icon | string | | No |
+| icon_background | string | | No |
+| icon_type | string | | No |
| id | string | | Yes |
| name | string | | Yes |
+| role | string | | No |
| scope | [AgentScope](#agentscope) | | Yes |
+| source | [AgentSource](#agentsource) | | No |
| status | [AgentStatus](#agentstatus) | | Yes |
#### AgentComposerBindingResponse
@@ -12456,6 +12592,25 @@ Risk marker for CLI tool bootstrap commands.
| current_snapshot_id | string | | No |
| workflow_node_count | integer | | Yes |
+#### AgentComposerKnowledgeDatasetCandidateResponse
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| description | string | | No |
+| id | string | | No |
+| missing | boolean | | No |
+| name | string | | No |
+
+#### AgentComposerKnowledgeSetCandidateResponse
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| datasets | [ [AgentComposerKnowledgeDatasetCandidateResponse](#agentcomposerknowledgedatasetcandidateresponse) ] | | No |
+| description | string | | No |
+| id | string | | Yes |
+| missing_dataset_ids | [ string ] | | No |
+| name | string | | Yes |
+
#### AgentComposerNodeJobCandidatesResponse
| Name | Type | Description | Required |
@@ -12471,7 +12626,7 @@ Risk marker for CLI tool bootstrap commands.
| cli_tools | [ [AgentCliToolConfig](#agentclitoolconfig) ] | | No |
| dify_tools | [ [AgentComposerDifyToolCandidateResponse](#agentcomposerdifytoolcandidateresponse) ] | | No |
| human_contacts | [ [AgentHumanContactConfig](#agenthumancontactconfig) ] | | No |
-| knowledge_datasets | [ [AgentKnowledgeDatasetConfig](#agentknowledgedatasetconfig) ] | | No |
+| knowledge_sets | [ [AgentComposerKnowledgeSetCandidateResponse](#agentcomposerknowledgesetcandidateresponse) ] | | No |
#### AgentComposerSoulLockResponse
@@ -12490,6 +12645,28 @@ Risk marker for CLI tool bootstrap commands.
| result | string | | Yes |
| warnings | [ [ComposerValidationWarningResponse](#composervalidationwarningresponse) ] | | No |
+#### AgentConfigDraftSummaryResponse
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| account_id | string | | No |
+| agent_id | string | | Yes |
+| base_snapshot_id | string | | No |
+| created_at | integer | | No |
+| created_by | string | | No |
+| draft_type | [AgentConfigDraftType](#agentconfigdrafttype) | | Yes |
+| id | string | | Yes |
+| updated_at | integer | | No |
+| updated_by | string | | No |
+
+#### AgentConfigDraftType
+
+Editable Agent Soul draft workspace type.
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| AgentConfigDraftType | string | Editable Agent Soul draft workspace type. | |
+
#### AgentConfigRevisionOperation
Audit operation recorded for Agent Soul version/revision changes.
@@ -12539,6 +12716,8 @@ Audit operation recorded for Agent Soul version/revision changes.
| Name | Type | Description | Required |
| ---- | ---- | ----------- | -------- |
| active_config_snapshot_id | string | | Yes |
+| draft_config_id | string | | No |
+| restored_version_id | string | | No |
| result | string | | Yes |
#### AgentConfigSnapshotSummaryResponse
@@ -12793,10 +12972,12 @@ Supported icon storage formats for Agent roster entries.
| app_id | string | | No |
| archived_at | integer | | No |
| archived_by | string | | No |
+| backing_app_id | string | | No |
| created_at | integer | | No |
| created_by | string | | No |
| description | string | | Yes |
| existing_node_ids | [ string ] | | No |
+| hidden_app_backed | boolean | | No |
| icon | string | | No |
| icon_background | string | | No |
| icon_type | [AgentIconType](#agenticontype) | | No |
@@ -12865,14 +13046,57 @@ the current roster/workflow APIs scoped to Dify Agent.
| id | string | | No |
| name | string | | No |
+#### AgentKnowledgeMetadataCondition
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| comparison_operator | string, <br>**Available values:** "<", "=", ">", "after", "before", "contains", "empty", "end with", "in", "is", "is not", "not contains", "not empty", "not in", "start with", "≠", "≤", "≥" | *Enum:* `"<"`, `"="`, `">"`, `"after"`, `"before"`, `"contains"`, `"empty"`, `"end with"`, `"in"`, `"is"`, `"is not"`, `"not contains"`, `"not empty"`, `"not in"`, `"start with"`, `"≠"`, `"≤"`, `"≥"` | Yes |
+| name | string | | Yes |
+| value | string<br>[ string ]<br>number | | No |
+
+#### AgentKnowledgeMetadataConditions
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| conditions | [ [AgentKnowledgeMetadataCondition](#agentknowledgemetadatacondition) ] | | No |
+| logical_operator | string, <br>**Available values:** "and", "or", <br>**Default:** and | *Enum:* `"and"`, `"or"` | No |
+
+#### AgentKnowledgeMetadataFilteringConfig
+
+Per-set metadata filtering policy.
+
+The Python attribute uses ``metadata_model_config`` for clarity because the
+model belongs to metadata filtering specifically, while the external API and
+generated schema keep the historical ``model_config`` field name via alias.
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| conditions | [AgentKnowledgeMetadataConditions](#agentknowledgemetadataconditions) | | No |
+| mode | string, <br>**Available values:** "automatic", "disabled", "manual", <br>**Default:** disabled | *Enum:* `"automatic"`, `"disabled"`, `"manual"` | No |
+| model_config | [AgentKnowledgeModelConfig](#agentknowledgemodelconfig) | | No |
+
+#### AgentKnowledgeModelConfig
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| completion_params | object | | No |
+| mode | string | | Yes |
+| name | string | | Yes |
+| provider | string | | Yes |
+
#### AgentKnowledgeQueryConfig
+Per-set query policy for Agent v2 knowledge retrieval.
+
+Agent v2 stores knowledge as explicit ``knowledge.sets`` rather than the
+legacy flat ``datasets`` / ``query_mode`` / ``query_config`` shape. Each
+set owns its own query policy, so ``user_query`` must carry an explicit
+``value`` while ``generated_query`` leaves that value empty.
+
| Name | Type | Description | Required |
| ---- | ---- | ----------- | -------- |
-| query | string | | No |
-| score_threshold | number | | No |
-| score_threshold_enabled | boolean | | No |
-| top_k | integer | | No |
+| mode | [AgentKnowledgeQueryMode](#agentknowledgequerymode) | | Yes |
+| value | string | | No |
#### AgentKnowledgeQueryMode
@@ -12880,6 +13104,59 @@ the current roster/workflow APIs scoped to Dify Agent.
| ---- | ---- | ----------- | -------- |
| AgentKnowledgeQueryMode | string | | |
+#### AgentKnowledgeRerankingModelConfig
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| model | string | | Yes |
+| provider | string | | Yes |
+
+#### AgentKnowledgeRetrievalConfig
+
+Per-set retrieval policy for Agent v2 knowledge retrieval.
+
+Retrieval settings now live on each knowledge set instead of one shared
+flat config. A set may use either ``multiple`` retrieval with ``top_k`` or
+``single`` retrieval with a required model config.
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| mode | string, <br>**Available values:** "multiple", "single" | *Enum:* `"multiple"`, `"single"` | Yes |
+| model | [AgentKnowledgeModelConfig](#agentknowledgemodelconfig) | | No |
+| reranking_enable | boolean, <br>**Default:** true | | No |
+| reranking_mode | string, <br>**Default:** reranking_model | | No |
+| reranking_model | [AgentKnowledgeRerankingModelConfig](#agentknowledgererankingmodelconfig) | | No |
+| score_threshold | number | | No |
+| top_k | integer | | No |
+| weights | [AgentKnowledgeWeightedScoreConfig](#agentknowledgeweightedscoreconfig) | | No |
+
+#### AgentKnowledgeSetConfig
+
+One explicit knowledge set in Agent v2.
+
+``knowledge.sets`` replaces the old flat knowledge config. Each set owns
+its datasets plus query, retrieval, and metadata policies. An individual
+set must contain at least one dataset id even though the overall knowledge
+section may be empty, which is how callers express "no knowledge layer".
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| datasets | [ [AgentKnowledgeDatasetConfig](#agentknowledgedatasetconfig) ] | | Yes |
+| description | string | | No |
+| id | string | | Yes |
+| metadata_filtering | [AgentKnowledgeMetadataFilteringConfig](#agentknowledgemetadatafilteringconfig) | | No |
+| name | string | | Yes |
+| query | [AgentKnowledgeQueryConfig](#agentknowledgequeryconfig) | | Yes |
+| retrieval | [AgentKnowledgeRetrievalConfig](#agentknowledgeretrievalconfig) | | Yes |
+
+#### AgentKnowledgeWeightedScoreConfig
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| keyword_setting | object | | No |
+| vector_setting | object | | No |
+| weight_type | string | | No |
+
#### AgentLogConversationItemResponse
| Name | Type | Description | Required |
@@ -13063,6 +13340,21 @@ the current roster/workflow APIs scoped to Dify Agent.
| ---- | ---- | ----------- | -------- |
| AgentProviderResponse | object | | |
+#### AgentPublishPayload
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| version_note | string | Optional note for this published Agent version | No |
+
+#### AgentPublishResponse
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| active_config_snapshot | object | | No |
+| active_config_snapshot_id | string | | Yes |
+| draft | object | | No |
+| result | string | | Yes |
+
#### AgentPublishedReferenceResponse
| Name | Type | Description | Required |
@@ -13120,9 +13412,11 @@ the current roster/workflow APIs scoped to Dify Agent.
| app_id | string | | No |
| archived_at | integer | | No |
| archived_by | string | | No |
+| backing_app_id | string | | No |
| created_at | integer | | No |
| created_by | string | | No |
| description | string | | Yes |
+| hidden_app_backed | boolean | | No |
| icon | string | | No |
| icon_background | string | | No |
| icon_type | [AgentIconType](#agenticontype) | | No |
@@ -13190,6 +13484,27 @@ Visibility and lifecycle scope of an Agent record.
| enabled | boolean | | No |
| type | string | | No |
+#### AgentSimpleResultResponse
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| result | string | | Yes |
+
+#### 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 |
@@ -13216,6 +13531,7 @@ Visibility and lifecycle scope of an Agent record.
| app_features | [AgentSoulAppFeaturesConfig](#agentsoulappfeaturesconfig) | | No |
| app_variables | [ [AppVariableConfig](#appvariableconfig) ] | | No |
| env | [AgentSoulEnvConfig](#agentsoulenvconfig) | | No |
+| files | [AgentSoulFilesConfig](#agentsoulfilesconfig) | | No |
| human | [AgentSoulHumanConfig](#agentsoulhumanconfig) | | No |
| knowledge | [AgentSoulKnowledgeConfig](#agentsoulknowledgeconfig) | | No |
| memory | [AgentSoulMemoryConfig](#agentsoulmemoryconfig) | | No |
@@ -13270,6 +13586,13 @@ old Agent tool payloads can be read while new payloads stay explicit.
| secret_refs | [ [AgentSecretRefConfig](#agentsecretrefconfig) ] | | No |
| variables | [ [AgentEnvVariableConfig](#agentenvvariableconfig) ] | | No |
+#### AgentSoulFilesConfig
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| files | [ [AgentFileRefConfig](#agentfilerefconfig) ] | | No |
+| skills | [ [AgentSkillRefConfig](#agentskillrefconfig) ] | | No |
+
#### AgentSoulHumanConfig
| Name | Type | Description | Required |
@@ -13279,11 +13602,17 @@ old Agent tool payloads can be read while new payloads stay explicit.
#### AgentSoulKnowledgeConfig
+Top-level Agent v2 knowledge config.
+
+Agent v2 models knowledge as explicit sets instead of one flat
+``datasets`` / ``query_mode`` / ``query_config`` block. An empty ``sets``
+list means no knowledge layer should be emitted at runtime, while set-name
+uniqueness stays case-insensitive because runtime selection addresses sets
+by name.
+
| Name | Type | Description | Required |
| ---- | ---- | ----------- | -------- |
-| datasets | [ [AgentKnowledgeDatasetConfig](#agentknowledgedatasetconfig) ] | | No |
-| query_config | [AgentKnowledgeQueryConfig](#agentknowledgequeryconfig) | | No |
-| query_mode | [AgentKnowledgeQueryMode](#agentknowledgequerymode) | | No |
+| sets | [ [AgentKnowledgeSetConfig](#agentknowledgesetconfig) ] | | No |
#### AgentSoulMemoryConfig
@@ -13756,6 +14085,36 @@ Enum class for api provider schema type.
| use_icon_as_answer_icon | boolean | | No |
| workflow | [WorkflowPartial](#workflowpartial) | | No |
+#### AppDetailSiteResponse
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| access_token | string | | No |
+| app_base_url | string | | No |
+| chat_color_theme | string | | No |
+| chat_color_theme_inverted | boolean | | No |
+| code | string | | No |
+| copyright | string | | No |
+| created_at | integer | | No |
+| created_by | string | | No |
+| custom_disclaimer | string | | No |
+| customize_domain | string | | No |
+| customize_token_strategy | string | | No |
+| default_language | string | | No |
+| description | string | | No |
+| icon | string | | No |
+| icon_background | string | | No |
+| icon_type | string<br>[IconType](#icontype) | | No |
+| icon_url | string | | Yes |
+| input_placeholder | string | | No |
+| privacy_policy | string | | No |
+| prompt_public | boolean | | No |
+| show_workflow_steps | boolean | | No |
+| title | string | | No |
+| updated_at | integer | | No |
+| updated_by | string | | No |
+| use_icon_as_answer_icon | boolean | | No |
+
#### AppDetailWithSite
| Name | Type | Description | Required |
@@ -13781,7 +14140,7 @@ Enum class for api provider schema type.
| model_config | [ModelConfig](#modelconfig) | | No |
| name | string | | Yes |
| permission_keys | [ string ] | | No |
-| site | [Site](#site) | | No |
+| site | [AppDetailSiteResponse](#appdetailsiteresponse) | | No |
| tags | [ [Tag](#tag) ] | | No |
| tracing | [JSONValue](#jsonvalue) | | No |
| updated_at | integer | | No |
@@ -14187,6 +14546,7 @@ Button styles for user actions.
| Name | Type | Description | Required |
| ---- | ---- | ----------- | -------- |
| conversation_id | string | Conversation ID | No |
+| draft_type | string, <br>**Available values:** "debug_build", "draft", <br>**Default:** draft | Agent App debug config source. Use debug_build while the Agent is in build mode.<br>*Enum:* `"debug_build"`, `"draft"` | No |
| files | [ object ] | Uploaded files | No |
| inputs | object | | Yes |
| model_config | object | | No |
@@ -20355,6 +20715,12 @@ How a workflow node is bound to an Agent.
| ---- | ---- | ----------- | -------- |
| WorkflowAgentBindingType | string | How a workflow node is bound to an Agent. | |
+#### WorkflowAgentComposerQuery
+
+| Name | Type | Description | Required |
+| ---- | ---- | ----------- | -------- |
+| snapshot_id | string | | No |
+
#### WorkflowAgentComposerResponse
| Name | Type | Description | Required |
@@ -20363,8 +20729,11 @@ How a workflow node is bound to an Agent.
| agent | [AgentComposerAgentResponse](#agentcomposeragentresponse) | | No |
| agent_soul | [AgentSoulConfig](#agentsoulconfig) | | Yes |
| app_id | string | | No |
+| backing_app_id | string | | No |
| binding | [AgentComposerBindingResponse](#agentcomposerbindingresponse) | | No |
+| chat_endpoint | string | | No |
| effective_declared_outputs | [ [DeclaredOutputConfig](#declaredoutputconfig) ] | | No |
+| hidden_app_backed | boolean | | No |
| impact_summary | [AgentComposerImpactResponse](#agentcomposerimpactresponse) | | No |
| node_id | string | | No |
| node_job | [WorkflowNodeJobConfig](#workflownodejobconfig) | | Yes |
diff --git a/api/services/agent/composer_candidates.py b/api/services/agent/composer_candidates.py
index 7868f2a2f63..a650b16e9bc 100644
--- a/api/services/agent/composer_candidates.py
+++ b/api/services/agent/composer_candidates.py
@@ -25,6 +25,7 @@ from models.agent_config_entities import (
AgentSoulConfig,
DeclaredOutputConfig,
)
+from services.agent.knowledge_datasets import list_agent_soul_knowledge_dataset_ids
MAX_CANDIDATES_PER_LIST = 200
@@ -139,19 +140,34 @@ def soul_candidates(
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]
+ dataset_ids = list_agent_soul_knowledge_dataset_ids(soul)
dataset_rows = dataset_lookup(dataset_ids) if dataset_ids else {}
- knowledge_datasets: list[dict[str, Any]] = []
- for dataset in soul.knowledge.datasets:
- if not dataset.id:
- continue
- row = dataset_rows.get(dataset.id)
- knowledge_datasets.append(
+ knowledge_sets: list[dict[str, Any]] = []
+ for knowledge_set in soul.knowledge.sets:
+ missing_dataset_ids: list[str] = []
+ datasets: list[dict[str, Any]] = []
+ for dataset in knowledge_set.datasets:
+ dataset_id = (dataset.id or "").strip()
+ if not dataset_id:
+ continue
+ row = dataset_rows.get(dataset_id)
+ if row is None:
+ missing_dataset_ids.append(dataset_id)
+ datasets.append(
+ {
+ "id": dataset_id,
+ "name": (getattr(row, "name", None) or dataset.name or dataset_id),
+ "description": getattr(row, "description", None) or dataset.description,
+ "missing": row is None,
+ }
+ )
+ knowledge_sets.append(
{
- "id": dataset.id,
- "name": (getattr(row, "name", None) or dataset.name or dataset.id),
- "description": getattr(row, "description", None) or dataset.description,
- "missing": row is None,
+ "id": knowledge_set.id,
+ "name": knowledge_set.name,
+ "description": knowledge_set.description,
+ "datasets": datasets,
+ "missing_dataset_ids": missing_dataset_ids,
}
)
@@ -161,7 +177,7 @@ def soul_candidates(
lists = {
"dify_tools": dify_tools,
"cli_tools": cli_tools,
- "knowledge_datasets": knowledge_datasets,
+ "knowledge_sets": knowledge_sets,
"human_contacts": human_contacts,
}
capped: dict[str, list[dict[str, Any]]] = {}
diff --git a/api/services/agent/composer_service.py b/api/services/agent/composer_service.py
index 8c83ee80031..ec81ab3daf2 100644
--- a/api/services/agent/composer_service.py
+++ b/api/services/agent/composer_service.py
@@ -11,6 +11,8 @@ from libs.helper import to_timestamp
from models import Account
from models.agent import (
Agent,
+ AgentConfigDraft,
+ AgentConfigDraftType,
AgentConfigRevision,
AgentConfigRevisionOperation,
AgentConfigSnapshot,
@@ -37,6 +39,10 @@ from services.agent.errors import (
AgentVersionNotFoundError,
InvalidComposerConfigError,
)
+from services.agent.knowledge_datasets import (
+ get_tenant_knowledge_dataset_rows,
+ list_missing_tenant_knowledge_dataset_ids,
+)
from services.agent.roster_service import AgentRosterService
from services.app_service import AppService, CreateAppParams
from services.entities.agent_entities import (
@@ -92,24 +98,62 @@ def _validate_composer_payload_for_strategy(payload: ComposerSavePayload) -> Non
class AgentComposerService:
@classmethod
- def load_workflow_composer(cls, *, tenant_id: str, app_id: str, node_id: str) -> dict[str, Any]:
+ def load_workflow_composer(
+ cls, *, tenant_id: str, app_id: str, node_id: str, snapshot_id: str | None = None
+ ) -> dict[str, Any]:
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)
if not binding:
+ if snapshot_id:
+ raise AgentVersionNotFoundError()
return cls._empty_workflow_state(app_id=app_id, workflow_id=workflow.id, node_id=node_id)
agent = cls._get_agent_if_present(tenant_id=tenant_id, agent_id=binding.agent_id)
+ version = cls._workflow_composer_version(
+ tenant_id=tenant_id,
+ binding=binding,
+ agent=agent,
+ snapshot_id=snapshot_id,
+ )
+ return cls._serialize_workflow_state(binding=binding, agent=agent, version=version)
+
+ @classmethod
+ def _workflow_composer_version(
+ cls,
+ *,
+ tenant_id: str,
+ binding: WorkflowAgentNodeBinding,
+ agent: Agent | None,
+ snapshot_id: str | None,
+ ) -> AgentConfigSnapshot | None:
+ if snapshot_id:
+ if agent is None:
+ raise AgentVersionNotFoundError()
+ if binding.binding_type == WorkflowAgentBindingType.ROSTER_AGENT:
+ if agent.scope != AgentScope.ROSTER:
+ raise AgentVersionNotFoundError()
+ elif binding.binding_type == WorkflowAgentBindingType.INLINE_AGENT:
+ if (
+ agent.scope != AgentScope.WORKFLOW_ONLY
+ or agent.app_id != binding.app_id
+ or agent.workflow_id != binding.workflow_id
+ or agent.workflow_node_id != binding.node_id
+ ):
+ raise AgentVersionNotFoundError()
+ else:
+ raise AgentVersionNotFoundError()
+ return cls._require_version(tenant_id=tenant_id, agent_id=agent.id, version_id=snapshot_id)
+
version_id = (
agent.active_config_snapshot_id
if agent and binding.binding_type == WorkflowAgentBindingType.ROSTER_AGENT
else binding.current_snapshot_id
)
- version = cls._get_version_if_present(
+ return cls._get_version_if_present(
tenant_id=tenant_id,
agent_id=agent.id if agent else None,
version_id=version_id,
)
- return cls._serialize_workflow_state(binding=binding, agent=agent, version=version)
@classmethod
def save_workflow_composer(
@@ -120,6 +164,7 @@ class AgentComposerService:
_backfill_cli_tool_ids(payload.agent_soul)
_validate_composer_payload_for_strategy(payload)
+ cls.validate_knowledge_datasets(tenant_id=tenant_id, agent_soul=payload.agent_soul)
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)
@@ -259,31 +304,37 @@ class AgentComposerService:
@classmethod
def load_agent_app_composer(cls, *, tenant_id: str, app_id: str) -> dict[str, Any]:
- agent = db.session.scalar(
- select(Agent)
- .where(
- Agent.tenant_id == tenant_id,
- Agent.app_id == app_id,
- Agent.scope == AgentScope.ROSTER,
- Agent.status == AgentStatus.ACTIVE,
- )
- .order_by(Agent.created_at.desc())
- .limit(1)
+ agent = cls._require_agent_app_agent(tenant_id=tenant_id, app_id=app_id)
+ return cls._load_agent_composer_for_agent(tenant_id=tenant_id, agent=agent)
+
+ @classmethod
+ def load_agent_composer(cls, *, tenant_id: str, agent_id: str) -> dict[str, Any]:
+ agent = cls._require_agent(tenant_id=tenant_id, agent_id=agent_id)
+ return cls._load_agent_composer_for_agent(tenant_id=tenant_id, agent=agent)
+
+ @classmethod
+ def _load_agent_composer_for_agent(cls, *, tenant_id: str, agent: Agent) -> dict[str, Any]:
+ draft = cls._get_or_create_agent_draft(
+ tenant_id=tenant_id,
+ agent=agent,
+ draft_type=AgentConfigDraftType.DRAFT,
+ account_id=None,
+ created_by=agent.updated_by or agent.created_by,
)
- if not agent:
- raise AgentNotFoundError()
- version = cls._require_version(
+ version = cls._get_version_if_present(
tenant_id=tenant_id, agent_id=agent.id, version_id=agent.active_config_snapshot_id
)
return {
"variant": ComposerVariant.AGENT_APP.value,
"agent": cls._serialize_agent(agent),
"active_config_snapshot": cls._serialize_version(version),
- "agent_soul": version.config_snapshot_dict,
- "save_options": [
- ComposerSaveStrategy.SAVE_TO_CURRENT_VERSION.value,
- ComposerSaveStrategy.SAVE_AS_NEW_VERSION.value,
- ],
+ "draft": cls._serialize_draft(draft),
+ "agent_soul": draft.config_snapshot_dict,
+ "save_options": [ComposerSaveStrategy.SAVE_TO_CURRENT_VERSION.value],
+ "app_id": agent.app_id,
+ "backing_app_id": agent.backing_app_id or agent.app_id,
+ "hidden_app_backed": bool(agent.scope == AgentScope.WORKFLOW_ONLY and agent.backing_app_id),
+ "chat_endpoint": f"/console/api/agent/{agent.id}/chat-messages",
}
@classmethod
@@ -292,22 +343,17 @@ class AgentComposerService:
) -> dict[str, Any]:
if payload.variant != ComposerVariant.AGENT_APP:
raise ValueError("Agent App composer endpoint only accepts agent_app variant")
- _backfill_cli_tool_ids(payload.agent_soul)
- _validate_composer_payload_for_strategy(payload)
+ if payload.save_strategy != ComposerSaveStrategy.SAVE_TO_CURRENT_VERSION:
+ raise InvalidComposerConfigError(
+ "Agent App composer only saves the normal draft. Use the publish endpoint to create a version."
+ )
if payload.agent_soul is None:
raise ValueError("agent_soul is required")
+ _backfill_cli_tool_ids(payload.agent_soul)
+ _validate_composer_payload_for_strategy(payload)
+ cls.validate_knowledge_datasets(tenant_id=tenant_id, agent_soul=payload.agent_soul)
- agent = db.session.scalar(
- select(Agent)
- .where(
- Agent.tenant_id == tenant_id,
- Agent.app_id == app_id,
- Agent.scope == AgentScope.ROSTER,
- Agent.status == AgentStatus.ACTIVE,
- )
- .order_by(Agent.created_at.desc())
- .limit(1)
- )
+ agent = cls._get_agent_app_agent(tenant_id=tenant_id, app_id=app_id)
if not agent:
agent = Agent(
tenant_id=tenant_id,
@@ -317,6 +363,7 @@ class AgentComposerService:
scope=AgentScope.ROSTER,
source=AgentSource.AGENT_APP,
app_id=app_id,
+ backing_app_id=app_id,
status=AgentStatus.ACTIVE,
created_by=account_id,
updated_by=account_id,
@@ -327,35 +374,55 @@ class AgentComposerService:
except IntegrityError as exc:
db.session.rollback()
raise AgentNameConflictError() from exc
+ return cls._save_agent_composer_for_agent(
+ tenant_id=tenant_id,
+ agent=agent,
+ account_id=account_id,
+ payload=payload,
+ )
- 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,
- agent_id=agent.id,
- account_id=account_id,
- agent_soul=payload.agent_soul,
- operation=AgentConfigRevisionOperation.SAVE_NEW_VERSION,
- version_note=payload.version_note,
- )
- agent.active_config_snapshot_id = version.id
- agent.active_config_has_model = agent_soul_has_model(payload.agent_soul)
- else:
- current_snapshot = cls._require_version(
- tenant_id=tenant_id, agent_id=agent.id, version_id=agent.active_config_snapshot_id
- )
- version = cls._update_current_version(
- current_snapshot=current_snapshot,
- account_id=account_id,
- agent_soul=payload.agent_soul,
- operation=AgentConfigRevisionOperation.SAVE_CURRENT_VERSION,
- version_note=payload.version_note,
+ @classmethod
+ def save_agent_composer(
+ cls, *, tenant_id: str, agent_id: str, account_id: str, payload: ComposerSavePayload
+ ) -> dict[str, Any]:
+ if payload.variant != ComposerVariant.AGENT_APP:
+ raise ValueError("Agent composer endpoint only accepts agent_app variant")
+ if payload.save_strategy != ComposerSaveStrategy.SAVE_TO_CURRENT_VERSION:
+ raise InvalidComposerConfigError(
+ "Agent composer only saves the normal draft. Use the publish endpoint to create a version."
)
- agent.active_config_snapshot_id = version.id
- agent.active_config_has_model = agent_soul_has_model(payload.agent_soul)
- agent.updated_by = account_id
+ if payload.agent_soul is None:
+ raise ValueError("agent_soul is required")
+ _backfill_cli_tool_ids(payload.agent_soul)
+ _validate_composer_payload_for_strategy(payload)
+ cls.validate_knowledge_datasets(tenant_id=tenant_id, agent_soul=payload.agent_soul)
+ agent = cls._require_agent(tenant_id=tenant_id, agent_id=agent_id)
+ return cls._save_agent_composer_for_agent(
+ tenant_id=tenant_id,
+ agent=agent,
+ account_id=account_id,
+ payload=payload,
+ )
+
+ @classmethod
+ def _save_agent_composer_for_agent(
+ cls, *, tenant_id: str, agent: Agent, account_id: str, payload: ComposerSavePayload
+ ) -> dict[str, Any]:
+ if payload.agent_soul is None:
+ raise ValueError("agent_soul is required")
+ cls._save_agent_draft(
+ tenant_id=tenant_id,
+ agent=agent,
+ draft_type=AgentConfigDraftType.DRAFT,
+ account_id=None,
+ agent_soul=payload.agent_soul,
+ account_id_for_audit=account_id,
+ )
+ agent.updated_by = account_id
+ agent.active_config_is_published = False
db.session.commit()
- state = cls.load_agent_app_composer(tenant_id=tenant_id, app_id=app_id)
+ state = cls.load_agent_composer(tenant_id=tenant_id, agent_id=agent.id)
state["validation"] = cls.collect_validation_findings(
tenant_id=tenant_id,
payload=payload,
@@ -363,6 +430,161 @@ class AgentComposerService:
)
return state
+ @classmethod
+ def publish_agent_app_draft(
+ cls, *, tenant_id: str, agent_id: str, account_id: str, version_note: str | None = None
+ ) -> dict[str, Any]:
+ agent = cls._require_agent(tenant_id=tenant_id, agent_id=agent_id)
+ if agent.scope != AgentScope.ROSTER or agent.source != AgentSource.AGENT_APP:
+ raise AgentNotFoundError()
+ draft = cls._get_or_create_agent_draft(
+ tenant_id=tenant_id,
+ agent=agent,
+ draft_type=AgentConfigDraftType.DRAFT,
+ account_id=None,
+ created_by=account_id,
+ )
+ agent_soul = AgentSoulConfig.model_validate(draft.config_snapshot_dict)
+ ComposerConfigValidator.validate_publish_payload(
+ ComposerSavePayload(
+ variant=ComposerVariant.AGENT_APP,
+ agent_soul=agent_soul,
+ save_strategy=ComposerSaveStrategy.SAVE_AS_NEW_VERSION,
+ version_note=version_note,
+ )
+ )
+ cls.validate_knowledge_datasets(tenant_id=tenant_id, agent_soul=agent_soul)
+ version = cls._create_config_version(
+ tenant_id=tenant_id,
+ agent_id=agent.id,
+ account_id=account_id,
+ agent_soul=agent_soul,
+ operation=AgentConfigRevisionOperation.PUBLISH_DRAFT,
+ version_note=version_note,
+ previous_snapshot_id=agent.active_config_snapshot_id,
+ )
+ agent.active_config_snapshot_id = version.id
+ agent.active_config_has_model = agent_soul_has_model(agent_soul)
+ agent.active_config_is_published = True
+ agent.updated_by = account_id
+ draft.base_snapshot_id = version.id
+ draft.updated_by = account_id
+ db.session.commit()
+ return {
+ "result": "success",
+ "active_config_snapshot_id": version.id,
+ "active_config_snapshot": cls._serialize_version(version),
+ "draft": cls._serialize_draft(draft),
+ }
+
+ @classmethod
+ def checkout_agent_app_build_draft(
+ cls, *, tenant_id: str, agent_id: str, account_id: str, force: bool = False
+ ) -> dict[str, Any]:
+ agent = cls._require_agent(tenant_id=tenant_id, agent_id=agent_id)
+ normal_draft = cls._get_or_create_agent_draft(
+ tenant_id=tenant_id,
+ agent=agent,
+ draft_type=AgentConfigDraftType.DRAFT,
+ account_id=None,
+ created_by=account_id,
+ )
+ build_draft = cls._get_agent_draft(
+ tenant_id=tenant_id,
+ agent_id=agent.id,
+ draft_type=AgentConfigDraftType.DEBUG_BUILD,
+ account_id=account_id,
+ )
+ if build_draft is not None and not force:
+ return cls._serialize_build_draft_state(build_draft)
+ if build_draft is None:
+ build_draft = AgentConfigDraft(
+ tenant_id=tenant_id,
+ agent_id=agent.id,
+ draft_type=AgentConfigDraftType.DEBUG_BUILD,
+ account_id=account_id,
+ draft_owner_key=account_id,
+ created_by=account_id,
+ )
+ db.session.add(build_draft)
+ build_draft.base_snapshot_id = normal_draft.base_snapshot_id
+ build_draft.config_snapshot = AgentSoulConfig.model_validate(normal_draft.config_snapshot_dict)
+ build_draft.updated_by = account_id
+ db.session.commit()
+ return cls._serialize_build_draft_state(build_draft)
+
+ @classmethod
+ def load_agent_app_build_draft(cls, *, tenant_id: str, agent_id: str, account_id: str) -> dict[str, Any]:
+ build_draft = cls._get_agent_draft(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ draft_type=AgentConfigDraftType.DEBUG_BUILD,
+ account_id=account_id,
+ )
+ if build_draft is None:
+ raise AgentVersionNotFoundError()
+ return cls._serialize_build_draft_state(build_draft)
+
+ @classmethod
+ def save_agent_app_build_draft(
+ cls, *, tenant_id: str, agent_id: str, account_id: str, payload: ComposerSavePayload
+ ) -> dict[str, Any]:
+ if payload.agent_soul is None:
+ raise ValueError("agent_soul is required")
+ _backfill_cli_tool_ids(payload.agent_soul)
+ ComposerConfigValidator.validate_draft_save_payload(payload)
+ cls.validate_knowledge_datasets(tenant_id=tenant_id, agent_soul=payload.agent_soul)
+ agent = cls._require_agent(tenant_id=tenant_id, agent_id=agent_id)
+ build_draft = cls._save_agent_draft(
+ tenant_id=tenant_id,
+ agent=agent,
+ draft_type=AgentConfigDraftType.DEBUG_BUILD,
+ account_id=account_id,
+ agent_soul=payload.agent_soul,
+ account_id_for_audit=account_id,
+ )
+ db.session.commit()
+ return cls._serialize_build_draft_state(build_draft)
+
+ @classmethod
+ def apply_agent_app_build_draft(cls, *, tenant_id: str, agent_id: str, account_id: str) -> dict[str, Any]:
+ agent = cls._require_agent(tenant_id=tenant_id, agent_id=agent_id)
+ build_draft = cls._get_agent_draft(
+ tenant_id=tenant_id,
+ agent_id=agent.id,
+ draft_type=AgentConfigDraftType.DEBUG_BUILD,
+ account_id=account_id,
+ )
+ if build_draft is None:
+ raise AgentVersionNotFoundError()
+ normal_draft = cls._save_agent_draft(
+ tenant_id=tenant_id,
+ agent=agent,
+ draft_type=AgentConfigDraftType.DRAFT,
+ account_id=None,
+ agent_soul=AgentSoulConfig.model_validate(build_draft.config_snapshot_dict),
+ account_id_for_audit=account_id,
+ base_snapshot_id=build_draft.base_snapshot_id,
+ )
+ agent.active_config_is_published = False
+ agent.updated_by = account_id
+ db.session.delete(build_draft)
+ db.session.commit()
+ return {"result": "success", "draft": cls._serialize_draft(normal_draft)}
+
+ @classmethod
+ def discard_agent_app_build_draft(cls, *, tenant_id: str, agent_id: str, account_id: str) -> dict[str, Any]:
+ build_draft = cls._get_agent_draft(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ draft_type=AgentConfigDraftType.DEBUG_BUILD,
+ account_id=account_id,
+ )
+ if build_draft is not None:
+ db.session.delete(build_draft)
+ db.session.commit()
+ return {"result": "success"}
+
@classmethod
def collect_validation_findings(
cls,
@@ -372,19 +594,15 @@ class AgentComposerService:
agent_id: str | None = None,
) -> dict[str, Any]:
"""ENG-617 soft findings, with DB-backed dataset and drive mention checks."""
- from services.agent.prompt_mentions import MentionKind, parse_prompt_mentions
-
- mentioned_ids: set[str] = set()
- if payload.agent_soul is not None:
- mentioned_ids |= {
- mention.ref_id
- for mention in parse_prompt_mentions(payload.agent_soul.prompt.system_prompt)
- if mention.kind == MentionKind.KNOWLEDGE
- }
- existing_dataset_ids: set[str] | None = None
- if mentioned_ids:
- existing_dataset_ids = set(cls._dataset_rows(tenant_id=tenant_id, dataset_ids=sorted(mentioned_ids)))
- findings = ComposerConfigValidator.collect_soft_findings(payload, existing_dataset_ids=existing_dataset_ids)
+ existing_knowledge_set_ids = (
+ {knowledge_set.id for knowledge_set in payload.agent_soul.knowledge.sets}
+ if payload.agent_soul is not None
+ else None
+ )
+ findings = ComposerConfigValidator.collect_soft_findings(
+ payload,
+ existing_knowledge_set_ids=existing_knowledge_set_ids,
+ )
if agent_id and payload.agent_soul is not None:
findings["warnings"].extend(
cls._drive_mention_findings(
@@ -395,6 +613,24 @@ class AgentComposerService:
)
return findings
+ @classmethod
+ def validate_knowledge_datasets(cls, *, tenant_id: str, agent_soul: AgentSoulConfig | None) -> None:
+ """Hard-validate tenant-scoped knowledge set datasets before saving.
+
+ DTO validators own set shape, duplicate set ids/names, and duplicate
+ dataset ids within one set. This service-level check owns database
+ existence and tenant ownership so invalid or cross-tenant datasets fail
+ before Agent Soul snapshots are persisted.
+ """
+ if agent_soul is None:
+ return
+ missing_ids = list_missing_tenant_knowledge_dataset_ids(tenant_id=tenant_id, agent_soul=agent_soul)
+ if missing_ids:
+ raise InvalidComposerConfigError(
+ "knowledge_dataset_not_found: knowledge sets reference missing or out-of-scope datasets: "
+ + ", ".join(missing_ids)
+ )
+
@classmethod
def 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)."""
@@ -509,7 +745,7 @@ class AgentComposerService:
soul_lists, soul_truncated = soul_candidates(
agent_soul=agent_soul,
- dataset_lookup=lambda ids: cls._dataset_rows(tenant_id=tenant_id, dataset_ids=ids),
+ dataset_lookup=lambda ids: get_tenant_knowledge_dataset_rows(tenant_id=tenant_id, dataset_ids=ids),
workspace_tools_loader=lambda: cls._workspace_dify_tools(tenant_id=tenant_id, user_id=user_id),
)
truncated = truncated or soul_truncated
@@ -529,14 +765,14 @@ class AgentComposerService:
return response.model_dump(mode="json")
@classmethod
- def get_agent_app_candidates(cls, *, tenant_id: str, app_id: str, user_id: str) -> dict[str, Any]:
+ def get_agent_app_candidates(cls, *, tenant_id: str, agent_id: str, user_id: str) -> dict[str, Any]:
"""Slash-menu data source for the Agent App (Console) composer (ENG-615)."""
from services.agent.composer_candidates import soul_candidates
- agent_soul = cls._load_agent_app_soul(tenant_id=tenant_id, app_id=app_id)
+ agent_soul = cls._load_agent_soul(tenant_id=tenant_id, agent_id=agent_id)
soul_lists, truncated = soul_candidates(
agent_soul=agent_soul,
- dataset_lookup=lambda ids: cls._dataset_rows(tenant_id=tenant_id, dataset_ids=ids),
+ dataset_lookup=lambda ids: get_tenant_knowledge_dataset_rows(tenant_id=tenant_id, dataset_ids=ids),
workspace_tools_loader=lambda: cls._workspace_dify_tools(tenant_id=tenant_id, user_id=user_id),
)
response = ComposerCandidatesResponse(
@@ -568,24 +804,18 @@ class AgentComposerService:
return cls._parse_soul_snapshot(version)
@classmethod
- def _load_agent_app_soul(cls, *, tenant_id: str, app_id: str) -> AgentSoulConfig | None:
- agent = db.session.scalar(
- select(Agent)
- .where(
- Agent.tenant_id == tenant_id,
- Agent.app_id == app_id,
- Agent.scope == AgentScope.ROSTER,
- Agent.status == AgentStatus.ACTIVE,
- )
- .order_by(Agent.created_at.desc())
- .limit(1)
- )
+ def _load_agent_soul(cls, *, tenant_id: str, agent_id: str) -> AgentSoulConfig | None:
+ agent = cls._get_agent_if_present(tenant_id=tenant_id, agent_id=agent_id)
if agent is None:
return None
- version = cls._get_version_if_present(
- tenant_id=tenant_id, agent_id=agent.id, version_id=agent.active_config_snapshot_id
+ draft = cls._get_or_create_agent_draft(
+ tenant_id=tenant_id,
+ agent=agent,
+ draft_type=AgentConfigDraftType.DRAFT,
+ account_id=None,
+ created_by=agent.updated_by or agent.created_by,
)
- return cls._parse_soul_snapshot(version)
+ return AgentSoulConfig.model_validate(draft.config_snapshot_dict)
@staticmethod
def _parse_soul_snapshot(version: AgentConfigSnapshot | None) -> AgentSoulConfig | None:
@@ -629,30 +859,6 @@ class AgentComposerService:
variables = WorkflowDraftVariableService(session=session).list_system_variables(app_id, user_id)
return [(variable.name, variable.value_type.value) for variable in variables.variables]
- @staticmethod
- def _dataset_rows(*, tenant_id: str, dataset_ids: list[str]) -> dict[str, Any]:
- """Tenant-scoped dataset lookup tolerating malformed ids.
-
- Mention ids come from user-editable prompt text; a non-UUID id can never
- match a dataset row, so it is simply absent from the result (-> missing/
- placeholder semantics) instead of breaking the UUID-typed query.
- """
- from uuid import UUID
-
- from services.dataset_service import DatasetService
-
- valid_ids: list[str] = []
- for dataset_id in dataset_ids:
- try:
- UUID(dataset_id)
- except (ValueError, TypeError):
- continue
- valid_ids.append(dataset_id)
- if not valid_ids:
- return {}
- rows, _ = DatasetService.get_datasets_by_ids(valid_ids, tenant_id)
- return {str(row.id): row for row in rows}
-
@staticmethod
def _workspace_dify_tools(*, tenant_id: str, user_id: str) -> list[dict[str, Any]]:
"""Workspace Dify Plugin tools, same source as the tool selector.
@@ -780,6 +986,7 @@ class AgentComposerService:
raise ValueError("Inline workflow agent binding must point to a workflow-only agent")
agent.active_config_snapshot_id = version.id
agent.active_config_has_model = agent_soul_has_model(payload.agent_soul)
+ agent.active_config_is_published = True
agent.updated_by = account_id
binding.current_snapshot_id = version.id
binding.updated_by = account_id
@@ -878,6 +1085,7 @@ class AgentComposerService:
agent = cls._require_agent(tenant_id=tenant_id, agent_id=binding.agent_id)
agent.active_config_snapshot_id = version.id
agent.active_config_has_model = agent_soul_has_model(payload.agent_soul)
+ agent.active_config_is_published = True
agent.updated_by = account_id
binding.current_snapshot_id = version.id
if payload.node_job is not None:
@@ -908,6 +1116,7 @@ class AgentComposerService:
agent = cls._require_agent(tenant_id=tenant_id, agent_id=binding.agent_id)
agent.active_config_snapshot_id = version.id
agent.active_config_has_model = agent_soul_has_model(payload.agent_soul)
+ agent.active_config_is_published = True
agent.updated_by = account_id
binding.current_snapshot_id = version.id
binding.updated_by = account_id
@@ -1028,6 +1237,15 @@ class AgentComposerService:
icon: str | None = None,
icon_background: str | None = None,
) -> Agent:
+ backing_app = AgentRosterService(db.session).create_hidden_backing_app_for_workflow_agent(
+ tenant_id=tenant_id,
+ account_id=account_id,
+ name=name or f"Workflow Agent {node_id}",
+ description=description,
+ icon_type=icon_type,
+ icon=icon,
+ icon_background=icon_background,
+ )
agent = Agent(
tenant_id=tenant_id,
name=name or f"Workflow Agent {node_id}",
@@ -1040,6 +1258,7 @@ class AgentComposerService:
scope=AgentScope.WORKFLOW_ONLY,
source=AgentSource.WORKFLOW,
app_id=app_id,
+ backing_app_id=backing_app.id,
workflow_id=workflow_id,
workflow_node_id=node_id,
status=AgentStatus.ACTIVE,
@@ -1058,6 +1277,7 @@ class AgentComposerService:
)
agent.active_config_snapshot_id = version.id
agent.active_config_has_model = agent_soul_has_model(agent_soul)
+ agent.active_config_is_published = True
return agent
@classmethod
@@ -1205,6 +1425,7 @@ class AgentComposerService:
)
agent.active_config_snapshot_id = version.id
agent.active_config_has_model = agent_soul_has_model(agent_soul)
+ agent.active_config_is_published = True
agent.updated_by = account_id
return agent
@@ -1285,6 +1506,145 @@ class AgentComposerService:
or 0
) + 1
+ @classmethod
+ def _get_agent_app_agent(cls, *, tenant_id: str, app_id: str) -> Agent | None:
+ return db.session.scalar(
+ select(Agent)
+ .where(
+ Agent.tenant_id == tenant_id,
+ Agent.app_id == app_id,
+ Agent.scope == AgentScope.ROSTER,
+ Agent.source == AgentSource.AGENT_APP,
+ Agent.status == AgentStatus.ACTIVE,
+ )
+ .order_by(Agent.created_at.desc())
+ .limit(1)
+ )
+
+ @classmethod
+ def _require_agent_app_agent(cls, *, tenant_id: str, app_id: str) -> Agent:
+ agent = cls._get_agent_app_agent(tenant_id=tenant_id, app_id=app_id)
+ if agent is None:
+ raise AgentNotFoundError()
+ return agent
+
+ @classmethod
+ def _get_agent_draft(
+ cls,
+ *,
+ tenant_id: str,
+ agent_id: str,
+ draft_type: AgentConfigDraftType,
+ account_id: str | None,
+ ) -> AgentConfigDraft | None:
+ stmt = select(AgentConfigDraft).where(
+ AgentConfigDraft.tenant_id == tenant_id,
+ AgentConfigDraft.agent_id == agent_id,
+ AgentConfigDraft.draft_type == draft_type,
+ )
+ if draft_type == AgentConfigDraftType.DEBUG_BUILD:
+ stmt = stmt.where(AgentConfigDraft.account_id == account_id)
+ else:
+ stmt = stmt.where(AgentConfigDraft.account_id.is_(None))
+ return db.session.scalar(stmt.order_by(AgentConfigDraft.updated_at.desc()).limit(1))
+
+ @classmethod
+ def _get_or_create_agent_draft(
+ cls,
+ *,
+ tenant_id: str,
+ agent: Agent,
+ draft_type: AgentConfigDraftType,
+ account_id: str | None,
+ created_by: str | None,
+ ) -> AgentConfigDraft:
+ draft = cls._get_agent_draft(
+ tenant_id=tenant_id,
+ agent_id=agent.id,
+ draft_type=draft_type,
+ account_id=account_id,
+ )
+ if draft is not None:
+ return draft
+ base_snapshot = cls._get_version_if_present(
+ tenant_id=tenant_id,
+ agent_id=agent.id,
+ version_id=agent.active_config_snapshot_id,
+ )
+ agent_soul = (
+ AgentSoulConfig.model_validate(base_snapshot.config_snapshot_dict)
+ if base_snapshot is not None
+ else AgentSoulConfig()
+ )
+ draft = AgentConfigDraft(
+ tenant_id=tenant_id,
+ agent_id=agent.id,
+ draft_type=draft_type,
+ account_id=account_id if draft_type == AgentConfigDraftType.DEBUG_BUILD else None,
+ draft_owner_key=account_id if draft_type == AgentConfigDraftType.DEBUG_BUILD and account_id else "",
+ base_snapshot_id=base_snapshot.id if base_snapshot else None,
+ config_snapshot=agent_soul,
+ created_by=created_by,
+ updated_by=created_by,
+ )
+ db.session.add(draft)
+ db.session.flush()
+ return draft
+
+ @classmethod
+ def _save_agent_draft(
+ cls,
+ *,
+ tenant_id: str,
+ agent: Agent,
+ draft_type: AgentConfigDraftType,
+ account_id: str | None,
+ agent_soul: AgentSoulConfig,
+ account_id_for_audit: str,
+ base_snapshot_id: str | None = None,
+ ) -> AgentConfigDraft:
+ draft = cls._get_or_create_agent_draft(
+ tenant_id=tenant_id,
+ agent=agent,
+ draft_type=draft_type,
+ account_id=account_id,
+ created_by=account_id_for_audit,
+ )
+ draft.config_snapshot = agent_soul
+ if base_snapshot_id is not None:
+ draft.base_snapshot_id = base_snapshot_id
+ elif draft.base_snapshot_id is None:
+ draft.base_snapshot_id = agent.active_config_snapshot_id
+ draft.updated_by = account_id_for_audit
+ if draft_type == AgentConfigDraftType.DRAFT and account_id is None:
+ agent.active_config_is_published = False
+ db.session.flush()
+ return draft
+
+ @classmethod
+ def _serialize_draft(cls, draft: AgentConfigDraft | None) -> dict[str, Any] | None:
+ if draft is None:
+ return None
+ return {
+ "id": draft.id,
+ "agent_id": draft.agent_id,
+ "draft_type": draft.draft_type.value,
+ "account_id": draft.account_id,
+ "base_snapshot_id": draft.base_snapshot_id,
+ "created_by": draft.created_by,
+ "updated_by": draft.updated_by,
+ "created_at": to_timestamp(draft.created_at),
+ "updated_at": to_timestamp(draft.updated_at),
+ }
+
+ @classmethod
+ def _serialize_build_draft_state(cls, draft: AgentConfigDraft) -> dict[str, Any]:
+ return {
+ "variant": ComposerVariant.AGENT_APP.value,
+ "draft": cls._serialize_draft(draft),
+ "agent_soul": draft.config_snapshot_dict,
+ }
+
@classmethod
def _get_draft_workflow(cls, *, tenant_id: str, app_id: str) -> Workflow:
workflow = db.session.scalar(
@@ -1471,6 +1831,12 @@ class AgentComposerService:
"impact_summary": cls.calculate_impact(tenant_id=binding.tenant_id, current_snapshot_id=version.id)
if version
else None,
+ "app_id": binding.app_id,
+ "backing_app_id": agent.backing_app_id if agent else None,
+ "hidden_app_backed": bool(agent and agent.scope == AgentScope.WORKFLOW_ONLY and agent.backing_app_id),
+ "chat_endpoint": f"/console/api/agent/{agent.id}/chat-messages" if agent else None,
+ "workflow_id": binding.workflow_id,
+ "node_id": binding.node_id,
}
@classmethod
@@ -1479,7 +1845,15 @@ class AgentComposerService:
"id": agent.id,
"name": agent.name,
"description": agent.description,
+ "role": agent.role,
+ "icon_type": agent.icon_type,
+ "icon": agent.icon,
+ "icon_background": agent.icon_background,
"scope": agent.scope.value,
+ "source": agent.source.value,
+ "app_id": agent.app_id,
+ "backing_app_id": agent.backing_app_id or agent.app_id,
+ "hidden_app_backed": bool(agent.scope == AgentScope.WORKFLOW_ONLY and agent.backing_app_id),
"status": agent.status.value,
"active_config_snapshot_id": agent.active_config_snapshot_id,
}
diff --git a/api/services/agent/composer_validator.py b/api/services/agent/composer_validator.py
index 34b80b8a9d0..4e7d4ff3c63 100644
--- a/api/services/agent/composer_validator.py
+++ b/api/services/agent/composer_validator.py
@@ -148,15 +148,15 @@ class ComposerConfigValidator:
cls,
payload: ComposerSavePayload,
*,
- existing_dataset_ids: set[str] | None = None,
+ existing_knowledge_set_ids: set[str] | None = None,
) -> dict[str, Any]:
"""ENG-617 §5.3/§5.4 soft findings — never block save.
``warnings`` carries ``mention_target_missing`` / ``mention_malformed``
- entries; ``knowledge_retrieval_placeholder`` keeps dangling knowledge
+ entries; ``knowledge_retrieval_placeholder`` keeps dangling knowledge-set
mentions with a placeholder name (0522 consensus) instead of dropping or
- rejecting them. With ``existing_dataset_ids`` provided, configured-but-
- deleted datasets surface as placeholders too.
+ rejecting them. With ``existing_knowledge_set_ids`` provided, mentions
+ that no longer exist in the current Agent Soul surface as placeholders too.
"""
warnings: list[dict[str, Any]] = []
placeholders: list[dict[str, str]] = []
@@ -188,7 +188,7 @@ class ComposerConfigValidator:
resolved = resolver(mention)
if mention.kind == MentionKind.KNOWLEDGE:
dangling = resolved is None or (
- existing_dataset_ids is not None and mention.ref_id not in existing_dataset_ids
+ existing_knowledge_set_ids is not None and mention.ref_id not in existing_knowledge_set_ids
)
if dangling:
placeholders.append(
diff --git a/api/services/agent/knowledge_datasets.py b/api/services/agent/knowledge_datasets.py
new file mode 100644
index 00000000000..962c562ce15
--- /dev/null
+++ b/api/services/agent/knowledge_datasets.py
@@ -0,0 +1,63 @@
+from __future__ import annotations
+
+from typing import Any
+from uuid import UUID
+
+from models.agent_config_entities import AgentSoulConfig
+
+
+def list_agent_soul_knowledge_dataset_ids(agent_soul: AgentSoulConfig) -> list[str]:
+ """Return normalized unique knowledge dataset ids in config order.
+
+ Agent v2 knowledge dataset selection is owned by ``knowledge.sets``. This
+ helper keeps composer, workflow validation, candidates, and runtime
+ diagnostics aligned on the same normalization rules: strip whitespace, drop
+ blanks, preserve first-seen order, and deduplicate.
+ """
+ dataset_ids: list[str] = []
+ seen: set[str] = set()
+ for knowledge_set in agent_soul.knowledge.sets:
+ for dataset in knowledge_set.datasets:
+ dataset_id = (dataset.id or "").strip()
+ if not dataset_id or dataset_id in seen:
+ continue
+ seen.add(dataset_id)
+ dataset_ids.append(dataset_id)
+ return dataset_ids
+
+
+def get_tenant_knowledge_dataset_rows(*, tenant_id: str, dataset_ids: list[str]) -> dict[str, Any]:
+ """Return tenant-scoped dataset rows for normalized knowledge dataset ids.
+
+ Knowledge ids come from user-editable config. Malformed ids can never match
+ a dataset row, so they are treated as missing instead of breaking the
+ UUID-typed dataset lookup.
+ """
+ from services.dataset_service import DatasetService
+
+ valid_ids: list[str] = []
+ for dataset_id in dataset_ids:
+ try:
+ UUID(dataset_id)
+ except (TypeError, ValueError):
+ continue
+ valid_ids.append(dataset_id)
+
+ if not valid_ids:
+ return {}
+
+ rows, _ = DatasetService.get_datasets_by_ids(valid_ids, tenant_id)
+ return {str(row.id): row for row in rows}
+
+
+def list_missing_tenant_knowledge_dataset_ids(*, tenant_id: str, agent_soul: AgentSoulConfig | None) -> list[str]:
+ """Return normalized knowledge dataset ids missing from the tenant scope."""
+ if agent_soul is None:
+ return []
+
+ dataset_ids = list_agent_soul_knowledge_dataset_ids(agent_soul)
+ if not dataset_ids:
+ return []
+
+ rows = get_tenant_knowledge_dataset_rows(tenant_id=tenant_id, dataset_ids=dataset_ids)
+ return [dataset_id for dataset_id in dataset_ids if dataset_id not in rows]
diff --git a/api/services/agent/prompt_mentions.py b/api/services/agent/prompt_mentions.py
index 27bed49c53b..520c36043bd 100644
--- a/api/services/agent/prompt_mentions.py
+++ b/api/services/agent/prompt_mentions.py
@@ -1,23 +1,26 @@
-"""Prompt mention (slash-reference) serialization contract — ENG-616.
+"""Prompt mention and workflow-marker parsing helpers for Agent surfaces.
-Slash-menu insertions are stored inline in the plain-string prompt as tokens:
+Slash-menu insertions are stored inline as mention tokens:
[§<kind>:<id>[:<label>]§]
-``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 appears
-in Dify template syntax (``{{var}}`` / ``{{#a.b#}}``) nor in normal prompt text,
-so these tokens can never collide with the existing template parsers. Runtime
-expansion (and the final scrub that guarantees no internal marker ever reaches
-the model) is owned by the run-request builders.
+Those tokens point at Agent-owned config such as Soul tools/knowledge/humans or
+workflow task config such as ``previous_node_output_refs`` / ``declared_outputs``.
+Runtime mention expansion is owned by the run-request builders.
+
+Workflow Agent tasks also carry frontend workflow variable markers:
+
+ {{#<node-id>.<output>[.<child>...]#}}
+
+Those frontend markers are a separate path from slash-reference expansion. They
+are parsed here only to derive ``previous_node_output_refs`` from the current
+task text. The markers remain literal in the workflow task prompt, while their
+resolved values appear under the workflow context prompt's ``Previous node
+outputs:`` section. Legacy ``[§node_output:...§]`` mention syntax is not part
+of that derivation path.
+
+Frontend output blocks still accept a legacy bare ``§output:...§`` form during
+migrations, so the mention parser keeps that alias for output mentions only.
"""
from __future__ import annotations
@@ -47,13 +50,16 @@ class MentionKind(StrEnum):
MENTION_PATTERN = re.compile(
- r"\[§(skill|file|tool|cli_tool|knowledge|human|node_output|output):([^:§]+?)(?::([^§]*?))?§\]"
+ r"(?:\[§(?P<bracket_kind>skill|file|tool|cli_tool|knowledge|human|node_output|output):"
+ r"(?P<bracket_id>[^:§]+?)(?::(?P<bracket_label>[^§]*?))?§\])"
+ r"|(?:§(?P<legacy_kind>output):(?P<legacy_id>[^:§]+?)(?::(?P<legacy_label>[^§]*?))?§)"
)
# Anything mention-shaped (``[§word:…§]``) that the strict pattern did not consume
# — unknown kinds, malformed bodies. The ``§`` wrapper + a kind-word + ``:``
# requirement keeps legacy ``{{#histories#}}`` / ``{{var}}`` template forms and
# ordinary bracketed text out of scope.
_RESIDUAL_MENTION_PATTERN = re.compile(r"\[§([A-Za-z_][A-Za-z0-9_]*:[^§]*?)§\]")
+WORKFLOW_VARIABLE_PATTERN = re.compile(r"\{\{#([^{}#]+?\.[^{}#]+?)#\}\}")
MAX_MENTIONS_PER_PROMPT = 200
# Drive keys are validated up to 512 Unicode code points before URL encoding.
@@ -71,7 +77,8 @@ MAX_MENTION_LABEL_LENGTH = 255
ALL_PROVIDER_TOOLS_SUFFIX = "*"
# Per-surface allowlists (design §2.4): the soul prompt may only reference
-# soul-owned entities; the workflow job prompt may only reference run-scoped ones.
+# soul-owned entities; the persisted workflow task prompt may only reference
+# run-scoped ones.
SOUL_PROMPT_ALLOWED_KINDS = frozenset(
{
MentionKind.SKILL,
@@ -83,6 +90,9 @@ SOUL_PROMPT_ALLOWED_KINDS = frozenset(
}
)
NODE_JOB_PROMPT_ALLOWED_KINDS = frozenset({MentionKind.NODE_OUTPUT, MentionKind.OUTPUT, MentionKind.HUMAN})
+WORKFLOW_NODE_OUTPUT_RESERVED_PREFIXES = frozenset(
+ {"sys", "env", "conversation", "rag", "current", "last_run", "error_message", "$output"}
+)
@dataclass(frozen=True, slots=True)
@@ -100,18 +110,24 @@ class PromptMention:
MentionResolver = Callable[[PromptMention], str | None]
+def _mention_groups(match: re.Match[str]) -> tuple[str, str, str | None]:
+ kind = match.group("bracket_kind") or match.group("legacy_kind")
+ ref_id = match.group("bracket_id") or match.group("legacy_id")
+ label = match.group("bracket_label") or match.group("legacy_label")
+ return kind, ref_id, label
+
+
def parse_prompt_mentions(prompt: str) -> list[PromptMention]:
"""Extract well-formed mentions. Oversized id/label tokens are skipped here
(treated as malformed) — the runtime scrub still degrades them safely."""
mentions: list[PromptMention] = []
for match in MENTION_PATTERN.finditer(prompt or ""):
- ref_id = match.group(2)
- label = match.group(3)
+ kind, ref_id, label = _mention_groups(match)
if len(ref_id) > MAX_MENTION_REF_ID_LENGTH or (label is not None and len(label) > MAX_MENTION_LABEL_LENGTH):
continue
mentions.append(
PromptMention(
- kind=MentionKind(match.group(1)),
+ kind=MentionKind(kind),
ref_id=ref_id,
label=label or None,
start=match.start(),
@@ -130,13 +146,13 @@ def expand_prompt_mentions(prompt: str, resolver: MentionResolver) -> str:
return prompt
def _replace(match: re.Match[str]) -> str:
- ref_id = match.group(2)
- label = match.group(3) or None
+ kind, ref_id, label = _mention_groups(match)
+ label = label or None
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 fallback
mention = PromptMention(
- kind=MentionKind(match.group(1)),
+ kind=MentionKind(kind),
ref_id=ref_id,
label=label,
start=match.start(),
@@ -161,6 +177,48 @@ def find_malformed_mention_markers(prompt: str) -> list[str]:
return [match.group(0) for match in _RESIDUAL_MENTION_PATTERN.finditer(prompt) if match.span() not in parsed_spans]
+def extract_workflow_variable_selectors(prompt: str) -> list[tuple[str, ...]]:
+ """Extract ``{{#node.output#}}``-style selectors from workflow prompts."""
+ selectors: list[tuple[str, ...]] = []
+ for match in WORKFLOW_VARIABLE_PATTERN.finditer(prompt or ""):
+ parts = tuple(part.strip() for part in match.group(1).split(".") if part.strip())
+ if len(parts) >= 2:
+ selectors.append(parts)
+ return selectors
+
+
+def extract_workflow_node_output_selectors(prompt: str) -> list[tuple[str, ...]]:
+ """Extract previous-node selectors from frontend workflow variable markers.
+
+ Reserved Dify namespaces such as ``sys`` are excluded because they are not
+ previous nodes.
+ """
+ selectors: list[tuple[str, ...]] = []
+ seen: set[tuple[str, ...]] = set()
+ for selector in extract_workflow_variable_selectors(prompt):
+ if selector[0] in WORKFLOW_NODE_OUTPUT_RESERVED_PREFIXES:
+ continue
+ if selector in seen:
+ continue
+ selectors.append(selector)
+ seen.add(selector)
+ return selectors
+
+
+def workflow_previous_node_output_refs_from_selectors(
+ selectors: list[tuple[str, ...]],
+) -> list[WorkflowPreviousNodeOutputRef]:
+ """Materialize persisted previous-node refs from parsed frontend selectors."""
+ return [
+ WorkflowPreviousNodeOutputRef(
+ selector=list(selector),
+ node_id=selector[0],
+ output=selector[1],
+ )
+ for selector in selectors
+ ]
+
+
def scrub_mention_markers(text: str) -> str:
"""Degrade any residual mention-shaped ``[§kind:…§]`` marker to readable text."""
@@ -211,9 +269,9 @@ def build_soul_mention_resolver(agent_soul: AgentSoulConfig) -> MentionResolver:
if mention.ref_id in (cli_tool.id, cli_tool.name):
return cli_tool.name or cli_tool.id
case MentionKind.KNOWLEDGE:
- for dataset in agent_soul.knowledge.datasets:
- if mention.ref_id == dataset.id:
- return dataset.name or dataset.id
+ for knowledge_set in agent_soul.knowledge.sets:
+ if mention.ref_id == knowledge_set.id:
+ return knowledge_set.name or knowledge_set.id
case MentionKind.HUMAN:
return _resolve_human_contact(agent_soul.human.contacts, mention.ref_id)
case _:
@@ -224,14 +282,17 @@ def build_soul_mention_resolver(agent_soul: AgentSoulConfig) -> MentionResolver:
def build_node_job_mention_resolver(node_job: WorkflowNodeJobConfig) -> MentionResolver:
- """Resolve job-surface mentions. ``node_output`` expands to the stored
- reference name only — values stay in the Workflow context block (design §4.2)."""
+ """Resolve persisted workflow task prompt mentions.
+
+ ``node_output`` expands to the stored reference name only; values stay in
+ the workflow context block for the run-scoped ``user_prompt``.
+ """
def _resolve(mention: PromptMention) -> str | None:
match mention.kind:
case MentionKind.NODE_OUTPUT:
for ref in node_job.previous_node_output_refs:
- selector = _selector_from_ref(ref)
+ selector = normalize_previous_node_output_selector(ref)
if selector and f"{selector[0]}.{selector[1]}" == mention.ref_id:
return ref.name or mention.label or mention.ref_id
case MentionKind.OUTPUT:
@@ -256,14 +317,27 @@ def _resolve_human_contact(contacts: list[AgentHumanContactConfig], ref_id: str)
return None
-def _selector_from_ref(ref: WorkflowPreviousNodeOutputRef) -> tuple[str, str] | None:
+def normalize_previous_node_output_selector(ref: WorkflowPreviousNodeOutputRef) -> tuple[str, ...] | None:
+ """Return the canonical previous-node selector for a persisted ref.
+
+ Explicit selector arrays win and must contain at least two string parts. The
+ legacy field form falls back to ``node_id`` plus the first available output
+ field. Callers that only need node/output identity should compare the first
+ two returned items.
+ """
for candidate in (ref.selector, ref.variable_selector, ref.value_selector):
if isinstance(candidate, list) and len(candidate) >= 2:
- return str(candidate[0]), str(candidate[1])
- if ref.node_id:
- output = ref.output or ref.variable or ref.key
- if output:
- return ref.node_id, output
+ selector_parts: list[str] = []
+ for item in candidate:
+ if not isinstance(item, str):
+ break
+ selector_parts.append(item)
+ if len(selector_parts) == len(candidate):
+ return tuple(selector_parts)
+ node_id = ref.get("node_id")
+ output_name = ref.get("output") or ref.get("name") or ref.get("variable") or ref.get("key")
+ if isinstance(node_id, str) and isinstance(output_name, str):
+ return node_id, output_name
return None
@@ -275,13 +349,18 @@ __all__ = [
"MENTION_PATTERN",
"NODE_JOB_PROMPT_ALLOWED_KINDS",
"SOUL_PROMPT_ALLOWED_KINDS",
+ "WORKFLOW_NODE_OUTPUT_RESERVED_PREFIXES",
"MentionKind",
"MentionResolver",
"PromptMention",
"build_node_job_mention_resolver",
"build_soul_mention_resolver",
"expand_prompt_mentions",
+ "extract_workflow_node_output_selectors",
+ "extract_workflow_variable_selectors",
"find_malformed_mention_markers",
+ "normalize_previous_node_output_selector",
"parse_prompt_mentions",
"scrub_mention_markers",
+ "workflow_previous_node_output_refs_from_selectors",
]
diff --git a/api/services/agent/roster_service.py b/api/services/agent/roster_service.py
index 97d91b50770..d18a1781892 100644
--- a/api/services/agent/roster_service.py
+++ b/api/services/agent/roster_service.py
@@ -3,11 +3,14 @@ from typing import Any, TypedDict
from sqlalchemy import and_, func, or_, select
from sqlalchemy.exc import IntegrityError
+from constants.model_template import default_app_templates
from core.app.entities.app_invoke_entities import InvokeFrom
from libs.datetime_utils import naive_utc_now
from libs.helper import to_timestamp
from models.agent import (
Agent,
+ AgentConfigDraft,
+ AgentConfigDraftType,
AgentConfigRevision,
AgentConfigRevisionOperation,
AgentConfigSnapshot,
@@ -21,7 +24,7 @@ from models.agent import (
)
from models.agent_config_entities import AgentSoulConfig
from models.enums import AppStatus, ConversationFromSource, ConversationStatus
-from models.model import App, AppMode, Conversation, IconType
+from models.model import App, AppMode, AppModelConfig, Conversation, IconType
from models.workflow import Workflow
from services.agent.agent_soul_state import agent_soul_has_model
from services.agent.composer_validator import ComposerConfigValidator
@@ -83,7 +86,7 @@ class AgentRosterService:
agent: Agent,
active_version: AgentConfigSnapshot | None = None,
published_references: list[AgentReferencingWorkflow] | None = None,
- active_config_is_published: bool = False,
+ active_config_is_published: bool | None = None,
) -> dict[str, Any]:
published_references = published_references or []
return {
@@ -98,12 +101,16 @@ class AgentRosterService:
"scope": agent.scope.value,
"source": agent.source.value,
"app_id": agent.app_id,
+ "backing_app_id": agent.backing_app_id,
+ "hidden_app_backed": bool(agent.scope == AgentScope.WORKFLOW_ONLY and agent.backing_app_id),
"debug_conversation_id": None,
"workflow_id": agent.workflow_id,
"workflow_node_id": agent.workflow_node_id,
"active_config_snapshot_id": agent.active_config_snapshot_id,
"active_config_snapshot": AgentRosterService.serialize_version(active_version) if active_version else None,
- "active_config_is_published": active_config_is_published,
+ "active_config_is_published": agent.active_config_is_published
+ if active_config_is_published is None
+ else active_config_is_published,
"status": agent.status.value,
"created_by": agent.created_by,
"updated_by": agent.updated_by,
@@ -321,6 +328,7 @@ class AgentRosterService:
self._session.add(revision)
agent.active_config_snapshot_id = version.id
agent.active_config_has_model = agent_soul_has_model(payload.agent_soul)
+ agent.active_config_is_published = True
try:
self._session.commit()
@@ -363,6 +371,7 @@ class AgentRosterService:
source=AgentSource.AGENT_APP,
status=AgentStatus.ACTIVE,
app_id=app_id,
+ backing_app_id=app_id,
created_by=account_id,
updated_by=account_id,
)
@@ -394,10 +403,58 @@ class AgentRosterService:
self._session.add(revision)
agent.active_config_snapshot_id = version.id
agent.active_config_has_model = agent_soul_has_model(AgentSoulConfig())
+ agent.active_config_is_published = False
self._session.flush()
self._get_or_create_agent_app_debug_conversation(agent=agent, account_id=account_id)
return agent
+ def create_hidden_backing_app_for_workflow_agent(
+ self,
+ *,
+ tenant_id: str,
+ account_id: str | None,
+ name: str,
+ description: str = "",
+ icon_type: Any = None,
+ icon: str | None = None,
+ icon_background: str | None = None,
+ ) -> App:
+ """Create an internal Agent App used only to back a workflow-only Agent.
+
+ This deliberately bypasses AppService.create_app because that public
+ creation path also creates a roster Agent. Inline Agents need App runtime
+ infrastructure for chat/logs/monitoring, but must stay hidden from the
+ workspace Agent Roster until explicitly saved to roster.
+ """
+
+ app_template = dict(default_app_templates[AppMode.AGENT]["app"])
+ app = App(**app_template)
+ app.name = name
+ app.description = description or ""
+ app.mode = AppMode.AGENT
+ normalized_icon_type = self._normalize_app_icon_type(icon_type)
+ app.icon_type = IconType(normalized_icon_type) if normalized_icon_type else IconType.EMOJI
+ app.icon = icon
+ app.icon_background = icon_background
+ app.tenant_id = tenant_id
+ app.enable_site = False
+ app.enable_api = False
+ app.api_rph = 0
+ app.api_rpm = 0
+ app.max_active_requests = None
+ app.created_by = account_id
+ app.maintainer = account_id
+ app.updated_by = account_id
+ self._session.add(app)
+ self._session.flush()
+
+ app_model_config = AppModelConfig(app_id=app.id, created_by=account_id, updated_by=account_id)
+ self._session.add(app_model_config)
+ self._session.flush()
+ app.app_model_config_id = app_model_config.id
+ self._session.flush()
+ return app
+
def _create_agent_app_debug_conversation(self, *, app_id: str, account_id: str) -> str:
"""Create one console debug conversation for an Agent App editor."""
@@ -423,8 +480,31 @@ class AgentRosterService:
self._session.flush()
return conversation.id
+ @staticmethod
+ def runtime_backing_app_id(agent: Agent) -> str | None:
+ """Return the App id that backs Agent runtime chat/log/monitoring."""
+
+ return agent.backing_app_id or agent.app_id
+
+ def _ensure_workflow_agent_backing_app(self, *, agent: Agent, account_id: str | None) -> str | None:
+ if agent.scope != AgentScope.WORKFLOW_ONLY or agent.backing_app_id:
+ return self.runtime_backing_app_id(agent)
+ backing_app = self.create_hidden_backing_app_for_workflow_agent(
+ tenant_id=agent.tenant_id,
+ account_id=account_id or agent.updated_by or agent.created_by,
+ name=agent.name,
+ description=agent.description,
+ icon_type=agent.icon_type,
+ icon=agent.icon,
+ icon_background=agent.icon_background,
+ )
+ agent.backing_app_id = backing_app.id
+ self._session.flush()
+ return backing_app.id
+
def _get_or_create_agent_app_debug_conversation(self, *, agent: Agent, account_id: str) -> str:
- if not agent.app_id:
+ backing_app_id = self._ensure_workflow_agent_backing_app(agent=agent, account_id=account_id)
+ if not backing_app_id:
raise AgentNotFoundError()
mapping = self._session.scalar(
@@ -438,7 +518,7 @@ class AgentRosterService:
conversation_id = self._session.scalar(
select(Conversation.id).where(
Conversation.id == mapping.conversation_id,
- Conversation.app_id == agent.app_id,
+ Conversation.app_id == backing_app_id,
Conversation.from_source == ConversationFromSource.CONSOLE,
Conversation.from_account_id == account_id,
Conversation.is_deleted.is_(False),
@@ -448,21 +528,22 @@ class AgentRosterService:
return conversation_id
mapping.conversation_id = self._create_agent_app_debug_conversation(
- app_id=agent.app_id,
+ app_id=backing_app_id,
account_id=account_id,
)
+ mapping.app_id = backing_app_id
self._session.flush()
return mapping.conversation_id
conversation_id = self._create_agent_app_debug_conversation(
- app_id=agent.app_id,
+ app_id=backing_app_id,
account_id=account_id,
)
self._session.add(
AgentDebugConversation(
tenant_id=agent.tenant_id,
agent_id=agent.id,
- app_id=agent.app_id,
+ app_id=backing_app_id,
account_id=account_id,
conversation_id=conversation_id,
)
@@ -479,8 +560,6 @@ class AgentRosterService:
select(Agent).where(
Agent.tenant_id == tenant_id,
Agent.id == agent_id,
- Agent.scope == AgentScope.ROSTER,
- Agent.source == AgentSource.AGENT_APP,
Agent.status == AgentStatus.ACTIVE,
)
)
@@ -501,16 +580,20 @@ class AgentRosterService:
select(Agent).where(
Agent.tenant_id == tenant_id,
Agent.id == agent_id,
- Agent.scope == AgentScope.ROSTER,
- Agent.source == AgentSource.AGENT_APP,
Agent.status == AgentStatus.ACTIVE,
)
)
- if agent is None or not agent.app_id:
+ if agent is None:
+ raise AgentNotFoundError()
+ backing_app_id = self._ensure_workflow_agent_backing_app(
+ agent=agent,
+ account_id=agent.updated_by or agent.created_by,
+ )
+ if not backing_app_id:
raise AgentNotFoundError()
conversation_id = self._create_agent_app_debug_conversation(
- app_id=agent.app_id,
+ app_id=backing_app_id,
account_id=account_id,
)
mapping = self._session.scalar(
@@ -525,13 +608,13 @@ class AgentRosterService:
AgentDebugConversation(
tenant_id=tenant_id,
agent_id=agent_id,
- app_id=agent.app_id,
+ app_id=backing_app_id,
account_id=account_id,
conversation_id=conversation_id,
)
)
else:
- mapping.app_id = agent.app_id
+ mapping.app_id = backing_app_id
mapping.conversation_id = conversation_id
self._session.flush()
if commit:
@@ -546,11 +629,7 @@ class AgentRosterService:
conversation_ids_by_agent_id: dict[str, str] = {}
changed = False
for agent in agents:
- if (
- agent.tenant_id != tenant_id
- or agent.scope != AgentScope.ROSTER
- or agent.source != AgentSource.AGENT_APP
- ):
+ if agent.tenant_id != tenant_id or agent.status != AgentStatus.ACTIVE:
continue
conversation_ids_by_agent_id[agent.id] = self._get_or_create_agent_app_debug_conversation(
agent=agent,
@@ -574,7 +653,7 @@ class AgentRosterService:
Agent.status == AgentStatus.ACTIVE,
)
).all()
- return {agent.app_id: agent for agent in agents if agent.app_id}
+ return {agent.app_id: agent for agent in agents if agent.app_id and agent.id}
def get_app_backing_agent(self, *, tenant_id: str, app_id: str) -> Agent | None:
"""Return the roster Agent that backs the given Agent App, if any."""
@@ -625,6 +704,59 @@ class AgentRosterService:
raise AgentNotFoundError()
return app
+ def get_agent_runtime_app_model(self, *, tenant_id: str, agent_id: str) -> App:
+ """Resolve the App that backs an Agent runtime surface.
+
+ Roster Agents use their public Agent App. Workflow-only Agents use a
+ hidden Agent App stored in ``backing_app_id`` so console chat/logs can
+ reuse the app runtime without exposing the resource in workspace app
+ lists.
+ """
+
+ agent = self._session.scalar(
+ select(Agent)
+ .where(
+ Agent.tenant_id == tenant_id,
+ Agent.id == agent_id,
+ Agent.status == AgentStatus.ACTIVE,
+ or_(
+ and_(Agent.scope == AgentScope.ROSTER, Agent.source == AgentSource.AGENT_APP),
+ and_(
+ Agent.scope == AgentScope.WORKFLOW_ONLY,
+ Agent.source == AgentSource.WORKFLOW,
+ Agent.workflow_id.is_not(None),
+ Agent.workflow_node_id.is_not(None),
+ ),
+ ),
+ )
+ .limit(1)
+ )
+ if agent is None:
+ raise AgentNotFoundError()
+ should_commit_backing_app = agent.scope == AgentScope.WORKFLOW_ONLY and not agent.backing_app_id
+ backing_app_id = self._ensure_workflow_agent_backing_app(
+ agent=agent,
+ account_id=agent.updated_by or agent.created_by,
+ )
+ if not backing_app_id:
+ raise AgentNotFoundError()
+ if should_commit_backing_app:
+ self._session.commit()
+
+ app = self._session.scalar(
+ select(App)
+ .where(
+ App.tenant_id == tenant_id,
+ App.id == backing_app_id,
+ App.mode == AppMode.AGENT,
+ App.status == AppStatus.NORMAL,
+ )
+ .limit(1)
+ )
+ if app is None:
+ raise AgentNotFoundError()
+ return app
+
def duplicate_agent_app(
self,
*,
@@ -692,10 +824,10 @@ class AgentRosterService:
return target_app
@staticmethod
- def _normalize_app_icon_type(icon_type: IconType | str | None) -> str | None:
+ def _normalize_app_icon_type(icon_type: Any | None) -> str | None:
if icon_type is None:
return None
- if isinstance(icon_type, IconType):
+ if isinstance(icon_type, IconType) or hasattr(icon_type, "value"):
return icon_type.value
return icon_type
@@ -737,6 +869,7 @@ class AgentRosterService:
target_version.version_note = source_version.version_note
target_version.created_by = account_id
target_agent.active_config_has_model = agent_soul_has_model(target_version.config_snapshot)
+ target_agent.active_config_is_published = source_agent.active_config_is_published
target_agent.updated_by = account_id
def _next_duplicate_agent_name(self, *, tenant_id: str, base_name: str) -> str:
@@ -836,6 +969,7 @@ class AgentRosterService:
def _visible_version_operations(agent: Agent) -> set[AgentConfigRevisionOperation]:
if agent.source == AgentSource.AGENT_APP:
return {
+ AgentConfigRevisionOperation.PUBLISH_DRAFT,
AgentConfigRevisionOperation.SAVE_NEW_VERSION,
AgentConfigRevisionOperation.SAVE_TO_ROSTER,
AgentConfigRevisionOperation.RESTORE_VERSION,
@@ -849,16 +983,26 @@ class AgentRosterService:
}
def active_config_is_published(self, *, tenant_id: str, agent: Agent) -> bool:
- """Return whether the Agent's current active snapshot is a visible published version."""
+ """Return whether the normal shared draft has been published into the active snapshot."""
return self.load_active_config_is_published_by_agent_id(tenant_id=tenant_id, agents=[agent]).get(
agent.id,
False,
)
def load_active_config_is_published_by_agent_id(self, *, tenant_id: str, agents: list[Agent]) -> dict[str, bool]:
- """Return publish-state flags for the active config snapshots of the given Agents."""
- published_agent_ids = self._load_published_active_snapshot_agent_ids(tenant_id=tenant_id, agents=agents)
- return {agent.id: agent.id in published_agent_ids for agent in agents}
+ """Return each Agent's stored normal-draft publish state.
+
+ The flag is maintained by write paths: normal shared draft writes mark it
+ dirty, while publish/version creation paths mark it clean. User-scoped
+ debug drafts intentionally do not affect this state.
+ """
+ agents = [agent for agent in agents if agent.id]
+ if not agents:
+ return {}
+
+ return {
+ agent.id: bool(agent.active_config_snapshot_id and agent.active_config_is_published) for agent in agents
+ }
def list_agent_versions(self, *, tenant_id: str, agent_id: str) -> list[dict[str, Any]]:
agent = self._get_agent(tenant_id=tenant_id, agent_id=agent_id, roster_only=True)
@@ -957,26 +1101,38 @@ class AgentRosterService:
raise AgentVersionNotFoundError()
version = self._get_version(tenant_id=tenant_id, agent_id=agent_id, version_id=version_id)
- if agent.active_config_snapshot_id == version.id:
- return {"result": "success", "active_config_snapshot_id": version.id}
-
- previous_snapshot_id = agent.active_config_snapshot_id
- agent.active_config_snapshot_id = version.id
- agent.active_config_has_model = agent_soul_has_model(version.config_snapshot)
- agent.updated_by = account_id
- self._session.add(
- AgentConfigRevision(
+ draft = self._session.scalar(
+ select(AgentConfigDraft)
+ .where(
+ AgentConfigDraft.tenant_id == tenant_id,
+ AgentConfigDraft.agent_id == agent_id,
+ AgentConfigDraft.draft_type == AgentConfigDraftType.DRAFT,
+ AgentConfigDraft.account_id.is_(None),
+ )
+ .limit(1)
+ )
+ if draft is None:
+ draft = AgentConfigDraft(
tenant_id=tenant_id,
agent_id=agent_id,
- previous_snapshot_id=previous_snapshot_id,
- current_snapshot_id=version.id,
- revision=self._next_revision(tenant_id=tenant_id, agent_id=agent_id),
- operation=AgentConfigRevisionOperation.RESTORE_VERSION,
+ draft_type=AgentConfigDraftType.DRAFT,
+ account_id=None,
+ draft_owner_key="",
created_by=account_id,
)
- )
+ self._session.add(draft)
+ draft.base_snapshot_id = version.id
+ draft.config_snapshot = AgentSoulConfig.model_validate(version.config_snapshot_dict)
+ draft.updated_by = account_id
+ agent.active_config_is_published = version.id == agent.active_config_snapshot_id
+ agent.updated_by = account_id
self._session.commit()
- return {"result": "success", "active_config_snapshot_id": version.id}
+ return {
+ "result": "success",
+ "active_config_snapshot_id": agent.active_config_snapshot_id or version.id,
+ "draft_config_id": draft.id,
+ "restored_version_id": version.id,
+ }
def _get_agent(self, *, tenant_id: str, agent_id: str, roster_only: bool = False) -> Agent:
stmt = select(Agent).where(Agent.tenant_id == tenant_id, Agent.id == agent_id)
diff --git a/api/services/agent/skill_package_service.py b/api/services/agent/skill_package_service.py
index c4c25d48143..3974d306a14 100644
--- a/api/services/agent/skill_package_service.py
+++ b/api/services/agent/skill_package_service.py
@@ -1,15 +1,17 @@
-"""Validate + extract metadata from an uploaded Skill package (ENG-370).
+"""Validate and normalize uploaded Skill packages for drive standardization.
A Skill is a ``.zip`` / ``.skill`` archive that must contain a ``SKILL.md`` entry
file (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 consumed by drive standardization.
+size, zip integrity, zip-slip safety, SKILL.md presence/encoding/fields),
+normalizes retained member paths relative to the selected skill root, rebuilds
+canonical archive bytes, and returns normalized metadata together with the
+archive-root ``SKILL.md`` bytes.
It does NOT execute or load the skill — the agent backend owns execution. It also
does not persist anything into Agent Soul or bind anything to config versions;
-``SkillStandardizeService`` consumes the manifest and commits the canonical drive
-rows instead.
+``SkillStandardizeService`` consumes the normalized package and commits the
+canonical drive rows instead.
"""
from __future__ import annotations
@@ -19,6 +21,7 @@ import io
import posixpath
import re
import zipfile
+import zlib
import yaml
from pydantic import BaseModel
@@ -58,10 +61,69 @@ class SkillManifest(BaseModel):
hash: str # sha256 of the archive bytes
+class NormalizedSkillPackage(BaseModel):
+ """Canonical skill package bytes and metadata ready to store in agent drive."""
+
+ manifest: SkillManifest
+ archive_bytes: bytes
+ skill_md_bytes: bytes
+ strip_prefix: str | None
+
+
class SkillPackageService:
- """Validate Skill archives and extract their manifest."""
+ """Validate Skill archives and produce the normalized package stored in drive."""
+
+ def validate_and_normalize(self, *, content: bytes, filename: str) -> NormalizedSkillPackage:
+ """Return the canonical drive package for an uploaded skill archive.
+
+ The shallowest ``SKILL.md`` defines the skill root. When exactly one
+ depth-2 ``<folder>/SKILL.md`` exists, normalization strips that top-level
+ folder and silently discards all members outside it, including nested
+ foreign paths. When that unique depth-2 condition does not apply, files
+ outside the selected skill root still raise ``files_outside_skill_root``.
+ The returned manifest is normalized to archive-root ``SKILL.md`` and its
+ hash describes the rebuilt archive bytes. Member read/decompression
+ failures while consuming the archive are mapped to ``invalid_archive``.
+ """
+ archive = self._open_archive(content=content, filename=filename)
+ with archive:
+ members = self._collect_file_members(archive)
+ member_paths = [safe_path for _, safe_path in members]
+ entry_path = self._find_skill_md(member_paths)
+ strip_prefix = self._skill_root_prefix(entry_path)
+ normalized_members = self._normalize_members(
+ members=members,
+ skill_root_prefix=strip_prefix,
+ ignore_outside_selected_root=self._can_strip_single_top_level_folder(
+ paths=member_paths, entry_path=entry_path
+ ),
+ )
+ skill_md_member = normalized_members[_SKILL_MD_NAME]
+ self._validate_skill_md_size(skill_md_member)
+ skill_md_bytes = self._read_member_bytes_from_archive(archive, member_info=skill_md_member)
+ skill_md = self._decode_skill_md(skill_md_bytes)
+ normalized_archive_bytes = self._build_normalized_archive(
+ archive=archive, normalized_members=normalized_members
+ )
+ normalized_size = sum(max(info.file_size, 0) for info in normalized_members.values())
- def validate_and_extract(self, *, content: bytes, filename: str) -> SkillManifest:
+ name, description = self._parse_skill_md(skill_md)
+ manifest = SkillManifest(
+ name=name,
+ description=description,
+ entry_path=_SKILL_MD_NAME,
+ files=sorted(normalized_members),
+ size=normalized_size,
+ hash=hashlib.sha256(normalized_archive_bytes).hexdigest(),
+ )
+ return NormalizedSkillPackage(
+ manifest=manifest,
+ archive_bytes=normalized_archive_bytes,
+ skill_md_bytes=skill_md_bytes,
+ strip_prefix=strip_prefix,
+ )
+
+ def _open_archive(self, *, content: bytes, filename: str) -> zipfile.ZipFile:
self._check_extension(filename)
if not content:
raise SkillPackageError("empty_archive", "skill archive is empty", status_code=400)
@@ -69,52 +131,90 @@ class SkillPackageService:
raise SkillPackageError("archive_too_large", "skill archive exceeds size limit", status_code=400)
try:
- archive = zipfile.ZipFile(io.BytesIO(content))
+ return zipfile.ZipFile(io.BytesIO(content))
except zipfile.BadZipFile as exc:
raise SkillPackageError("invalid_archive", "skill archive is not a valid zip", status_code=400) from exc
- with archive:
- infos = [info for info in archive.infolist() if not info.is_dir()]
- if len(infos) > _MAX_ENTRIES:
- raise SkillPackageError("too_many_entries", "skill archive has too many files", status_code=400)
-
- safe_paths: list[str] = []
- total_uncompressed = 0
- for info in infos:
- safe_paths.append(self._safe_member_path(info.filename))
- total_uncompressed += max(info.file_size, 0)
- if total_uncompressed > _MAX_UNCOMPRESSED_BYTES:
+ def _collect_file_members(self, archive: zipfile.ZipFile) -> list[tuple[zipfile.ZipInfo, str]]:
+ infos = [info for info in archive.infolist() if not info.is_dir()]
+ if len(infos) > _MAX_ENTRIES:
+ raise SkillPackageError("too_many_entries", "skill archive has too many files", status_code=400)
+
+ members: list[tuple[zipfile.ZipInfo, str]] = []
+ total_uncompressed = 0
+ for info in infos:
+ members.append((info, self._safe_member_path(info.filename)))
+ total_uncompressed += max(info.file_size, 0)
+ if total_uncompressed > _MAX_UNCOMPRESSED_BYTES:
+ raise SkillPackageError(
+ "archive_too_large",
+ "skill archive uncompressed size exceeds limit",
+ status_code=400,
+ )
+ return members
+
+ @staticmethod
+ def _skill_root_prefix(entry_path: str) -> str | None:
+ skill_root = posixpath.dirname(entry_path)
+ if not skill_root:
+ return None
+ return f"{skill_root}/"
+
+ def _normalize_members(
+ self,
+ *,
+ members: list[tuple[zipfile.ZipInfo, str]],
+ skill_root_prefix: str | None,
+ ignore_outside_selected_root: bool = False,
+ ) -> dict[str, zipfile.ZipInfo]:
+ normalized_members: dict[str, zipfile.ZipInfo] = {}
+ for info, safe_path in members:
+ if skill_root_prefix is not None:
+ if not safe_path.startswith(skill_root_prefix):
+ if ignore_outside_selected_root:
+ continue
+ raise SkillPackageError(
+ "files_outside_skill_root",
+ "skill archive contains files outside the selected skill root",
+ status_code=400,
+ )
+ normalized_path = safe_path.removeprefix(skill_root_prefix)
+ else:
+ normalized_path = safe_path
+
+ if (
+ not normalized_path
+ or normalized_path in {".", ".."}
+ or normalized_path.startswith("/")
+ or "\\" in normalized_path
+ ):
+ raise SkillPackageError("unsafe_path", "skill archive contains an unsafe path", status_code=400)
+ if normalized_path in normalized_members:
raise SkillPackageError(
- "archive_too_large", "skill archive uncompressed size exceeds limit", status_code=400
+ "duplicate_member_path",
+ "skill archive contains duplicate normalized paths",
+ status_code=400,
)
+ normalized_members[normalized_path] = info
- entry_path = self._find_skill_md(safe_paths)
- skill_md = self._read_skill_md(archive, entry_path)
-
- name, description = self._parse_skill_md(skill_md)
- return SkillManifest(
- name=name,
- description=description,
- entry_path=entry_path,
- files=sorted(safe_paths),
- size=total_uncompressed,
- hash=hashlib.sha256(content).hexdigest(),
- )
+ if _SKILL_MD_NAME not in normalized_members:
+ raise SkillPackageError("missing_skill_md", "skill archive must contain a SKILL.md", status_code=400)
+ return normalized_members
- def read_member_bytes(self, *, content: bytes, member_path: str) -> bytes:
- """Read a single archive member's bytes (used by standardization, ENG-594)."""
- try:
- archive = zipfile.ZipFile(io.BytesIO(content))
- except zipfile.BadZipFile as exc:
- raise SkillPackageError("invalid_archive", "skill archive is not a valid zip", status_code=400) from exc
- with archive:
- member = next(
- (info for info in archive.infolist() if posixpath.normpath(info.filename) == member_path),
- None,
- )
- if member is None:
- raise SkillPackageError("member_not_found", f"{member_path} not found in archive", status_code=400)
- return archive.read(member)
+ def _build_normalized_archive(
+ self,
+ *,
+ archive: zipfile.ZipFile,
+ normalized_members: dict[str, zipfile.ZipInfo],
+ ) -> bytes:
+ output = io.BytesIO()
+ with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_DEFLATED) as normalized_archive:
+ for normalized_path in sorted(normalized_members):
+ normalized_archive.writestr(
+ normalized_path,
+ self._read_member_bytes_from_archive(archive, member_info=normalized_members[normalized_path]),
+ )
+ return output.getvalue()
@staticmethod
def _check_extension(filename: str) -> None:
@@ -145,17 +245,26 @@ class SkillPackageService:
return min(candidates, key=lambda p: (p.count("/"), len(p)))
@staticmethod
- def _read_skill_md(archive: zipfile.ZipFile, entry_path: str) -> str:
- # Look the member up by its original name (normpath may differ from the stored name).
- member = next(
- (info for info in archive.infolist() if posixpath.normpath(info.filename) == entry_path),
- None,
- )
- if member is None:
- raise SkillPackageError("missing_skill_md", "skill archive must contain a SKILL.md", status_code=400)
- if member.file_size > _MAX_SKILL_MD_BYTES:
+ def _can_strip_single_top_level_folder(*, paths: list[str], entry_path: str) -> bool:
+ if entry_path.count("/") != 1:
+ return False
+ candidates = [path for path in paths if path.count("/") == 1 and posixpath.basename(path) == _SKILL_MD_NAME]
+ return len(candidates) == 1 and candidates[0] == entry_path
+
+ @staticmethod
+ def _read_member_bytes_from_archive(archive: zipfile.ZipFile, *, member_info: zipfile.ZipInfo) -> bytes:
+ try:
+ return archive.read(member_info)
+ except (zipfile.BadZipFile, EOFError, OSError, RuntimeError, ValueError, zlib.error) as exc:
+ raise SkillPackageError("invalid_archive", "skill archive is not a valid zip", status_code=400) from exc
+
+ @staticmethod
+ def _validate_skill_md_size(member_info: zipfile.ZipInfo) -> None:
+ if member_info.file_size > _MAX_SKILL_MD_BYTES:
raise SkillPackageError("skill_md_too_large", "SKILL.md exceeds size limit", status_code=400)
- raw = archive.read(member)
+
+ @staticmethod
+ def _decode_skill_md(raw: bytes) -> str:
try:
return raw.decode("utf-8")
except UnicodeDecodeError as exc:
@@ -193,4 +302,4 @@ class SkillPackageService:
return loaded if isinstance(loaded, dict) else {}
-__all__ = ["SkillManifest", "SkillPackageError", "SkillPackageService"]
+__all__ = ["NormalizedSkillPackage", "SkillManifest", "SkillPackageError", "SkillPackageService"]
diff --git a/api/services/agent/skill_standardize_service.py b/api/services/agent/skill_standardize_service.py
index 7e64d6f0422..cc2ba4b9bdc 100644
--- a/api/services/agent/skill_standardize_service.py
+++ b/api/services/agent/skill_standardize_service.py
@@ -7,19 +7,14 @@ to the agent drive (Agent Files §5.4 / §4):
* ``<slug>/.DIFY-SKILL-FULL.zip`` — the full archive, kept only to restore the
complete skill contents.
-Both are stored as ``ToolFile`` records and bound via ``AgentDriveService.commit``
-with ``value_owned_by_drive=True`` (the drive owns their lifecycle). The returned
-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.
+The archive's member list is stored in skill metadata and resolved lazily for
+inspect/preview/runtime. Upload must not eagerly materialize every archive member
+as a separate ToolFile; small archives with many files would otherwise perform
+hundreds of storage writes and DB commits inside the request.
"""
from __future__ import annotations
-import mimetypes
-import posixpath
import re
from typing import Any
@@ -38,7 +33,11 @@ def slugify_skill_name(name: str) -> str:
class SkillStandardizeService:
- """Validate + standardize a Skill package into a per-agent drive upload result."""
+ """Persist a normalized skill package into drive-owned files for one agent.
+
+ Instances are intentionally stateful: ``standardize()`` updates
+ ``last_committed_items`` with the drive commit result for the most recent call.
+ """
def __init__(
self,
@@ -50,6 +49,7 @@ class SkillStandardizeService:
self._package = package_service or SkillPackageService()
self._drive = drive_service or AgentDriveService()
self._tool_files = tool_file_manager or ToolFileManager()
+ self.last_committed_items: list[dict[str, Any]] = []
def standardize(
self,
@@ -60,17 +60,23 @@ class SkillStandardizeService:
user_id: str,
agent_id: str,
) -> dict[str, Any]:
- manifest = self._package.validate_and_extract(content=content, filename=filename)
- skill_md_bytes = self._package.read_member_bytes(content=content, member_path=manifest.entry_path)
+ """Create two ToolFiles, commit two drive-owned keys, and return skill metadata.
+
+ This writes ``<slug>/SKILL.md`` and ``<slug>/.DIFY-SKILL-FULL.zip``,
+ stores the drive commit rows in ``last_committed_items``, and returns the
+ console response shape ``{"skill": ..., "manifest": ...}``.
+ """
+ package = self._package.validate_and_normalize(content=content, filename=filename)
+ manifest = package.manifest
slug = slugify_skill_name(manifest.name)
- # Drive-owned files: canonical SKILL.md, every inspectable archive file,
- # and the full archive for future restore/export.
+ # Drive-owned files: canonical SKILL.md and the full archive. The
+ # archive member tree is preserved in metadata and resolved lazily.
md_tool_file = self._tool_files.create_file_by_raw(
user_id=user_id,
tenant_id=tenant_id,
conversation_id=None,
- file_binary=skill_md_bytes,
+ file_binary=package.skill_md_bytes,
mimetype="text/markdown",
filename=_SKILL_MD_NAME,
)
@@ -78,38 +84,14 @@ class SkillStandardizeService:
user_id=user_id,
tenant_id=tenant_id,
conversation_id=None,
- file_binary=content,
+ file_binary=package.archive_bytes,
mimetype="application/zip",
filename=_FULL_ARCHIVE_NAME,
)
skill_md_key = f"{slug}/{_SKILL_MD_NAME}"
archive_key = f"{slug}/{_FULL_ARCHIVE_NAME}"
- member_items: list[DriveCommitItem] = []
- for member_path in sorted(set(manifest.files)):
- member_key = f"{slug}/{member_path}"
- if member_key in {skill_md_key, archive_key}:
- continue
-
- member_bytes = self._package.read_member_bytes(content=content, member_path=member_path)
- mimetype = mimetypes.guess_type(member_path)[0] or "application/octet-stream"
- member_tool_file = self._tool_files.create_file_by_raw(
- user_id=user_id,
- tenant_id=tenant_id,
- conversation_id=None,
- file_binary=member_bytes,
- mimetype=mimetype,
- filename=posixpath.basename(member_path),
- )
- member_items.append(
- DriveCommitItem(
- key=member_key,
- file_ref=DriveFileRef(kind="tool_file", id=member_tool_file.id),
- value_owned_by_drive=True,
- )
- )
-
- self._drive.commit(
+ committed_items = self._drive.commit(
tenant_id=tenant_id,
user_id=user_id,
agent_id=agent_id,
@@ -130,23 +112,17 @@ class SkillStandardizeService:
file_ref=DriveFileRef(kind="tool_file", id=archive_tool_file.id),
value_owned_by_drive=True,
),
- *member_items,
],
)
-
- 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
- )
+ self.last_committed_items = committed_items
return {
"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"],
+ "name": manifest.name,
+ "description": manifest.description,
+ "path": slug,
+ "skill_md_key": skill_md_key,
+ "archive_key": archive_key,
},
"manifest": manifest.model_dump(),
}
diff --git a/api/services/agent/workflow_publish_service.py b/api/services/agent/workflow_publish_service.py
index eb3766996bf..fb20c5c4dac 100644
--- a/api/services/agent/workflow_publish_service.py
+++ b/api/services/agent/workflow_publish_service.py
@@ -18,9 +18,18 @@ from models.agent import (
WorkflowAgentBindingType,
WorkflowAgentNodeBinding,
)
-from models.agent_config_entities import AgentSoulConfig, DeclaredOutputConfig, WorkflowNodeJobConfig
+from models.agent_config_entities import (
+ AgentSoulConfig,
+ DeclaredOutputConfig,
+ WorkflowNodeJobConfig,
+ WorkflowPreviousNodeOutputRef,
+)
from models.workflow import Workflow
from services.agent.composer_validator import ComposerConfigValidator
+from services.agent.prompt_mentions import (
+ extract_workflow_node_output_selectors,
+ workflow_previous_node_output_refs_from_selectors,
+)
from services.entities.agent_entities import (
ComposerSavePayload,
ComposerSaveStrategy,
@@ -39,10 +48,10 @@ class WorkflowAgentPublishService:
@classmethod
def project_draft_bindings_to_graph(cls, *, session: Session, draft_workflow: Workflow) -> dict[str, Any]:
- """Return draft graph with persisted Agent node job config projected into node data.
+ """Return draft graph with persisted Agent binding fields projected into node data.
Workflow draft graph is the front-end's editing source of truth, while
- runtime/publish reads WorkflowAgentNodeBinding.node_job_config. This
+ runtime/publish reads WorkflowAgentNodeBinding. This
response-only projection keeps reads aligned without writing binding
details back into the stored graph JSON.
"""
@@ -64,6 +73,18 @@ class WorkflowAgentPublishService:
node_data = agent_nodes.get(binding.node_id)
if not isinstance(node_data, dict):
continue
+ graph_binding = node_data.get(cls._AGENT_BINDING_KEY)
+ is_pending_inline_graph_binding = (
+ isinstance(graph_binding, Mapping)
+ and graph_binding.get("binding_type") == WorkflowAgentBindingType.INLINE_AGENT.value
+ and (not graph_binding.get("agent_id") or not graph_binding.get("current_snapshot_id"))
+ )
+ if not is_pending_inline_graph_binding or binding.binding_type == WorkflowAgentBindingType.INLINE_AGENT:
+ node_data[cls._AGENT_BINDING_KEY] = {
+ "binding_type": binding.binding_type.value,
+ "agent_id": binding.agent_id,
+ "current_snapshot_id": binding.current_snapshot_id,
+ }
node_job = WorkflowNodeJobConfig.model_validate(binding.node_job_config_dict)
if node_job.workflow_prompt is not None:
node_data[cls._AGENT_TASK_KEY] = node_job.workflow_prompt
@@ -231,6 +252,10 @@ class WorkflowAgentPublishService:
continue
if not isinstance(binding_payload, Mapping):
raise ValueError(f"Workflow Agent node {node_id} has invalid agent_binding.")
+ if binding_payload.get("binding_type") == WorkflowAgentBindingType.INLINE_AGENT.value and (
+ not binding_payload.get("agent_id") or not binding_payload.get("current_snapshot_id")
+ ):
+ continue
cls._sync_agent_binding_for_node(
session=session,
draft_workflow=draft_workflow,
@@ -409,6 +434,7 @@ class WorkflowAgentPublishService:
agent_task = node_data.get(cls._AGENT_TASK_KEY)
if isinstance(agent_task, str):
node_job.workflow_prompt = agent_task
+ node_job.previous_node_output_refs = cls._previous_node_output_refs_from_prompt(agent_task)
declared_outputs_payload = node_data.get(cls._AGENT_DECLARED_OUTPUTS_KEY)
if declared_outputs_payload is not None:
@@ -423,6 +449,11 @@ class WorkflowAgentPublishService:
return node_job
+ @classmethod
+ def _previous_node_output_refs_from_prompt(cls, prompt: str) -> list[WorkflowPreviousNodeOutputRef]:
+ """Derive persisted refs from the current frontend workflow markers only."""
+ return workflow_previous_node_output_refs_from_selectors(extract_workflow_node_output_selectors(prompt))
+
@classmethod
def copy_agent_node_bindings_to_published(
cls,
diff --git a/api/services/agent_drive_service.py b/api/services/agent_drive_service.py
index c20b3f570a3..d79aa1abe9c 100644
--- a/api/services/agent_drive_service.py
+++ b/api/services/agent_drive_service.py
@@ -19,10 +19,18 @@ ToolFile records (see ``AgentDriveFile``). This service is the control plane:
from __future__ import annotations
+import base64
+import hashlib
+import hmac
+import io
import json
import logging
+import mimetypes
+import os
import re
+import time
import urllib.parse
+import zipfile
from typing import Any, Literal, TypedDict
from urllib.parse import unquote
@@ -31,6 +39,7 @@ from sqlalchemy import func, select
from sqlalchemy.exc import DataError, SQLAlchemyError
from sqlalchemy.orm import Session
+from configs import dify_config
from core.app.file_access.controller import DatabaseFileAccessController
from core.db.session_factory import session_factory
from extensions.ext_storage import storage
@@ -46,6 +55,7 @@ _MAX_KEY_LENGTH = 512
_DRIVE_REF_PREFIX = "agent-"
_SKILL_MD_SUFFIX = "/SKILL.md"
_SKILL_ARCHIVE_NAME = ".DIFY-SKILL-FULL.zip"
+_ARCHIVE_MEMBER_DOWNLOAD_PURPOSE = "agent-drive-archive-member"
class AgentDriveError(Exception):
@@ -365,6 +375,7 @@ class AgentDriveService:
skill_md_key=skill_md_key,
manifest_files=manifest_files,
drive_keys=drive_keys,
+ archive_available=catalog["archive_key"] in drive_keys if catalog["archive_key"] else False,
)
return {
**catalog,
@@ -598,6 +609,7 @@ class AgentDriveService:
skill_md_key: str,
manifest_files: list[str] | None,
drive_keys: set[str],
+ archive_available: bool = False,
) -> tuple[list[AgentDriveSkillFileInfo], list[str]]:
warnings: list[str] = []
if manifest_files:
@@ -617,13 +629,14 @@ class AgentDriveService:
if path == _SKILL_ARCHIVE_NAME:
continue
drive_key = f"{skill_path}/{path}"
+ available_in_drive = drive_key in drive_keys or (archive_available and path != _SKILL_ARCHIVE_NAME)
files.append(
{
"path": path,
"name": path.rsplit("/", 1)[-1],
"type": "file",
- "drive_key": drive_key if drive_key in drive_keys else None,
- "available_in_drive": drive_key in drive_keys,
+ "drive_key": drive_key if available_in_drive else None,
+ "available_in_drive": available_in_drive,
}
)
if "SKILL.md" not in {file["path"] for file in files}:
@@ -844,56 +857,209 @@ class AgentDriveService:
return row
def _storage_key_for_row(self, session: Session, *, tenant_id: str, row: AgentDriveFile) -> str:
- if row.file_kind == AgentDriveFileKind.TOOL_FILE:
- tool_file = session.scalar(
- select(ToolFile).where(ToolFile.id == row.file_id, ToolFile.tenant_id == tenant_id)
- )
+ return self._storage_key_for_ref(
+ session,
+ tenant_id=tenant_id,
+ file_kind=row.file_kind,
+ file_id=row.file_id,
+ )
+
+ def _storage_key_for_ref(
+ self,
+ session: Session,
+ *,
+ tenant_id: str,
+ file_kind: AgentDriveFileKind,
+ file_id: str,
+ ) -> str:
+ if file_kind == AgentDriveFileKind.TOOL_FILE:
+ tool_file = session.scalar(select(ToolFile).where(ToolFile.id == file_id, ToolFile.tenant_id == tenant_id))
if tool_file is None:
raise AgentDriveError("drive_key_not_found", "drive value record is missing", status_code=404)
return tool_file.file_key
upload_file = session.scalar(
- select(UploadFile).where(UploadFile.id == row.file_id, UploadFile.tenant_id == tenant_id)
+ select(UploadFile).where(UploadFile.id == file_id, UploadFile.tenant_id == tenant_id)
)
if upload_file is None:
raise AgentDriveError("drive_key_not_found", "drive value record is missing", status_code=404)
return upload_file.key
- def preview(self, *, tenant_id: str, agent_id: str, key: str) -> dict[str, Any]:
- """Truncated text preview of one drive value (binary-safe, never 500s on size)."""
+ def _archive_member_for_key(
+ self,
+ session: Session,
+ *,
+ tenant_id: str,
+ agent_id: str,
+ key: str,
+ ) -> tuple[AgentDriveFile, str]:
+ normalized_key = normalize_drive_key(key)
+ if "/" not in normalized_key:
+ raise AgentDriveError("drive_key_not_found", "no drive entry for this key", status_code=404)
+ skill_path, member_path = normalized_key.split("/", 1)
+ if member_path in {_SKILL_ARCHIVE_NAME, ""}:
+ raise AgentDriveError("drive_key_not_found", "no archive member for this key", status_code=404)
+
+ skill_md_key = f"{skill_path}{_SKILL_MD_SUFFIX}"
+ skill_row = session.scalar(
+ select(AgentDriveFile).where(
+ AgentDriveFile.tenant_id == tenant_id,
+ AgentDriveFile.agent_id == agent_id,
+ AgentDriveFile.key == skill_md_key,
+ AgentDriveFile.is_skill.is_(True),
+ )
+ )
+ if skill_row is None:
+ raise AgentDriveError("drive_key_not_found", "no drive entry for this key", status_code=404)
+ metadata = self._parse_skill_metadata(skill_row.key, skill_row.skill_metadata)
+ manifest_files = {normalize_drive_key(path) for path in (metadata.manifest_files or [])}
+ if member_path not in manifest_files:
+ raise AgentDriveError("drive_key_not_found", "archive member is not part of this skill", status_code=404)
+ archive_row = session.scalar(
+ select(AgentDriveFile).where(
+ AgentDriveFile.tenant_id == tenant_id,
+ AgentDriveFile.agent_id == agent_id,
+ AgentDriveFile.key == self._skill_archive_key(skill_md_key),
+ )
+ )
+ if archive_row is None:
+ raise AgentDriveError("drive_key_not_found", "skill archive is missing", status_code=404)
+ return archive_row, member_path
+
+ def _load_archive_member_bytes(
+ self,
+ *,
+ tenant_id: str,
+ archive_file_kind: AgentDriveFileKind,
+ archive_file_id: str,
+ member_path: str,
+ ) -> bytes:
+ member_path = normalize_drive_key(member_path)
with session_factory.create_session() as session:
- self._assert_agent_belongs_to_tenant(session, tenant_id=tenant_id, agent_id=agent_id)
- row = self._require_row(session, tenant_id=tenant_id, agent_id=agent_id, key=key)
- storage_key = self._storage_key_for_row(session, tenant_id=tenant_id, row=row)
- size = row.size
+ storage_key = self._storage_key_for_ref(
+ session,
+ tenant_id=tenant_id,
+ file_kind=archive_file_kind,
+ file_id=archive_file_id,
+ )
+ archive_bytes = b"".join(storage.load_stream(storage_key))
+ try:
+ with zipfile.ZipFile(io.BytesIO(archive_bytes)) as archive:
+ member = next(
+ (
+ info
+ for info in archive.infolist()
+ if not info.is_dir() and normalize_drive_key(info.filename) == member_path
+ ),
+ None,
+ )
+ if member is None:
+ raise AgentDriveError(
+ "drive_key_not_found", "archive member is missing from the skill archive", status_code=404
+ )
+ return archive.read(member)
+ except zipfile.BadZipFile as exc:
+ raise AgentDriveError("invalid_skill_archive", "skill archive is not a valid zip", status_code=500) from exc
- data = bytearray()
- for chunk in storage.load_stream(storage_key):
- data.extend(chunk)
- if len(data) > self.PREVIEW_MAX_BYTES:
- break
- truncated = len(data) > self.PREVIEW_MAX_BYTES
- sample = bytes(data[: self.PREVIEW_MAX_BYTES])
- # Same semantics as the sandbox read endpoint: NUL or undecodable -> binary.
+ @classmethod
+ def _preview_bytes(cls, *, key: str, size: int | None, payload: bytes) -> dict[str, Any]:
+ truncated = len(payload) > cls.PREVIEW_MAX_BYTES
+ sample = payload[: cls.PREVIEW_MAX_BYTES]
if b"\x00" in sample:
- return {"key": row.key, "size": size, "truncated": truncated, "binary": True, "text": None}
+ return {"key": key, "size": size, "truncated": truncated, "binary": True, "text": None}
try:
text = sample.decode("utf-8")
except UnicodeDecodeError:
if truncated:
- # A multi-byte char may sit on the cut point; retry without the tail.
try:
text = sample[:-3].decode("utf-8", errors="strict")
except UnicodeDecodeError:
- return {"key": row.key, "size": size, "truncated": truncated, "binary": True, "text": None}
+ return {"key": key, "size": size, "truncated": truncated, "binary": True, "text": None}
else:
- return {"key": row.key, "size": size, "truncated": truncated, "binary": True, "text": None}
- return {"key": row.key, "size": size, "truncated": truncated, "binary": False, "text": text}
+ return {"key": key, "size": size, "truncated": truncated, "binary": True, "text": None}
+ return {"key": key, "size": size, "truncated": truncated, "binary": False, "text": text}
+
+ def preview(self, *, tenant_id: str, agent_id: str, key: str) -> dict[str, Any]:
+ """Truncated text preview of one drive value (binary-safe, never 500s on size)."""
+ with session_factory.create_session() as session:
+ self._assert_agent_belongs_to_tenant(session, tenant_id=tenant_id, agent_id=agent_id)
+ try:
+ row = self._require_row(session, tenant_id=tenant_id, agent_id=agent_id, key=key)
+ storage_key = self._storage_key_for_row(session, tenant_id=tenant_id, row=row)
+ size = row.size
+ response_key = row.key
+ archive_ref: tuple[AgentDriveFile, str] | None = None
+ except AgentDriveError:
+ archive_ref = self._archive_member_for_key(
+ session,
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ key=key,
+ )
+ storage_key = None
+ size = None
+ response_key = normalize_drive_key(key)
+
+ if archive_ref is not None:
+ archive_row, member_path = archive_ref
+ payload = self._load_archive_member_bytes(
+ tenant_id=tenant_id,
+ archive_file_kind=archive_row.file_kind,
+ archive_file_id=archive_row.file_id,
+ member_path=member_path,
+ )
+ return self._preview_bytes(key=response_key, size=len(payload), payload=payload)
+
+ data = bytearray()
+ assert storage_key is not None
+ for chunk in storage.load_stream(storage_key):
+ data.extend(chunk)
+ if len(data) > self.PREVIEW_MAX_BYTES:
+ break
+ return self._preview_bytes(key=response_key, size=size, payload=bytes(data))
+
+ def preview_archive_member_for_ref(
+ self,
+ *,
+ tenant_id: str,
+ agent_id: str,
+ key: str,
+ archive_file_kind: AgentDriveFileKind,
+ archive_file_id: str,
+ member_path: str,
+ ) -> dict[str, Any]:
+ with session_factory.create_session() as session:
+ self._assert_agent_belongs_to_tenant(session, tenant_id=tenant_id, agent_id=agent_id)
+ payload = self._load_archive_member_bytes(
+ tenant_id=tenant_id,
+ archive_file_kind=archive_file_kind,
+ archive_file_id=archive_file_id,
+ member_path=member_path,
+ )
+ return self._preview_bytes(key=normalize_drive_key(key), size=len(payload), payload=payload)
def download_url(self, *, tenant_id: str, agent_id: str, key: str) -> str:
"""External signed URL for a browser download of one drive value."""
with session_factory.create_session() as session:
self._assert_agent_belongs_to_tenant(session, tenant_id=tenant_id, agent_id=agent_id)
- row = self._require_row(session, tenant_id=tenant_id, agent_id=agent_id, key=key)
+ try:
+ row = self._require_row(session, tenant_id=tenant_id, agent_id=agent_id, key=key)
+ except AgentDriveError:
+ archive_row, member_path = self._archive_member_for_key(
+ session,
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ key=key,
+ )
+ return self.sign_archive_member_url(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ key=key,
+ archive_file_kind=archive_row.file_kind,
+ archive_file_id=archive_row.file_id,
+ member_path=member_path,
+ for_external=True,
+ as_attachment=True,
+ )
url = self._resolve_download_url(
tenant_id=tenant_id,
file_kind=row.file_kind,
@@ -905,6 +1071,159 @@ class AgentDriveService:
raise AgentDriveError("drive_key_not_found", "drive value cannot be resolved", status_code=404)
return url
+ def download_url_archive_member_for_ref(
+ self,
+ *,
+ tenant_id: str,
+ agent_id: str,
+ key: str,
+ archive_file_kind: AgentDriveFileKind,
+ archive_file_id: str,
+ member_path: str,
+ for_external: bool = True,
+ ) -> str:
+ with session_factory.create_session() as session:
+ self._assert_agent_belongs_to_tenant(session, tenant_id=tenant_id, agent_id=agent_id)
+ return self.sign_archive_member_url(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ key=key,
+ archive_file_kind=archive_file_kind,
+ archive_file_id=archive_file_id,
+ member_path=member_path,
+ for_external=for_external,
+ as_attachment=True,
+ )
+
+ @staticmethod
+ def _secret_key() -> bytes:
+ return dify_config.SECRET_KEY.encode()
+
+ @classmethod
+ def _archive_member_signature_payload(
+ cls,
+ *,
+ tenant_id: str,
+ agent_id: str,
+ key: str,
+ archive_file_kind: AgentDriveFileKind,
+ archive_file_id: str,
+ member_path: str,
+ timestamp: str,
+ nonce: str,
+ ) -> str:
+ return "|".join(
+ [
+ _ARCHIVE_MEMBER_DOWNLOAD_PURPOSE,
+ tenant_id,
+ agent_id,
+ normalize_drive_key(key),
+ archive_file_kind.value,
+ archive_file_id,
+ normalize_drive_key(member_path),
+ timestamp,
+ nonce,
+ ]
+ )
+
+ @classmethod
+ def _sign_archive_member_payload(cls, payload: str) -> str:
+ digest = hmac.new(cls._secret_key(), payload.encode(), hashlib.sha256).digest()
+ return base64.urlsafe_b64encode(digest).decode()
+
+ @classmethod
+ def sign_archive_member_url(
+ cls,
+ *,
+ tenant_id: str,
+ agent_id: str,
+ key: str,
+ archive_file_kind: AgentDriveFileKind,
+ archive_file_id: str,
+ member_path: str,
+ for_external: bool,
+ as_attachment: bool = False,
+ ) -> str:
+ base_url = dify_config.FILES_URL if for_external else (dify_config.INTERNAL_FILES_URL or dify_config.FILES_URL)
+ timestamp = str(int(time.time()))
+ nonce = os.urandom(16).hex()
+ payload = cls._archive_member_signature_payload(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ key=key,
+ archive_file_kind=archive_file_kind,
+ archive_file_id=archive_file_id,
+ member_path=member_path,
+ timestamp=timestamp,
+ nonce=nonce,
+ )
+ query = urllib.parse.urlencode(
+ {
+ "tenant_id": tenant_id,
+ "agent_id": agent_id,
+ "key": normalize_drive_key(key),
+ "archive_file_kind": archive_file_kind.value,
+ "archive_file_id": archive_file_id,
+ "member_path": normalize_drive_key(member_path),
+ "timestamp": timestamp,
+ "nonce": nonce,
+ "sign": cls._sign_archive_member_payload(payload),
+ "as_attachment": str(as_attachment).lower(),
+ }
+ )
+ return f"{base_url}/files/agent-drive/archive-member?{query}"
+
+ @classmethod
+ def verify_archive_member_signature(
+ cls,
+ *,
+ tenant_id: str,
+ agent_id: str,
+ key: str,
+ archive_file_kind: AgentDriveFileKind,
+ archive_file_id: str,
+ member_path: str,
+ timestamp: str,
+ nonce: str,
+ sign: str,
+ ) -> bool:
+ payload = cls._archive_member_signature_payload(
+ tenant_id=tenant_id,
+ agent_id=agent_id,
+ key=key,
+ archive_file_kind=archive_file_kind,
+ archive_file_id=archive_file_id,
+ member_path=member_path,
+ timestamp=timestamp,
+ nonce=nonce,
+ )
+ if sign != cls._sign_archive_member_payload(payload):
+ return False
+ current_time = int(time.time())
+ return current_time - int(timestamp) <= dify_config.FILES_ACCESS_TIMEOUT
+
+ def load_archive_member_for_signed_request(
+ self,
+ *,
+ tenant_id: str,
+ agent_id: str,
+ key: str,
+ archive_file_kind: AgentDriveFileKind,
+ archive_file_id: str,
+ member_path: str,
+ ) -> tuple[bytes, str, str]:
+ with session_factory.create_session() as session:
+ self._assert_agent_belongs_to_tenant(session, tenant_id=tenant_id, agent_id=agent_id)
+ payload = self._load_archive_member_bytes(
+ tenant_id=tenant_id,
+ archive_file_kind=archive_file_kind,
+ archive_file_id=archive_file_id,
+ member_path=member_path,
+ )
+ mime_type = mimetypes.guess_type(member_path)[0] or "application/octet-stream"
+ filename = normalize_drive_key(key).rsplit("/", 1)[-1]
+ return payload, mime_type, filename
+
__all__ = [
"AgentDriveError",
diff --git a/api/services/app_service.py b/api/services/app_service.py
index 941855b8321..bd0e3fd08e0 100644
--- a/api/services/app_service.py
+++ b/api/services/app_service.py
@@ -96,6 +96,17 @@ class AppService:
filters.append(App.mode == AppMode.AGENT_CHAT)
elif params.mode == "agent":
filters.append(App.mode == AppMode.AGENT)
+ filters.append(
+ sa.exists()
+ .where(
+ Agent.tenant_id == tenant_id,
+ Agent.app_id == App.id,
+ Agent.scope == AgentScope.ROSTER,
+ Agent.source == AgentSource.AGENT_APP,
+ Agent.status == AgentStatus.ACTIVE,
+ )
+ .correlate(App)
+ )
elif params.mode == "all":
filters.append(App.mode != AppMode.AGENT)
diff --git a/api/services/entities/agent_entities.py b/api/services/entities/agent_entities.py
index a8634bceb09..3184455d0a4 100644
--- a/api/services/entities/agent_entities.py
+++ b/api/services/entities/agent_entities.py
@@ -31,6 +31,10 @@ class ComposerSoulLockPayload(BaseModel):
unlocked_from_version_id: str | None = None
+class WorkflowAgentComposerQuery(BaseModel):
+ snapshot_id: str | None = Field(default=None, max_length=255)
+
+
class ComposerSavePayload(BaseModel):
variant: ComposerVariant
binding: ComposerBindingPayload | None = None
diff --git a/api/services/entities/knowledge_retrieval_inner.py b/api/services/entities/knowledge_retrieval_inner.py
index 86276b80177..aaf686da44c 100644
--- a/api/services/entities/knowledge_retrieval_inner.py
+++ b/api/services/entities/knowledge_retrieval_inner.py
@@ -173,14 +173,6 @@ class InnerKnowledgeRetrieveRequest(BaseModel):
class InnerKnowledgeRetrieveUsage(ResponseModel):
"""Serialized LLM usage payload returned by dataset retrieval."""
- model_config = ConfigDict(
- from_attributes=True,
- extra="forbid",
- populate_by_name=True,
- serialize_by_alias=True,
- protected_namespaces=(),
- )
-
prompt_tokens: int
completion_tokens: int
total_tokens: int
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.py
index c91d0fd3e8a..274ab737328 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
@@ -109,7 +109,9 @@ def test_request_builder_separates_agent_soul_and_workflow_job_prompt():
dumped = request.model_dump(mode="json")
assert dumped["composition"]["layers"][0]["config"]["prefix"] == "You are a careful reviewer."
- assert dumped["composition"]["layers"][1]["config"]["prefix"] == "Review the previous node output."
+ workflow_job_config = dumped["composition"]["layers"][1]["config"]
+ assert workflow_job_config["user"] == "Review the previous node output."
+ assert not workflow_job_config.get("prefix")
assert dumped["composition"]["layers"][2]["config"]["user"] == "Summarize the report."
@@ -162,8 +164,15 @@ def test_request_builder_adds_knowledge_layer_when_configured():
run_input = _run_input()
run_input.knowledge = DifyKnowledgeBaseLayerConfig.model_validate(
{
- "dataset_ids": ["dataset-1"],
- "retrieval": {"mode": "multiple", "top_k": 4},
+ "sets": [
+ {
+ "id": "support",
+ "name": "Support KB",
+ "datasets": [{"id": "dataset-1"}],
+ "query": {"mode": "generated_query"},
+ "retrieval": {"mode": "multiple", "top_k": 4},
+ }
+ ],
}
)
@@ -174,7 +183,7 @@ def test_request_builder_adds_knowledge_layer_when_configured():
assert layers[DIFY_KNOWLEDGE_BASE_LAYER_ID].type == DIFY_KNOWLEDGE_BASE_LAYER_TYPE_ID
assert layers[DIFY_KNOWLEDGE_BASE_LAYER_ID].deps == {"execution_context": DIFY_EXECUTION_CONTEXT_LAYER_ID}
knowledge_config = cast(DifyKnowledgeBaseLayerConfig, layers[DIFY_KNOWLEDGE_BASE_LAYER_ID].config)
- assert knowledge_config.dataset_ids == ["dataset-1"]
+ assert knowledge_config.sets[0].dataset_ids == ["dataset-1"]
def test_request_builder_can_delete_on_exit_for_cleanup_paths():
@@ -332,7 +341,7 @@ 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():
+def test_workflow_request_builder_binds_drive_to_shell_when_configured():
run_input = _run_input()
run_input.include_shell = True
run_input.drive_config = DifyDriveLayerConfig(drive_ref="agent-agent-1")
@@ -341,11 +350,11 @@ def test_workflow_request_builder_binds_shell_to_drive_when_configured():
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)
+ assert layers[DIFY_SHELL_LAYER_ID].deps == {"execution_context": DIFY_EXECUTION_CONTEXT_LAYER_ID}
+ shell_config = cast(DifyShellLayerConfig, layers[DIFY_SHELL_LAYER_ID].config)
+ assert shell_config.agent_stub_drive_ref == "agent-agent-1"
+ assert layers[DIFY_DRIVE_LAYER_ID].deps == {"shell": DIFY_SHELL_LAYER_ID}
+ assert layer_names.index(DIFY_SHELL_LAYER_ID) < layer_names.index(DIFY_DRIVE_LAYER_ID)
def test_agent_app_request_builder_omits_shell_layer_by_default():
@@ -367,7 +376,7 @@ 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():
+def test_agent_app_request_builder_binds_drive_to_shell_when_configured():
run_input = _agent_app_input(include_shell=True)
run_input.drive_config = DifyDriveLayerConfig(drive_ref="agent-agent-1")
@@ -375,19 +384,26 @@ def test_agent_app_request_builder_binds_shell_to_drive_when_configured():
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)
+ assert layers[DIFY_SHELL_LAYER_ID].deps == {"execution_context": DIFY_EXECUTION_CONTEXT_LAYER_ID}
+ shell_config = cast(DifyShellLayerConfig, layers[DIFY_SHELL_LAYER_ID].config)
+ assert shell_config.agent_stub_drive_ref == "agent-agent-1"
+ assert layers[DIFY_DRIVE_LAYER_ID].deps == {"shell": DIFY_SHELL_LAYER_ID}
+ assert layer_names.index(DIFY_SHELL_LAYER_ID) < layer_names.index(DIFY_DRIVE_LAYER_ID)
def test_agent_app_request_builder_adds_knowledge_layer_when_configured():
run_input = _agent_app_input()
run_input.knowledge = DifyKnowledgeBaseLayerConfig.model_validate(
{
- "dataset_ids": ["dataset-1", "dataset-2"],
- "retrieval": {"mode": "multiple", "top_k": 2},
+ "sets": [
+ {
+ "id": "support",
+ "name": "Support KB",
+ "datasets": [{"id": "dataset-1"}, {"id": "dataset-2"}],
+ "query": {"mode": "generated_query"},
+ "retrieval": {"mode": "multiple", "top_k": 2},
+ }
+ ],
}
)
@@ -398,7 +414,7 @@ def test_agent_app_request_builder_adds_knowledge_layer_when_configured():
assert layers[DIFY_KNOWLEDGE_BASE_LAYER_ID].type == DIFY_KNOWLEDGE_BASE_LAYER_TYPE_ID
assert layers[DIFY_KNOWLEDGE_BASE_LAYER_ID].deps == {"execution_context": DIFY_EXECUTION_CONTEXT_LAYER_ID}
knowledge_config = cast(DifyKnowledgeBaseLayerConfig, layers[DIFY_KNOWLEDGE_BASE_LAYER_ID].config)
- assert knowledge_config.dataset_ids == ["dataset-1", "dataset-2"]
+ assert knowledge_config.sets[0].dataset_ids == ["dataset-1", "dataset-2"]
# ── ENG-635 / ENG-638: ask_human layer injection + deferred_tool_results ─────
diff --git a/api/tests/unit_tests/commands/test_generate_swagger_specs.py b/api/tests/unit_tests/commands/test_generate_swagger_specs.py
index c30386c9d65..403fb0e94a4 100644
--- a/api/tests/unit_tests/commands/test_generate_swagger_specs.py
+++ b/api/tests/unit_tests/commands/test_generate_swagger_specs.py
@@ -149,3 +149,55 @@ def test_generate_specs_is_idempotent(tmp_path):
assert [path.name for path in first_paths] == [path.name for path in second_paths]
for first_path, second_path in zip(first_paths, second_paths):
assert first_path.read_text(encoding="utf-8") == second_path.read_text(encoding="utf-8")
+
+
+def test_generate_specs_include_agent_v2_knowledge_set_schema_and_query_enums(tmp_path):
+ module = _load_generate_swagger_specs_module()
+
+ written_paths = module.generate_specs(tmp_path)
+ console_path = next(path for path in written_paths if path.name == "console-openapi.json")
+ payload = json.loads(console_path.read_text(encoding="utf-8"))
+ schemas = payload["components"]["schemas"]
+
+ assert "AgentKnowledgeSetConfig" in schemas
+ assert schemas["AgentSoulKnowledgeConfig"]["properties"]["sets"]["items"]["$ref"] == (
+ "#/components/schemas/AgentKnowledgeSetConfig"
+ )
+ assert schemas["AgentKnowledgeQueryMode"]["enum"] == ["generated_query", "user_query"]
+
+
+def test_checked_in_agent_v2_knowledge_openapi_and_generated_contracts_are_in_sync():
+ api_dir = Path(__file__).resolve().parents[3]
+ repo_root = api_dir.parent
+
+ markdown = (api_dir / "openapi" / "markdown" / "console-openapi.md").read_text(encoding="utf-8")
+ agent_types = (
+ repo_root / "packages" / "contracts" / "generated" / "api" / "console" / "agent" / "types.gen.ts"
+ ).read_text(encoding="utf-8")
+ apps_types = (
+ repo_root / "packages" / "contracts" / "generated" / "api" / "console" / "apps" / "types.gen.ts"
+ ).read_text(encoding="utf-8")
+ agent_zod = (
+ repo_root / "packages" / "contracts" / "generated" / "api" / "console" / "agent" / "zod.gen.ts"
+ ).read_text(encoding="utf-8")
+ apps_zod = (
+ repo_root / "packages" / "contracts" / "generated" / "api" / "console" / "apps" / "zod.gen.ts"
+ ).read_text(encoding="utf-8")
+
+ assert "#### AgentKnowledgeSetConfig" in markdown
+ assert "#### AgentSoulKnowledgeConfig" in markdown
+ assert "#### AgentKnowledgeQueryMode" in markdown
+
+ for content in (agent_types, apps_types):
+ assert "export type AgentKnowledgeSetConfig = {" in content
+ assert "export type AgentSoulKnowledgeConfig = {" in content
+ assert "AgentKnowledgeQueryMode" in content
+ assert "generated_query" in content
+ assert "user_query" in content
+
+ for content in (agent_zod, apps_zod):
+ assert "export const zAgentKnowledgeSetConfig = z.object({" in content
+ assert "export const zAgentSoulKnowledgeConfig = z.object({" in content
+ assert "zAgentKnowledgeQueryMode = z.enum([" in content
+ assert "generated_query" in content
+ assert "user_query" in content
diff --git a/api/tests/unit_tests/controllers/console/agent/test_agent_controllers.py b/api/tests/unit_tests/controllers/console/agent/test_agent_controllers.py
index 3d84f899379..847f60c2570 100644
--- a/api/tests/unit_tests/controllers/console/agent/test_agent_controllers.py
+++ b/api/tests/unit_tests/controllers/console/agent/test_agent_controllers.py
@@ -28,11 +28,15 @@ from controllers.console.agent.roster import (
AgentAppApi,
AgentAppCopyApi,
AgentAppListApi,
+ AgentBuildDraftApi,
+ AgentBuildDraftApplyApi,
+ AgentBuildDraftCheckoutApi,
AgentDebugConversationRefreshApi,
AgentInviteOptionsApi,
AgentLogMessagesApi,
AgentLogsApi,
AgentLogSourcesApi,
+ AgentPublishApi,
AgentRosterVersionDetailApi,
AgentRosterVersionRestoreApi,
AgentRosterVersionsApi,
@@ -95,7 +99,7 @@ def _agent_app_composer_response() -> dict:
},
"active_config_snapshot": _version_response(),
"agent_soul": {},
- "save_options": ["save_to_current_version", "save_as_new_version"],
+ "save_options": ["save_to_current_version"],
}
@@ -151,6 +155,10 @@ def test_agent_v2_console_routes_are_agent_id_first() -> None:
"/agent/<uuid:agent_id>/composer/candidates",
"/agent/<uuid:agent_id>/features",
"/agent/<uuid:agent_id>/copy",
+ "/agent/<uuid:agent_id>/publish",
+ "/agent/<uuid:agent_id>/build-draft/checkout",
+ "/agent/<uuid:agent_id>/build-draft",
+ "/agent/<uuid:agent_id>/build-draft/apply",
"/agent/<uuid:agent_id>/referencing-workflows",
"/agent/<uuid:agent_id>/drive/files",
"/agent/<uuid:agent_id>/sandbox/files",
@@ -233,6 +241,8 @@ def test_agent_app_list_and_create_use_agent_route(
lambda _self, **kwargs: {
"app-list": SimpleNamespace(
id="agent-list",
+ app_id="app-list",
+ backing_app_id=None,
role="List role",
debug_conversation_id="debug-conversation-list",
active_config_snapshot_id=None,
@@ -244,6 +254,8 @@ def test_agent_app_list_and_create_use_agent_route(
"get_app_backing_agent",
lambda _self, **kwargs: SimpleNamespace(
id="agent-created",
+ app_id="app-created",
+ backing_app_id=None,
role="Created role",
debug_conversation_id="debug-conversation-created",
active_config_snapshot_id=None,
@@ -368,6 +380,14 @@ def test_agent_app_detail_update_delete_resolve_app_from_agent_id(
) -> None:
agent_id = "00000000-0000-0000-0000-000000000001"
app_model = _app_detail_obj(id="app-1", bound_agent_id=agent_id)
+ agent = SimpleNamespace(
+ id=agent_id,
+ app_id="app-1",
+ backing_app_id=None,
+ role="Resolved role",
+ debug_conversation_id="debug-conversation-detail",
+ active_config_snapshot_id=None,
+ )
captured: dict[str, object] = {}
monkeypatch.setattr(
@@ -375,15 +395,12 @@ def test_agent_app_detail_update_delete_resolve_app_from_agent_id(
"get_agent_app_model",
lambda _self, **kwargs: app_model,
)
+ monkeypatch.setattr(roster_controller, "resolve_agent_runtime_app_model", lambda **kwargs: app_model)
+ monkeypatch.setattr(roster_controller.db.session, "scalar", lambda _stmt: agent)
monkeypatch.setattr(
roster_controller.AgentRosterService,
"get_app_backing_agent",
- lambda _self, **kwargs: SimpleNamespace(
- id=agent_id,
- role="Resolved role",
- debug_conversation_id="debug-conversation-detail",
- active_config_snapshot_id=None,
- ),
+ lambda _self, **kwargs: agent,
)
monkeypatch.setattr(
roster_controller.AgentRosterService,
@@ -520,6 +537,129 @@ def test_agent_debug_conversation_refresh_uses_current_user(
}
+def test_agent_publish_and_build_draft_routes_call_composer_service(
+ app: Flask, monkeypatch: pytest.MonkeyPatch, account_id: str
+) -> None:
+ agent_id = "00000000-0000-0000-0000-000000000001"
+ current_user = SimpleNamespace(id=account_id)
+ captured: dict[str, object] = {}
+
+ def publish_agent_app_draft(**kwargs: object) -> dict[str, object]:
+ captured["publish"] = kwargs
+ return {"result": "success", "active_config_snapshot_id": "version-1"}
+
+ def checkout_agent_app_build_draft(**kwargs: object) -> dict[str, object]:
+ captured["checkout"] = kwargs
+ return {"variant": "agent_app", "draft": {"id": "build-draft-1"}, "agent_soul": {}}
+
+ def load_agent_app_build_draft(**kwargs: object) -> dict[str, object]:
+ captured["load"] = kwargs
+ return {"variant": "agent_app", "draft": {"id": "build-draft-1"}, "agent_soul": {}}
+
+ def save_agent_app_build_draft(**kwargs: object) -> dict[str, object]:
+ captured["save"] = kwargs
+ return {"variant": "agent_app", "draft": {"id": "build-draft-1"}, "agent_soul": {}}
+
+ def apply_agent_app_build_draft(**kwargs: object) -> dict[str, object]:
+ captured["apply"] = kwargs
+ return {"result": "success", "draft": {"id": "draft-1"}}
+
+ def discard_agent_app_build_draft(**kwargs: object) -> dict[str, object]:
+ captured["discard"] = kwargs
+ return {"result": "success"}
+
+ monkeypatch.setattr(
+ roster_controller.AgentComposerService,
+ "publish_agent_app_draft",
+ publish_agent_app_draft,
+ )
+ monkeypatch.setattr(
+ roster_controller.AgentComposerService,
+ "checkout_agent_app_build_draft",
+ checkout_agent_app_build_draft,
+ )
+ monkeypatch.setattr(
+ roster_controller.AgentComposerService,
+ "load_agent_app_build_draft",
+ load_agent_app_build_draft,
+ )
+ monkeypatch.setattr(
+ roster_controller.AgentComposerService,
+ "save_agent_app_build_draft",
+ save_agent_app_build_draft,
+ )
+ monkeypatch.setattr(
+ roster_controller.AgentComposerService,
+ "apply_agent_app_build_draft",
+ apply_agent_app_build_draft,
+ )
+ monkeypatch.setattr(
+ roster_controller.AgentComposerService,
+ "discard_agent_app_build_draft",
+ discard_agent_app_build_draft,
+ )
+
+ with app.test_request_context(
+ "/console/api/agent/00000000-0000-0000-0000-000000000001/publish",
+ json={"version_note": "publish v1"},
+ ):
+ published = unwrap(AgentPublishApi.post)(AgentPublishApi(), "tenant-1", current_user, agent_id)
+ assert published["active_config_snapshot_id"] == "version-1"
+ assert captured["publish"] == {
+ "tenant_id": "tenant-1",
+ "agent_id": agent_id,
+ "account_id": account_id,
+ "version_note": "publish v1",
+ }
+
+ with app.test_request_context(
+ "/console/api/agent/00000000-0000-0000-0000-000000000001/build-draft/checkout",
+ json={"force": True},
+ ):
+ checked_out = unwrap(AgentBuildDraftCheckoutApi.post)(
+ AgentBuildDraftCheckoutApi(), "tenant-1", current_user, agent_id
+ )
+ assert checked_out["draft"]["id"] == "build-draft-1"
+ assert captured["checkout"] == {
+ "tenant_id": "tenant-1",
+ "agent_id": agent_id,
+ "account_id": account_id,
+ "force": True,
+ }
+
+ with app.test_request_context("/console/api/agent/00000000-0000-0000-0000-000000000001/build-draft"):
+ loaded = unwrap(AgentBuildDraftApi.get)(AgentBuildDraftApi(), "tenant-1", current_user, agent_id)
+ assert loaded["draft"]["id"] == "build-draft-1"
+ assert captured["load"] == {"tenant_id": "tenant-1", "agent_id": agent_id, "account_id": account_id}
+
+ with app.test_request_context(
+ "/console/api/agent/00000000-0000-0000-0000-000000000001/build-draft",
+ json={"variant": "agent_app", "save_strategy": "save_to_current_version", "agent_soul": {}},
+ ):
+ saved = unwrap(AgentBuildDraftApi.put)(AgentBuildDraftApi(), "tenant-1", current_user, agent_id)
+ assert saved["draft"]["id"] == "build-draft-1"
+ assert captured["save"]["tenant_id"] == "tenant-1"
+ assert captured["save"]["agent_id"] == agent_id
+ assert captured["save"]["account_id"] == account_id
+ assert captured["save"]["payload"].variant == ComposerVariant.AGENT_APP
+
+ with app.test_request_context(
+ "/console/api/agent/00000000-0000-0000-0000-000000000001/build-draft/apply",
+ method="POST",
+ ):
+ applied = unwrap(AgentBuildDraftApplyApi.post)(AgentBuildDraftApplyApi(), "tenant-1", current_user, agent_id)
+ assert applied == {"result": "success", "draft": {"id": "draft-1"}}
+ assert captured["apply"] == {"tenant_id": "tenant-1", "agent_id": agent_id, "account_id": account_id}
+
+ with app.test_request_context(
+ "/console/api/agent/00000000-0000-0000-0000-000000000001/build-draft",
+ method="DELETE",
+ ):
+ discarded = unwrap(AgentBuildDraftApi.delete)(AgentBuildDraftApi(), "tenant-1", current_user, agent_id)
+ assert discarded == {"result": "success"}
+ assert captured["discard"] == {"tenant_id": "tenant-1", "agent_id": agent_id, "account_id": account_id}
+
+
def test_agent_api_access_uses_agent_id_and_returns_service_api_metadata(
monkeypatch: pytest.MonkeyPatch,
) -> None:
@@ -751,7 +891,12 @@ def test_agent_versions_call_services(app: Flask, monkeypatch: pytest.MonkeyPatc
restored = unwrap(AgentRosterVersionRestoreApi.post)(
AgentRosterVersionRestoreApi(), "tenant-1", SimpleNamespace(id="account-1"), agent_id, version_id
)
- assert restored == {"result": "success", "active_config_snapshot_id": version_id}
+ assert restored == {
+ "result": "success",
+ "active_config_snapshot_id": version_id,
+ "draft_config_id": None,
+ "restored_version_id": None,
+ }
assert captured_restore == {
"tenant_id": "tenant-1",
"agent_id": agent_id,
@@ -887,7 +1032,7 @@ def test_agent_observability_routes_resolve_app_from_agent_id(
},
}
- monkeypatch.setattr(roster_controller, "_resolve_agent_app_model", lambda **kwargs: app_model)
+ monkeypatch.setattr(roster_controller, "resolve_agent_runtime_app_model", lambda **kwargs: app_model)
monkeypatch.setattr(roster_controller, "_agent_observability_service", lambda: FakeObservabilityService())
account = SimpleNamespace(id=account_id, timezone="UTC")
@@ -963,10 +1108,11 @@ def test_workflow_composer_get_put_validate_candidates_impact_and_save(
"save_strategy": ComposerSaveStrategy.NODE_JOB_ONLY.value,
"binding": {"binding_type": "roster_agent", "current_snapshot_id": "version-1"},
}
+ captured_load: dict[str, object] = {}
monkeypatch.setattr(
composer_controller.AgentComposerService,
"load_workflow_composer",
- lambda **kwargs: _workflow_composer_response(node_id=kwargs["node_id"]),
+ lambda **kwargs: captured_load.update(kwargs) or _workflow_composer_response(node_id=kwargs["node_id"]),
)
monkeypatch.setattr(
composer_controller.AgentComposerService,
@@ -993,8 +1139,12 @@ def test_workflow_composer_get_put_validate_candidates_impact_and_save(
},
)
- workflow_state = unwrap(WorkflowAgentComposerApi.get)(WorkflowAgentComposerApi(), "tenant-1", app_model, "node-1")
+ with app.test_request_context("?snapshot_id=preview-version"):
+ workflow_state = unwrap(WorkflowAgentComposerApi.get)(
+ WorkflowAgentComposerApi(), "tenant-1", app_model, "node-1"
+ )
assert workflow_state["node_id"] == "node-1"
+ assert captured_load["snapshot_id"] == "preview-version"
with app.test_request_context(json=payload):
saved_state = unwrap(WorkflowAgentComposerApi.put)(
WorkflowAgentComposerApi(), "tenant-1", account_id, app_model, "node-1"
@@ -1092,13 +1242,11 @@ def test_agent_composer_routes_resolve_app_from_agent_id(
"agent_soul": {"prompt": {"system_prompt": "x"}},
}
- monkeypatch.setattr(composer_controller, "resolve_agent_app_model", lambda **kwargs: SimpleNamespace(id="app-1"))
-
- def load_agent_app_composer(**kwargs: object) -> dict:
+ def load_agent_composer(**kwargs: object) -> dict:
captured["load"] = kwargs
return _agent_app_composer_response()
- def save_agent_app_composer(**kwargs: object) -> dict:
+ def save_agent_composer(**kwargs: object) -> dict:
captured["save"] = kwargs
return _agent_app_composer_response()
@@ -1112,13 +1260,13 @@ def test_agent_composer_routes_resolve_app_from_agent_id(
monkeypatch.setattr(
composer_controller.AgentComposerService,
- "load_agent_app_composer",
- load_agent_app_composer,
+ "load_agent_composer",
+ load_agent_composer,
)
monkeypatch.setattr(
composer_controller.AgentComposerService,
- "save_agent_app_composer",
- save_agent_app_composer,
+ "save_agent_composer",
+ save_agent_composer,
)
monkeypatch.setattr(composer_controller.ComposerConfigValidator, "validate_publish_payload", lambda payload: None)
monkeypatch.setattr(
@@ -1133,13 +1281,13 @@ def test_agent_composer_routes_resolve_app_from_agent_id(
)
assert unwrap(AgentComposerApi.get)(AgentComposerApi(), "tenant-1", agent_id)["variant"] == "agent_app"
- assert cast(dict[str, object], captured["load"])["app_id"] == "app-1"
+ assert cast(dict[str, object], captured["load"])["agent_id"] == agent_id
with app.test_request_context(json=payload):
assert (
unwrap(AgentComposerApi.put)(AgentComposerApi(), "tenant-1", account_id, agent_id)["variant"] == "agent_app"
)
- assert cast(dict[str, object], captured["save"])["app_id"] == "app-1"
+ assert cast(dict[str, object], captured["save"])["agent_id"] == agent_id
assert unwrap(AgentComposerValidateApi.post)(AgentComposerValidateApi(), "tenant-1", agent_id) == {
"result": "success",
"errors": [],
@@ -1150,7 +1298,7 @@ def test_agent_composer_routes_resolve_app_from_agent_id(
candidates = unwrap(AgentComposerCandidatesApi.get)(AgentComposerCandidatesApi(), "tenant-1", account_id, agent_id)
assert candidates["variant"] == "agent_app"
- assert cast(dict[str, object], captured["candidates"])["app_id"] == "app-1"
+ assert cast(dict[str, object], captured["candidates"])["agent_id"] == agent_id
def test_agent_chat_generate_and_stop_routes_resolve_app_from_agent_id(
@@ -1172,7 +1320,7 @@ def test_agent_chat_generate_and_stop_routes_resolve_app_from_agent_id(
captured["stop"] = kwargs
return {"result": "success"}, 200
- monkeypatch.setattr(completion_controller, "resolve_agent_app_model", resolve_agent_app_model)
+ monkeypatch.setattr(completion_controller, "resolve_agent_runtime_app_model", resolve_agent_app_model)
monkeypatch.setattr(completion_controller, "_create_chat_message", create_chat_message)
monkeypatch.setattr(completion_controller, "_stop_chat_message", stop_chat_message)
@@ -1375,7 +1523,7 @@ def test_agent_chat_message_routes_resolve_app_from_agent_id(app: Flask, monkeyp
captured["detail"] = kwargs
return {"id": message_id}
- monkeypatch.setattr(message_controller, "resolve_agent_app_model", resolve_agent_app_model)
+ monkeypatch.setattr(message_controller, "resolve_agent_runtime_app_model", resolve_agent_app_model)
monkeypatch.setattr(message_controller, "_list_chat_messages", list_chat_messages)
monkeypatch.setattr(message_controller, "_update_message_feedback", update_message_feedback)
monkeypatch.setattr(message_controller, "_get_message_suggested_questions", get_message_suggested_questions)
diff --git a/api/tests/unit_tests/controllers/console/app/test_agent_app_sandbox.py b/api/tests/unit_tests/controllers/console/app/test_agent_app_sandbox.py
index 3cda0a34332..9b0c530f4fd 100644
--- a/api/tests/unit_tests/controllers/console/app/test_agent_app_sandbox.py
+++ b/api/tests/unit_tests/controllers/console/app/test_agent_app_sandbox.py
@@ -119,7 +119,7 @@ def test_handle_maps_sandbox_and_agent_backend_errors() -> None:
def test_agent_app_sandbox_resources_proxy_service(monkeypatch: pytest.MonkeyPatch) -> None:
service = _AgentAppService()
monkeypatch.setattr(module, "AgentAppSandboxService", lambda: service)
- monkeypatch.setattr(module, "resolve_agent_app_model", lambda *, tenant_id, agent_id: _app_model())
+ monkeypatch.setattr(module, "resolve_agent_runtime_app_model", lambda *, tenant_id, agent_id: _app_model())
monkeypatch.setattr(
module,
"query_params_from_request",
@@ -151,7 +151,7 @@ def test_agent_app_sandbox_resource_returns_normalized_errors(monkeypatch: pytes
raise AgentSandboxInspectorError("no_active_session", "no active session", status_code=404)
monkeypatch.setattr(module, "AgentAppSandboxService", FailingService)
- monkeypatch.setattr(module, "resolve_agent_app_model", lambda *, tenant_id, agent_id: _app_model())
+ monkeypatch.setattr(module, "resolve_agent_runtime_app_model", lambda *, tenant_id, agent_id: _app_model())
monkeypatch.setattr(
module, "query_params_from_request", lambda model: SimpleNamespace(conversation_id="conv-1", path=".")
)
diff --git a/api/tests/unit_tests/controllers/console/app/test_agent_drive_inspector.py b/api/tests/unit_tests/controllers/console/app/test_agent_drive_inspector.py
index 81f6fcf36bf..c8b28ef29f0 100644
--- a/api/tests/unit_tests/controllers/console/app/test_agent_drive_inspector.py
+++ b/api/tests/unit_tests/controllers/console/app/test_agent_drive_inspector.py
@@ -64,7 +64,7 @@ def test_list_by_agent_filters_value_pointers_out_of_console_payload():
raw = _raw(AgentDriveListByAgentApi.get)
with app.test_request_context("/?prefix=pdf-toolkit/"):
with (
- patch(f"{_MOD}.resolve_agent_app_model", return_value=_APP) as resolve_app,
+ patch(f"{_MOD}.resolve_agent_runtime_app_model", return_value=_APP) as resolve_app,
patch(f"{_MOD}.AgentDriveService") as drive,
):
drive.return_value.manifest.return_value = [
@@ -105,7 +105,7 @@ def test_skill_list_by_agent_calls_service():
raw = _raw(AgentDriveSkillListByAgentApi.get)
with app.test_request_context("/"):
with (
- patch(f"{_MOD}.resolve_agent_app_model", return_value=_APP) as resolve_app,
+ patch(f"{_MOD}.resolve_agent_runtime_app_model", return_value=_APP) as resolve_app,
patch(f"{_MOD}.AgentDriveService") as drive,
):
drive.return_value.list_skills.return_value = [
@@ -177,7 +177,7 @@ def test_skill_inspect_by_agent_returns_strict_json_response():
}
with app.test_request_context("/"):
with (
- patch(f"{_MOD}.resolve_agent_app_model", return_value=_APP),
+ patch(f"{_MOD}.resolve_agent_runtime_app_model", return_value=_APP),
patch(f"{_MOD}.AgentDriveService") as drive,
):
drive.return_value.inspect_skill.return_value = payload
@@ -256,7 +256,7 @@ def test_preview_by_agent_passes_through_and_maps_errors():
raw = _raw(AgentDrivePreviewByAgentApi.get)
with app.test_request_context("/?key=pdf-toolkit/SKILL.md"):
with (
- patch(f"{_MOD}.resolve_agent_app_model", return_value=_APP) as resolve_app,
+ patch(f"{_MOD}.resolve_agent_runtime_app_model", return_value=_APP) as resolve_app,
patch(f"{_MOD}.AgentDriveService") as drive,
):
drive.return_value.preview.return_value = {
@@ -272,7 +272,7 @@ def test_preview_by_agent_passes_through_and_maps_errors():
with app.test_request_context("/?key=ghost/SKILL.md"):
with (
- patch(f"{_MOD}.resolve_agent_app_model", return_value=_APP),
+ patch(f"{_MOD}.resolve_agent_runtime_app_model", return_value=_APP),
patch(f"{_MOD}.AgentDriveService") as drive,
):
drive.return_value.preview.side_effect = AgentDriveError(
@@ -296,7 +296,7 @@ def test_download_by_agent_returns_signed_url_json():
raw = _raw(AgentDriveDownloadByAgentApi.get)
with app.test_request_context("/?key=pdf-toolkit/.DIFY-SKILL-FULL.zip"):
with (
- patch(f"{_MOD}.resolve_agent_app_model", return_value=_APP) as resolve_app,
+ patch(f"{_MOD}.resolve_agent_runtime_app_model", return_value=_APP) as resolve_app,
patch(f"{_MOD}.AgentDriveService") as drive,
):
drive.return_value.download_url.return_value = "https://signed.example/zip"
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.py
index bafdc3b46ac..79a363e74ca 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
@@ -67,7 +67,7 @@ def test_upload_by_agent_resolves_app_and_standardizes_into_drive():
with _file_ctx(files={"file": b"zip-bytes"}):
with (
- patch(f"{_MOD}.resolve_agent_app_model", return_value=_APP) as resolve_app,
+ patch(f"{_MOD}.resolve_agent_runtime_app_model", return_value=_APP) as resolve_app,
patch(f"{_MOD}.SkillStandardizeService") as svc,
):
svc.return_value.standardize.return_value = {"skill": {"path": "skill-a"}, "manifest": {}}
@@ -174,7 +174,7 @@ def test_files_by_agent_commit_uses_agent_route_and_ignores_node_id():
upload = SimpleNamespace(id="uf-1", name="sample.pdf")
with _json_ctx({"upload_file_id": "0fa6f9bc-3416-4476-8857-a13129704dd9"}, query_string="node_id=ignored"):
with (
- patch(f"{_MOD}.resolve_agent_app_model", return_value=_APP) as resolve_app,
+ patch(f"{_MOD}.resolve_agent_runtime_app_model", return_value=_APP) as resolve_app,
patch(f"{_MOD}.console_ns") as ns,
patch(f"{_MOD}.db") as db_mock,
patch(f"{_MOD}.AgentDriveService") as drive,
@@ -252,7 +252,7 @@ def test_files_by_agent_delete_uses_agent_route_and_ignores_node_id():
raw = _raw(AgentDriveFilesByAgentApi.delete)
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}.resolve_agent_runtime_app_model", return_value=_APP) as resolve_app,
patch(f"{_MOD}.AgentDriveService") as drive,
):
drive.return_value.commit.return_value = [{"key": "files/sample.pdf", "removed": True}]
@@ -316,7 +316,7 @@ def test_skill_delete_by_agent_uses_agent_route():
raw = _raw(AgentSkillByAgentApi.delete)
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}.resolve_agent_runtime_app_model", return_value=_APP) as resolve_app,
patch(f"{_MOD}.AgentDriveService") as drive,
):
drive.return_value.commit.return_value = [{"key": "tender-analyzer/SKILL.md", "removed": True}]
@@ -360,7 +360,7 @@ def test_infer_tools_by_agent_uses_agent_route():
raw = _raw(AgentSkillInferToolsByAgentApi.post)
with _json_ctx(query_string="node_id=ignored"):
with (
- patch(f"{_MOD}.resolve_agent_app_model", return_value=_APP) as resolve_app,
+ patch(f"{_MOD}.resolve_agent_runtime_app_model", return_value=_APP) as resolve_app,
patch(f"{_MOD}.SkillToolInferenceService") as svc,
):
svc.return_value.infer.return_value = {"inferable": True, "cli_tools": [], "reason": None}
diff --git a/api/tests/unit_tests/core/app/apps/agent_app/test_app_generator.py b/api/tests/unit_tests/core/app/apps/agent_app/test_app_generator.py
index b8cdf471ca3..7418ca2660a 100644
--- a/api/tests/unit_tests/core/app/apps/agent_app/test_app_generator.py
+++ b/api/tests/unit_tests/core/app/apps/agent_app/test_app_generator.py
@@ -69,7 +69,7 @@ class TestGenerateSuccess:
def test_runtime_session_snapshot_id_is_stable_for_debugger_only(self):
assert (
AgentAppGenerator._runtime_session_snapshot_id(invoke_from=InvokeFrom.DEBUGGER, snapshot_id="snap-1")
- is None
+ == "snap-1"
)
assert (
AgentAppGenerator._runtime_session_snapshot_id(invoke_from=InvokeFrom.WEB_APP, snapshot_id="snap-1")
@@ -111,7 +111,12 @@ class TestGenerateSuccess:
assert result == {"result": "ok"}
thread_obj.start.assert_called_once()
- generator._resolve_agent.assert_called_once_with(app_model)
+ generator._resolve_agent.assert_called_once_with(
+ app_model,
+ invoke_from=InvokeFrom.WEB_APP,
+ draft_type=None,
+ user=user,
+ )
def test_generate_loads_existing_conversation(self, generator: AgentAppGenerator, mocker: MockerFixture):
app_model = mocker.MagicMock(id="app1", tenant_id="tenant", mode="agent")
diff --git a/api/tests/unit_tests/core/app/apps/agent_app/test_app_runner.py b/api/tests/unit_tests/core/app/apps/agent_app/test_app_runner.py
index 4f920df0ec6..f5f6c12365f 100644
--- a/api/tests/unit_tests/core/app/apps/agent_app/test_app_runner.py
+++ b/api/tests/unit_tests/core/app/apps/agent_app/test_app_runner.py
@@ -46,6 +46,13 @@ class _FakeCredentialsProvider:
return {"openai_api_key": "sk-test"}
[email protected](autouse=True)
+def _disable_drive_manifest_by_default(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ "core.app.apps.agent_app.runtime_request_builder.dify_config.AGENT_DRIVE_MANIFEST_ENABLED", False
+ )
+
+
class _NoToolsBuilder:
def build(self, **kwargs):
del kwargs
diff --git a/api/tests/unit_tests/core/app/apps/agent_app/test_resolve_agent.py b/api/tests/unit_tests/core/app/apps/agent_app/test_resolve_agent.py
index c0a226ad575..15f1bacb8f6 100644
--- a/api/tests/unit_tests/core/app/apps/agent_app/test_resolve_agent.py
+++ b/api/tests/unit_tests/core/app/apps/agent_app/test_resolve_agent.py
@@ -14,6 +14,7 @@ import pytest
from core.app.apps.agent_app import app_generator as gen_mod
from core.app.apps.agent_app.app_generator import AgentAppGenerator, AgentAppGeneratorError
+from core.app.entities.app_invoke_entities import InvokeFrom
_SOUL_DICT = {
"model": {
@@ -84,14 +85,24 @@ class TestResolveAgent:
_patch_session(monkeypatch, [bound_agent, inner_agent, snapshot])
app_model = SimpleNamespace(id="app-1", tenant_id="t1")
- agent, snap, soul = AgentAppGenerator()._resolve_agent(app_model) # type: ignore[arg-type]
+ agent, snap, soul = AgentAppGenerator()._resolve_agent(
+ app_model,
+ invoke_from=InvokeFrom.WEB_APP,
+ draft_type=None,
+ user=SimpleNamespace(id="user-1"),
+ ) # type: ignore[arg-type]
- assert agent is inner_agent
- assert snap is snapshot
+ assert agent is bound_agent
+ assert snap == snapshot.id
assert soul.model is not None
def test_unbound_app_raises(self, monkeypatch: pytest.MonkeyPatch):
_patch_session(monkeypatch, [None])
app_model = SimpleNamespace(id="app-1", tenant_id="t1")
with pytest.raises(AgentAppGeneratorError, match="has no bound Agent"):
- AgentAppGenerator()._resolve_agent(app_model) # type: ignore[arg-type]
+ AgentAppGenerator()._resolve_agent(
+ app_model,
+ invoke_from=InvokeFrom.WEB_APP,
+ draft_type=None,
+ user=SimpleNamespace(id="user-1"),
+ ) # type: ignore[arg-type]
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.py
index 4f292d90bb4..61bf3443cc8 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
@@ -85,6 +85,49 @@ class _NoToolsBuilder:
del kwargs
+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 _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},
+ ],
+ )
+
+
[email protected](autouse=True)
+def _mock_default_agent_app_drive_catalog(monkeypatch: pytest.MonkeyPatch) -> None:
+ _mock_empty_drive_catalog(monkeypatch)
+
+
def _ctx(soul: AgentSoulConfig, *, query: str = "hello") -> AgentAppRuntimeBuildContext:
dify_context = SimpleNamespace(
tenant_id="tenant-1",
@@ -128,7 +171,15 @@ class TestAgentAppRuntimeRequestBuilder:
req = result.request
assert req.purpose == "agent_app"
names = [layer.name for layer in req.composition.layers]
- assert names == ["agent_soul_prompt", "agent_app_user_prompt", "execution_context", "history", "llm"]
+ assert names == [
+ "agent_soul_prompt",
+ "agent_app_user_prompt",
+ "execution_context",
+ "shell",
+ "drive",
+ "history",
+ "llm",
+ ]
# plugin_id / provider normalized for plugin-daemon transport.
llm = next(layer for layer in req.composition.layers if layer.name == "llm")
assert llm.config.plugin_id == "langgenius/openai"
@@ -169,12 +220,19 @@ class TestAgentAppRuntimeRequestBuilder:
"model": "gpt-4o-mini",
},
"knowledge": {
- "datasets": [{"id": "dataset-1"}, {"id": "dataset-2"}],
- "query_config": {
- "top_k": 3,
- "score_threshold": 0.5,
- "score_threshold_enabled": False,
- },
+ "sets": [
+ {
+ "id": "support",
+ "name": "Support KB",
+ "datasets": [{"id": "dataset-1"}, {"id": "dataset-2"}],
+ "query": {"mode": "generated_query"},
+ "retrieval": {
+ "mode": "multiple",
+ "top_k": 3,
+ "score_threshold": None,
+ },
+ }
+ ],
},
}
)
@@ -189,10 +247,12 @@ class TestAgentAppRuntimeRequestBuilder:
assert knowledge.type == "dify.knowledge_base"
assert knowledge.deps == {"execution_context": "execution_context"}
dumped_config = knowledge.config.model_dump(mode="json", by_alias=True)
- assert dumped_config["dataset_ids"] == ["dataset-1", "dataset-2"]
- assert dumped_config["retrieval"]["mode"] == "multiple"
- assert dumped_config["retrieval"]["top_k"] == 3
- assert dumped_config["retrieval"]["score_threshold"] == 0.0
+ knowledge_set = dumped_config["sets"][0]
+ assert [dataset["id"] for dataset in knowledge_set["datasets"]] == ["dataset-1", "dataset-2"]
+ assert knowledge_set["query"] == {"mode": "generated_query", "value": None}
+ assert knowledge_set["retrieval"]["mode"] == "multiple"
+ assert knowledge_set["retrieval"]["top_k"] == 3
+ assert knowledge_set["retrieval"]["score_threshold"] == 0.0
def test_build_raises_when_model_missing(self):
builder = AgentAppRuntimeRequestBuilder(
@@ -242,9 +302,26 @@ class TestAgentAppRuntimeRequestBuilder:
def _soul_with_model_and_skill() -> AgentSoulConfig:
- soul = _soul_with_model()
- soul.prompt.system_prompt = "Use [§skill:tender-analyzer%2FSKILL.md:Tender Analyzer§]"
- return soul
+ return AgentSoulConfig.model_validate(
+ {
+ "model": {
+ "plugin_id": "langgenius/openai",
+ "model_provider": "langgenius/openai/openai",
+ "model": "gpt-4o-mini",
+ },
+ "prompt": {"system_prompt": "Use [§skill:tender-analyzer%2FSKILL.md:Tender Analyzer§]"},
+ "files": {
+ "skills": [
+ {
+ "path": "tender-analyzer",
+ "skill_md_key": "tender-analyzer/SKILL.md",
+ "name": "Tender Analyzer",
+ "description": "Parses RFPs.",
+ }
+ ]
+ },
+ }
+ )
class TestAgentAppDriveLayer:
@@ -252,28 +329,7 @@ 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}
- ],
- )
+ _mock_drive_catalog(monkeypatch)
builder = AgentAppRuntimeRequestBuilder(
credentials_provider=_FakeCredentialsProvider(),
plugin_tools_builder=_NoToolsBuilder(), # type: ignore[arg-type]
@@ -283,27 +339,20 @@ 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.deps == {"shell": DIFY_SHELL_LAYER_ID}
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 surface
+ # shell enters first; drive uses that shell to materialize mentioned targets.
names = [layer.name for layer in result.request.composition.layers]
- assert names.index("drive") == names.index("execution_context") + 1
+ assert names.index(DIFY_SHELL_LAYER_ID) == names.index("execution_context") + 1
+ assert names.index("drive") == names.index(DIFY_SHELL_LAYER_ID) + 1
- def test_drive_layer_injected_with_empty_catalog_and_shell_depends_on_it(self, monkeypatch: pytest.MonkeyPatch):
+ def test_drive_layer_injected_with_empty_catalog_and_drive_depends_on_shell(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]
@@ -314,12 +363,14 @@ class TestAgentAppDriveLayer:
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",
- }
+ assert layers[DIFY_SHELL_LAYER_ID].deps == {"execution_context": "execution_context"}
+ assert layers[DIFY_SHELL_LAYER_ID].config.agent_stub_drive_ref == "agent-agent-1"
+ assert layers["drive"].deps == {"shell": DIFY_SHELL_LAYER_ID}
- def test_no_drive_layer_when_flag_disabled(self):
+ def test_no_drive_layer_when_flag_disabled(self, monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setattr(
+ "core.app.apps.agent_app.runtime_request_builder.dify_config.AGENT_DRIVE_MANIFEST_ENABLED", False
+ )
builder = AgentAppRuntimeRequestBuilder(
credentials_provider=_FakeCredentialsProvider(),
plugin_tools_builder=_NoToolsBuilder(), # type: ignore[arg-type]
@@ -334,29 +385,7 @@ 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},
- {"key": "files/sample.pdf", "is_skill": False},
- ],
- )
+ _mock_drive_catalog(monkeypatch)
soul = _soul_with_model()
soul.prompt.system_prompt = (
"Use [§skill:tender-analyzer%2FSKILL.md:Tender Analyzer§] and [§file:files%2Fsample.pdf:sample.pdf§]."
@@ -379,14 +408,7 @@ 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: [],
- )
- monkeypatch.setattr(
- "core.workflow.nodes.agent_v2.runtime_request_builder.AgentDriveService.manifest",
- lambda self, *, tenant_id, agent_id, prefix="", include_download_url=False: [],
- )
+ _mock_drive_catalog(monkeypatch)
soul = _soul_with_model()
soul.prompt.system_prompt = (
"Use [§skill:ghost%2FSKILL.md:Ghost Skill§], [§file:files%2Fghost.txt:Ghost File§], "
@@ -407,29 +429,7 @@ 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},
- {"key": "files/sample.pdf", "is_skill": False},
- ],
- )
+ _mock_drive_catalog(monkeypatch)
soul = _soul_with_model()
soul.prompt.system_prompt = (
"Use [§skill:tender-analyzer%2FSKILL.md:Tender Analyzer§] and [§file:files%2Fsample.pdf:sample.pdf§]"
@@ -452,14 +452,6 @@ 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: [],
- )
- 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§], "
diff --git a/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_agent_node.py b/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_agent_node.py
index b2a5ef3931e..4e719d74000 100644
--- a/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_agent_node.py
+++ b/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_agent_node.py
@@ -2,6 +2,7 @@ from types import SimpleNamespace
from typing import cast
from unittest.mock import MagicMock, patch
+import pytest
from agenton.compositor import CompositorSessionSnapshot
from dify_agent.layers.ask_human import AskHumanToolResult
from dify_agent.protocol import RunStartedEvent, RunSucceededEvent, RunSucceededEventData
@@ -50,6 +51,13 @@ class FakeCredentialsProvider:
return {"api_key": "secret-key"}
[email protected](autouse=True)
+def _disable_drive_manifest_by_default(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ "core.workflow.nodes.agent_v2.runtime_request_builder.dify_config.AGENT_DRIVE_MANIFEST_ENABLED", False
+ )
+
+
def _restored_file(*, transfer_method: FileTransferMethod, reference: str) -> File:
return File(
type=FileType.DOCUMENT,
@@ -245,6 +253,23 @@ def _node(
)
+def test_extract_variable_selector_to_variable_mapping_uses_frontend_agent_task_markers():
+ mapping = DifyAgentNode._extract_variable_selector_to_variable_mapping(
+ graph_config={},
+ node_id="agent-node",
+ node_data={
+ "agent_task": (
+ "Review {{#previous-node.report#}}, ignore {{#sys.query#}}, "
+ "ignore [§node_output:legacy-node.output:LEGACY§], then use {{#previous-node.report#}} again."
+ )
+ },
+ )
+
+ assert mapping == {
+ "agent-node.previous-node.report": ["previous-node", "report"],
+ }
+
+
def test_agent_node_run_maps_successful_agent_backend_run_to_node_result():
events = list(_node()._run())
diff --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.py
index ffa7ccdbca7..289319d74cb 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
@@ -1,3 +1,4 @@
+import json
from dataclasses import replace
from typing import cast
@@ -9,6 +10,7 @@ from dify_agent.protocol import DIFY_AGENT_HISTORY_LAYER_ID, DIFY_AGENT_MODEL_LA
from clients.agent_backend import DIFY_EXECUTION_CONTEXT_LAYER_ID, DIFY_PLUGIN_TOOLS_LAYER_ID
from clients.agent_backend.request_builder import DIFY_SHELL_LAYER_ID
from core.app.entities.app_invoke_entities import DifyRunContext, InvokeFrom, UserFrom
+from core.workflow.file_reference import build_file_reference
from core.workflow.nodes.agent_v2.plugin_tools_builder import WorkflowAgentPluginToolsBuilder
from core.workflow.nodes.agent_v2.runtime_request_builder import (
WorkflowAgentRuntimeBuildContext,
@@ -16,7 +18,8 @@ from core.workflow.nodes.agent_v2.runtime_request_builder import (
WorkflowAgentRuntimeRequestBuildError,
build_shell_layer_config,
)
-from graphon.variables.segments import StringSegment
+from graphon.file import File, FileTransferMethod, FileType
+from graphon.variables.segments import ArrayFileSegment, FileSegment, StringSegment
from models.agent import Agent, AgentConfigSnapshot, WorkflowAgentNodeBinding
from models.agent_config_entities import (
AgentSoulConfig,
@@ -36,6 +39,13 @@ class FakeCredentialsProvider:
return {"api_key": "secret-key"}
[email protected](autouse=True)
+def _disable_drive_manifest_by_default(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ "core.workflow.nodes.agent_v2.runtime_request_builder.dify_config.AGENT_DRIVE_MANIFEST_ENABLED", False
+ )
+
+
class CapturingCredentialsProvider:
def __init__(self) -> None:
self.provider_name: str | None = None
@@ -165,6 +175,27 @@ def _context() -> WorkflowAgentRuntimeBuildContext:
)
+def _request_layers(result) -> dict[str, dict[str, object]]:
+ dumped = result.request.model_dump(mode="json")
+ return {layer["name"]: layer for layer in dumped["composition"]["layers"]}
+
+
+def _workflow_user_prompt(result) -> str:
+ from clients.agent_backend import WORKFLOW_USER_PROMPT_LAYER_ID
+
+ layer = _request_layers(result)[WORKFLOW_USER_PROMPT_LAYER_ID]
+ return cast(str, layer["config"]["user"])
+
+
+def _previous_node_prompt_payload(result, selector: str) -> object:
+ prefix = f" - {selector}: "
+ user_prompt = _workflow_user_prompt(result)
+ for line in user_prompt.splitlines():
+ if line.startswith(prefix):
+ return json.loads(line.removeprefix(prefix))
+ raise AssertionError(f"missing prompt payload for {selector}")
+
+
def test_builds_create_run_request_from_agent_soul_and_node_job():
result = WorkflowAgentRuntimeRequestBuilder(credentials_provider=FakeCredentialsProvider()).build(_context())
@@ -177,11 +208,14 @@ def test_builds_create_run_request_from_agent_soul_and_node_job():
assert layers[DIFY_EXECUTION_CONTEXT_LAYER_ID]["config"]["invoke_from"] == "debugger"
assert dumped["idempotency_key"] == "run-1:node-exec-1"
assert dumped["composition"]["layers"][0]["config"]["prefix"] == "You are careful."
- assert dumped["composition"]["layers"][1]["config"]["prefix"] == "Use the previous output."
- assert "Previous result" in dumped["composition"]["layers"][2]["config"]["user"]
+ assert dumped["composition"]["layers"][1]["config"]["user"] == "Use the previous output."
+ assert "Agent task for this workflow run:" not in dumped["composition"]["layers"][2]["config"]["user"]
+ assert "User query: Summarize the report." in dumped["composition"]["layers"][2]["config"]["user"]
+ assert "Previous node outputs:" not in dumped["composition"]["layers"][2]["config"]["user"]
assert dumped["composition"]["layers"][-1]["config"]["json_schema"]["properties"]["summary"]["type"] == "string"
assert DIFY_AGENT_HISTORY_LAYER_ID in layers
- assert result.redacted_request["composition"]["layers"][5]["config"]["credentials"] == "[REDACTED]"
+ redacted_layers = {layer["name"]: layer for layer in result.redacted_request["composition"]["layers"]}
+ assert redacted_layers[DIFY_AGENT_MODEL_LAYER_ID]["config"]["credentials"] == "[REDACTED]"
def test_normalizes_langgenius_model_provider_for_agent_backend_transport():
@@ -262,7 +296,7 @@ def test_builds_workflow_run_request_with_file_output_schema_and_reserved_metada
assert report_schema["oneOf"][3]["required"] == ["transfer_method", "url"]
assert output_schema["properties"]["confidence"]["type"] == "number"
assert output_schema["required"] == ["report"]
- assert dumped["composition"]["layers"][5]["config"]["model_settings"] == {"temperature": 0.2}
+ assert layers[DIFY_AGENT_MODEL_LAYER_ID]["config"]["model_settings"] == {"temperature": 0.2}
assert result.metadata["runtime_support"]["reserved_status"]["tools.dify_tools"] == "supported_when_config_valid"
assert result.metadata["runtime_support"]["reserved_status"]["tools.cli_tools"] == "supported_by_shell_bootstrap"
assert result.metadata["runtime_support"]["unsupported_runtime_warnings"] == []
@@ -512,12 +546,55 @@ def test_build_maps_agent_soul_knowledge_to_knowledge_layer_config():
"model": "gpt-test",
},
"knowledge": {
- "datasets": [{"id": "dataset-1"}, {"id": " "}, {"id": "dataset-2"}],
- "query_config": {
- "top_k": 6,
- "score_threshold": 0.4,
- "score_threshold_enabled": True,
- },
+ "sets": [
+ {
+ "id": "support",
+ "name": "Support KB",
+ "description": "Support content",
+ "datasets": [{"id": "dataset-1"}, {"id": "dataset-2"}],
+ "query": {"mode": "generated_query"},
+ "retrieval": {
+ "mode": "multiple",
+ "top_k": 6,
+ "score_threshold": 0.4,
+ "reranking_model": {"provider": "cohere", "model": "rerank-v3"},
+ "weights": {"weight_type": "weighted_score", "vector_setting": {"vector_weight": 0.7}},
+ },
+ "metadata_filtering": {
+ "mode": "manual",
+ "conditions": {
+ "logical_operator": "and",
+ "conditions": [
+ {"name": "category", "comparison_operator": "contains", "value": "auth"}
+ ],
+ },
+ },
+ },
+ {
+ "id": "release",
+ "name": "Release Notes",
+ "datasets": [{"id": "dataset-3"}],
+ "query": {"mode": "user_query", "value": "release notes"},
+ "retrieval": {
+ "mode": "single",
+ "model": {
+ "provider": "openai",
+ "name": "gpt-4o-mini",
+ "mode": "chat",
+ "completion_params": {"temperature": 0.2},
+ },
+ },
+ "metadata_filtering": {
+ "mode": "automatic",
+ "model_config": {
+ "provider": "openai",
+ "name": "gpt-4o-mini",
+ "mode": "chat",
+ "completion_params": {},
+ },
+ },
+ },
+ ],
},
}
),
@@ -531,25 +608,73 @@ def test_build_maps_agent_soul_knowledge_to_knowledge_layer_config():
knowledge_layer = layers["knowledge"]
assert knowledge_layer["type"] == "dify.knowledge_base"
assert knowledge_layer["deps"] == {"execution_context": DIFY_EXECUTION_CONTEXT_LAYER_ID}
- assert knowledge_layer["config"] == {
- "dataset_ids": ["dataset-1", "dataset-2"],
- "retrieval": {
- "mode": "multiple",
- "top_k": 6,
- "score_threshold": 0.4,
- "reranking_mode": "reranking_model",
- "reranking_enable": True,
- "reranking_model": None,
- "weights": None,
- "model": None,
+ assert knowledge_layer["config"]["sets"] == [
+ {
+ "id": "support",
+ "name": "Support KB",
+ "description": "Support content",
+ "datasets": [
+ {"id": "dataset-1", "name": None, "description": None},
+ {"id": "dataset-2", "name": None, "description": None},
+ ],
+ "query": {"mode": "generated_query", "value": None},
+ "retrieval": {
+ "mode": "multiple",
+ "top_k": 6,
+ "score_threshold": 0.4,
+ "reranking_mode": "reranking_model",
+ "reranking_enable": True,
+ "reranking_model": {"provider": "cohere", "model": "rerank-v3"},
+ "weights": {"weight_type": "weighted_score", "vector_setting": {"vector_weight": 0.7}},
+ "model": None,
+ },
+ "metadata_filtering": {
+ "mode": "manual",
+ "metadata_model_config": None,
+ "conditions": {
+ "logical_operator": "and",
+ "conditions": [{"name": "category", "comparison_operator": "contains", "value": "auth"}],
+ },
+ },
},
- "metadata_filtering": {"mode": "disabled", "metadata_model_config": None, "conditions": None},
- "max_result_content_chars": 2000,
- "max_observation_chars": 12000,
- }
+ {
+ "id": "release",
+ "name": "Release Notes",
+ "description": None,
+ "datasets": [{"id": "dataset-3", "name": None, "description": None}],
+ "query": {"mode": "user_query", "value": "release notes"},
+ "retrieval": {
+ "mode": "single",
+ "top_k": None,
+ "score_threshold": 0.0,
+ "reranking_mode": "reranking_model",
+ "reranking_enable": True,
+ "reranking_model": None,
+ "weights": None,
+ "model": {
+ "provider": "openai",
+ "name": "gpt-4o-mini",
+ "mode": "chat",
+ "completion_params": {"temperature": 0.2},
+ },
+ },
+ "metadata_filtering": {
+ "mode": "automatic",
+ "metadata_model_config": {
+ "provider": "openai",
+ "name": "gpt-4o-mini",
+ "mode": "chat",
+ "completion_params": {},
+ },
+ "conditions": None,
+ },
+ },
+ ]
+ assert knowledge_layer["config"]["max_result_content_chars"] == 2000
+ assert knowledge_layer["config"]["max_observation_chars"] == 12000
-def test_build_knowledge_layer_uses_stable_default_top_k_when_query_config_omits_it():
+def test_build_knowledge_layer_maps_disabled_score_threshold_to_zero():
context = _context()
snapshot = AgentConfigSnapshot(
id="snapshot-1",
@@ -565,8 +690,19 @@ def test_build_knowledge_layer_uses_stable_default_top_k_when_query_config_omits
"model": "gpt-test",
},
"knowledge": {
- "datasets": [{"id": "dataset-1"}],
- "query_config": {},
+ "sets": [
+ {
+ "id": "support",
+ "name": "Support KB",
+ "datasets": [{"id": "dataset-1"}],
+ "query": {"mode": "generated_query"},
+ "retrieval": {
+ "mode": "multiple",
+ "top_k": 4,
+ "score_threshold": None,
+ },
+ }
+ ],
},
}
),
@@ -577,10 +713,10 @@ def test_build_knowledge_layer_uses_stable_default_top_k_when_query_config_omits
dumped = result.request.model_dump(mode="json")
knowledge_layer = next(layer for layer in dumped["composition"]["layers"] if layer["name"] == "knowledge")
- assert knowledge_layer["config"]["retrieval"]["top_k"] == 4
+ assert knowledge_layer["config"]["sets"][0]["retrieval"]["score_threshold"] == 0.0
-def test_build_skips_knowledge_layer_when_agent_soul_has_no_valid_dataset_ids():
+def test_build_skips_knowledge_layer_when_agent_soul_has_no_sets():
context = _context()
snapshot = AgentConfigSnapshot(
id="snapshot-1",
@@ -595,9 +731,7 @@ def test_build_skips_knowledge_layer_when_agent_soul_has_no_valid_dataset_ids():
"model_provider": "openai",
"model": "gpt-test",
},
- "knowledge": {
- "datasets": [{"id": " "}, {}],
- },
+ "knowledge": {"sets": []},
}
),
)
@@ -793,11 +927,8 @@ def test_effective_declared_outputs_passthrough_when_user_declared():
def test_mentions_expand_in_soul_and_job_prompts_without_token_leak():
- """ENG-616: slash-menu mention tokens expand to canonical names; node_output
- mentions expand to the reference name only (the value stays in the Workflow
- context user prompt), and no ``[§…§]`` marker leaks into the request."""
- import json
-
+ """ENG-616: soul/output mentions expand, while frontend workflow markers stay
+ literal in the workflow task layer and resolve under workflow context."""
context = _context()
context.snapshot.config_snapshot = AgentSoulConfig(
prompt={"system_prompt": "Careful. Ask [§human:c-1:EMAIL · DAVE§] when unsure."},
@@ -807,26 +938,189 @@ def test_mentions_expand_in_soul_and_job_prompts_without_token_leak():
context.binding.node_job_config = WorkflowNodeJobConfig.model_validate(
{
"workflow_prompt": (
- "Read [§node_output:previous-node.text:PREV/text§] and produce [§output:summary§]. "
+ "Read {{#previous-node.text#}} and produce [§output:summary§]. "
"Unknown [§knowledge:gone:旧手册§] degrades."
),
- "previous_node_output_refs": [
- {"selector": ["previous-node", "text"], "name": "PREV/text"},
- ],
"declared_outputs": [{"name": "summary", "type": "string"}],
}
)
result = WorkflowAgentRuntimeRequestBuilder(credentials_provider=FakeCredentialsProvider()).build(context)
- dumped = result.request.model_dump(mode="json")
- assert dumped["composition"]["layers"][0]["config"]["prefix"] == ("Careful. Ask EMAIL · David Hayes when unsure.")
- assert dumped["composition"]["layers"][1]["config"]["prefix"] == (
- "Read PREV/text and produce summary (string). Unknown 旧手册 degrades."
+ layers = _request_layers(result)
+ agent_soul_prompt = layers["agent_soul_prompt"]["config"]["prefix"]
+ job_prompt = layers["workflow_node_job_prompt"]["config"]["user"]
+ assert agent_soul_prompt == ("Careful. Ask EMAIL · David Hayes when unsure.")
+ assert job_prompt == "Read {{#previous-node.text#}} and produce summary (string). Unknown 旧手册 degrades."
+ user_prompt = _workflow_user_prompt(result)
+ assert "Agent task for this workflow run:" not in user_prompt
+ assert "Previous result" in user_prompt
+ for prompt_text in (agent_soul_prompt, job_prompt, user_prompt):
+ assert "[§" not in prompt_text
+ assert "{{#" in job_prompt
+ assert "{{#" not in agent_soul_prompt
+ assert "{{#" not in user_prompt
+
+
+def test_previous_node_file_output_uses_agent_stub_download_mapping_in_workflow_context():
+ file_reference = build_file_reference(record_id="tool-file-1")
+
+ class FileVariablePool(FakeVariablePool):
+ def get(self, selector):
+ if list(selector) == ["previous-node", "report"]:
+ return FileSegment(
+ value=File(
+ type=FileType.DOCUMENT,
+ transfer_method=FileTransferMethod.TOOL_FILE,
+ reference=file_reference,
+ remote_url=None,
+ filename="report.pdf",
+ extension=".pdf",
+ mime_type="application/pdf",
+ size=12,
+ )
+ )
+ return super().get(selector)
+
+ context = replace(_context(), variable_pool=FileVariablePool())
+ context.binding.node_job_config = WorkflowNodeJobConfig.model_validate(
+ {
+ "workflow_prompt": "Review {{#previous-node.report#}} before responding.",
+ }
+ )
+
+ result = WorkflowAgentRuntimeRequestBuilder(credentials_provider=FakeCredentialsProvider()).build(context)
+
+ assert _request_layers(result)["workflow_node_job_prompt"]["config"]["user"] == (
+ "Review {{#previous-node.report#}} before responding."
+ )
+ assert _previous_node_prompt_payload(result, "previous-node.report") == {
+ "transfer_method": "tool_file",
+ "reference": file_reference,
+ }
+
+
+def test_scalar_previous_node_output_appears_in_workflow_context_section():
+ context = _context()
+ context.binding.node_job_config = WorkflowNodeJobConfig.model_validate(
+ {
+ "workflow_prompt": "Review {{#previous-node.text#}} before responding.",
+ }
)
- # the value still rides the Workflow context block, not the job prompt
- assert "Previous result" in dumped["composition"]["layers"][2]["config"]["user"]
- assert "[§" not in json.dumps(dumped["composition"]["layers"][:3])
+
+ result = WorkflowAgentRuntimeRequestBuilder(credentials_provider=FakeCredentialsProvider()).build(context)
+
+ user_prompt = _workflow_user_prompt(result)
+
+ assert "- Previous node outputs:" in user_prompt
+ assert " - previous-node.text: Previous result" in user_prompt
+
+
+def test_stale_previous_node_refs_are_ignored_when_workflow_prompt_has_no_frontend_markers():
+ context = _context()
+ context.binding.node_job_config = WorkflowNodeJobConfig.model_validate(
+ {
+ "workflow_prompt": "Review the current request without upstream context.",
+ "previous_node_output_refs": [{"node_id": "missing-node", "output": "text"}],
+ }
+ )
+
+ result = WorkflowAgentRuntimeRequestBuilder(credentials_provider=FakeCredentialsProvider()).build(context)
+
+ assert _request_layers(result)["workflow_node_job_prompt"]["config"]["user"] == (
+ "Review the current request without upstream context."
+ )
+ assert "Previous node outputs:" not in _workflow_user_prompt(result)
+
+
+def test_previous_node_file_array_uses_agent_stub_download_mappings_in_workflow_context():
+ first_reference = build_file_reference(record_id="tool-file-1")
+ second_reference = build_file_reference(record_id="tool-file-2")
+
+ class FileArrayVariablePool(FakeVariablePool):
+ def get(self, selector):
+ if list(selector) == ["previous-node", "attachments"]:
+ return ArrayFileSegment(
+ value=[
+ File(
+ type=FileType.DOCUMENT,
+ transfer_method=FileTransferMethod.TOOL_FILE,
+ reference=first_reference,
+ remote_url=None,
+ filename="first.pdf",
+ extension=".pdf",
+ mime_type="application/pdf",
+ size=12,
+ ),
+ File(
+ type=FileType.DOCUMENT,
+ transfer_method=FileTransferMethod.REMOTE_URL,
+ reference=None,
+ remote_url="https://example.com/second.pdf",
+ filename="second.pdf",
+ extension=".pdf",
+ mime_type="application/pdf",
+ size=12,
+ ),
+ ]
+ )
+ return super().get(selector)
+
+ context = replace(_context(), variable_pool=FileArrayVariablePool())
+ context.binding.node_job_config = WorkflowNodeJobConfig.model_validate(
+ {
+ "workflow_prompt": "Inspect {{#previous-node.attachments#}}",
+ }
+ )
+
+ result = WorkflowAgentRuntimeRequestBuilder(credentials_provider=FakeCredentialsProvider()).build(context)
+
+ assert _previous_node_prompt_payload(result, "previous-node.attachments") == [
+ {
+ "transfer_method": "tool_file",
+ "reference": first_reference,
+ },
+ {
+ "transfer_method": "remote_url",
+ "url": "https://example.com/second.pdf",
+ },
+ ]
+
+
+def test_previous_node_remote_url_file_mapping_is_not_truncated_in_workflow_context():
+ remote_url = "https://example.com/" + ("a" * 2100) + ".pdf"
+
+ class LongRemoteUrlVariablePool(FakeVariablePool):
+ def get(self, selector):
+ if list(selector) == ["previous-node", "report"]:
+ return FileSegment(
+ value=File(
+ type=FileType.DOCUMENT,
+ transfer_method=FileTransferMethod.REMOTE_URL,
+ reference=None,
+ remote_url=remote_url,
+ filename="report.pdf",
+ extension=".pdf",
+ mime_type="application/pdf",
+ size=12,
+ )
+ )
+ return super().get(selector)
+
+ context = replace(_context(), variable_pool=LongRemoteUrlVariablePool())
+ context.binding.node_job_config = WorkflowNodeJobConfig.model_validate(
+ {
+ "workflow_prompt": "Use {{#previous-node.report#}}",
+ }
+ )
+
+ result = WorkflowAgentRuntimeRequestBuilder(credentials_provider=FakeCredentialsProvider()).build(context)
+
+ assert _previous_node_prompt_payload(result, "previous-node.report") == {
+ "transfer_method": "remote_url",
+ "url": remote_url,
+ }
+ assert "...[truncated]" not in _workflow_user_prompt(result)
# ── ENG-623: dify.drive declaration layer ─────────────────────────────────────
@@ -931,10 +1225,9 @@ def test_workflow_run_request_contains_drive_layer_with_empty_catalog(monkeypatc
"mentioned_skill_keys": [],
"mentioned_file_keys": [],
}
- assert layers[DIFY_SHELL_LAYER_ID]["deps"] == {
- "execution_context": DIFY_EXECUTION_CONTEXT_LAYER_ID,
- "drive": "drive",
- }
+ assert layers[DIFY_SHELL_LAYER_ID]["deps"] == {"execution_context": DIFY_EXECUTION_CONTEXT_LAYER_ID}
+ assert layers[DIFY_SHELL_LAYER_ID]["config"]["agent_stub_drive_ref"] == "agent-agent-1"
+ assert layers["drive"]["deps"] == {"shell": DIFY_SHELL_LAYER_ID}
def test_build_drive_layer_config_requires_agent_identity():
@@ -960,11 +1253,12 @@ def test_workflow_run_request_contains_drive_layer_when_flag_enabled(monkeypatch
dumped = result.request.model_dump(mode="json")
layer_names = [layer["name"] for layer in dumped["composition"]["layers"]]
assert "drive" in layer_names
- # injected right after execution_context, before history/llm
- assert layer_names.index("drive") == layer_names.index("execution_context") + 1
+ # shell enters first; drive uses that shell to materialize mentioned targets.
+ assert layer_names.index(DIFY_SHELL_LAYER_ID) == layer_names.index("execution_context") + 1
+ assert layer_names.index("drive") == layer_names.index(DIFY_SHELL_LAYER_ID) + 1
drive = 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["deps"] == {"shell": DIFY_SHELL_LAYER_ID}
assert drive["config"]["drive_ref"] == "agent-agent-1"
assert drive["config"]["skills"] == [
{
@@ -1031,7 +1325,10 @@ def test_workflow_runtime_missing_drive_mentions_fall_back_to_label_then_decoded
assert "[§" not in soul_prompt.config.prefix
-def test_workflow_run_request_has_no_drive_layer_when_flag_disabled():
+def test_workflow_run_request_has_no_drive_layer_when_flag_disabled(monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setattr(
+ "core.workflow.nodes.agent_v2.runtime_request_builder.dify_config.AGENT_DRIVE_MANIFEST_ENABLED", False
+ )
context = _context()
context.snapshot.config_snapshot = _soul_with_drive_skill()
@@ -1094,7 +1391,15 @@ def test_feature_manifest_marks_knowledge_supported_without_warning_when_configu
soul = AgentSoulConfig.model_validate(
{
"knowledge": {
- "datasets": [{"id": "dataset-1", "name": "Product Docs"}],
+ "sets": [
+ {
+ "id": "product",
+ "name": "Product Docs",
+ "datasets": [{"id": "dataset-1", "name": "Product Docs"}],
+ "query": {"mode": "generated_query"},
+ "retrieval": {"mode": "multiple", "top_k": 4},
+ }
+ ],
}
}
)
@@ -1106,13 +1411,13 @@ def test_feature_manifest_marks_knowledge_supported_without_warning_when_configu
assert all("knowledge" not in w["section"] for w in manifest["unsupported_runtime_warnings"])
-def test_feature_manifest_treats_blank_knowledge_dataset_ids_as_not_configured():
+def test_feature_manifest_treats_empty_knowledge_sets_as_not_configured():
from core.workflow.nodes.agent_v2.runtime_feature_manifest import build_runtime_feature_manifest
soul = AgentSoulConfig.model_validate(
{
"knowledge": {
- "datasets": [{"id": " "}, {}],
+ "sets": [],
}
}
)
diff --git a/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_validators.py b/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_validators.py
index 440bd49e5c0..2254cd16d49 100644
--- a/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_validators.py
+++ b/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_validators.py
@@ -55,6 +55,33 @@ def _snapshot() -> AgentConfigSnapshot:
)
+def _snapshot_with_knowledge_dataset(dataset_id: str) -> AgentConfigSnapshot:
+ return AgentConfigSnapshot(
+ id="snapshot-1",
+ tenant_id="tenant-1",
+ agent_id="agent-1",
+ version=1,
+ config_snapshot=AgentSoulConfig(
+ model=AgentSoulModelConfig(
+ plugin_id="langgenius/openai",
+ model_provider="openai",
+ model="gpt-test",
+ ),
+ knowledge={
+ "sets": [
+ {
+ "id": "support",
+ "name": "Support KB",
+ "datasets": [{"id": dataset_id}],
+ "query": {"mode": "generated_query"},
+ "retrieval": {"mode": "multiple", "top_k": 4},
+ }
+ ]
+ },
+ ),
+ )
+
+
def _graph(edges: list[dict]) -> dict:
return {
"nodes": [
@@ -515,6 +542,35 @@ def test_publish_validation_rejects_missing_file_ref():
)
+def test_publish_validation_rejects_missing_or_out_of_scope_knowledge_datasets(
+ monkeypatch: pytest.MonkeyPatch,
+):
+ dataset_id = "550e8400-e29b-41d4-a716-446655440000"
+ node_job = WorkflowNodeJobConfig.model_validate({})
+ snapshot = _snapshot_with_knowledge_dataset(dataset_id)
+ session = Mock()
+ session.scalar.side_effect = [_binding(node_job), _agent(), snapshot]
+
+ captured = {}
+
+ def fake_get_datasets_by_ids(ids, tenant_id):
+ captured["ids"] = ids
+ captured["tenant_id"] = tenant_id
+ return [], 0
+
+ import services.dataset_service as dataset_service_module
+
+ monkeypatch.setattr(dataset_service_module.DatasetService, "get_datasets_by_ids", fake_get_datasets_by_ids)
+
+ with pytest.raises(WorkflowAgentNodeValidationError, match=dataset_id):
+ WorkflowAgentNodeValidator.validate_published_workflow(
+ session=session,
+ workflow=_workflow(_graph([{"source": "start", "target": "agent-node"}])),
+ )
+
+ assert captured == {"ids": [dataset_id], "tenant_id": "tenant-1"}
+
+
def test_publish_validation_accepts_tool_node_agentic_manual_mode():
session = Mock()
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.py
index cd97559725e..691a1c61cc5 100644
--- 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.py
@@ -64,7 +64,7 @@ def _run_migration_step(module: object, engine: sa.Engine, step_name: str) -> No
module.op = original_op
-def test_upgrade_adds_skill_columns_and_index_and_strips_snapshot_data() -> None:
+def test_upgrade_adds_skill_columns_and_index_and_preserves_snapshot_data() -> None:
engine = sa.create_engine("sqlite:///:memory:")
_create_pre_upgrade_schema(engine)
snapshot = {
@@ -91,7 +91,7 @@ def test_upgrade_adds_skill_columns_and_index_and_strips_snapshot_data() -> None
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)
+ assert json.loads(stored_snapshot) == snapshot
def test_downgrade_drops_skill_columns_and_index_without_reconstructing_legacy_data() -> None:
diff --git a/api/tests/unit_tests/models/test_agent.py b/api/tests/unit_tests/models/test_agent.py
index 422a3218eaa..fb2e834e8ac 100644
--- a/api/tests/unit_tests/models/test_agent.py
+++ b/api/tests/unit_tests/models/test_agent.py
@@ -7,6 +7,8 @@ from sqlalchemy.exc import IntegrityError
from models.agent import (
Agent,
+ AgentConfigDraft,
+ AgentConfigDraftType,
AgentConfigRevision,
AgentConfigRevisionOperation,
AgentConfigSnapshot,
@@ -34,6 +36,9 @@ def test_agent_enums_match_prd_boundaries():
assert AgentStatus.ARCHIVED.value == "archived"
assert AgentConfigRevisionOperation.SAVE_CURRENT_VERSION.value == "save_current_version"
assert AgentConfigRevisionOperation.RESTORE_VERSION.value == "restore_version"
+ assert AgentConfigRevisionOperation.PUBLISH_DRAFT.value == "publish_draft"
+ assert AgentConfigDraftType.DRAFT.value == "draft"
+ assert AgentConfigDraftType.DEBUG_BUILD.value == "debug_build"
assert WorkflowAgentBindingType.ROSTER_AGENT.value == "roster_agent"
assert WorkflowAgentBindingType.INLINE_AGENT.value == "inline_agent"
@@ -136,6 +141,23 @@ def test_current_snapshot_stores_agent_soul_snapshot_as_long_text_json():
assert version.config_snapshot_dict["env"]["secret_refs"][0]["provider_credential_id"] == "cred-1"
+def test_agent_config_draft_stores_editable_agent_soul_as_long_text_json():
+ config_snapshot = AgentSoulConfig.model_validate({"prompt": {"system_prompt": "draft prompt"}})
+ draft = AgentConfigDraft(
+ tenant_id="tenant-1",
+ agent_id="agent-1",
+ draft_type=AgentConfigDraftType.DRAFT,
+ draft_owner_key="",
+ config_snapshot=config_snapshot,
+ )
+
+ config_snapshot_column = AgentConfigDraft.__table__.c.config_snapshot
+ assert isinstance(config_snapshot_column.type, JSONModelColumn)
+ assert config_snapshot_column.server_default is None
+ assert draft.config_snapshot_dict == config_snapshot.model_dump(mode="json")
+ assert draft.config_snapshot_dict["prompt"]["system_prompt"] == "draft prompt"
+
+
def test_workflow_binding_stores_node_job_config_separately_from_agent_soul():
node_job_config = {
"schema_version": 1,
@@ -166,6 +188,7 @@ def test_long_text_columns_do_not_use_mysql_incompatible_server_defaults():
assert isinstance(column.type, LongText)
assert column.server_default is None
assert AgentConfigSnapshot.__table__.c.config_snapshot.server_default is None
+ assert AgentConfigDraft.__table__.c.config_snapshot.server_default is None
assert WorkflowAgentNodeBinding.__table__.c.node_job_config.server_default is None
diff --git a/api/tests/unit_tests/services/agent/test_agent_composer_entities.py b/api/tests/unit_tests/services/agent/test_agent_composer_entities.py
index 23988c2ec20..43323ca49b4 100644
--- a/api/tests/unit_tests/services/agent/test_agent_composer_entities.py
+++ b/api/tests/unit_tests/services/agent/test_agent_composer_entities.py
@@ -1,4 +1,5 @@
import pytest
+from pydantic import ValidationError
from models.agent_config_entities import AgentKnowledgeQueryMode, AgentSoulModelConfig, DeclaredOutputType
from services.agent.composer_service import AgentComposerService
@@ -26,6 +27,24 @@ def test_workflow_variant_rejects_agent_app_only_fields():
)
+def test_workflow_variant_accepts_agent_soul_files_section():
+ payload = ComposerSavePayload.model_validate(
+ {
+ "variant": ComposerVariant.WORKFLOW,
+ "save_strategy": ComposerSaveStrategy.NODE_JOB_ONLY,
+ "agent_soul": {
+ "schema_version": 1,
+ "prompt": {"system_prompt": "jjjj"},
+ "files": {"skills": [], "files": []},
+ },
+ }
+ )
+
+ assert payload.agent_soul is not None
+ assert payload.agent_soul.files.skills == []
+ assert payload.agent_soul.files.files == []
+
+
def test_agent_app_variant_rejects_workflow_node_job():
with pytest.raises(ValueError):
ComposerSavePayload.model_validate(
@@ -131,14 +150,144 @@ def test_knowledge_query_mode_uses_stable_backend_enums():
config = AgentSoulConfig.model_validate(
{
"knowledge": {
- "datasets": [{"dataset_id": "dataset-1"}],
- "query_mode": "generated_query",
- "query_config": {"generation_prompt": "Create a retrieval query."},
+ "sets": [
+ {
+ "id": "support",
+ "name": "Support KB",
+ "datasets": [{"id": "dataset-1"}],
+ "query": {"mode": "generated_query"},
+ "retrieval": {"mode": "multiple", "top_k": 4},
+ }
+ ],
}
}
)
- assert config.knowledge.query_mode == AgentKnowledgeQueryMode.GENERATED_QUERY
+ assert config.knowledge.sets[0].query.mode == AgentKnowledgeQueryMode.GENERATED_QUERY
+
+
+ ("knowledge_payload", "match"),
+ [
+ (
+ {
+ "sets": [
+ {
+ "id": "support",
+ "name": "Support KB",
+ "datasets": [{"id": "dataset-1"}],
+ "query": {"mode": "generated_query"},
+ "retrieval": {"mode": "multiple", "top_k": 4},
+ },
+ {
+ "id": "support",
+ "name": "Billing KB",
+ "datasets": [{"id": "dataset-2"}],
+ "query": {"mode": "generated_query"},
+ "retrieval": {"mode": "multiple", "top_k": 4},
+ },
+ ]
+ },
+ "knowledge set ids must be unique",
+ ),
+ (
+ {
+ "sets": [
+ {
+ "id": "support",
+ "name": "Shared KB",
+ "datasets": [{"id": "dataset-1"}],
+ "query": {"mode": "generated_query"},
+ "retrieval": {"mode": "multiple", "top_k": 4},
+ },
+ {
+ "id": "billing",
+ "name": "Shared KB",
+ "datasets": [{"id": "dataset-2"}],
+ "query": {"mode": "generated_query"},
+ "retrieval": {"mode": "multiple", "top_k": 4},
+ },
+ ]
+ },
+ "knowledge set names must be unique",
+ ),
+ (
+ {
+ "sets": [
+ {
+ "id": "support",
+ "name": "Support KB",
+ "datasets": [{"id": "dataset-1"}, {"id": " dataset-1 "}],
+ "query": {"mode": "generated_query"},
+ "retrieval": {"mode": "multiple", "top_k": 4},
+ },
+ ]
+ },
+ "knowledge set dataset ids must be unique",
+ ),
+ (
+ {
+ "sets": [
+ {
+ "id": "support",
+ "name": "Support KB",
+ "datasets": [{"id": "dataset-1"}],
+ "query": {"mode": "user_query"},
+ "retrieval": {"mode": "multiple", "top_k": 4},
+ },
+ ]
+ },
+ "knowledge query.value is required for user_query mode",
+ ),
+ (
+ {
+ "sets": [
+ {
+ "id": "support",
+ "name": "Support KB",
+ "datasets": [{"id": "dataset-1"}],
+ "query": {"mode": "generated_query"},
+ "retrieval": {"mode": "single"},
+ },
+ ]
+ },
+ "knowledge retrieval.model is required for single mode",
+ ),
+ (
+ {
+ "sets": [
+ {
+ "id": "support",
+ "name": "Support KB",
+ "datasets": [{"id": "dataset-1"}],
+ "query": {"mode": "generated_query"},
+ "retrieval": {"mode": "multiple", "top_k": 4},
+ "metadata_filtering": {"mode": "automatic"},
+ },
+ ]
+ },
+ "metadata_filtering.model_config is required for automatic mode",
+ ),
+ (
+ {
+ "sets": [
+ {
+ "id": "support",
+ "name": "Support KB",
+ "datasets": [{"id": "dataset-1"}],
+ "query": {"mode": "generated_query"},
+ "retrieval": {"mode": "multiple", "top_k": 4},
+ "metadata_filtering": {"mode": "manual"},
+ },
+ ]
+ },
+ "metadata_filtering.conditions is required for manual mode",
+ ),
+ ],
+)
+def test_knowledge_sets_contract_rejects_invalid_configs(knowledge_payload, match: str):
+ with pytest.raises(ValidationError, match=match):
+ AgentSoulConfig.model_validate({"knowledge": knowledge_payload})
def test_agent_soul_model_config_is_first_class_without_credentials():
diff --git a/api/tests/unit_tests/services/agent/test_agent_services.py b/api/tests/unit_tests/services/agent/test_agent_services.py
index 1bac183c39f..60bc36c773f 100644
--- a/api/tests/unit_tests/services/agent/test_agent_services.py
+++ b/api/tests/unit_tests/services/agent/test_agent_services.py
@@ -8,6 +8,8 @@ from sqlalchemy.exc import IntegrityError
from core.workflow.nodes.agent_v2.validators import WorkflowAgentNodeValidationError
from models.agent import (
Agent,
+ AgentConfigDraft,
+ AgentConfigDraftType,
AgentConfigRevisionOperation,
AgentConfigSnapshot,
AgentDebugConversation,
@@ -26,8 +28,8 @@ from models.agent_config_entities import (
DeclaredOutputType,
WorkflowNodeJobConfig,
)
-from models.enums import ConversationFromSource, ConversationStatus
-from models.model import Conversation, IconType
+from models.enums import AppStatus, ConversationFromSource, ConversationStatus
+from models.model import App, AppMode, Conversation, IconType
from models.workflow import Workflow
from services.agent import composer_service, roster_service
from services.agent.agent_soul_state import agent_soul_has_model
@@ -37,6 +39,7 @@ from services.agent.errors import (
AgentNameConflictError,
AgentNotFoundError,
AgentVersionConflictError,
+ AgentVersionNotFoundError,
InvalidComposerConfigError,
)
from services.agent.roster_service import AgentRosterService
@@ -156,6 +159,96 @@ def test_load_workflow_composer_serializes_existing_binding(monkeypatch: pytest.
assert result == {"agent": "agent-1", "version": "version-1"}
+def test_load_workflow_composer_uses_roster_preview_snapshot(monkeypatch: pytest.MonkeyPatch):
+ binding = SimpleNamespace(
+ agent_id="agent-1",
+ binding_type=WorkflowAgentBindingType.ROSTER_AGENT,
+ current_snapshot_id="binding-version",
+ )
+ agent = SimpleNamespace(id="agent-1", scope=AgentScope.ROSTER, active_config_snapshot_id="active-version")
+
+ monkeypatch.setattr(AgentComposerService, "_get_draft_workflow", lambda **kwargs: SimpleNamespace(id="workflow-1"))
+ monkeypatch.setattr(AgentComposerService, "_get_workflow_binding", lambda **kwargs: binding)
+ monkeypatch.setattr(AgentComposerService, "_get_agent_if_present", lambda **kwargs: agent)
+ monkeypatch.setattr(
+ AgentComposerService,
+ "_require_version",
+ lambda **kwargs: SimpleNamespace(id=kwargs["version_id"]),
+ )
+ monkeypatch.setattr(
+ AgentComposerService,
+ "_serialize_workflow_state",
+ lambda **kwargs: {
+ "binding_snapshot_id": kwargs["binding"].current_snapshot_id,
+ "version": kwargs["version"].id,
+ },
+ )
+
+ result = AgentComposerService.load_workflow_composer(
+ tenant_id="tenant-1",
+ app_id="app-1",
+ node_id="node-1",
+ snapshot_id="preview-version",
+ )
+
+ assert result == {"binding_snapshot_id": "binding-version", "version": "preview-version"}
+
+
+def test_load_workflow_composer_uses_inline_preview_snapshot(monkeypatch: pytest.MonkeyPatch):
+ binding = SimpleNamespace(
+ agent_id="inline-agent-1",
+ binding_type=WorkflowAgentBindingType.INLINE_AGENT,
+ current_snapshot_id="inline-version-1",
+ app_id="app-1",
+ workflow_id="workflow-1",
+ node_id="node-1",
+ )
+ agent = SimpleNamespace(
+ id="inline-agent-1",
+ scope=AgentScope.WORKFLOW_ONLY,
+ app_id="app-1",
+ workflow_id="workflow-1",
+ workflow_node_id="node-1",
+ active_config_snapshot_id="inline-version-1",
+ )
+
+ monkeypatch.setattr(AgentComposerService, "_get_draft_workflow", lambda **kwargs: SimpleNamespace(id="workflow-1"))
+ monkeypatch.setattr(AgentComposerService, "_get_workflow_binding", lambda **kwargs: binding)
+ monkeypatch.setattr(AgentComposerService, "_get_agent_if_present", lambda **kwargs: agent)
+ monkeypatch.setattr(
+ AgentComposerService,
+ "_require_version",
+ lambda **kwargs: SimpleNamespace(id=kwargs["version_id"]),
+ )
+ monkeypatch.setattr(
+ AgentComposerService,
+ "_serialize_workflow_state",
+ lambda **kwargs: {"agent": kwargs["agent"].id, "version": kwargs["version"].id},
+ )
+
+ result = AgentComposerService.load_workflow_composer(
+ tenant_id="tenant-1",
+ app_id="app-1",
+ node_id="node-1",
+ snapshot_id="inline-preview-version",
+ )
+
+ assert result == {"agent": "inline-agent-1", "version": "inline-preview-version"}
+
+
+def test_load_workflow_composer_rejects_preview_without_binding(monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setattr(AgentComposerService, "_get_draft_workflow", lambda **kwargs: SimpleNamespace(id="workflow-1"))
+ monkeypatch.setattr(AgentComposerService, "_get_workflow_binding", lambda **kwargs: None)
+
+ with pytest.raises(AgentVersionNotFoundError):
+ AgentComposerService.load_workflow_composer(
+ tenant_id="tenant-1",
+ app_id="app-1",
+ node_id="node-1",
+ snapshot_id="preview-version",
+ )
+
+
@pytest.mark.parametrize(
("strategy", "helper_name"),
[
@@ -271,16 +364,16 @@ def test_publish_save_strategies_run_publish_validation(strategy: ComposerSaveSt
def test_save_agent_app_composer_creates_agent_when_missing(monkeypatch: pytest.MonkeyPatch):
fake_session = FakeSession(scalar=[None])
- created_version = SimpleNamespace(id="version-1")
+ saved_draft = SimpleNamespace(id="draft-1", config_snapshot_dict={"prompt": {"system_prompt": "x"}})
monkeypatch.setattr(composer_service.db, "session", fake_session)
monkeypatch.setattr(composer_service.ComposerConfigValidator, "validate_draft_save_payload", lambda payload: None)
- monkeypatch.setattr(AgentComposerService, "_create_config_version", lambda **kwargs: created_version)
- monkeypatch.setattr(AgentComposerService, "load_agent_app_composer", lambda **kwargs: {"loaded": True})
+ monkeypatch.setattr(AgentComposerService, "_save_agent_draft", lambda **kwargs: saved_draft)
+ monkeypatch.setattr(AgentComposerService, "load_agent_composer", lambda **kwargs: {"loaded": True})
payload = ComposerSavePayload.model_validate(
{
"variant": ComposerVariant.AGENT_APP.value,
- "save_strategy": ComposerSaveStrategy.SAVE_AS_NEW_VERSION.value,
+ "save_strategy": ComposerSaveStrategy.SAVE_TO_CURRENT_VERSION.value,
"new_agent_name": "Analyst",
"agent_soul": {"prompt": {"system_prompt": "x"}},
}
@@ -293,25 +386,72 @@ def test_save_agent_app_composer_creates_agent_when_missing(monkeypatch: pytest.
assert result.pop("validation") == {"warnings": [], "knowledge_retrieval_placeholder": []}
assert result == {"loaded": True}
assert fake_session.added[0].name == "Analyst"
- assert fake_session.added[0].active_config_snapshot_id == "version-1"
- assert fake_session.added[0].active_config_has_model is False
+ assert fake_session.added[0].active_config_snapshot_id is None
+ assert fake_session.added[0].active_config_is_published is False
assert fake_session.commits == 1
-def test_save_agent_app_composer_updates_current_version(monkeypatch: pytest.MonkeyPatch):
- agent = SimpleNamespace(id="agent-1", active_config_snapshot_id="version-1", updated_by=None)
+def test_load_agent_app_composer_exposes_draft_save_only(monkeypatch: pytest.MonkeyPatch):
+ agent = SimpleNamespace(
+ id="agent-1",
+ active_config_snapshot_id="version-1",
+ updated_by="account-1",
+ created_by="account-1",
+ app_id="app-1",
+ backing_app_id="app-1",
+ scope=AgentScope.ROSTER,
+ status=AgentStatus.ACTIVE,
+ )
+ draft = SimpleNamespace(config_snapshot_dict={"prompt": {"system_prompt": "x"}})
+
+ monkeypatch.setattr(AgentComposerService, "_require_agent_app_agent", lambda **kwargs: agent)
+ monkeypatch.setattr(AgentComposerService, "_get_or_create_agent_draft", lambda **kwargs: draft)
+ monkeypatch.setattr(AgentComposerService, "_get_version_if_present", lambda **kwargs: None)
+ monkeypatch.setattr(AgentComposerService, "_serialize_agent", lambda _agent: {"id": _agent.id})
+ monkeypatch.setattr(AgentComposerService, "_serialize_version", lambda _version: None)
+ monkeypatch.setattr(AgentComposerService, "_serialize_draft", lambda _draft: {"id": "draft-1"})
+
+ result = AgentComposerService.load_agent_app_composer(tenant_id="tenant-1", app_id="app-1")
+
+ assert result["save_options"] == [ComposerSaveStrategy.SAVE_TO_CURRENT_VERSION.value]
+
+
+def test_save_agent_app_composer_rejects_version_save_strategy():
+ payload = ComposerSavePayload.model_validate(
+ {
+ "variant": ComposerVariant.AGENT_APP.value,
+ "save_strategy": ComposerSaveStrategy.SAVE_AS_NEW_VERSION.value,
+ "agent_soul": {"prompt": {"system_prompt": "x"}},
+ }
+ )
+
+ with pytest.raises(InvalidComposerConfigError, match="Use the publish endpoint"):
+ AgentComposerService.save_agent_app_composer(
+ tenant_id="tenant-1",
+ app_id="app-1",
+ account_id="account-1",
+ payload=payload,
+ )
+
+
+def test_save_agent_app_composer_updates_normal_draft(monkeypatch: pytest.MonkeyPatch):
+ agent = SimpleNamespace(
+ id="agent-1",
+ active_config_snapshot_id="version-1",
+ active_config_is_published=True,
+ updated_by=None,
+ )
fake_session = FakeSession(scalar=[agent])
- updated = {}
+ saved = {}
monkeypatch.setattr(composer_service.db, "session", fake_session)
monkeypatch.setattr(composer_service.ComposerConfigValidator, "validate_draft_save_payload", lambda payload: None)
- monkeypatch.setattr(AgentComposerService, "_require_version", lambda **kwargs: SimpleNamespace(id="version-1"))
monkeypatch.setattr(
AgentComposerService,
- "_update_current_version",
- lambda **kwargs: updated.update(kwargs) or SimpleNamespace(id="version-2"),
+ "_save_agent_draft",
+ lambda **kwargs: saved.update(kwargs) or SimpleNamespace(id="draft-1"),
)
- monkeypatch.setattr(AgentComposerService, "load_agent_app_composer", lambda **kwargs: {"loaded": True})
+ monkeypatch.setattr(AgentComposerService, "load_agent_composer", lambda **kwargs: {"loaded": True})
payload = ComposerSavePayload.model_validate(
{
"variant": ComposerVariant.AGENT_APP.value,
@@ -326,12 +466,122 @@ def test_save_agent_app_composer_updates_current_version(monkeypatch: pytest.Mon
assert result.pop("validation") == {"warnings": [], "knowledge_retrieval_placeholder": []}
assert result == {"loaded": True}
- assert updated["operation"].value == "save_current_version"
- assert agent.active_config_has_model is True
+ assert saved["draft_type"] == AgentConfigDraftType.DRAFT
+ assert saved["agent_soul"].model_dump(mode="json") == _agent_soul_with_model().model_dump(mode="json")
+ assert agent.active_config_is_published is False
assert fake_session._scalar == []
assert fake_session.commits == 1
+def test_publish_agent_app_draft_creates_published_snapshot(monkeypatch: pytest.MonkeyPatch):
+ agent = Agent(
+ id="agent-1",
+ tenant_id="tenant-1",
+ name="Iris",
+ description="",
+ agent_kind=AgentKind.DIFY_AGENT,
+ scope=AgentScope.ROSTER,
+ source=AgentSource.AGENT_APP,
+ status=AgentStatus.ACTIVE,
+ active_config_snapshot_id="version-1",
+ )
+ draft = AgentConfigDraft(
+ tenant_id="tenant-1",
+ agent_id="agent-1",
+ draft_type=AgentConfigDraftType.DRAFT,
+ draft_owner_key="",
+ base_snapshot_id="version-1",
+ config_snapshot=_agent_soul_with_model(),
+ )
+ version = SimpleNamespace(id="version-2")
+ fake_session = FakeSession(scalar=[agent, draft])
+ created: dict[str, object] = {}
+
+ monkeypatch.setattr(composer_service.db, "session", fake_session)
+ monkeypatch.setattr(composer_service.ComposerConfigValidator, "validate_publish_payload", lambda payload: None)
+ monkeypatch.setattr(AgentComposerService, "validate_knowledge_datasets", lambda **kwargs: None)
+ monkeypatch.setattr(
+ AgentComposerService,
+ "_create_config_version",
+ lambda **kwargs: created.update(kwargs) or version,
+ )
+ monkeypatch.setattr(AgentComposerService, "_serialize_version", lambda _version: {"id": _version.id})
+
+ result = AgentComposerService.publish_agent_app_draft(
+ tenant_id="tenant-1",
+ agent_id="agent-1",
+ account_id="account-1",
+ version_note="ship it",
+ )
+
+ assert result["result"] == "success"
+ assert result["active_config_snapshot_id"] == "version-2"
+ assert result["draft"]["base_snapshot_id"] == "version-2"
+ assert created["operation"] == AgentConfigRevisionOperation.PUBLISH_DRAFT
+ assert created["previous_snapshot_id"] == "version-1"
+ assert agent.active_config_snapshot_id == "version-2"
+ assert agent.active_config_has_model is True
+ assert agent.active_config_is_published is True
+ assert fake_session.commits == 1
+
+
+def test_agent_app_build_draft_checkout_and_apply_use_user_isolated_draft(monkeypatch: pytest.MonkeyPatch):
+ agent = Agent(
+ id="agent-1",
+ tenant_id="tenant-1",
+ name="Iris",
+ description="",
+ agent_kind=AgentKind.DIFY_AGENT,
+ scope=AgentScope.ROSTER,
+ source=AgentSource.AGENT_APP,
+ status=AgentStatus.ACTIVE,
+ active_config_snapshot_id="version-1",
+ active_config_is_published=True,
+ )
+ normal_draft = AgentConfigDraft(
+ tenant_id="tenant-1",
+ agent_id="agent-1",
+ draft_type=AgentConfigDraftType.DRAFT,
+ account_id=None,
+ draft_owner_key="",
+ base_snapshot_id="version-1",
+ config_snapshot=_agent_soul_with_model(),
+ )
+ fake_session = FakeSession(scalar=[agent, normal_draft, None])
+
+ monkeypatch.setattr(composer_service.db, "session", fake_session)
+
+ checked_out = AgentComposerService.checkout_agent_app_build_draft(
+ tenant_id="tenant-1",
+ agent_id="agent-1",
+ account_id="account-1",
+ )
+
+ build_draft = fake_session.added[0]
+ assert checked_out["draft"]["id"] == build_draft.id
+ assert checked_out["draft"]["draft_type"] == AgentConfigDraftType.DEBUG_BUILD.value
+ assert checked_out["draft"]["account_id"] == "account-1"
+ assert checked_out["draft"]["base_snapshot_id"] == "version-1"
+ assert checked_out["agent_soul"] == normal_draft.config_snapshot_dict
+ assert fake_session.commits == 1
+
+ fake_session = FakeSession(scalar=[agent, build_draft, normal_draft])
+ monkeypatch.setattr(composer_service.db, "session", fake_session)
+
+ applied = AgentComposerService.apply_agent_app_build_draft(
+ tenant_id="tenant-1",
+ agent_id="agent-1",
+ account_id="account-1",
+ )
+
+ assert applied["result"] == "success"
+ assert applied["draft"]["id"] == normal_draft.id
+ assert normal_draft.config_snapshot_dict == build_draft.config_snapshot_dict
+ assert agent.active_config_is_published is False
+ assert fake_session.deleted == [build_draft]
+ assert fake_session.commits == 1
+
+
def test_agent_app_composer_candidates_and_impact(monkeypatch: pytest.MonkeyPatch):
bindings = [
SimpleNamespace(app_id="app-1", workflow_id="workflow-1", node_id="node-1"),
@@ -345,14 +595,14 @@ def test_agent_app_composer_candidates_and_impact(monkeypatch: pytest.MonkeyPatc
raise ValueError("draft workflow not found")
monkeypatch.setattr(AgentComposerService, "_get_draft_workflow", _no_draft_workflow)
- monkeypatch.setattr(AgentComposerService, "_load_agent_app_soul", lambda **kwargs: None)
+ monkeypatch.setattr(AgentComposerService, "_load_agent_soul", lambda **kwargs: None)
monkeypatch.setattr(AgentComposerService, "_workspace_dify_tools", lambda **kwargs: [])
workflow_candidates = AgentComposerService.get_workflow_candidates(
tenant_id="tenant-1", app_id="app-1", node_id="node-1", user_id="account-1"
)
agent_app_candidates = AgentComposerService.get_agent_app_candidates(
- tenant_id="tenant-1", app_id="app-1", user_id="account-1"
+ tenant_id="tenant-1", agent_id="agent-1", user_id="account-1"
)
impact = AgentComposerService.calculate_impact(tenant_id="tenant-1", current_snapshot_id="version-1")
@@ -376,13 +626,28 @@ def test_serialize_workflow_state_changes_lock_and_save_options(monkeypatch: pyt
node_id="node-1",
node_job_config='{"workflow_prompt":"do work"}',
)
- agent = Agent(id="agent-1", name="Analyst", description="", scope=AgentScope.ROSTER, status=AgentStatus.ACTIVE)
+ agent = Agent(
+ id="agent-1",
+ name="Analyst",
+ description="Clarifies tenders",
+ role="Tender Analyst",
+ icon_type="emoji",
+ icon="robot",
+ icon_background="#F5F3FF",
+ scope=AgentScope.ROSTER,
+ source=AgentSource.ROSTER,
+ status=AgentStatus.ACTIVE,
+ )
version = AgentConfigSnapshot(id="version-1", version=1, config_snapshot='{"prompt":{"system_prompt":"x"}}')
monkeypatch.setattr(AgentComposerService, "calculate_impact", lambda **kwargs: {"workflow_node_count": 1})
state = AgentComposerService._serialize_workflow_state(binding=binding, agent=agent, version=version)
assert state["soul_lock"]["locked"] is True
+ assert state["agent"]["role"] == "Tender Analyst"
+ assert state["agent"]["icon_type"] == "emoji"
+ assert state["agent"]["icon"] == "robot"
+ assert state["agent"]["icon_background"] == "#F5F3FF"
assert "save_as_new_version" in state["save_options"]
assert state["agent_soul"]["app_features"] == {}
# Stage 4 §10.1 (D-3): binding with no declared_outputs → response surfaces
@@ -404,7 +669,14 @@ def test_serialize_workflow_state_passes_user_declared_outputs_through_effective
'{"workflow_prompt":"work","declared_outputs":[{"name":"summary","type":"string","required":true}]}'
),
)
- agent = Agent(id="agent-1", name="Analyst", description="", scope=AgentScope.ROSTER, status=AgentStatus.ACTIVE)
+ agent = Agent(
+ id="agent-1",
+ name="Analyst",
+ description="",
+ scope=AgentScope.ROSTER,
+ source=AgentSource.ROSTER,
+ status=AgentStatus.ACTIVE,
+ )
version = AgentConfigSnapshot(id="version-1", version=1, config_snapshot='{"prompt":{"system_prompt":"x"}}')
monkeypatch.setattr(AgentComposerService, "calculate_impact", lambda **kwargs: {"workflow_node_count": 1})
@@ -1196,6 +1468,7 @@ def test_composer_create_agents_syncs_active_config_has_model(monkeypatch: pytes
fake_session = FakeSession()
monkeypatch.setattr(composer_service.db, "session", fake_session)
created_apps = []
+ hidden_backing_apps = []
backing_agent = Agent(
id="roster-agent-1",
tenant_id="tenant-1",
@@ -1215,6 +1488,10 @@ def test_composer_create_agents_syncs_active_config_has_model(monkeypatch: pytes
def __init__(self, session):
self.session = session
+ def create_hidden_backing_app_for_workflow_agent(self, **kwargs):
+ hidden_backing_apps.append(kwargs)
+ return SimpleNamespace(id="hidden-app-1")
+
def get_app_backing_agent(self, *, tenant_id, app_id):
assert tenant_id == "tenant-1"
assert app_id == "app-agent-1"
@@ -1253,6 +1530,8 @@ def test_composer_create_agents_syncs_active_config_has_model(monkeypatch: pytes
assert workflow_agent.active_config_snapshot_id == "version-with-model"
assert workflow_agent.active_config_has_model is True
+ assert workflow_agent.backing_app_id == "hidden-app-1"
+ assert hidden_backing_apps[0]["name"] == "Workflow Agent node-1"
assert roster_agent.active_config_snapshot_id == "version-with-model"
assert roster_agent.active_config_has_model is True
assert roster_agent.source == AgentSource.AGENT_APP
@@ -1411,7 +1690,11 @@ def test_composer_current_version_and_error_paths(monkeypatch: pytest.MonkeyPatc
config_snapshot='{"prompt":{"system_prompt":"old"}}',
)
monkeypatch.setattr(AgentComposerService, "_require_version", lambda **kwargs: version)
- monkeypatch.setattr(AgentComposerService, "_require_agent", lambda **kwargs: SimpleNamespace(updated_by=None))
+ monkeypatch.setattr(
+ AgentComposerService,
+ "_require_agent",
+ lambda **kwargs: SimpleNamespace(updated_by=None, active_config_is_published=False),
+ )
result = AgentComposerService._save_to_current_version(
tenant_id="tenant-1", account_id="account-1", binding=binding, payload=payload
@@ -1461,6 +1744,7 @@ def test_roster_list_and_invite_options(monkeypatch: pytest.MonkeyPatch):
version.created_at = version_created_at
agent.active_config_snapshot_id = "version-1"
agent.active_config_has_model = True
+ agent.active_config_is_published = True
unconfigured_agent = Agent(
id="agent-2",
tenant_id="tenant-1",
@@ -1492,7 +1776,6 @@ def test_roster_list_and_invite_options(monkeypatch: pytest.MonkeyPatch):
lambda version_ids: {"version-1": version, "version-2": unconfigured_version},
)
monkeypatch.setattr(service, "_load_published_references_by_agent_id", lambda **kwargs: {})
- monkeypatch.setattr(service, "_load_published_active_snapshot_agent_ids", lambda **kwargs: {"agent-1"})
listed = service.list_roster_agents(tenant_id="tenant-1", page=1, limit=20)
invited = service.list_invite_options(tenant_id="tenant-1", page=1, limit=20, app_id="app-1")
@@ -1536,7 +1819,6 @@ def test_invite_options_uses_db_filtered_pagination(monkeypatch: pytest.MonkeyPa
},
)
monkeypatch.setattr(service, "_load_published_references_by_agent_id", lambda **kwargs: {})
- monkeypatch.setattr(service, "_load_published_active_snapshot_agent_ids", lambda **kwargs: set())
result = service.list_invite_options(tenant_id="tenant-1", page=1, limit=1)
@@ -1545,7 +1827,7 @@ def test_invite_options_uses_db_filtered_pagination(monkeypatch: pytest.MonkeyPa
assert [item["id"] for item in result["data"]] == ["agent-2"]
-def test_active_config_is_published_flags_handle_matching_and_empty_snapshots():
+def test_active_config_is_published_flags_use_stored_agent_state():
agent = Agent(
id="agent-1",
tenant_id="tenant-1",
@@ -1556,6 +1838,7 @@ def test_active_config_is_published_flags_handle_matching_and_empty_snapshots():
source=AgentSource.AGENT_APP,
status=AgentStatus.ACTIVE,
active_config_snapshot_id="version-1",
+ active_config_is_published=True,
)
draft_agent = Agent(
id="agent-2",
@@ -1567,12 +1850,27 @@ def test_active_config_is_published_flags_handle_matching_and_empty_snapshots():
source=AgentSource.AGENT_APP,
status=AgentStatus.ACTIVE,
active_config_snapshot_id=None,
+ active_config_is_published=True,
+ )
+ dirty_agent = Agent(
+ id="agent-3",
+ tenant_id="tenant-1",
+ name="Dirty",
+ description="",
+ agent_kind=AgentKind.DIFY_AGENT,
+ scope=AgentScope.ROSTER,
+ source=AgentSource.AGENT_APP,
+ status=AgentStatus.ACTIVE,
+ active_config_snapshot_id="version-3",
+ active_config_is_published=False,
)
- service = AgentRosterService(FakeSession(scalars=[["agent-1"], ["agent-1"]]))
+ service = AgentRosterService(FakeSession())
- flags = service.load_active_config_is_published_by_agent_id(tenant_id="tenant-1", agents=[agent, draft_agent])
+ flags = service.load_active_config_is_published_by_agent_id(
+ tenant_id="tenant-1", agents=[agent, draft_agent, dirty_agent]
+ )
- assert flags == {"agent-1": True, "agent-2": False}
+ assert flags == {"agent-1": True, "agent-2": False, "agent-3": False}
assert service.active_config_is_published(tenant_id="tenant-1", agent=agent) is True
assert AgentRosterService(FakeSession()).load_active_config_is_published_by_agent_id(
tenant_id="tenant-1",
@@ -1580,6 +1878,62 @@ def test_active_config_is_published_flags_handle_matching_and_empty_snapshots():
) == {"agent-2": False}
+def test_active_config_is_published_skips_empty_agent_ids():
+ empty_id_agent = Agent(
+ id="",
+ tenant_id="tenant-1",
+ name="Broken",
+ description="",
+ agent_kind=AgentKind.DIFY_AGENT,
+ scope=AgentScope.ROSTER,
+ source=AgentSource.AGENT_APP,
+ status=AgentStatus.ACTIVE,
+ active_config_snapshot_id=None,
+ )
+ fake_session = FakeSession(scalars=[["should-not-be-read"]])
+
+ assert (
+ AgentRosterService(fake_session).load_active_config_is_published_by_agent_id(
+ tenant_id="tenant-1",
+ agents=[empty_id_agent],
+ )
+ == {}
+ )
+ assert fake_session._scalars == [["should-not-be-read"]]
+
+
+def test_load_app_backing_agents_skips_empty_agent_ids():
+ valid_agent = Agent(
+ id="agent-1",
+ tenant_id="tenant-1",
+ name="Valid",
+ description="",
+ agent_kind=AgentKind.DIFY_AGENT,
+ scope=AgentScope.ROSTER,
+ source=AgentSource.AGENT_APP,
+ app_id="app-1",
+ status=AgentStatus.ACTIVE,
+ )
+ empty_id_agent = Agent(
+ id="",
+ tenant_id="tenant-1",
+ name="Broken",
+ description="",
+ agent_kind=AgentKind.DIFY_AGENT,
+ scope=AgentScope.ROSTER,
+ source=AgentSource.AGENT_APP,
+ app_id="app-2",
+ status=AgentStatus.ACTIVE,
+ )
+
+ result = AgentRosterService(FakeSession(scalars=[[valid_agent, empty_id_agent]])).load_app_backing_agents_by_app_id(
+ tenant_id="tenant-1",
+ app_ids=["app-1", "app-2"],
+ )
+
+ assert result == {"app-1": valid_agent}
+
+
def test_published_references_include_app_display_fields_and_sort_by_updated_at():
recent_updated_at = datetime(2026, 1, 7, 3, 4, 5, tzinfo=UTC)
stale_updated_at = datetime(2026, 1, 6, 3, 4, 5, tzinfo=UTC)
@@ -1765,6 +2119,42 @@ def test_roster_create_detail_and_lookup_helpers(monkeypatch: pytest.MonkeyPatch
assert loaded_versions["version-1"].agent_id == "agent-1"
+def test_get_agent_runtime_app_model_creates_hidden_backing_app_for_existing_inline_agent():
+ agent = Agent(
+ id="agent-1",
+ tenant_id="tenant-1",
+ app_id="workflow-app-1",
+ workflow_id="workflow-1",
+ workflow_node_id="node-1",
+ name="Inline Agent",
+ description="desc",
+ agent_kind=AgentKind.DIFY_AGENT,
+ scope=AgentScope.WORKFLOW_ONLY,
+ source=AgentSource.WORKFLOW,
+ status=AgentStatus.ACTIVE,
+ created_by="account-1",
+ updated_by="account-1",
+ )
+ backing_app = App(
+ id="generated-1",
+ tenant_id="tenant-1",
+ name="Inline Agent",
+ mode=AppMode.AGENT,
+ status=AppStatus.NORMAL,
+ )
+ session = FakeSession(scalar=[agent, backing_app])
+ service = AgentRosterService(session)
+
+ resolved_app = service.get_agent_runtime_app_model(tenant_id="tenant-1", agent_id="agent-1")
+
+ assert resolved_app is backing_app
+ assert agent.backing_app_id == "generated-1"
+ assert session.commits == 1
+ created_app = next(value for value in session.added if isinstance(value, App))
+ assert created_app.enable_site is False
+ assert created_app.enable_api is False
+
+
def test_agent_app_debug_conversation_create_reuse_and_recreate():
agent = Agent(
id="agent-1",
@@ -1849,7 +2239,7 @@ def test_agent_app_debug_conversation_requires_app_binding():
)
-def test_load_or_create_agent_app_debug_conversations_filters_agent_apps():
+def test_load_or_create_agent_app_debug_conversations_supports_runtime_backed_agents():
valid_agent = Agent(
id="agent-1",
tenant_id="tenant-1",
@@ -1888,10 +2278,11 @@ def test_load_or_create_agent_app_debug_conversations_filters_agent_apps():
account_id="account-1",
)
- assert list(result) == ["agent-1"]
+ assert list(result) == ["agent-1", "agent-3"]
assert result["agent-1"]
+ assert result["agent-3"]
assert fake_session.commits == 1
- assert len([value for value in fake_session.added if isinstance(value, AgentDebugConversation)]) == 1
+ assert len([value for value in fake_session.added if isinstance(value, AgentDebugConversation)]) == 2
def test_agent_app_visible_versions_exclude_draft_saves():
@@ -1902,6 +2293,7 @@ def test_agent_app_visible_versions_exclude_draft_saves():
roster_operations = AgentRosterService._visible_version_operations(roster_agent)
assert agent_app_operations == {
+ AgentConfigRevisionOperation.PUBLISH_DRAFT,
AgentConfigRevisionOperation.SAVE_NEW_VERSION,
AgentConfigRevisionOperation.SAVE_TO_ROSTER,
AgentConfigRevisionOperation.RESTORE_VERSION,
@@ -1913,7 +2305,7 @@ def test_agent_app_visible_versions_exclude_draft_saves():
def test_restore_roster_agent_version_switches_active_snapshot(monkeypatch: pytest.MonkeyPatch):
- fake_session = FakeSession(scalar=["version-2", 6])
+ fake_session = FakeSession(scalar=["version-2", None])
service = AgentRosterService(fake_session)
agent = Agent(
id="agent-1",
@@ -1925,6 +2317,7 @@ def test_restore_roster_agent_version_switches_active_snapshot(monkeypatch: pyte
source=AgentSource.AGENT_APP,
status=AgentStatus.ACTIVE,
active_config_snapshot_id="version-4",
+ active_config_is_published=True,
)
version = AgentConfigSnapshot(
id="version-2",
@@ -1944,19 +2337,23 @@ def test_restore_roster_agent_version_switches_active_snapshot(monkeypatch: pyte
account_id="account-1",
)
- assert restored == {"result": "success", "active_config_snapshot_id": "version-2"}
- assert agent.active_config_snapshot_id == "version-2"
- assert agent.active_config_has_model is True
+ assert restored == {
+ "result": "success",
+ "active_config_snapshot_id": "version-4",
+ "draft_config_id": fake_session.added[0].id,
+ "restored_version_id": "version-2",
+ }
+ assert agent.active_config_snapshot_id == "version-4"
+ assert agent.active_config_is_published is False
assert agent.updated_by == "account-1"
assert fake_session.commits == 1
- revision = fake_session.added[0]
- assert revision.tenant_id == "tenant-1"
- assert revision.agent_id == "agent-1"
- assert revision.previous_snapshot_id == "version-4"
- assert revision.current_snapshot_id == "version-2"
- assert revision.revision == 7
- assert revision.operation == AgentConfigRevisionOperation.RESTORE_VERSION
- assert revision.created_by == "account-1"
+ draft = fake_session.added[0]
+ assert draft.tenant_id == "tenant-1"
+ assert draft.agent_id == "agent-1"
+ assert draft.draft_type == AgentConfigDraftType.DRAFT
+ assert draft.base_snapshot_id == "version-2"
+ assert draft.config_snapshot_dict == _agent_soul_with_model().model_dump(mode="json")
+ assert draft.updated_by == "account-1"
def test_restore_roster_agent_version_rejects_invisible_versions(monkeypatch: pytest.MonkeyPatch):
@@ -1998,6 +2395,18 @@ def test_app_list_all_excludes_agent_apps_by_default():
assert "apps.mode != :mode_1" in sql
+def test_app_list_agent_mode_requires_visible_roster_backing_agent():
+ filters = AppService._build_app_list_filters(
+ "account-1", "tenant-1", AppListParams(mode="agent"), FakeSession(scalar=None, scalars=None)
+ )
+ sql = " ".join(str(filter_) for filter_ in filters)
+
+ assert "EXISTS" in sql
+ assert "agents.app_id = apps.id" in sql
+ assert "agents.scope" in sql
+ assert "agents.source" in sql
+
+
def test_validator_dict_helpers_wrap_validation_errors():
valid_soul = ComposerConfigValidator.validate_agent_soul_dict({"prompt": {"system_prompt": "x"}})
valid_node_job = ComposerConfigValidator.validate_node_job_dict({"workflow_prompt": "x"})
@@ -2733,6 +3142,78 @@ class TestWorkflowAgentDraftBindingSync:
config_snapshot=agent_soul,
)
+ def _sync_roster_agent_task_refs(
+ self,
+ *,
+ agent_task: str,
+ existing_ref_selectors: list[list[str]] | None = None,
+ ) -> WorkflowNodeJobConfig:
+ workflow = Workflow(
+ id="workflow-1",
+ tenant_id="tenant-1",
+ app_id="app-1",
+ version=Workflow.VERSION_DRAFT,
+ graph=json.dumps(
+ {
+ "nodes": [
+ {
+ "id": "agent-node",
+ "data": {
+ "type": "agent",
+ "version": "2",
+ "agent_task": agent_task,
+ "agent_binding": {
+ "binding_type": "roster_agent",
+ "agent_id": "agent-1",
+ },
+ },
+ }
+ ]
+ }
+ ),
+ )
+ agent = Agent(
+ id="agent-1",
+ tenant_id="tenant-1",
+ name="Agent",
+ agent_kind=AgentKind.DIFY_AGENT,
+ scope=AgentScope.ROSTER,
+ source=AgentSource.AGENT_APP,
+ status=AgentStatus.ACTIVE,
+ active_config_snapshot_id="snapshot-2",
+ )
+ existing_binding = None
+ if existing_ref_selectors is None:
+ session = FakeSession(scalar=[agent], scalars=[[]])
+ else:
+ existing_binding = WorkflowAgentNodeBinding(
+ id="binding-1",
+ tenant_id="tenant-1",
+ app_id="app-1",
+ workflow_id="workflow-1",
+ workflow_version=Workflow.VERSION_DRAFT,
+ node_id="agent-node",
+ binding_type=WorkflowAgentBindingType.ROSTER_AGENT,
+ agent_id="agent-1",
+ current_snapshot_id="snapshot-1",
+ node_job_config=WorkflowNodeJobConfig.model_validate(
+ {
+ "workflow_prompt": "Old prompt",
+ "previous_node_output_refs": [{"selector": selector} for selector in existing_ref_selectors],
+ }
+ ),
+ )
+ session = FakeSession(scalar=[agent], scalars=[[existing_binding]])
+
+ WorkflowAgentPublishService.sync_roster_agent_bindings_for_draft(
+ session=session,
+ draft_workflow=workflow,
+ account_id="account-1",
+ )
+
+ binding = existing_binding or next(item for item in session.added if isinstance(item, WorkflowAgentNodeBinding))
+ return WorkflowNodeJobConfig.model_validate(binding.node_job_config_dict)
+
def test_publish_validation_rejects_agent_soul_publish_only_errors(self):
binding = self._agent_binding()
agent_soul = AgentSoulConfig.model_validate(
@@ -2843,6 +3324,11 @@ class TestWorkflowAgentDraftBindingSync:
)
node_data = graph["nodes"][0]["data"]
+ assert node_data["agent_binding"] == {
+ "binding_type": "roster_agent",
+ "agent_id": "agent-1",
+ "current_snapshot_id": "snapshot-1",
+ }
assert node_data["agent_task"] == "Summarize the upstream result."
assert node_data["agent_declared_outputs"][0]["name"] == "summary"
assert node_data["agent_declared_outputs"][0]["type"] == "string"
@@ -2852,6 +3338,103 @@ class TestWorkflowAgentDraftBindingSync:
assert profile_output["children"][1]["array_item"]["children"][0]["name"] == "city"
assert "agent_declared_outputs" not in workflow.graph_dict["nodes"][0]["data"]
+ def test_projects_inline_binding_over_pending_inline_graph_response(self):
+ workflow = Workflow(
+ id="workflow-1",
+ tenant_id="tenant-1",
+ app_id="app-1",
+ version=Workflow.VERSION_DRAFT,
+ graph=json.dumps(
+ {
+ "nodes": [
+ {
+ "id": "agent-node",
+ "data": {
+ "type": "agent",
+ "version": "2",
+ "agent_binding": {
+ "binding_type": "inline_agent",
+ },
+ },
+ }
+ ],
+ "edges": [],
+ }
+ ),
+ )
+ binding = WorkflowAgentNodeBinding(
+ id="binding-1",
+ tenant_id="tenant-1",
+ app_id="app-1",
+ workflow_id="workflow-1",
+ workflow_version=Workflow.VERSION_DRAFT,
+ node_id="agent-node",
+ binding_type=WorkflowAgentBindingType.INLINE_AGENT,
+ agent_id="inline-agent-1",
+ current_snapshot_id="inline-snapshot-1",
+ )
+ session = FakeSession(scalars=[[binding]])
+
+ graph = WorkflowAgentPublishService.project_draft_bindings_to_graph(
+ session=session,
+ draft_workflow=workflow,
+ )
+
+ assert graph["nodes"][0]["data"]["agent_binding"] == {
+ "binding_type": "inline_agent",
+ "agent_id": "inline-agent-1",
+ "current_snapshot_id": "inline-snapshot-1",
+ }
+ assert workflow.graph_dict["nodes"][0]["data"]["agent_binding"] == {
+ "binding_type": "inline_agent",
+ }
+
+ def test_keeps_pending_inline_graph_response_over_existing_roster_binding(self):
+ workflow = Workflow(
+ id="workflow-1",
+ tenant_id="tenant-1",
+ app_id="app-1",
+ version=Workflow.VERSION_DRAFT,
+ graph=json.dumps(
+ {
+ "nodes": [
+ {
+ "id": "agent-node",
+ "data": {
+ "type": "agent",
+ "version": "2",
+ "agent_binding": {
+ "binding_type": "inline_agent",
+ },
+ },
+ }
+ ],
+ "edges": [],
+ }
+ ),
+ )
+ binding = WorkflowAgentNodeBinding(
+ id="binding-1",
+ tenant_id="tenant-1",
+ app_id="app-1",
+ workflow_id="workflow-1",
+ workflow_version=Workflow.VERSION_DRAFT,
+ node_id="agent-node",
+ binding_type=WorkflowAgentBindingType.ROSTER_AGENT,
+ agent_id="agent-1",
+ current_snapshot_id="snapshot-1",
+ )
+ session = FakeSession(scalars=[[binding]])
+
+ graph = WorkflowAgentPublishService.project_draft_bindings_to_graph(
+ session=session,
+ draft_workflow=workflow,
+ )
+
+ assert graph["nodes"][0]["data"]["agent_binding"] == {
+ "binding_type": "inline_agent",
+ }
+
def test_creates_roster_binding_from_agent_node_graph(self):
workflow = Workflow(
id="workflow-1",
@@ -2917,6 +3500,32 @@ class TestWorkflowAgentDraftBindingSync:
],
).model_dump(mode="json")
+ def test_creates_roster_binding_deriving_previous_node_refs_from_agent_task(self):
+ node_job = self._sync_roster_agent_task_refs(
+ agent_task="Review {{#previous-node.report#}} for {{#sys.query#}}.",
+ )
+
+ assert node_job.workflow_prompt == "Review {{#previous-node.report#}} for {{#sys.query#}}."
+ assert [ref.selector for ref in node_job.previous_node_output_refs] == [["previous-node", "report"]]
+
+ def test_updates_existing_roster_binding_clearing_legacy_only_previous_node_refs(self):
+ node_job = self._sync_roster_agent_task_refs(
+ agent_task="Review [§node_output:previous-node.report:PREV/report§].",
+ existing_ref_selectors=[["previous-node", "report"]],
+ )
+
+ assert node_job.workflow_prompt == "Review [§node_output:previous-node.report:PREV/report§]."
+ assert node_job.previous_node_output_refs == []
+
+ def test_updates_existing_roster_binding_clearing_stale_previous_node_refs(self):
+ node_job = self._sync_roster_agent_task_refs(
+ agent_task="Review the current request without upstream context.",
+ existing_ref_selectors=[["previous-node", "report"]],
+ )
+
+ assert node_job.workflow_prompt == "Review the current request without upstream context."
+ assert node_job.previous_node_output_refs == []
+
def test_creates_inline_binding_from_agent_node_graph(self):
workflow = Workflow(
id="workflow-1",
@@ -2979,6 +3588,52 @@ class TestWorkflowAgentDraftBindingSync:
workflow_prompt="Use the current node context.",
).model_dump(mode="json")
+ def test_keeps_pending_inline_binding_in_draft_graph_without_db_binding(self):
+ workflow = Workflow(
+ id="workflow-1",
+ tenant_id="tenant-1",
+ app_id="app-1",
+ version=Workflow.VERSION_DRAFT,
+ graph=json.dumps(
+ {
+ "nodes": [
+ {
+ "id": "agent-node",
+ "data": {
+ "type": "agent",
+ "version": "2",
+ "agent_binding": {
+ "binding_type": "inline_agent",
+ },
+ },
+ }
+ ]
+ }
+ ),
+ )
+ existing_binding = WorkflowAgentNodeBinding(
+ id="binding-1",
+ tenant_id="tenant-1",
+ app_id="app-1",
+ workflow_id="workflow-1",
+ workflow_version=Workflow.VERSION_DRAFT,
+ node_id="agent-node",
+ binding_type=WorkflowAgentBindingType.ROSTER_AGENT,
+ agent_id="agent-1",
+ current_snapshot_id="snapshot-1",
+ )
+ session = FakeSession(scalars=[[existing_binding]])
+
+ WorkflowAgentPublishService.sync_agent_bindings_for_draft(
+ session=session,
+ draft_workflow=workflow,
+ account_id="account-1",
+ )
+
+ assert session.deleted == []
+ assert session.added == []
+ assert session.flushes == 1
+
def test_rejects_inline_binding_for_agent_owned_by_another_node(self):
workflow = Workflow(
id="workflow-1",
@@ -3058,7 +3713,7 @@ class TestWorkflowAgentDraftBindingSync:
account_id="account-1",
)
- def test_rejects_inline_binding_without_current_snapshot_id(self):
+ def test_treats_partial_inline_binding_as_pending_draft_state(self):
workflow = Workflow(
id="workflow-1",
tenant_id="tenant-1",
@@ -3083,12 +3738,17 @@ class TestWorkflowAgentDraftBindingSync:
),
)
- with pytest.raises(ValueError, match="inline_agent binding requires current_snapshot_id"):
- WorkflowAgentPublishService.sync_agent_bindings_for_draft(
- session=FakeSession(scalars=[[]]),
- draft_workflow=workflow,
- account_id="account-1",
- )
+ session = FakeSession(scalars=[[]])
+
+ WorkflowAgentPublishService.sync_agent_bindings_for_draft(
+ session=session,
+ draft_workflow=workflow,
+ account_id="account-1",
+ )
+
+ assert session.added == []
+ assert session.deleted == []
+ assert session.flushes == 1
def test_rejects_inline_binding_with_missing_snapshot(self):
workflow = Workflow(
@@ -3312,20 +3972,151 @@ def test_dataset_rows_filters_malformed_ids(monkeypatch: pytest.MonkeyPatch):
return [], 0
import services.dataset_service as dataset_service_module
+ from services.agent.knowledge_datasets import get_tenant_knowledge_dataset_rows
monkeypatch.setattr(dataset_service_module.DatasetService, "get_datasets_by_ids", fake_get_datasets_by_ids)
valid = "550e8400-e29b-41d4-a716-446655440000"
- rows = AgentComposerService._dataset_rows(tenant_id="tenant-1", dataset_ids=["9999dead-beef", valid])
+ rows = get_tenant_knowledge_dataset_rows(tenant_id="tenant-1", dataset_ids=["9999dead-beef", valid])
assert rows == {}
assert captured["ids"] == [valid]
# all-malformed input never touches the DB
captured.clear()
- assert AgentComposerService._dataset_rows(tenant_id="tenant-1", dataset_ids=["nope"]) == {}
+ assert get_tenant_knowledge_dataset_rows(tenant_id="tenant-1", dataset_ids=["nope"]) == {}
assert captured == {}
+ ("variant", "save_call"),
+ [
+ (
+ ComposerVariant.AGENT_APP,
+ lambda payload: AgentComposerService.save_agent_app_composer(
+ tenant_id="tenant-1",
+ app_id="app-1",
+ account_id="account-1",
+ payload=payload,
+ ),
+ ),
+ (
+ ComposerVariant.WORKFLOW,
+ lambda payload: AgentComposerService.save_workflow_composer(
+ tenant_id="tenant-1",
+ app_id="app-1",
+ node_id="node-1",
+ account_id="account-1",
+ payload=payload,
+ ),
+ ),
+ ],
+)
+def test_composer_save_rejects_malformed_knowledge_dataset_ids(monkeypatch: pytest.MonkeyPatch, variant, save_call):
+ captured = {"calls": 0}
+
+ def fake_get_datasets_by_ids(ids, tenant_id):
+ captured["calls"] += 1
+ captured["ids"] = ids
+ captured["tenant_id"] = tenant_id
+ return [], 0
+
+ import services.dataset_service as dataset_service_module
+
+ monkeypatch.setattr(dataset_service_module.DatasetService, "get_datasets_by_ids", fake_get_datasets_by_ids)
+
+ payload = ComposerSavePayload.model_validate(
+ {
+ "variant": variant.value,
+ "save_strategy": ComposerSaveStrategy.SAVE_TO_CURRENT_VERSION.value,
+ "soul_lock": {"locked": False},
+ "agent_soul": {
+ "knowledge": {
+ "sets": [
+ {
+ "id": "support",
+ "name": "Support KB",
+ "datasets": [{"id": "not-a-uuid"}],
+ "query": {"mode": "generated_query"},
+ "retrieval": {"mode": "multiple", "top_k": 4},
+ }
+ ]
+ }
+ },
+ }
+ )
+
+ with pytest.raises(InvalidComposerConfigError, match="not-a-uuid"):
+ save_call(payload)
+
+ assert captured == {"calls": 0}
+
+
+ ("variant", "save_call"),
+ [
+ (
+ ComposerVariant.AGENT_APP,
+ lambda payload: AgentComposerService.save_agent_app_composer(
+ tenant_id="tenant-1",
+ app_id="app-1",
+ account_id="account-1",
+ payload=payload,
+ ),
+ ),
+ (
+ ComposerVariant.WORKFLOW,
+ lambda payload: AgentComposerService.save_workflow_composer(
+ tenant_id="tenant-1",
+ app_id="app-1",
+ node_id="node-1",
+ account_id="account-1",
+ payload=payload,
+ ),
+ ),
+ ],
+)
+def test_composer_save_rejects_missing_or_out_of_scope_knowledge_datasets(
+ monkeypatch: pytest.MonkeyPatch, variant, save_call
+):
+ captured = {}
+ missing_dataset_id = "550e8400-e29b-41d4-a716-446655440000"
+
+ def fake_get_datasets_by_ids(ids, tenant_id):
+ captured["ids"] = ids
+ captured["tenant_id"] = tenant_id
+ return [], 0
+
+ import services.dataset_service as dataset_service_module
+
+ monkeypatch.setattr(dataset_service_module.DatasetService, "get_datasets_by_ids", fake_get_datasets_by_ids)
+
+ payload = ComposerSavePayload.model_validate(
+ {
+ "variant": variant.value,
+ "save_strategy": ComposerSaveStrategy.SAVE_TO_CURRENT_VERSION.value,
+ "soul_lock": {"locked": False},
+ "agent_soul": {
+ "knowledge": {
+ "sets": [
+ {
+ "id": "support",
+ "name": "Support KB",
+ "datasets": [{"id": missing_dataset_id}],
+ "query": {"mode": "generated_query"},
+ "retrieval": {"mode": "multiple", "top_k": 4},
+ }
+ ]
+ }
+ },
+ }
+ )
+
+ with pytest.raises(InvalidComposerConfigError, match=missing_dataset_id):
+ save_call(payload)
+
+ assert captured == {"ids": [missing_dataset_id], "tenant_id": "tenant-1"}
+
+
def test_workspace_dify_tools_returns_provider_and_tool_granularities(monkeypatch: pytest.MonkeyPatch):
"""The slash-menu Tools tab needs both selection granularities: a provider
hosts many tools (like an MCP server), so candidates return one
diff --git a/api/tests/unit_tests/services/agent/test_composer_candidates.py b/api/tests/unit_tests/services/agent/test_composer_candidates.py
index 863ebafc994..5566d48c690 100644
--- a/api/tests/unit_tests/services/agent/test_composer_candidates.py
+++ b/api/tests/unit_tests/services/agent/test_composer_candidates.py
@@ -124,7 +124,18 @@ def _soul() -> AgentSoulConfig:
{"id": "ct-2", "name": "disabled-one", "enabled": False},
],
},
- "knowledge": {"datasets": [{"id": "ds-1", "name": "旧名"}, {"id": "ds-gone", "name": "已删"}]},
+ "knowledge": {
+ "sets": [
+ {
+ "id": "kb-1",
+ "name": "产品知识",
+ "description": "knowledge set",
+ "datasets": [{"id": "ds-1", "name": "旧名"}, {"id": "ds-gone", "name": "已删"}],
+ "query": {"mode": "generated_query"},
+ "retrieval": {"mode": "multiple", "top_k": 4},
+ }
+ ]
+ },
"human": {"contacts": [{"id": "c-1", "name": "David Hayes", "channel": "email"}]},
}
)
@@ -143,12 +154,16 @@ def test_soul_candidates_lists_configured_items_only():
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"]
- # enriched from DB; dangling dataset kept with missing flag (placeholder, 0522)
- knowledge = {item["id"]: item for item in lists["knowledge_datasets"]}
- assert knowledge["ds-1"]["name"] == "产品手册"
- assert knowledge["ds-1"]["missing"] is False
- assert knowledge["ds-gone"]["missing"] is True
- assert knowledge["ds-gone"]["name"] == "已删"
+ # Knowledge mentions point at set ids; nested datasets are hydrated for context.
+ knowledge_set = lists["knowledge_sets"][0]
+ assert knowledge_set["id"] == "kb-1"
+ assert knowledge_set["name"] == "产品知识"
+ assert knowledge_set["missing_dataset_ids"] == ["ds-gone"]
+ datasets = {item["id"]: item for item in knowledge_set["datasets"]}
+ assert datasets["ds-1"]["name"] == "产品手册"
+ assert datasets["ds-1"]["missing"] is False
+ assert datasets["ds-gone"]["missing"] is True
+ assert datasets["ds-gone"]["name"] == "已删"
assert lists["human_contacts"][0]["id"] == "c-1"
assert lists["dify_tools"][0]["id"] == "tavily/tavily_search"
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.py
index ffbec86f4e6..f56ae3751e8 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
@@ -149,22 +149,32 @@ def test_dangling_knowledge_without_label_gets_fallback_name():
]
-def test_configured_but_deleted_dataset_surfaces_as_placeholder():
+def test_configured_but_deleted_knowledge_set_surfaces_as_placeholder():
payload = ComposerSavePayload.model_validate(
{
"variant": "agent_app",
"agent_soul": {
- "prompt": {"system_prompt": "see [§knowledge:ds-1:产品手册§]"},
- "knowledge": {"datasets": [{"id": "ds-1", "name": "产品手册"}]},
+ "prompt": {"system_prompt": "see [§knowledge:kb-1:产品手册§]"},
+ "knowledge": {
+ "sets": [
+ {
+ "id": "kb-1",
+ "name": "产品手册",
+ "datasets": [{"id": "ds-1", "name": "产品手册"}],
+ "query": {"mode": "generated_query"},
+ "retrieval": {"mode": "multiple", "top_k": 4},
+ }
+ ]
+ },
},
"save_strategy": "save_to_current_version",
}
)
- # configured + DB row exists -> clean
- assert _findings(payload, existing_dataset_ids={"ds-1"})["knowledge_retrieval_placeholder"] == []
- # configured but deleted in DB -> placeholder
- assert _findings(payload, existing_dataset_ids=set())["knowledge_retrieval_placeholder"] == [
- {"id": "ds-1", "placeholder_name": "产品手册"}
+ # configured + current Agent Soul row exists -> clean
+ assert _findings(payload, existing_knowledge_set_ids={"kb-1"})["knowledge_retrieval_placeholder"] == []
+ # configured but removed from the current Agent Soul surface -> placeholder
+ assert _findings(payload, existing_knowledge_set_ids=set())["knowledge_retrieval_placeholder"] == [
+ {"id": "kb-1", "placeholder_name": "产品手册"}
]
diff --git a/api/tests/unit_tests/services/agent/test_prompt_mentions.py b/api/tests/unit_tests/services/agent/test_prompt_mentions.py
index b8b908d432f..588093b89ca 100644
--- a/api/tests/unit_tests/services/agent/test_prompt_mentions.py
+++ b/api/tests/unit_tests/services/agent/test_prompt_mentions.py
@@ -11,7 +11,7 @@ from urllib.parse import quote
import pytest
-from models.agent_config_entities import AgentSoulConfig, WorkflowNodeJobConfig
+from models.agent_config_entities import AgentSoulConfig, WorkflowNodeJobConfig, WorkflowPreviousNodeOutputRef
from services.agent.prompt_mentions import (
MAX_MENTION_REF_ID_LENGTH,
NODE_JOB_PROMPT_ALLOWED_KINDS,
@@ -20,8 +20,12 @@ from services.agent.prompt_mentions import (
build_node_job_mention_resolver,
build_soul_mention_resolver,
expand_prompt_mentions,
+ extract_workflow_node_output_selectors,
+ extract_workflow_variable_selectors,
+ normalize_previous_node_output_selector,
parse_prompt_mentions,
scrub_mention_markers,
+ workflow_previous_node_output_refs_from_selectors,
)
# ── parse ─────────────────────────────────────────────────────────────────────
@@ -44,6 +48,13 @@ def test_parse_supports_ids_with_slash_and_dot():
assert mentions[1].ref_id == "node-1.tenders"
+def test_parse_supports_legacy_bare_output_tokens():
+ mentions = parse_prompt_mentions("Use §output:summary:summary§")
+ assert [(mention.kind, mention.ref_id, mention.label) for mention in mentions] == [
+ (MentionKind.OUTPUT, "summary", "summary")
+ ]
+
+
def test_parse_ignores_legacy_template_forms_and_unknown_kinds():
prompt = "{{var}} {{#context#}} {{#sys.query#}} [§bogus_kind:x§]"
assert parse_prompt_mentions(prompt) == []
@@ -89,6 +100,34 @@ def test_expand_empty_prompt_is_noop():
assert expand_prompt_mentions("", lambda m: "x") == ""
+def test_extract_workflow_variable_selectors_supports_frontend_agent_task_format():
+ selectors = extract_workflow_variable_selectors(
+ "Read {{#node-1.output#}}, compare {{#start.question#}}, leave {{#context#}} alone."
+ )
+ assert selectors == [("node-1", "output"), ("start", "question")]
+
+
+def test_extract_workflow_node_output_selectors_supports_current_frontend_markers_only():
+ selectors = extract_workflow_node_output_selectors(
+ "Read {{#node-1.output#}}, {{#sys.query#}}, [§node_output:legacy-node.report:PREV/report§], "
+ "and {{#node-1.output#}} again."
+ )
+ assert selectors == [("node-1", "output")]
+
+
+def test_workflow_previous_node_output_refs_from_selectors_materializes_refs():
+ refs = workflow_previous_node_output_refs_from_selectors([("node-1", "output"), ("node-2", "report", "url")])
+
+ assert refs == [
+ WorkflowPreviousNodeOutputRef(selector=["node-1", "output"], node_id="node-1", output="output"),
+ WorkflowPreviousNodeOutputRef(
+ selector=["node-2", "report", "url"],
+ node_id="node-2",
+ output="report",
+ ),
+ ]
+
+
# ── soul resolver ─────────────────────────────────────────────────────────────
@@ -107,7 +146,17 @@ def soul() -> AgentSoulConfig:
],
"cli_tools": [{"id": "ct-1", "name": "ffmpeg"}],
},
- "knowledge": {"datasets": [{"id": "ds-1", "name": "产品手册"}]},
+ "knowledge": {
+ "sets": [
+ {
+ "id": "kb-1",
+ "name": "产品手册",
+ "datasets": [{"id": "ds-1", "name": "产品手册"}],
+ "query": {"mode": "generated_query"},
+ "retrieval": {"mode": "multiple", "top_k": 4},
+ }
+ ]
+ },
"human": {"contacts": [{"id": "c-1", "name": "David Hayes", "channel": "email"}]},
}
)
@@ -117,7 +166,7 @@ def test_soul_resolver_resolves_each_kind(soul: AgentSoulConfig):
resolver = build_soul_mention_resolver(soul)
prompt = (
"Use [§tool:tavily/tavily_search:tavily§], run [§cli_tool:ct-1:ffmpeg§], "
- "ground in [§knowledge:ds-1§], ask [§human:c-1§]."
+ "ground in [§knowledge:kb-1§], ask [§human:c-1§]."
)
expanded = expand_prompt_mentions(prompt, resolver)
@@ -204,6 +253,17 @@ def test_node_job_resolver_matches_ref_by_node_id_and_output_fields():
assert expanded == "LLM/text"
+def test_normalize_previous_node_output_selector_returns_canonical_selector():
+ assert normalize_previous_node_output_selector(
+ WorkflowPreviousNodeOutputRef(selector=["node-1", "report", "url"])
+ ) == ("node-1", "report", "url")
+ assert normalize_previous_node_output_selector(WorkflowPreviousNodeOutputRef(node_id="node-2", output="text")) == (
+ "node-2",
+ "text",
+ )
+ assert normalize_previous_node_output_selector(WorkflowPreviousNodeOutputRef(selector=["node-3", 1])) is None
+
+
# ── allowlists ────────────────────────────────────────────────────────────────
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.py
index c88b72b3fcc..5c4e479e187 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
@@ -1,13 +1,16 @@
-"""Unit tests for the Skill package validator/extractor (ENG-370)."""
+"""Unit tests for the Skill package validator/normalizer (ENG-370)."""
from __future__ import annotations
+import hashlib
import io
import zipfile
+import zlib
import pytest
-from services.agent.skill_package_service import SkillPackageError, SkillPackageService
+from services.agent import skill_package_service as skill_package_service_module
+from services.agent.skill_package_service import NormalizedSkillPackage, SkillPackageError, SkillPackageService
_SKILL_MD = """---
name: PDF Toolkit
@@ -28,12 +31,17 @@ def _zip(members: dict[str, bytes], *, compression: int = zipfile.ZIP_DEFLATED)
return buffer.getvalue()
-def _extract(members: dict[str, bytes], *, filename: str = "skill.zip"):
- return SkillPackageService().validate_and_extract(content=_zip(members), filename=filename)
+def _normalize(members: dict[str, bytes], *, filename: str = "skill.zip") -> NormalizedSkillPackage:
+ return SkillPackageService().validate_and_normalize(content=_zip(members), filename=filename)
-def test_valid_skill_extracts_manifest():
- manifest = _extract({"SKILL.md": _SKILL_MD.encode(), "scripts/run.py": b"print('hi')\n"})
+def _archive_members(content: bytes) -> list[str]:
+ with zipfile.ZipFile(io.BytesIO(content)) as archive:
+ return sorted(info.filename for info in archive.infolist() if not info.is_dir())
+
+
+def test_valid_skill_normalizes_manifest():
+ manifest = _normalize({"SKILL.md": _SKILL_MD.encode(), "scripts/run.py": b"print('hi')\n"}).manifest
assert manifest.name == "PDF Toolkit"
assert manifest.description == "Tools for working with PDF files."
@@ -44,19 +52,101 @@ def test_valid_skill_extracts_manifest():
def test_name_falls_back_to_heading_without_frontmatter():
- manifest = _extract({"SKILL.md": b"# Heading Name\n\nbody"})
+ manifest = _normalize({"SKILL.md": b"# Heading Name\n\nbody"}).manifest
assert manifest.name == "Heading Name"
assert manifest.description == ""
-def test_nested_skill_md_is_found():
- manifest = _extract({"pdf-toolkit/SKILL.md": _SKILL_MD.encode()})
- assert manifest.entry_path == "pdf-toolkit/SKILL.md"
-
-
-def test_shallowest_skill_md_preferred():
- manifest = _extract({"SKILL.md": _SKILL_MD.encode(), "nested/SKILL.md": _SKILL_MD.encode()})
+def test_shallowest_skill_md_preferred_during_normalization():
+ manifest = _normalize({"SKILL.md": _SKILL_MD.encode(), "nested/SKILL.md": _SKILL_MD.encode()}).manifest
assert manifest.entry_path == "SKILL.md"
+ assert manifest.files == ["SKILL.md", "nested/SKILL.md"]
+
+
+def test_validate_and_normalize_keeps_root_skill_unchanged():
+ package = _normalize({"SKILL.md": _SKILL_MD.encode(), "scripts/run.py": b"print('hi')\n"})
+
+ assert package.manifest.entry_path == "SKILL.md"
+ assert package.manifest.files == ["SKILL.md", "scripts/run.py"]
+ assert package.skill_md_bytes == _SKILL_MD.encode()
+ assert package.strip_prefix is None
+ assert _archive_members(package.archive_bytes) == ["SKILL.md", "scripts/run.py"]
+ assert len(package.manifest.hash) == 64
+
+
+def test_validate_and_normalize_strips_single_top_level_folder():
+ package = _normalize(
+ {
+ "pdf-toolkit/SKILL.md": _SKILL_MD.encode(),
+ "pdf-toolkit/scripts/run.py": b"print('hi')\n",
+ }
+ )
+
+ assert package.manifest.entry_path == "SKILL.md"
+ assert package.manifest.files == ["SKILL.md", "scripts/run.py"]
+ assert package.skill_md_bytes == _SKILL_MD.encode()
+ assert package.strip_prefix == "pdf-toolkit/"
+ assert _archive_members(package.archive_bytes) == ["SKILL.md", "scripts/run.py"]
+
+
+def test_validate_and_normalize_strips_single_top_level_folder_ignoring_other_root_entries():
+ package = _normalize(
+ {
+ "pdf-toolkit/SKILL.md": _SKILL_MD.encode(),
+ "pdf-toolkit/scripts/run.py": b"print('hi')\n",
+ "README.md": b"bundle notes\n",
+ }
+ )
+
+ assert package.manifest.entry_path == "SKILL.md"
+ assert package.manifest.files == ["SKILL.md", "scripts/run.py"]
+ assert package.skill_md_bytes == _SKILL_MD.encode()
+ assert package.strip_prefix == "pdf-toolkit/"
+ assert _archive_members(package.archive_bytes) == ["SKILL.md", "scripts/run.py"]
+
+
+def test_validate_and_normalize_strips_single_top_level_folder_dropping_nested_foreign_paths():
+ package = _normalize(
+ {
+ "pdf-toolkit/SKILL.md": _SKILL_MD.encode(),
+ "pdf-toolkit/scripts/run.py": b"print('hi')\n",
+ "bundle/other.txt": b"x",
+ }
+ )
+
+ assert package.manifest.entry_path == "SKILL.md"
+ assert package.manifest.files == ["SKILL.md", "scripts/run.py"]
+ assert package.skill_md_bytes == _SKILL_MD.encode()
+ assert package.strip_prefix == "pdf-toolkit/"
+ assert _archive_members(package.archive_bytes) == ["SKILL.md", "scripts/run.py"]
+
+
+def test_validate_and_normalize_rejects_multiple_depth_2_skill_roots_with_sibling_skill_tree():
+ with pytest.raises(SkillPackageError) as exc_info:
+ _normalize(
+ {
+ "pdf-toolkit/SKILL.md": _SKILL_MD.encode(),
+ "pdf-toolkit/scripts/run.py": b"print('hi')\n",
+ "other-tool/SKILL.md": _SKILL_MD.encode(),
+ }
+ )
+ assert exc_info.value.code == "files_outside_skill_root"
+
+
+def test_validate_and_normalize_strips_deeper_selected_skill_root():
+ members = {
+ "bundle/pdf-toolkit/SKILL.md": _SKILL_MD.encode(),
+ "bundle/pdf-toolkit/scripts/run.py": b"print('hi')\n",
+ }
+ original_upload_bytes = _zip(members)
+ package = SkillPackageService().validate_and_normalize(content=original_upload_bytes, filename="skill.zip")
+
+ assert package.manifest.entry_path == "SKILL.md"
+ assert package.manifest.files == ["SKILL.md", "scripts/run.py"]
+ assert package.strip_prefix == "bundle/pdf-toolkit/"
+ assert _archive_members(package.archive_bytes) == ["SKILL.md", "scripts/run.py"]
+ assert package.manifest.hash == hashlib.sha256(package.archive_bytes).hexdigest()
+ assert package.manifest.hash != hashlib.sha256(original_upload_bytes).hexdigest()
@pytest.mark.parametrize(
@@ -71,53 +161,105 @@ def test_shallowest_skill_md_preferred():
)
def test_invalid_packages_rejected(members: dict[str, bytes], filename: str, code: str):
with pytest.raises(SkillPackageError) as exc_info:
- _extract(members, filename=filename)
+ _normalize(members, filename=filename)
assert exc_info.value.code == code
assert exc_info.value.status_code == 400
def test_non_zip_content_rejected():
with pytest.raises(SkillPackageError) as exc_info:
- SkillPackageService().validate_and_extract(content=b"not a zip", filename="skill.zip")
+ SkillPackageService().validate_and_normalize(content=b"not a zip", filename="skill.zip")
assert exc_info.value.code == "invalid_archive"
def test_zip_slip_member_rejected():
payload = _zip({"../evil.txt": b"x", "SKILL.md": _SKILL_MD.encode()})
with pytest.raises(SkillPackageError) as exc_info:
- SkillPackageService().validate_and_extract(content=payload, filename="skill.zip")
+ SkillPackageService().validate_and_normalize(content=payload, filename="skill.zip")
assert exc_info.value.code == "unsafe_path"
def test_empty_archive_rejected():
with pytest.raises(SkillPackageError) as exc_info:
- SkillPackageService().validate_and_extract(content=b"", filename="skill.zip")
+ SkillPackageService().validate_and_normalize(content=b"", filename="skill.zip")
assert exc_info.value.code == "empty_archive"
+def test_validate_and_normalize_rejects_skill_md_too_large(monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setattr(skill_package_service_module, "_MAX_SKILL_MD_BYTES", 8)
+
+ with pytest.raises(SkillPackageError) as exc_info:
+ _normalize({"SKILL.md": _SKILL_MD.encode()})
+ assert exc_info.value.code == "skill_md_too_large"
+
+
+def test_validate_and_normalize_rejects_too_many_entries(monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setattr(skill_package_service_module, "_MAX_ENTRIES", 1)
+
+ with pytest.raises(SkillPackageError) as exc_info:
+ _normalize({"SKILL.md": _SKILL_MD.encode(), "scripts/run.py": b"print('x')\n"})
+ assert exc_info.value.code == "too_many_entries"
+
+
+def test_validate_and_normalize_rejects_archive_too_large_uncompressed(monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setattr(skill_package_service_module, "_MAX_UNCOMPRESSED_BYTES", 32)
+
+ with pytest.raises(SkillPackageError) as exc_info:
+ _normalize({"SKILL.md": _SKILL_MD.encode(), "scripts/run.py": b"x" * 33})
+ assert exc_info.value.code == "archive_too_large"
+
+
+def test_validate_and_normalize_rejects_archive_too_large_uploaded_bytes(monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setattr(skill_package_service_module, "_MAX_ARCHIVE_BYTES", 8)
+
+ with pytest.raises(SkillPackageError) as exc_info:
+ SkillPackageService().validate_and_normalize(content=b"x" * 9, filename="skill.zip")
+ assert exc_info.value.code == "archive_too_large"
+
+
def test_bad_frontmatter_yaml_rejected():
bad = b"---\n: : : not yaml\n---\n# x\n"
with pytest.raises(SkillPackageError) as exc_info:
- _extract({"SKILL.md": bad})
+ _normalize({"SKILL.md": bad})
assert exc_info.value.code == "invalid_frontmatter"
def test_unterminated_frontmatter_falls_back_to_heading():
# leading '---' with no closing fence -> no frontmatter, use the heading
- manifest = _extract({"SKILL.md": b"---\n# Heading Wins\nbody"})
+ manifest = _normalize({"SKILL.md": b"---\n# Heading Wins\nbody"}).manifest
assert manifest.name == "Heading Wins"
-def test_read_member_bytes_roundtrip_and_errors():
- service = SkillPackageService()
- payload = _zip({"SKILL.md": _SKILL_MD.encode(), "scripts/run.py": b"print('x')\n"})
+def test_validate_and_normalize_rejects_files_outside_selected_skill_root():
+ with pytest.raises(SkillPackageError) as exc_info:
+ _normalize({"bundle/pdf-toolkit/SKILL.md": _SKILL_MD.encode(), "README.md": b"x"})
+ assert exc_info.value.code == "files_outside_skill_root"
+
+
+def test_validate_and_normalize_rejects_duplicate_normalized_paths():
+ with pytest.raises(SkillPackageError) as exc_info:
+ _normalize(
+ {
+ "pdf-toolkit/SKILL.md": _SKILL_MD.encode(),
+ "pdf-toolkit/scripts/run.py": b"print('x')\n",
+ "pdf-toolkit/scripts/./run.py": b"print('y')\n",
+ }
+ )
+ assert exc_info.value.code == "duplicate_member_path"
+
- assert service.read_member_bytes(content=payload, member_path="scripts/run.py") == b"print('x')\n"
+def test_validate_and_normalize_maps_member_decompression_failures_to_invalid_archive(monkeypatch: pytest.MonkeyPatch):
+ original_read = zipfile.ZipFile.read
- with pytest.raises(SkillPackageError) as missing:
- service.read_member_bytes(content=payload, member_path="nope.txt")
- assert missing.value.code == "member_not_found"
+ def corrupted_read(self: zipfile.ZipFile, member: str | zipfile.ZipInfo, *args: object, **kwargs: object) -> bytes:
+ filename = member.filename if isinstance(member, zipfile.ZipInfo) else member
+ if filename == "scripts/run.py":
+ raise zlib.error("invalid distance too far back")
+ return original_read(self, member, *args, **kwargs)
- 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"
+ monkeypatch.setattr(zipfile.ZipFile, "read", corrupted_read)
+
+ with pytest.raises(SkillPackageError) as exc_info:
+ _normalize({"SKILL.md": _SKILL_MD.encode(), "scripts/run.py": b"print('x')\n"})
+ assert exc_info.value.code == "invalid_archive"
+ assert exc_info.value.message == "skill archive is not a valid zip"
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.py
index fa47c9bd905..074ac59bb1c 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
@@ -32,30 +32,16 @@ def test_slugify_skill_name():
assert slugify_skill_name("") == "skill"
-def test_standardize_creates_drive_owned_toolfiles_and_commits_archive_members():
- content = _zip({"SKILL.md": _SKILL_MD, "scripts/run.py": b"print('x')\n"})
+def test_standardize_creates_drive_owned_toolfiles_and_commits_archive_manifest():
+ content = _zip({"pdf-toolkit/SKILL.md": _SKILL_MD, "pdf-toolkit/scripts/run.py": b"print('x')\n"})
tool_files = MagicMock()
tool_files.create_file_by_raw.side_effect = [
SimpleNamespace(id="md-tool-file"),
SimpleNamespace(id="zip-tool-file"),
- SimpleNamespace(id="script-tool-file"),
]
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(
@@ -66,34 +52,35 @@ def test_standardize_creates_drive_owned_toolfiles_and_commits_archive_members()
agent_id="agent-1",
)
- # ToolFiles: SKILL.md, full archive, and each inspectable package member.
- assert tool_files.create_file_by_raw.call_count == 3
- md_call, zip_call, script_call = tool_files.create_file_by_raw.call_args_list
+ # ToolFiles: SKILL.md and the full archive. Archive members stay lazy.
+ assert tool_files.create_file_by_raw.call_count == 2
+ md_call, zip_call = tool_files.create_file_by_raw.call_args_list
assert md_call.kwargs["mimetype"] == "text/markdown"
assert md_call.kwargs["file_binary"] == _SKILL_MD
assert zip_call.kwargs["mimetype"] == "application/zip"
- assert zip_call.kwargs["file_binary"] == content
- assert script_call.kwargs["mimetype"] in {"text/x-python", "text/plain", "application/octet-stream"}
- assert script_call.kwargs["file_binary"] == b"print('x')\n"
- assert script_call.kwargs["filename"] == "run.py"
-
- # Committed as drive-owned with the standardized keys.
+ assert zip_call.kwargs["file_binary"] != content
+ with zipfile.ZipFile(io.BytesIO(zip_call.kwargs["file_binary"])) as archive:
+ assert sorted(info.filename for info in archive.infolist() if not info.is_dir()) == [
+ "SKILL.md",
+ "scripts/run.py",
+ ]
+
+ # Committed as drive-owned with the standardized keys. Member paths are
+ # carried in metadata for inspect/preview/runtime lazy resolution.
commit_kwargs = drive.commit.call_args.kwargs
assert commit_kwargs["agent_id"] == "agent-1"
items = commit_kwargs["items"]
assert [item.key for item in items] == [
"pdf-toolkit/SKILL.md",
"pdf-toolkit/.DIFY-SKILL-FULL.zip",
- "pdf-toolkit/scripts/run.py",
]
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 [item.file_ref.id for item in items] == ["md-tool-file", "zip-tool-file"]
assert items[0].is_skill is True
assert items[0].skill_metadata is not None
assert 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 False
- assert items[2].is_skill is False
# The returned upload response carries only the drive-derived fields the UI needs.
skill = result["skill"]
@@ -101,4 +88,7 @@ def test_standardize_creates_drive_owned_toolfiles_and_commits_archive_members()
assert skill["name"] == "PDF Toolkit"
assert skill["archive_key"] == "pdf-toolkit/.DIFY-SKILL-FULL.zip"
assert skill["skill_md_key"] == "pdf-toolkit/SKILL.md"
+ assert result["manifest"]["entry_path"] == "SKILL.md"
assert result["manifest"]["files"] == ["SKILL.md", "scripts/run.py"]
+ drive.list_skills.assert_not_called()
+ assert "_committed_items" not in result
diff --git a/api/tests/unit_tests/services/test_agent_drive_service.py b/api/tests/unit_tests/services/test_agent_drive_service.py
index e4a22b64a48..ad72e142522 100644
--- a/api/tests/unit_tests/services/test_agent_drive_service.py
+++ b/api/tests/unit_tests/services/test_agent_drive_service.py
@@ -7,6 +7,8 @@ exercised against the project's in-memory SQLite engine with seeded ToolFiles.
from __future__ import annotations
import datetime
+import io
+import zipfile
from collections.abc import Generator
from unittest.mock import patch
@@ -103,6 +105,14 @@ def _seed_tool_file(*, user_id: str = USER, name: str = "f.txt") -> str:
return tool_file.id
+def _zip_bytes(members: dict[str, bytes]) -> bytes:
+ buffer = io.BytesIO()
+ with zipfile.ZipFile(buffer, "w") as archive:
+ for name, data in members.items():
+ archive.writestr(name, data)
+ return buffer.getvalue()
+
+
def _commit(key: str, tool_file_id: str, *, owned: bool = True):
return AgentDriveService().commit(
tenant_id=TENANT,
@@ -769,7 +779,8 @@ def test_inspect_skill_returns_manifest_files_and_file_tree():
assert result["warnings"] == []
assert [file["path"] for file in result["files"]] == ["SKILL.md", "references/guide.md", "scripts/run.py"]
assert result["files"][0]["available_in_drive"] is True
- assert result["files"][1]["available_in_drive"] is False
+ assert result["files"][1]["available_in_drive"] is True
+ assert result["files"][1]["drive_key"] == "pdf-toolkit/references/guide.md"
assert result["file_tree"][0]["name"] == "references"
assert result["file_tree"][1]["name"] == "scripts"
assert result["file_tree"][2]["name"] == "SKILL.md"
@@ -787,6 +798,48 @@ def test_inspect_skill_falls_back_to_drive_keys_when_manifest_missing():
assert [file["path"] for file in result["files"]] == ["SKILL.md"]
+def test_preview_skill_archive_member_from_manifest_without_drive_row():
+ _commit_skill(manifest_files=["SKILL.md", "references/guide.md"])
+ archive = _zip_bytes({"SKILL.md": b"# PDF Toolkit\n", "references/guide.md": b"Guide content\n"})
+
+ with patch("services.agent_drive_service.storage") as storage_mock:
+ storage_mock.load_stream.return_value = iter([archive])
+ result = AgentDriveService().preview(
+ tenant_id=TENANT,
+ agent_id=AGENT,
+ key="pdf-toolkit/references/guide.md",
+ )
+
+ assert result == {
+ "key": "pdf-toolkit/references/guide.md",
+ "size": len(b"Guide content\n"),
+ "truncated": False,
+ "binary": False,
+ "text": "Guide content\n",
+ }
+
+
+def test_download_url_signs_skill_archive_member_from_manifest_without_drive_row():
+ _commit_skill(manifest_files=["SKILL.md", "references/guide.md"])
+
+ with patch.object(
+ AgentDriveService,
+ "sign_archive_member_url",
+ return_value="https://signed.example/member",
+ ) as sign:
+ url = AgentDriveService().download_url(
+ tenant_id=TENANT,
+ agent_id=AGENT,
+ key="pdf-toolkit/references/guide.md",
+ )
+
+ assert url == "https://signed.example/member"
+ kwargs = sign.call_args.kwargs
+ assert kwargs["key"] == "pdf-toolkit/references/guide.md"
+ assert kwargs["member_path"] == "references/guide.md"
+ assert kwargs["for_external"] is True
+
+
def test_skill_metadata_rejects_non_canonical_rows():
tf = _seed_tool_file(name="not-skill.md")
with pytest.raises(AgentDriveError) as exc_info:
diff --git a/api/tests/unit_tests/services/test_knowledge_retrieval_inner_service.py b/api/tests/unit_tests/services/test_knowledge_retrieval_inner_service.py
index 7a8efe85f13..321b1a7c046 100644
--- a/api/tests/unit_tests/services/test_knowledge_retrieval_inner_service.py
+++ b/api/tests/unit_tests/services/test_knowledge_retrieval_inner_service.py
@@ -98,6 +98,8 @@ class TestInnerKnowledgeRetrievalService:
"total_price": "0",
"currency": "USD",
"latency": 0,
+ "time_to_first_token": None,
+ "time_to_generate": None,
}
mock_rag_cls.return_value = rag
diff --git a/api/uv.lock b/api/uv.lock
index 38578c812ae..dfdbc7343c9 100644
--- a/api/uv.lock
+++ b/api/uv.lock
@@ -1299,6 +1299,7 @@ requires-dist = [
{ name = "httpx", specifier = "==0.28.1" },
{ name = "jsonschema", marker = "extra == 'server'", specifier = ">=4.23.0,<5.0.0" },
{ name = "jwcrypto", marker = "extra == 'server'", specifier = ">=1.5.6,<2" },
+ { name = "logfire", extras = ["fastapi", "httpx", "redis"], marker = "extra == 'server'", specifier = ">=4.37.0,<5.0.0" },
{ name = "protobuf", marker = "extra == 'grpc'", specifier = ">=6.33.5,<7.0.0" },
{ name = "pydantic", specifier = ">=2.12.5,<2.13" },
{ name = "pydantic-ai-slim", specifier = ">=1.85.1,<2.0.0" },
diff --git a/dify-agent/pyproject.toml b/dify-agent/pyproject.toml
index c6f1138e087..00cf16359d0 100644
--- a/dify-agent/pyproject.toml
+++ b/dify-agent/pyproject.toml
@@ -23,6 +23,7 @@ server = [
"graphon==0.5.2",
"jsonschema>=4.23.0,<5.0.0",
"jwcrypto>=1.5.6,<2",
+ "logfire[fastapi,httpx,redis]>=4.37.0,<5.0.0",
"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",
diff --git a/dify-agent/src/dify_agent/agent_stub/_drive_materialization.py b/dify-agent/src/dify_agent/agent_stub/_drive_materialization.py
new file mode 100644
index 00000000000..cf2ec969ae2
--- /dev/null
+++ b/dify-agent/src/dify_agent/agent_stub/_drive_materialization.py
@@ -0,0 +1,169 @@
+"""Shared drive download materialization helpers.
+
+This module centralizes the safety-critical filesystem logic used by both the
+sandbox-visible CLI and the runtime drive layer. It owns path resolution under
+one local drive base, overwrite-via-temp-file semantics, payload size checks,
+and safe extraction of downloaded skill archives so those invariants cannot
+drift between the two call sites.
+"""
+
+from __future__ import annotations
+
+import stat
+from dataclasses import dataclass
+from pathlib import Path, PurePosixPath
+from tempfile import TemporaryDirectory
+from typing import Final
+from uuid import uuid4
+from zipfile import BadZipFile, ZipFile, ZipInfo
+
+
+SKILL_ARCHIVE_FILENAME: Final[str] = ".DIFY-SKILL-FULL.zip"
+
+
+@dataclass(frozen=True, slots=True)
+class DriveDownloadPayload:
+ """One downloaded drive payload ready to materialize under a local base."""
+
+ key: str
+ payload: bytes
+ size: int | None = None
+
+
+class DriveMaterializationValidationError(ValueError):
+ """Raised when one drive key or archive entry is structurally unsafe."""
+
+
+class DriveMaterializationTransferError(RuntimeError):
+ """Raised when one downloaded payload cannot be safely materialized."""
+
+
+def materialize_drive_downloads(
+ *,
+ base_path: Path,
+ downloads: list[DriveDownloadPayload],
+) -> list[Path]:
+ """Write downloaded drive payloads under one local base and extract skills.
+
+ The helper preserves caller-provided order in the returned list of paths.
+ Skill archives are extracted and deleted only after every payload has been
+ written successfully so partial extraction cannot outlive a later failure in
+ the same batch. The returned path for an archive is the path where it was
+ downloaded before successful extraction.
+ """
+
+ resolved_base_path = base_path.expanduser().resolve()
+ try:
+ _ = resolved_base_path.mkdir(parents=True, exist_ok=True)
+ except OSError as exc:
+ raise DriveMaterializationTransferError(f"failed to prepare drive base {resolved_base_path}") from exc
+
+ written_paths: list[Path] = []
+ archive_paths: list[Path] = []
+ for download in downloads:
+ if download.size is not None and len(download.payload) != download.size:
+ raise DriveMaterializationTransferError(f"downloaded drive file size mismatch for {download.key}")
+ destination = resolve_drive_destination(resolved_base_path, download.key)
+ try:
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ temp_path = destination.with_name(f"{destination.name}.tmp-{uuid4().hex}")
+ _ = temp_path.write_bytes(download.payload)
+ _ = temp_path.replace(destination)
+ except OSError as exc:
+ raise DriveMaterializationTransferError(f"failed to materialize drive file {download.key}") from exc
+ written_paths.append(destination)
+ if destination.name == SKILL_ARCHIVE_FILENAME:
+ archive_paths.append(destination)
+
+ for archive_path in sorted(archive_paths):
+ extract_skill_archive(archive_path)
+ _delete_extracted_archive(archive_path)
+ return written_paths
+
+
+def resolve_drive_destination(base_path: Path, drive_key: str) -> Path:
+ """Resolve one drive key under a local base and reject path traversal."""
+
+ destination = (base_path / Path(drive_key)).resolve()
+ try:
+ destination.relative_to(base_path)
+ except ValueError as exc:
+ raise DriveMaterializationValidationError(f"drive key resolves outside the drive base: {drive_key}") from exc
+ return destination
+
+
+def extract_skill_archive(archive_path: Path) -> None:
+ """Safely extract one downloaded skill archive into its containing directory."""
+
+ 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():
+ destination = _resolve_zip_entry_destination(staging_dir, zip_info.filename)
+ if _is_zip_symlink(zip_info):
+ raise DriveMaterializationValidationError(
+ 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 DriveMaterializationValidationError:
+ raise
+ except (BadZipFile, OSError) as exc:
+ raise DriveMaterializationTransferError(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 DriveMaterializationValidationError(f"skill archive contains unsafe absolute path: {entry_name}")
+ if any(part in {"", ".", ".."} for part in pure_path.parts):
+ raise DriveMaterializationValidationError(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 DriveMaterializationValidationError(
+ 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 stat.S_ISLNK(file_mode)
+
+
+def _delete_extracted_archive(archive_path: Path) -> None:
+ try:
+ archive_path.unlink(missing_ok=True)
+ except OSError as exc:
+ raise DriveMaterializationTransferError(
+ f"failed to delete extracted skill archive: {archive_path.name}"
+ ) from exc
+
+
+__all__ = [
+ "DriveDownloadPayload",
+ "DriveMaterializationTransferError",
+ "DriveMaterializationValidationError",
+ "SKILL_ARCHIVE_FILENAME",
+ "extract_skill_archive",
+ "materialize_drive_downloads",
+ "resolve_drive_destination",
+]
diff --git a/dify-agent/src/dify_agent/agent_stub/cli/_drive.py b/dify-agent/src/dify_agent/agent_stub/cli/_drive.py
index d3d6241449b..69c9d5455bd 100644
--- a/dify-agent/src/dify_agent/agent_stub/cli/_drive.py
+++ b/dify-agent/src/dify_agent/agent_stub/cli/_drive.py
@@ -10,14 +10,23 @@ ToolFile ids back into the drive.
from __future__ import annotations
-import stat
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
-from pathlib import Path, PurePosixPath
+from pathlib import Path
from tempfile import TemporaryDirectory
-from uuid import uuid4
-from zipfile import BadZipFile, ZIP_DEFLATED, ZipFile, ZipInfo
-
+from typing import ClassVar, Literal
+from zipfile import ZIP_DEFLATED, ZipFile
+
+from pydantic import BaseModel, ConfigDict
+
+from dify_agent.agent_stub._drive_materialization import (
+ DriveDownloadPayload,
+ DriveMaterializationTransferError,
+ DriveMaterializationValidationError,
+ SKILL_ARCHIVE_FILENAME,
+ materialize_drive_downloads,
+ resolve_drive_destination,
+)
from dify_agent.agent_stub.cli._env import read_agent_stub_environment
from dify_agent.agent_stub.cli._files import upload_tool_file_resource_from_environment
from dify_agent.agent_stub.client._agent_stub import (
@@ -37,11 +46,11 @@ from dify_agent.agent_stub.protocol.agent_stub import (
)
_SKILL_MD_FILENAME = "SKILL.md"
-_SKILL_ARCHIVE_FILENAME = ".DIFY-SKILL-FULL.zip"
_SKIP_DIR_NAMES = frozenset(
{".git", "__pycache__", ".pytest_cache", ".mypy_cache", ".ruff_cache", ".venv", "node_modules"}
)
-_SKIP_FILE_NAMES = frozenset({".DS_Store", _SKILL_ARCHIVE_FILENAME})
+_SKIP_FILE_NAMES = frozenset({".DS_Store", SKILL_ARCHIVE_FILENAME})
+DrivePushKind = Literal["file", "skill", "dir"]
@dataclass(frozen=True, slots=True)
@@ -52,18 +61,28 @@ class _DriveUploadItem:
drive_key: str
-def list_drive_from_environment(prefix: str, json_output: bool) -> str | AgentStubDriveManifestResponse:
+class DrivePullResult(BaseModel):
+ """Structured JSON result for ``dify-agent drive pull --json``."""
+
+ class Item(BaseModel):
+ key: str
+ local_path: str
+
+ model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid")
+
+ items: list[Item]
+
+ model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid")
+
+
+def list_drive_manifest_from_environment(prefix: str) -> AgentStubDriveManifestResponse:
"""List drive items through the Agent Stub using the current environment.
Args:
prefix: Optional drive-key prefix forwarded to the manifest request.
- json_output: When ``True``, return the validated manifest response model.
- When ``False``, return one human-readable tab-separated line per item
- containing size, mime type, hash, and key.
Returns:
- Either ``AgentStubDriveManifestResponse`` for JSON callers or a formatted
- string for human-facing CLI output.
+ The validated manifest response model.
Side effects:
Calls the Agent Stub drive manifest control-plane endpoint with
@@ -78,24 +97,24 @@ def list_drive_from_environment(prefix: str, json_output: bool) -> str | AgentSt
prefix=prefix,
include_download_url=False,
)
- if json_output:
- return response
- return _format_manifest(response)
+ return response
def pull_drive_from_environment(
targets: list[str] | None = None,
- drive_base: str = DEFAULT_AGENT_STUB_DRIVE_BASE,
-) -> list[Path]:
+ local_base: str | None = None,
+) -> DrivePullResult:
"""Pull drive files into one local drive base via signed download URLs.
Args:
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.
+ local_base: Local base directory that receives downloaded drive files.
+ When omitted, the historical Agent Stub drive base is used.
Returns:
- A list of written local paths under ``drive_base``.
+ A structured JSON-ready result with requested drive targets/prefixes
+ that matched at least one manifest item and their local paths.
Observable behavior:
Requests a manifest with ``include_download_url=True``, requires every
@@ -107,10 +126,12 @@ def pull_drive_from_environment(
``.DIFY-SKILL-FULL.zip`` archives into their containing skill
directory with the same path-safety checks. Archive extraction is staged
under a temporary directory and only moved into place after the full
- archive validates successfully.
+ archive validates successfully. Successfully extracted skill archives
+ are deleted from disk.
- The return value remains the list of downloaded paths only; extracted
- files are materialized on disk but are not added to the returned list.
+ Downloaded files and extracted files are materialized on disk but are
+ not enumerated in the returned item list; prefix pulls return the local
+ path corresponding to the requested prefix.
Raises:
AgentStubValidationError: if a manifest item omits ``download_url``, a
@@ -124,48 +145,68 @@ def pull_drive_from_environment(
environment = read_agent_stub_environment()
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,
- )
+
+ def _fetch_manifest(target: str) -> AgentStubDriveManifestResponse:
+ return request_agent_stub_drive_manifest_sync(
+ url=environment.url,
+ auth_jwe=environment.auth_jwe,
+ prefix=target,
+ include_download_url=True,
)
- base_path = Path(drive_base).expanduser().resolve()
- base_path.mkdir(parents=True, exist_ok=True)
- written_paths: list[Path] = []
+
+ with ThreadPoolExecutor(max_workers=min(len(manifest_targets), 4)) as executor:
+ responses = list(executor.map(_fetch_manifest, manifest_targets))
+ downloads: list[DriveDownloadPayload] = []
+ resolved_base_path = Path(local_base or DEFAULT_AGENT_STUB_DRIVE_BASE).expanduser().resolve()
+ result_items: list[DrivePullResult.Item] = []
+ seen_result_targets: set[str] = set()
+ for target, response in zip(manifest_targets, responses, strict=True):
+ if not response.items or target in seen_result_targets:
+ continue
+ seen_result_targets.add(target)
+ try:
+ local_path = resolve_drive_destination(resolved_base_path, target)
+ except DriveMaterializationValidationError as exc:
+ raise AgentStubValidationError(str(exc)) from exc
+ result_items.append(DrivePullResult.Item(key=target, local_path=str(local_path)))
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_url
if not isinstance(download_url, str) or not download_url:
raise AgentStubValidationError(f"drive manifest item is missing download_url: {item.key}")
- destination = _resolve_drive_destination(base_path, item.key)
+ try:
+ _ = resolve_drive_destination(resolved_base_path, item.key)
+ except DriveMaterializationValidationError as exc:
+ raise AgentStubValidationError(str(exc)) from exc
payload = download_file_bytes_from_signed_url_sync(download_url=download_url)
- if item.size is not None and len(payload) != item.size:
- raise AgentStubTransferError(f"downloaded drive file size mismatch for {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)
- written_paths.append(destination)
- if destination.name == _SKILL_ARCHIVE_FILENAME:
- _extract_skill_archive(destination)
- return written_paths
-
-
-def push_drive_from_environment(local_path: str, drive_path: str, recursive: bool) -> AgentStubDriveCommitResponse:
+ downloads.append(DriveDownloadPayload(key=item.key, payload=payload, size=item.size))
+
+ try:
+ _ = materialize_drive_downloads(
+ base_path=resolved_base_path,
+ downloads=downloads,
+ )
+ except DriveMaterializationValidationError as exc:
+ raise AgentStubValidationError(str(exc)) from exc
+ except DriveMaterializationTransferError as exc:
+ raise AgentStubTransferError(str(exc)) from exc
+
+ return DrivePullResult(items=result_items)
+
+
+def push_drive_from_environment(
+ local_path: str,
+ drive_path: str,
+ *,
+ kind: DrivePushKind | None,
+) -> AgentStubDriveCommitResponse:
"""Upload local files through the Agent Stub and commit them into the drive.
Args:
local_path: Source file or directory in the sandbox filesystem.
drive_path: Destination drive key or drive-key prefix.
- recursive: Select directory mode. ``False`` standardizes skill
- directories, while ``True`` uploads raw directory contents.
+ kind: Optional public upload mode. Files infer file mode when omitted,
+ while directories require explicit ``skill`` or ``dir`` selection.
Returns:
The validated drive commit response returned by the Agent Stub.
@@ -173,25 +214,40 @@ def push_drive_from_environment(local_path: str, drive_path: str, recursive: boo
Mode split:
* If ``local_path`` is a file, upload that file and commit exactly one
``tool_file`` binding to ``drive_path``.
- * If ``local_path`` is a directory and ``recursive`` is ``False``,
+ * If ``local_path`` is a directory and ``kind`` is ``"skill"``,
require ``SKILL.md`` and standardize the upload into
``<drive_path>/SKILL.md`` plus ``<drive_path>/.DIFY-SKILL-FULL.zip``.
- * If ``local_path`` is a directory and ``recursive`` is ``True``, upload
+ * If ``local_path`` is a directory and ``kind`` is ``"dir"``, upload
each regular file under ``drive_path/<relative_path>`` without skill
standardization.
Observable safety behavior:
- Rejects missing local paths, rejects recursive directory pushes with no
- regular files, and rejects symlinked or escaping paths while preparing
- directory uploads or skill archives.
+ Rejects missing local paths, rejects directory pushes without an
+ explicit mode, rejects raw directory pushes with no regular files, and
+ rejects symlinked or escaping paths, including symlinked top-level
+ ``local_path`` roots, while preparing directory uploads or skill
+ archives.
"""
- source_path = Path(local_path).expanduser().resolve()
+ source_path = Path(local_path).expanduser()
+ if kind not in {None, "file", "skill", "dir"}:
+ raise AgentStubValidationError(f"invalid drive push kind: {kind}")
+ if source_path.is_symlink():
+ raise AgentStubValidationError(f"drive push does not support symlinked local paths: {source_path}")
+ source_path = source_path.resolve()
if source_path.is_file():
+ if kind == "skill":
+ raise AgentStubValidationError("--kind skill requires a directory containing SKILL.md")
+ if kind == "dir":
+ raise AgentStubValidationError("--kind dir requires a directory")
return _commit_uploaded_items([_prepare_uploaded_file(source_path, drive_path)])
if not source_path.is_dir():
raise AgentStubValidationError(f"local path not found: {source_path}")
- if recursive:
+ if kind is None:
+ raise AgentStubValidationError("directory drive push requires --kind skill or --kind dir")
+ if kind == "file":
+ raise AgentStubValidationError("--kind file requires a file")
+ if kind == "dir":
upload_items = [
_prepare_uploaded_file(path, _join_drive_key(drive_path, relative_path))
for path, relative_path in _iter_regular_files(source_path)
@@ -205,14 +261,14 @@ def push_drive_from_environment(local_path: str, drive_path: str, recursive: boo
def _push_skill_directory(source_path: Path, drive_path: str) -> AgentStubDriveCommitResponse:
skill_md_path = source_path / _SKILL_MD_FILENAME
if not skill_md_path.is_file():
- raise AgentStubValidationError(f"non-recursive drive push requires {_SKILL_MD_FILENAME}: {source_path}")
+ raise AgentStubValidationError("--kind skill requires a directory containing SKILL.md")
with TemporaryDirectory() as temp_dir:
- archive_path = Path(temp_dir) / _SKILL_ARCHIVE_FILENAME
+ archive_path = Path(temp_dir) / SKILL_ARCHIVE_FILENAME
_build_skill_archive(source_path, archive_path)
return _commit_uploaded_items(
[
_prepare_uploaded_file(skill_md_path.resolve(), _join_drive_key(drive_path, _SKILL_MD_FILENAME)),
- _prepare_uploaded_file(archive_path, _join_drive_key(drive_path, _SKILL_ARCHIVE_FILENAME)),
+ _prepare_uploaded_file(archive_path, _join_drive_key(drive_path, SKILL_ARCHIVE_FILENAME)),
]
)
@@ -239,7 +295,7 @@ def _commit_uploaded_items(items: list[_DriveUploadItem]) -> AgentStubDriveCommi
)
-def _format_manifest(response: AgentStubDriveManifestResponse) -> str:
+def format_drive_manifest(response: AgentStubDriveManifestResponse) -> str:
return "\n".join(_format_manifest_item(item) for item in response.items)
@@ -250,15 +306,6 @@ def _format_manifest_item(item: AgentStubDriveItem) -> str:
return f"{size}\t{mime_type}\t{item_hash}\t{item.key}"
-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 AgentStubValidationError(f"drive key resolves outside the drive base: {drive_key}") from exc
- return destination
-
-
def _iter_regular_files(root_path: Path) -> list[tuple[Path, str]]:
"""Return all regular files under one directory, rejecting unsafe symlinks."""
@@ -305,82 +352,6 @@ def _build_skill_archive(source_path: Path, archive_path: Path) -> None:
archive.write(file_path, arcname=relative_path)
-def _extract_skill_archive(archive_path: Path) -> None:
- """Safely extract one downloaded skill archive into its containing directory.
-
- Extraction is staged under a temporary directory created inside the target
- skill directory. Every entry is validated and materialized into staging
- first, and only after the full archive succeeds are staged files moved into
- their final locations under the skill directory. Existing files at those
- final locations are overwritten in place by the extracted archive content.
-
- Error mapping is intentionally stable for CLI callers: unsafe archive entry
- names raise ``AgentStubValidationError``, while malformed archives and zip
- parsing / archive I/O failures are translated into ``AgentStubTransferError``.
- """
-
- 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():
- destination = _resolve_zip_entry_destination(staging_dir, zip_info.filename)
- if _is_zip_symlink(zip_info):
- raise AgentStubValidationError(
- 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 AgentStubValidationError:
- raise
- except (BadZipFile, OSError) as exc:
- raise AgentStubTransferError(f"downloaded skill archive is invalid: {archive_path.name}") from exc
-
-
-def _resolve_zip_entry_destination(target_dir: Path, entry_name: str) -> Path:
- """Resolve one zip entry path under a target skill directory.
-
- Zip metadata may contain POSIX or backslash-separated names, so entry names
- are normalized to forward slashes before validation. The resolved entry must
- not be absolute, empty, ``.`` / ``..`` based, or otherwise escape the target
- skill directory after resolution.
- """
-
- normalized_name = entry_name.replace("\\", "/")
- pure_path = PurePosixPath(normalized_name)
- if not normalized_name or normalized_name.startswith("/") or pure_path.is_absolute():
- raise AgentStubValidationError(f"skill archive contains unsafe absolute path: {entry_name}")
- if any(part in {"", ".", ".."} for part in pure_path.parts):
- raise AgentStubValidationError(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 AgentStubValidationError(
- 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 stat.S_ISLNK(file_mode)
-
-
def _join_drive_key(base_key: str, child_key: str) -> str:
stripped_base = base_key.rstrip("/")
stripped_child = child_key.lstrip("/")
@@ -388,7 +359,10 @@ def _join_drive_key(base_key: str, child_key: str) -> str:
__all__ = [
- "list_drive_from_environment",
+ "DrivePullResult",
+ "DrivePushKind",
+ "format_drive_manifest",
+ "list_drive_manifest_from_environment",
"pull_drive_from_environment",
"push_drive_from_environment",
]
diff --git a/dify-agent/src/dify_agent/agent_stub/cli/_files.py b/dify-agent/src/dify_agent/agent_stub/cli/_files.py
index dccc6d36c44..9c3c017c51f 100644
--- a/dify-agent/src/dify_agent/agent_stub/cli/_files.py
+++ b/dify-agent/src/dify_agent/agent_stub/cli/_files.py
@@ -5,7 +5,7 @@ from __future__ import annotations
import mimetypes
from dataclasses import dataclass
from pathlib import Path
-from typing import Literal, cast
+from typing import ClassVar, Literal, cast
from pydantic import BaseModel, ConfigDict, ValidationError
@@ -26,7 +26,7 @@ class UploadedToolFileMapping(BaseModel):
transfer_method: Literal["tool_file"] = "tool_file"
reference: str
- model_config = ConfigDict(extra="forbid")
+ model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid")
@dataclass(frozen=True, slots=True)
@@ -76,12 +76,14 @@ def upload_tool_file_resource_from_environment(*, path: str) -> UploadedToolFile
environment = read_agent_stub_environment()
filename = source_path.name
mime_type = mimetypes.guess_type(filename)[0] or "application/octet-stream"
- upload_request = request_agent_stub_file_upload_sync(
+ upload_request: object = request_agent_stub_file_upload_sync(
url=environment.url,
auth_jwe=environment.auth_jwe,
filename=filename,
mimetype=mime_type,
)
+ if not hasattr(upload_request, "upload_url") or not isinstance(upload_request.upload_url, str):
+ raise AgentStubTransferError("signed file upload response is missing upload_url")
with source_path.open("rb") as file_obj:
payload = upload_file_to_signed_url_sync(
upload_url=upload_request.upload_url,
@@ -94,19 +96,65 @@ def upload_tool_file_resource_from_environment(*, path: str) -> UploadedToolFile
def download_file_from_environment(
*,
- transfer_method: str,
- reference_or_url: str,
- directory: str | None = None,
+ transfer_method: str | None = None,
+ reference_or_url: str | None = None,
+ mapping: str | None = None,
+ local_dir: str | None = None,
) -> DownloadedFileResult:
- """Download one workflow file mapping into the sandbox filesystem."""
+ """Download one workflow file mapping into the sandbox filesystem.
+ Callers may provide either the public positional pair
+ ``TRANSFER_METHOD REFERENCE_OR_URL`` or one JSON ``--mapping`` payload.
+ The helper normalizes both forms into ``AgentStubFileMapping`` before
+ requesting a signed download URL from the Agent Stub.
+ """
+
+ file_mapping = _build_download_mapping(
+ transfer_method=transfer_method,
+ reference_or_url=reference_or_url,
+ mapping=mapping,
+ )
environment = read_agent_stub_environment()
+
+ download_request: object = request_agent_stub_file_download_sync(
+ url=environment.url,
+ auth_jwe=environment.auth_jwe,
+ file=file_mapping,
+ )
+ if not hasattr(download_request, "filename") or not isinstance(download_request.filename, str):
+ raise AgentStubTransferError("signed file download response is missing filename")
+ if not hasattr(download_request, "download_url") or not isinstance(download_request.download_url, str):
+ raise AgentStubTransferError("signed file download response is missing download_url")
+ target_dir = Path(local_dir).expanduser().resolve() if local_dir else Path.cwd()
+ target_dir.mkdir(parents=True, exist_ok=True)
+ destination = _deduplicate_destination_path(target_dir / _sanitize_download_filename(download_request.filename))
+ _ = destination.write_bytes(download_file_bytes_from_signed_url_sync(download_url=download_request.download_url))
+ return DownloadedFileResult(path=destination)
+
+
+def _build_download_mapping(
+ *,
+ transfer_method: str | None,
+ reference_or_url: str | None,
+ mapping: str | None,
+) -> AgentStubFileMapping:
+ if mapping is not None:
+ if transfer_method is not None or reference_or_url is not None:
+ raise AgentStubValidationError("--mapping cannot be combined with TRANSFER_METHOD or REFERENCE_OR_URL")
+ try:
+ return AgentStubFileMapping.model_validate_json(mapping)
+ except ValidationError as exc:
+ raise AgentStubValidationError("invalid file download mapping") from exc
+
+ if transfer_method is None or reference_or_url is None:
+ raise AgentStubValidationError("file download requires either --mapping or TRANSFER_METHOD REFERENCE_OR_URL")
+
normalized_transfer_method = cast(
Literal["local_file", "tool_file", "datasource_file", "remote_url"],
transfer_method,
)
try:
- file_mapping = AgentStubFileMapping(
+ return AgentStubFileMapping(
transfer_method=normalized_transfer_method,
url=reference_or_url if normalized_transfer_method == "remote_url" else None,
reference=reference_or_url if normalized_transfer_method != "remote_url" else None,
@@ -114,17 +162,6 @@ def download_file_from_environment(
except ValidationError as exc:
raise AgentStubValidationError("invalid file download arguments") from exc
- download_request = request_agent_stub_file_download_sync(
- url=environment.url,
- auth_jwe=environment.auth_jwe,
- file=file_mapping,
- )
- target_dir = Path(directory).expanduser().resolve() if directory else Path.cwd()
- target_dir.mkdir(parents=True, exist_ok=True)
- destination = _deduplicate_destination_path(target_dir / _sanitize_download_filename(download_request.filename))
- destination.write_bytes(download_file_bytes_from_signed_url_sync(download_url=download_request.download_url))
- return DownloadedFileResult(path=destination)
-
def _normalize_uploaded_tool_file_resource(payload: dict[str, object]) -> UploadedToolFileResource:
reference = payload.get("reference")
diff --git a/dify-agent/src/dify_agent/agent_stub/cli/main.py b/dify-agent/src/dify_agent/agent_stub/cli/main.py
index c5c722d7e03..3d34b96d62e 100644
--- a/dify-agent/src/dify_agent/agent_stub/cli/main.py
+++ b/dify-agent/src/dify_agent/agent_stub/cli/main.py
@@ -11,13 +11,16 @@ does not pull in FastAPI, Redis, shellctl, or JWE runtime dependencies.
from __future__ import annotations
import sys
+from typing import cast
import typer
from typer.main import get_command
from dify_agent.agent_stub.cli._agent_stub import connect_from_environment
from dify_agent.agent_stub.cli._drive import (
- list_drive_from_environment,
+ DrivePushKind,
+ format_drive_manifest,
+ list_drive_manifest_from_environment,
pull_drive_from_environment,
push_drive_from_environment,
)
@@ -60,21 +63,23 @@ def upload(path: str = typer.Argument(..., metavar="PATH")) -> None:
@file_app.command("download")
def download(
- transfer_method: str = typer.Argument(..., metavar="TRANSFER_METHOD"),
- reference_or_url: str = typer.Argument(..., metavar="REFERENCE_OR_URL"),
- directory: str | None = typer.Argument(default=None, metavar="DIR"),
+ transfer_method: str | None = typer.Argument(None, metavar="TRANSFER_METHOD"),
+ reference_or_url: str | None = typer.Argument(None, metavar="REFERENCE_OR_URL"),
+ mapping: str | None = typer.Option(None, "--mapping", help="Download one file from a mapping JSON object."),
+ local_dir: str | None = typer.Option(None, "--to", help="Local directory for the downloaded file."),
) -> None:
"""Download one workflow file mapping into the local sandbox directory."""
_run_file_download(
transfer_method=transfer_method,
reference_or_url=reference_or_url,
- directory=directory,
+ mapping=mapping,
+ local_dir=local_dir,
)
@drive_app.command("list")
def drive_list(
- path_prefix: str = typer.Argument("", metavar="PATH_PREFIX"),
+ path_prefix: str = typer.Argument("", metavar="REMOTE_PREFIX"),
json_output: bool = typer.Option(False, "--json", help="Emit the drive manifest as JSON."),
) -> None:
"""List drive files visible to the current sandbox execution."""
@@ -83,32 +88,39 @@ def drive_list(
@drive_app.command("pull")
def drive_pull(
- targets: list[str] = typer.Argument(None, metavar="TARGET"),
- drive_base: str | None = typer.Option(
+ targets: list[str] = typer.Argument(None, metavar="REMOTE"),
+ local_base: str | None = typer.Option(
None,
- "--drive-base",
+ "--to",
help=(
f"Local base directory for pulled drive files. Defaults to ${AGENT_STUB_DRIVE_BASE_ENV_VAR} "
f"or {DEFAULT_AGENT_STUB_DRIVE_BASE}."
),
),
+ json_output: bool = typer.Option(False, "--json", help="Emit the pull result as JSON."),
) -> None:
"""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)
+ _run_drive_pull(targets=targets or None, local_base=local_base, json_output=json_output)
@drive_app.command("push")
def drive_push(
local_path: str = typer.Argument(..., metavar="LOCAL_PATH"),
- drive_path: str = typer.Argument(..., metavar="DRIVE_PATH"),
- recursive: bool = typer.Option(False, "-r", "--recursive", help="Recursively upload directory contents."),
+ drive_path: str = typer.Argument(..., metavar="REMOTE_PATH"),
+ kind: str | None = typer.Option(None, "--kind", help="Directory upload kind: skill or dir."),
+ json_output: bool = typer.Option(
+ False,
+ "--json",
+ help="Accepted for consistency; drive push output is already emitted as JSON.",
+ ),
) -> None:
"""Upload one local file or directory into the agent drive."""
- _run_drive_push(local_path=local_path, drive_path=drive_path, recursive=recursive)
+ del json_output
+ _run_drive_push(local_path=local_path, drive_path=drive_path, kind=kind)
def main(argv: list[str] | None = None) -> None:
@@ -190,12 +202,19 @@ def _run_file_upload(*, path: str) -> None:
typer.echo(response.model_dump_json())
-def _run_file_download(*, transfer_method: str, reference_or_url: str, directory: str | None) -> None:
+def _run_file_download(
+ *,
+ transfer_method: str | None,
+ reference_or_url: str | None,
+ mapping: str | None,
+ local_dir: str | None,
+) -> None:
try:
response = download_file_from_environment(
transfer_method=transfer_method,
reference_or_url=reference_or_url,
- directory=directory,
+ mapping=mapping,
+ local_dir=local_dir,
)
except MissingAgentStubEnvironmentError as exc:
typer.echo(str(exc), err=True)
@@ -208,7 +227,7 @@ def _run_file_download(*, transfer_method: str, reference_or_url: str, directory
def _run_drive_list(*, path_prefix: str, json_output: bool) -> None:
try:
- response = list_drive_from_environment(prefix=path_prefix, json_output=json_output)
+ response = list_drive_manifest_from_environment(prefix=path_prefix)
except MissingAgentStubEnvironmentError as exc:
typer.echo(str(exc), err=True)
raise SystemExit(2) from exc
@@ -216,29 +235,34 @@ def _run_drive_list(*, path_prefix: str, json_output: bool) -> None:
typer.echo(str(exc), err=True)
raise SystemExit(1) from exc
if json_output:
- if isinstance(response, str):
- raise RuntimeError("drive list JSON output expected a manifest response")
typer.echo(response.model_dump_json())
return
- typer.echo(response)
+ typer.echo(format_drive_manifest(response))
-def _run_drive_pull(*, targets: list[str] | None, drive_base: str | None) -> None:
+def _run_drive_pull(*, targets: list[str] | None, local_base: str | None, json_output: bool) -> None:
try:
- response = pull_drive_from_environment(targets=targets, drive_base=drive_base or read_agent_stub_drive_base())
+ response = pull_drive_from_environment(targets=targets, local_base=local_base or read_agent_stub_drive_base())
except MissingAgentStubEnvironmentError as exc:
typer.echo(str(exc), err=True)
raise SystemExit(2) from exc
except AgentStubClientError as exc:
typer.echo(str(exc), err=True)
raise SystemExit(1) from exc
- for path in response:
- typer.echo(str(path))
+ if json_output:
+ typer.echo(response.model_dump_json())
+ return
+ for item in response.items:
+ typer.echo(item.local_path)
-def _run_drive_push(*, local_path: str, drive_path: str, recursive: bool) -> None:
+def _run_drive_push(*, local_path: str, drive_path: str, kind: str | None) -> None:
try:
- response = push_drive_from_environment(local_path=local_path, drive_path=drive_path, recursive=recursive)
+ response = push_drive_from_environment(
+ local_path=local_path,
+ drive_path=drive_path,
+ kind=cast(DrivePushKind | None, kind),
+ )
except MissingAgentStubEnvironmentError as exc:
typer.echo(str(exc), err=True)
raise SystemExit(2) from exc
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.py
index a6a0d4793fe..c6d0333cd5c 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
@@ -267,7 +267,11 @@ class AgentStubDriveCommitRequest(BaseModel):
class AgentStubDriveItem(BaseModel):
- """One manifest or commit item returned by the Agent Stub drive API."""
+ """One manifest or commit item returned by the Agent Stub drive API.
+
+ Known stable fields stay typed, while extra response metadata from the Dify
+ API is preserved for forward compatibility.
+ """
key: str
size: int | None = None
@@ -282,7 +286,7 @@ class AgentStubDriveItem(BaseModel):
is_skill: bool | None = None
skill_metadata: str | None = None
- model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid")
+ model_config: ClassVar[ConfigDict] = ConfigDict(extra="allow")
class AgentStubDriveManifestResponse(BaseModel):
diff --git a/dify-agent/src/dify_agent/layers/drive/configs.py b/dify-agent/src/dify_agent/layers/drive/configs.py
index f74a24298fd..20fd514baf2 100644
--- a/dify-agent/src/dify_agent/layers/drive/configs.py
+++ b/dify-agent/src/dify_agent/layers/drive/configs.py
@@ -6,7 +6,9 @@ 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).
+by running sandbox-visible ``dify-agent drive pull`` commands through the shell
+layer so materialized files live in the same filesystem that model shell jobs
+use.
"""
from typing import Final
diff --git a/dify-agent/src/dify_agent/layers/drive/layer.py b/dify-agent/src/dify_agent/layers/drive/layer.py
index e38704d2b9d..e6941b50cbe 100644
--- a/dify-agent/src/dify_agent/layers/drive/layer.py
+++ b/dify-agent/src/dify_agent/layers/drive/layer.py
@@ -1,32 +1,49 @@
-"""Runtime Dify drive layer with eager pull for prompt-mentioned targets.
+"""Runtime Dify drive layer with shell-backed eager pulls.
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.
+those mentioned skills/files through the already-active shell layer by running
+the sandbox-visible ``dify-agent drive pull`` command, then contributes a
+concise prompt block describing what was loaded. It also contributes a suffix
+prompt with the remaining skill catalog plus ``dify-agent drive`` and
+``dify-agent file`` usage so the model has concrete Agent Stub commands for
+materializing drive content and workflow files.
"""
from __future__ import annotations
-import asyncio
+import shlex
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
+from pathlib import Path
+from typing import ClassVar
-import httpx
from typing_extensions import Self, override
-from agenton.layers import EmptyRuntimeState, Layer, LayerDeps, PlainLayer
+from agenton.layers import EmptyRuntimeState, LayerDeps, PlainLayer
from dify_agent.agent_stub.protocol import agent_stub_drive_base_for_ref
from dify_agent.layers.drive.configs import DIFY_DRIVE_LAYER_TYPE_ID, DifyDriveLayerConfig
+from dify_agent.layers.shell.layer import DifyShellLayer
-_SKILL_ARCHIVE_FILENAME = ".DIFY-SKILL-FULL.zip"
-_DOWNLOAD_CONCURRENCY = 4
+_AGENT_STUB_CLI_USAGE_PROMPT = """Agent Stub CLI usage is available inside shell jobs:
+
+Drive assets are Agent Soul versioned assets:
+
+- List drive assets: `dify-agent drive list [REMOTE_PREFIX]`
+- Pull drive assets: `dify-agent drive pull [REMOTE ...] [--to LOCAL_DIR]`
+ With no remote, pulls the whole visible drive. Pull overwrites local files.
+ Defaults to `$DIFY_AGENT_STUB_DRIVE_BASE`; use `--to .` for cwd.
+ `--to` is a local root; remote keys keep their path under it.
+ Skill archives are automatically extracted after pull.
+- Push one file: `dify-agent drive push LOCAL_FILE REMOTE_PATH`
+- Push a skill package: `dify-agent drive push LOCAL_DIR REMOTE_PATH --kind skill`
+- Push a raw directory: `dify-agent drive push LOCAL_DIR REMOTE_PATH --kind dir`
+
+Workflow file mappings:
+
+- Download a mapping: `dify-agent file download TRANSFER_METHOD REFERENCE_OR_URL [--to LOCAL_DIR]`
+- Or pass a mapping object: `dify-agent file download --mapping '{"transfer_method":"tool_file","reference":"..."}'`
+- Upload an output file: `dify-agent file upload PATH`
+ Prints JSON like `{"transfer_method":"tool_file","reference":"..."}`."""
class DifyDriveLayerError(RuntimeError):
@@ -34,53 +51,34 @@ class DifyDriveLayerError(RuntimeError):
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
+ shell: DifyShellLayer # pyright: ignore[reportUninitializedInstanceVariable]
@dataclass(slots=True)
class DifyDriveLayer(PlainLayer[DifyDriveDeps, DifyDriveLayerConfig, EmptyRuntimeState]):
- """Drive runtime layer that eagerly materializes prompt-mentioned drive targets."""
+ """Drive runtime layer that materializes prompt-mentioned targets via shell."""
type_id: ClassVar[str | None] = DIFY_DRIVE_LAYER_TYPE_ID
config: 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
@override
def from_config(cls, config: DifyDriveLayerConfig) -> Self:
- 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,
- )
+ return cls(config=DifyDriveLayerConfig.model_validate(config))
@property
@override
def prefix_prompts(self) -> list[str]:
return [self.build_prompt_context()]
+ @property
+ @override
+ def suffix_prompts(self) -> list[str]:
+ return [self.build_suffix_prompt()]
+
@override
async def on_context_create(self) -> None:
await self._pull_mentioned_targets()
@@ -100,7 +98,11 @@ class DifyDriveLayer(PlainLayer[DifyDriveDeps, DifyDriveLayerConfig, EmptyRuntim
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}")
+ pulled_skill_path = self._pulled_file_paths.get(skill_key)
+ if pulled_skill_path is None:
+ continue
+ local_path = Path(pulled_skill_path).parent
+ loaded_skill_sections.append(f"Path: {skill.path}\nLocal path: {local_path}\nSKILL.md:\n{body}")
if loaded_skill_sections:
sections.append("Loaded mentioned skills:\n\n" + "\n\n".join(loaded_skill_sections))
@@ -112,217 +114,138 @@ class DifyDriveLayer(PlainLayer[DifyDriveDeps, DifyDriveLayerConfig, EmptyRuntim
if mentioned_files:
sections.append("Mentioned files pulled to local drive:\n" + "\n".join(mentioned_files))
+ if not sections:
+ return ""
+ return "\n\n".join(sections)
+
+ def build_suffix_prompt(self) -> str:
+ sections: list[str] = []
+ mentioned_skill_keys = set(self.config.mentioned_skill_keys)
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 skill.skill_md_key not in 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."
- )
+ pull_and_read_command = (
+ '`skill_dir="$(dify-agent drive pull <SKILL_PATH> --to /tmp/drive)"; '
+ + 'printf "%s\\n" "$skill_dir"; cat "$skill_dir/SKILL.md"`'
+ )
+ sections.append(
+ "Other available skills:\n"
+ + "\n".join(other_skills)
+ + "\n\nTo use one, pull it and read its SKILL.md in one command: "
+ + pull_and_read_command
+ + "."
+ )
+ sections.append(_AGENT_STUB_CLI_USAGE_PROMPT)
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]
+ targets = self._mentioned_pull_targets()
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)
+ script = self._build_shell_pull_script(targets=targets)
+ result = await self.deps.shell.run_remote_script(script, inject_agent_stub_env=True)
+ if result.exit_code != 0:
+ raise DifyDriveLayerError(
+ f"drive mentioned pull failed in shell: {result.status} exit_code={result.exit_code}\n{result.output}"
+ )
+ if result.truncated:
+ raise DifyDriveLayerError("drive mentioned pull output was truncated before SKILL.md content was loaded")
+
+ written_paths, skill_bodies = self._parse_shell_pull_output(result.output)
+ self._record_pulled_paths(written_paths)
+ for skill_key in self.config.mentioned_skill_keys:
+ body = skill_bodies.get(skill_key)
+ if body is None:
+ raise DifyDriveLayerError(f"missing pulled SKILL.md content for mentioned skill {skill_key}")
+ self._loaded_skill_bodies[skill_key] = body
+
+ def _build_shell_pull_script(self, *, targets: list[tuple[str, bool]]) -> str:
+ pull_targets = list(dict.fromkeys(prefix for prefix, _exact in targets))
+ base_path = agent_stub_drive_base_for_ref(self.config.drive_ref)
+ lines = [
+ "set -eu",
+ f"base={shlex.quote(base_path)}",
+ "dify-agent drive pull " + " ".join(shlex.quote(target) for target in pull_targets) + ' --to "$base"',
+ ]
+ for skill_key in self.config.mentioned_skill_keys:
+ skill_path = self._shell_local_path(skill_key)
+ lines.extend(
+ [
+ f"test -f {shlex.quote(skill_path)}",
+ f"printf '\\n__DIFY_DRIVE_MENTIONED_PATH__\\t%s\\t%s\\n' {shlex.quote(skill_key)} {shlex.quote(skill_path)}",
+ f"printf '__DIFY_DRIVE_SKILL_BEGIN__\\t%s\\n' {shlex.quote(skill_key)}",
+ f"cat {shlex.quote(skill_path)}",
+ f"printf '\\n__DIFY_DRIVE_SKILL_END__\\t%s\\n' {shlex.quote(skill_key)}",
+ ]
+ )
+ for file_key in self.config.mentioned_file_keys:
+ file_path = self._shell_local_path(file_key)
+ lines.extend(
+ [
+ f"test -e {shlex.quote(file_path)}",
+ f"printf '\\n__DIFY_DRIVE_MENTIONED_PATH__\\t%s\\t%s\\n' {shlex.quote(file_key)} {shlex.quote(file_path)}",
+ ]
+ )
+ return "\n".join(lines)
+
+ def _parse_shell_pull_output(self, output: str) -> tuple[dict[str, str], dict[str, str]]:
+ written_paths: dict[str, str] = {}
+ skill_bodies: dict[str, str] = {}
+ current_skill_key: str | None = None
+ current_skill_body: list[str] = []
+
+ for line in output.splitlines(keepends=True):
+ stripped_line = line.rstrip("\n")
+ if current_skill_key is not None:
+ if stripped_line == f"__DIFY_DRIVE_SKILL_END__\t{current_skill_key}":
+ skill_bodies[current_skill_key] = "".join(current_skill_body)
+ current_skill_key = None
+ current_skill_body = []
+ continue
+ current_skill_body.append(line)
+ continue
+
+ if stripped_line.startswith("__DIFY_DRIVE_MENTIONED_PATH__\t"):
+ parts = stripped_line.split("\t", 2)
+ if len(parts) != 3:
+ raise DifyDriveLayerError("drive mentioned pull emitted an invalid path marker")
+ _marker, key, path = parts
+ written_paths[key] = path
+ continue
+ if stripped_line.startswith("__DIFY_DRIVE_SKILL_BEGIN__\t"):
+ current_skill_key = stripped_line.split("\t", 1)[1]
+ current_skill_body = []
+
+ if current_skill_key is not None:
+ raise DifyDriveLayerError(f"drive mentioned pull omitted SKILL.md end marker for {current_skill_key}")
+ return written_paths, skill_bodies
+
+ def _record_pulled_paths(self, written_paths: dict[str, str]) -> None:
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:
+ if skill_key not in written_paths:
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()
+
+ def _mentioned_pull_targets(self) -> list[tuple[str, bool]]:
+ return [(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
+ ]
+
+ def _shell_local_path(self, drive_key: str) -> str:
+ return f"{agent_stub_drive_base_for_ref(self.config.drive_ref).rstrip('/')}/{drive_key.lstrip('/')}"
@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", "DifyDriveLayerError"]
diff --git a/dify-agent/src/dify_agent/layers/knowledge/__init__.py b/dify-agent/src/dify_agent/layers/knowledge/__init__.py
index 569512d8004..86a9405bce3 100644
--- a/dify-agent/src/dify_agent/layers/knowledge/__init__.py
+++ b/dify-agent/src/dify_agent/layers/knowledge/__init__.py
@@ -7,21 +7,31 @@ root stays import-safe for callers that only need to construct run requests.
from dify_agent.layers.knowledge.configs import (
DIFY_KNOWLEDGE_BASE_LAYER_TYPE_ID,
DifyKnowledgeBaseLayerConfig,
+ DifyKnowledgeDatasetConfig,
+ DifyKnowledgeEagerResult,
DifyKnowledgeMetadataCondition,
DifyKnowledgeMetadataConditions,
DifyKnowledgeMetadataFilteringConfig,
DifyKnowledgeModelConfig,
+ DifyKnowledgeQueryConfig,
DifyKnowledgeRerankingModelConfig,
DifyKnowledgeRetrievalConfig,
+ DifyKnowledgeRuntimeState,
+ DifyKnowledgeSetConfig,
)
__all__ = [
"DIFY_KNOWLEDGE_BASE_LAYER_TYPE_ID",
"DifyKnowledgeBaseLayerConfig",
+ "DifyKnowledgeDatasetConfig",
+ "DifyKnowledgeEagerResult",
"DifyKnowledgeMetadataCondition",
"DifyKnowledgeMetadataConditions",
"DifyKnowledgeMetadataFilteringConfig",
"DifyKnowledgeModelConfig",
+ "DifyKnowledgeQueryConfig",
"DifyKnowledgeRerankingModelConfig",
"DifyKnowledgeRetrievalConfig",
+ "DifyKnowledgeRuntimeState",
+ "DifyKnowledgeSetConfig",
]
diff --git a/dify-agent/src/dify_agent/layers/knowledge/configs.py b/dify-agent/src/dify_agent/layers/knowledge/configs.py
index 9ada075d1cc..b7b71ab9c42 100644
--- a/dify-agent/src/dify_agent/layers/knowledge/configs.py
+++ b/dify-agent/src/dify_agent/layers/knowledge/configs.py
@@ -1,12 +1,11 @@
"""Client-safe DTOs for the Dify knowledge-base Agenton layer.
-The public layer config exposes only static retrieval controls: dataset ids,
-retrieval strategy, metadata filtering, and observation-size limits. The agent
-model itself should only ever see a single ``query`` tool argument; tenant/
-app/user context comes from the execution-context layer and the actual
-retrieval is delegated to the Dify API inner endpoint. Tool naming is not
-caller-configurable: the runtime always exposes the same stable knowledge-base
-search tool.
+The public layer config carries one or more named knowledge sets. Each set owns
+its dataset ids plus query, retrieval, and metadata-filtering policy. Generated-
+query sets are exposed through one stable model-visible search tool whose
+schema lets the model pick ``set_name`` and ``query``; user-query sets are
+retrieved eagerly when the layer enters a run and their formatted observations
+are kept only in JSON-safe ``runtime_state`` for session snapshots.
"""
from __future__ import annotations
@@ -61,6 +60,44 @@ class DifyKnowledgeRerankingModelConfig(BaseModel):
model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid")
+class DifyKnowledgeDatasetConfig(BaseModel):
+ """One dataset selected by a knowledge set.
+
+ Only ``id`` is used for retrieval. ``name`` and ``description`` are retained
+ because callers already have them and they are useful in runtime/debug
+ snapshots without changing the inner retrieval request contract.
+ """
+
+ id: str
+ name: str | None = None
+ description: str | None = None
+
+ model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid")
+
+ @field_validator("id")
+ @classmethod
+ def validate_id(cls, value: str) -> str:
+ normalized = value.strip()
+ if not normalized:
+ raise ValueError("dataset id must not be blank")
+ return normalized
+
+
+class DifyKnowledgeQueryConfig(BaseModel):
+ """Query policy for one knowledge set."""
+
+ mode: Literal["user_query", "generated_query"]
+ value: str | None = None
+
+ model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid")
+
+ @model_validator(mode="after")
+ def validate_mode_specific_fields(self) -> DifyKnowledgeQueryConfig:
+ if self.mode == "user_query" and not (self.value or "").strip():
+ raise ValueError("query.value is required for user_query mode")
+ return self
+
+
class DifyKnowledgeRetrievalConfig(BaseModel):
"""Static retrieval controls mirrored into the inner API request."""
@@ -151,38 +188,90 @@ class DifyKnowledgeMetadataFilteringConfig(BaseModel):
return payload
-class DifyKnowledgeBaseLayerConfig(LayerConfig):
- """Public config for one model-visible knowledge search tool.
+class DifyKnowledgeSetConfig(BaseModel):
+ """One independently searchable or eagerly-preloaded knowledge set."""
- The model only gets to choose whether to call the tool and what ``query``
- to send. Dataset ids, retrieval settings, metadata filtering, and caller
- context remain config/runtime concerns outside the model-visible tool
- schema. The tool name and description are fixed by the layer runtime and do
- not appear in the public config DTO.
- """
-
- dataset_ids: list[str]
+ id: str
+ name: str
+ description: str | None = None
+ datasets: list[DifyKnowledgeDatasetConfig]
+ query: DifyKnowledgeQueryConfig
retrieval: DifyKnowledgeRetrievalConfig
metadata_filtering: DifyKnowledgeMetadataFilteringConfig = Field(
default_factory=DifyKnowledgeMetadataFilteringConfig
)
- max_result_content_chars: int = Field(default=2000, ge=1)
- max_observation_chars: int = Field(default=12000, ge=1)
model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid")
- @field_validator("dataset_ids")
+ @field_validator("id", "name")
@classmethod
- def validate_dataset_ids(cls, value: list[str]) -> list[str]:
- if not value:
- raise ValueError("dataset_ids must contain at least one item")
- normalized_ids = [item.strip() for item in value]
- if any(not item for item in normalized_ids):
- raise ValueError("dataset_ids must not contain blank items")
- return normalized_ids
+ def validate_non_blank_identity(cls, value: str) -> str:
+ normalized = value.strip()
+ if not normalized:
+ raise ValueError("knowledge set id and name must not be blank")
+ return normalized
+
+ @model_validator(mode="after")
+ def validate_dataset_ids(self) -> DifyKnowledgeSetConfig:
+ if not self.datasets:
+ raise ValueError("knowledge set requires at least one dataset")
+ dataset_ids = [dataset.id for dataset in self.datasets]
+ if len(dataset_ids) != len(set(dataset_ids)):
+ raise ValueError("knowledge set dataset ids must be unique")
+ return self
+
+ @property
+ def dataset_ids(self) -> list[str]:
+ """Return the selected dataset ids for the inner retrieval request."""
+ return [dataset.id for dataset in self.datasets]
+
+
+class DifyKnowledgeEagerResult(BaseModel):
+ """JSON-safe eager user-query result stored in layer runtime state."""
+
+ set_id: str
+ set_name: str
+ query: str
+ observation: str
+ status: Literal["success", "empty", "temporarily_unavailable"]
+
+ model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid")
+
+
+class DifyKnowledgeRuntimeState(BaseModel):
+ """Serializable eager-retrieval state stored in Agenton session snapshots."""
+
+ eager_config_fingerprint: str | None = None
+ eager_results: list[DifyKnowledgeEagerResult] = Field(default_factory=list)
+
+ model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid", validate_assignment=True)
+
+
+class DifyKnowledgeBaseLayerConfig(LayerConfig):
+ """Public config for one knowledge-base layer.
+
+ The model-visible surface stays fixed to ``knowledge_base_search``. Set
+ names are the only model-visible selection labels; dataset ids, retrieval
+ controls, metadata filtering, and caller identity remain config/runtime
+ concerns outside the tool schema.
+ """
+
+ sets: list[DifyKnowledgeSetConfig]
+ max_result_content_chars: int = Field(default=2000, ge=1)
+ max_observation_chars: int = Field(default=12000, ge=1)
+
+ model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid")
@model_validator(mode="after")
- def validate_observation_limits(self) -> DifyKnowledgeBaseLayerConfig:
+ def validate_sets_and_observation_limits(self) -> DifyKnowledgeBaseLayerConfig:
+ if not self.sets:
+ raise ValueError("sets must contain at least one knowledge set")
+ set_ids = [knowledge_set.id for knowledge_set in self.sets]
+ if len(set_ids) != len(set(set_ids)):
+ raise ValueError("knowledge set ids must be unique")
+ normalized_names = [knowledge_set.name.strip().lower() for knowledge_set in self.sets]
+ if len(normalized_names) != len(set(normalized_names)):
+ raise ValueError("knowledge set names must be unique")
if self.max_observation_chars < self.max_result_content_chars:
raise ValueError("max_observation_chars must be greater than or equal to max_result_content_chars")
return self
@@ -191,10 +280,15 @@ class DifyKnowledgeBaseLayerConfig(LayerConfig):
__all__ = [
"DIFY_KNOWLEDGE_BASE_LAYER_TYPE_ID",
"DifyKnowledgeBaseLayerConfig",
+ "DifyKnowledgeDatasetConfig",
+ "DifyKnowledgeEagerResult",
"DifyKnowledgeMetadataCondition",
"DifyKnowledgeMetadataConditions",
"DifyKnowledgeMetadataFilteringConfig",
"DifyKnowledgeModelConfig",
+ "DifyKnowledgeQueryConfig",
"DifyKnowledgeRerankingModelConfig",
"DifyKnowledgeRetrievalConfig",
+ "DifyKnowledgeRuntimeState",
+ "DifyKnowledgeSetConfig",
]
diff --git a/dify-agent/src/dify_agent/layers/knowledge/layer.py b/dify-agent/src/dify_agent/layers/knowledge/layer.py
index 02c9f07dd56..df07dc3cd36 100644
--- a/dify-agent/src/dify_agent/layers/knowledge/layer.py
+++ b/dify-agent/src/dify_agent/layers/knowledge/layer.py
@@ -1,17 +1,18 @@
-"""Dify knowledge-base layer exposing one model-visible search tool.
+"""Dify knowledge-base layer exposing set-aware retrieval.
The layer depends on ``DifyExecutionContextLayer`` for tenant/app/user/invoke
-identity, keeps retrieval controls in config only, and borrows a lifespan-owned
-HTTP client for each tool invocation. It never owns live clients or stores
-retrieved source content in layer state. Tool identity is intentionally fixed at
-runtime: callers cannot rename the knowledge tool or override its description
-through public layer config because the model-visible surface must stay stable
-across API-side Agent Soul mappings.
+identity. Generated-query sets become one stable model-visible
+``knowledge_base_search(set_name, query)`` tool, while user-query sets are
+retrieved eagerly during context entry and exposed as additional user prompt
+content. Eager observations are persisted only as JSON-safe runtime state so
+Agenton session snapshots can resume without repeating unchanged retrievals.
"""
from __future__ import annotations
from dataclasses import dataclass
+import hashlib
+import json
import logging
from typing import ClassVar, cast
@@ -27,7 +28,13 @@ from dify_agent.layers.knowledge.client import (
DifyKnowledgeBaseClientError,
DifyKnowledgeRetrieveResponse,
)
-from dify_agent.layers.knowledge.configs import DIFY_KNOWLEDGE_BASE_LAYER_TYPE_ID, DifyKnowledgeBaseLayerConfig
+from dify_agent.layers.knowledge.configs import (
+ DIFY_KNOWLEDGE_BASE_LAYER_TYPE_ID,
+ DifyKnowledgeBaseLayerConfig,
+ DifyKnowledgeEagerResult,
+ DifyKnowledgeRuntimeState,
+ DifyKnowledgeSetConfig,
+)
logger = logging.getLogger(__name__)
@@ -35,23 +42,14 @@ logger = logging.getLogger(__name__)
# public DTO cannot grow a parallel naming contract that diverges from the
# runtime knowledge-search surface.
_KNOWLEDGE_BASE_TOOL_NAME = "knowledge_base_search"
-_KNOWLEDGE_BASE_TOOL_DESCRIPTION = "Search configured knowledge bases for information relevant to the query."
+_KNOWLEDGE_BASE_TOOL_DESCRIPTION = (
+ "Search a configured knowledge set. Pick one configured set_name and provide a focused search query."
+)
BLANK_QUERY_OBSERVATION = "knowledge base search requires a non-empty query"
NO_RESULTS_OBSERVATION = "No relevant knowledge base results were found."
TEMPORARY_UNAVAILABLE_OBSERVATION = (
"Knowledge base search is temporarily unavailable. Please continue without it if possible."
)
-QUERY_TOOL_SCHEMA = {
- "type": "object",
- "properties": {
- "query": {
- "type": "string",
- "description": "Search query for the configured knowledge bases.",
- }
- },
- "required": ["query"],
- "additionalProperties": False,
-}
class DifyKnowledgeBaseDeps(LayerDeps):
@@ -61,8 +59,10 @@ class DifyKnowledgeBaseDeps(LayerDeps):
@dataclass(slots=True)
-class DifyKnowledgeBaseLayer(PlainLayer[DifyKnowledgeBaseDeps, DifyKnowledgeBaseLayerConfig]):
- """Layer that resolves one config-scoped knowledge search tool."""
+class DifyKnowledgeBaseLayer(
+ PlainLayer[DifyKnowledgeBaseDeps, DifyKnowledgeBaseLayerConfig, DifyKnowledgeRuntimeState]
+):
+ """Layer that resolves set-scoped knowledge tools and eager user prompts."""
type_id: ClassVar[str | None] = DIFY_KNOWLEDGE_BASE_LAYER_TYPE_ID
@@ -95,7 +95,7 @@ class DifyKnowledgeBaseLayer(PlainLayer[DifyKnowledgeBaseDeps, DifyKnowledgeBase
)
async def get_tools(self, *, http_client: httpx.AsyncClient) -> list[Tool[object]]:
- """Build one Pydantic AI tool that exposes only ``query`` to the model.
+ """Build the unified generated-query Pydantic AI tool, when needed.
Knowledge tools depend on execution-context identity that is optional for
other run types but mandatory here: ``tenant_id``, ``user_id``,
@@ -103,11 +103,15 @@ class DifyKnowledgeBaseLayer(PlainLayer[DifyKnowledgeBaseDeps, DifyKnowledgeBase
any HTTP request is attempted. Tool execution then follows a strict
observation policy:
+ - unknown ``set_name`` returns a local validation observation;
- blank ``query`` returns a local validation observation;
- retryable client failures (timeouts, connection failures, HTTP
``429``/``502``) become a temporary-unavailable observation;
- non-retryable client failures are raised so the run fails fast.
"""
+ generated_sets = self._generated_query_sets()
+ if not generated_sets:
+ return []
if http_client.is_closed:
raise RuntimeError("DifyKnowledgeBaseLayer.get_tools() requires an open shared HTTP client.")
@@ -118,54 +122,28 @@ class DifyKnowledgeBaseLayer(PlainLayer[DifyKnowledgeBaseDeps, DifyKnowledgeBase
api_key=self.inner_api_key,
http_client=http_client,
)
+ set_by_name = {knowledge_set.name: knowledge_set for knowledge_set in generated_sets}
- async def knowledge_base_search(_ctx: RunContext[object], query: str) -> str:
+ async def knowledge_base_search(_ctx: RunContext[object], set_name: str, query: str) -> str:
+ knowledge_set = set_by_name.get(set_name)
+ if knowledge_set is None:
+ return f"unknown knowledge set: {set_name}"
normalized_query = query.strip()
if not normalized_query:
return BLANK_QUERY_OBSERVATION
- try:
- response = await client.retrieve(
- tenant_id=caller["tenant_id"],
- user_id=caller["user_id"],
- app_id=caller["app_id"],
- user_from=caller["user_from"],
- invoke_from=caller["invoke_from"],
- dataset_ids=list(self.config.dataset_ids),
- query=normalized_query,
- retrieval=self.config.retrieval,
- metadata_filtering=self.config.metadata_filtering,
- )
- except DifyKnowledgeBaseClientError as exc:
- if exc.retryable:
- logger.warning(
- "knowledge base search temporarily unavailable",
- extra={
- "tenant_id": caller["tenant_id"],
- "app_id": caller["app_id"],
- "invoke_from": caller["invoke_from"],
- "error_code": exc.error_code,
- "status_code": exc.status_code,
- },
- )
- return TEMPORARY_UNAVAILABLE_OBSERVATION
- logger.error(
- "knowledge base search failed",
- extra={
- "tenant_id": caller["tenant_id"],
- "app_id": caller["app_id"],
- "invoke_from": caller["invoke_from"],
- "error_code": exc.error_code,
- "status_code": exc.status_code,
- },
- )
- raise
- return _format_observation(response, self.config)
+ return await self._retrieve_for_set(
+ client=client,
+ caller=caller,
+ knowledge_set=knowledge_set,
+ query=normalized_query,
+ retryable_observation=True,
+ )
async def prepare_tool_definition(_ctx: RunContext[object], tool_def: ToolDefinition) -> ToolDefinition:
return ToolDefinition(
name=tool_def.name,
description=tool_def.description,
- parameters_json_schema=QUERY_TOOL_SCHEMA,
+ parameters_json_schema=_tool_schema(generated_sets),
strict=tool_def.strict,
sequential=tool_def.sequential,
metadata=tool_def.metadata,
@@ -181,11 +159,177 @@ class DifyKnowledgeBaseLayer(PlainLayer[DifyKnowledgeBaseDeps, DifyKnowledgeBase
knowledge_base_search,
takes_ctx=True,
name=_KNOWLEDGE_BASE_TOOL_NAME,
- description=_KNOWLEDGE_BASE_TOOL_DESCRIPTION,
+ description=_tool_description(generated_sets),
prepare=prepare_tool_definition,
)
]
+ @property
+ @override
+ def user_prompts(self) -> list[str]:
+ """Expose eager user-query results as an additional user prompt."""
+ if not self.runtime_state.eager_results:
+ return []
+
+ sections: list[str] = []
+ for result in self.runtime_state.eager_results:
+ sections.append(
+ "\n".join(
+ [
+ f"Set: {result.set_name}",
+ f"Query: {result.query}",
+ "Results:",
+ result.observation,
+ ]
+ )
+ )
+ return ["Knowledge retrieval results:\n\n" + "\n\n".join(sections)]
+
+ @override
+ async def on_context_create(self) -> None:
+ await self._refresh_eager_results_if_needed()
+
+ @override
+ async def on_context_resume(self) -> None:
+ await self._refresh_eager_results_if_needed()
+
+ def _generated_query_sets(self) -> list[DifyKnowledgeSetConfig]:
+ return [knowledge_set for knowledge_set in self.config.sets if knowledge_set.query.mode == "generated_query"]
+
+ def _user_query_sets(self) -> list[DifyKnowledgeSetConfig]:
+ return [knowledge_set for knowledge_set in self.config.sets if knowledge_set.query.mode == "user_query"]
+
+ async def _refresh_eager_results_if_needed(self) -> None:
+ user_query_sets = self._user_query_sets()
+ if not user_query_sets:
+ self.runtime_state.eager_config_fingerprint = None
+ self.runtime_state.eager_results = []
+ return
+
+ fingerprint = _eager_config_fingerprint(user_query_sets)
+ if self.runtime_state.eager_config_fingerprint == fingerprint:
+ return
+
+ caller = _build_caller_context(self.deps.execution_context.config)
+ async with httpx.AsyncClient() as http_client:
+ client = DifyKnowledgeBaseClient(
+ base_url=self.inner_api_url,
+ api_key=self.inner_api_key,
+ http_client=http_client,
+ )
+ eager_results: list[DifyKnowledgeEagerResult] = []
+ for knowledge_set in user_query_sets:
+ query = (knowledge_set.query.value or "").strip()
+ try:
+ response = await client.retrieve(
+ tenant_id=caller["tenant_id"],
+ user_id=caller["user_id"],
+ app_id=caller["app_id"],
+ user_from=caller["user_from"],
+ invoke_from=caller["invoke_from"],
+ dataset_ids=knowledge_set.dataset_ids,
+ query=query,
+ retrieval=knowledge_set.retrieval,
+ metadata_filtering=knowledge_set.metadata_filtering,
+ )
+ except DifyKnowledgeBaseClientError as exc:
+ if exc.retryable:
+ logger.warning(
+ "eager knowledge retrieval temporarily unavailable",
+ extra={
+ "tenant_id": caller["tenant_id"],
+ "app_id": caller["app_id"],
+ "invoke_from": caller["invoke_from"],
+ "knowledge_set_id": knowledge_set.id,
+ "error_code": exc.error_code,
+ "status_code": exc.status_code,
+ },
+ )
+ eager_results.append(
+ DifyKnowledgeEagerResult(
+ set_id=knowledge_set.id,
+ set_name=knowledge_set.name,
+ query=query,
+ observation=TEMPORARY_UNAVAILABLE_OBSERVATION,
+ status="temporarily_unavailable",
+ )
+ )
+ continue
+ logger.error(
+ "eager knowledge retrieval failed",
+ extra={
+ "tenant_id": caller["tenant_id"],
+ "app_id": caller["app_id"],
+ "invoke_from": caller["invoke_from"],
+ "knowledge_set_id": knowledge_set.id,
+ "error_code": exc.error_code,
+ "status_code": exc.status_code,
+ },
+ )
+ raise
+
+ eager_results.append(
+ DifyKnowledgeEagerResult(
+ set_id=knowledge_set.id,
+ set_name=knowledge_set.name,
+ query=query,
+ observation=_format_observation(response, self.config, include_heading=False),
+ status="success" if response.results else "empty",
+ )
+ )
+
+ self.runtime_state.eager_results = eager_results
+ self.runtime_state.eager_config_fingerprint = fingerprint
+
+ async def _retrieve_for_set(
+ self,
+ *,
+ client: DifyKnowledgeBaseClient,
+ caller: dict[str, str],
+ knowledge_set: DifyKnowledgeSetConfig,
+ query: str,
+ retryable_observation: bool,
+ ) -> str:
+ try:
+ response = await client.retrieve(
+ tenant_id=caller["tenant_id"],
+ user_id=caller["user_id"],
+ app_id=caller["app_id"],
+ user_from=caller["user_from"],
+ invoke_from=caller["invoke_from"],
+ dataset_ids=knowledge_set.dataset_ids,
+ query=query,
+ retrieval=knowledge_set.retrieval,
+ metadata_filtering=knowledge_set.metadata_filtering,
+ )
+ except DifyKnowledgeBaseClientError as exc:
+ if exc.retryable and retryable_observation:
+ logger.warning(
+ "knowledge base search temporarily unavailable",
+ extra={
+ "tenant_id": caller["tenant_id"],
+ "app_id": caller["app_id"],
+ "invoke_from": caller["invoke_from"],
+ "knowledge_set_id": knowledge_set.id,
+ "error_code": exc.error_code,
+ "status_code": exc.status_code,
+ },
+ )
+ return TEMPORARY_UNAVAILABLE_OBSERVATION
+ logger.error(
+ "knowledge base search failed",
+ extra={
+ "tenant_id": caller["tenant_id"],
+ "app_id": caller["app_id"],
+ "invoke_from": caller["invoke_from"],
+ "knowledge_set_id": knowledge_set.id,
+ "error_code": exc.error_code,
+ "status_code": exc.status_code,
+ },
+ )
+ raise
+ return _format_observation(response, self.config)
+
def _build_caller_context(execution_context: object) -> dict[str, str]:
"""Extract the inner-API caller identity from execution-context config.
@@ -232,7 +376,56 @@ def _build_caller_context(execution_context: object) -> dict[str, str]:
}
-def _format_observation(response: DifyKnowledgeRetrieveResponse, config: DifyKnowledgeBaseLayerConfig) -> str:
+def _tool_schema(generated_sets: list[DifyKnowledgeSetConfig]) -> dict[str, object]:
+ return {
+ "type": "object",
+ "properties": {
+ "set_name": {
+ "type": "string",
+ "enum": [knowledge_set.name for knowledge_set in generated_sets],
+ "description": "Knowledge set to search.",
+ },
+ "query": {
+ "type": "string",
+ "description": "Search query for the selected knowledge set.",
+ },
+ },
+ "required": ["set_name", "query"],
+ "additionalProperties": False,
+ }
+
+
+def _tool_description(generated_sets: list[DifyKnowledgeSetConfig]) -> str:
+ set_descriptions = []
+ for knowledge_set in generated_sets:
+ if knowledge_set.description:
+ set_descriptions.append(f"{knowledge_set.name}: {knowledge_set.description}")
+ else:
+ set_descriptions.append(knowledge_set.name)
+ return f"{_KNOWLEDGE_BASE_TOOL_DESCRIPTION} Configured sets: {', '.join(set_descriptions)}."
+
+
+def _eager_config_fingerprint(user_query_sets: list[DifyKnowledgeSetConfig]) -> str:
+ payload = [
+ {
+ "id": knowledge_set.id,
+ "query": knowledge_set.query.model_dump(mode="json"),
+ "dataset_ids": knowledge_set.dataset_ids,
+ "retrieval": knowledge_set.retrieval.model_dump(mode="json"),
+ "metadata_filtering": knowledge_set.metadata_filtering.model_dump(mode="json", by_alias=True),
+ }
+ for knowledge_set in user_query_sets
+ ]
+ serialized = json.dumps(payload, sort_keys=True, separators=(",", ":"))
+ return hashlib.sha256(serialized.encode("utf-8")).hexdigest()
+
+
+def _format_observation(
+ response: DifyKnowledgeRetrieveResponse,
+ config: DifyKnowledgeBaseLayerConfig,
+ *,
+ include_heading: bool = True,
+) -> str:
"""Render inner-API retrieval results into the model-visible tool response.
The formatting contract is intentionally simple and stable for the model:
@@ -248,7 +441,7 @@ def _format_observation(response: DifyKnowledgeRetrieveResponse, config: DifyKno
if not response.results:
return NO_RESULTS_OBSERVATION
- lines = ["Knowledge base search results:"]
+ lines = ["Knowledge base search results:"] if include_heading else []
for index, result in enumerate(response.results, start=1):
metadata = result.metadata
title = result.title or metadata.document_name or "Untitled"
@@ -280,6 +473,5 @@ __all__ = [
"DifyKnowledgeBaseDeps",
"DifyKnowledgeBaseLayer",
"NO_RESULTS_OBSERVATION",
- "QUERY_TOOL_SCHEMA",
"TEMPORARY_UNAVAILABLE_OBSERVATION",
]
diff --git a/dify-agent/src/dify_agent/layers/shell/configs.py b/dify-agent/src/dify_agent/layers/shell/configs.py
index fafab6a3bd9..f538ffa2636 100644
--- a/dify-agent/src/dify_agent/layers/shell/configs.py
+++ b/dify-agent/src/dify_agent/layers/shell/configs.py
@@ -3,7 +3,8 @@
Server-only shellctl connection settings are injected by the runtime provider
factory. Public config carries product-level Agent Soul settings that must affect
the sandbox workspace itself: CLI tool bootstrap commands, normal environment
-variables, secret environment variable names, and sandbox-provider metadata.
+variables, secret environment variable names, sandbox-provider metadata, and the
+Agent Stub drive ref used by shell-visible drive commands.
"""
import re
@@ -80,6 +81,8 @@ class DifyShellLayerConfig(LayerConfig):
model_config: ClassVar[ConfigDict] = ConfigDict(extra="forbid")
+ # Optional because shell can be used without a drive layer.
+ agent_stub_drive_ref: str | None = Field(default=None, max_length=1024)
cli_tools: list[DifyShellCliToolConfig] = Field(default_factory=list)
env: list[DifyShellEnvVarConfig] = Field(default_factory=list)
secret_refs: list[DifyShellSecretRefConfig] = Field(default_factory=list)
diff --git a/dify-agent/src/dify_agent/layers/shell/layer.py b/dify-agent/src/dify_agent/layers/shell/layer.py
index a8f46d628a6..5efb072ace9 100644
--- a/dify-agent/src/dify_agent/layers/shell/layer.py
+++ b/dify-agent/src/dify_agent/layers/shell/layer.py
@@ -51,7 +51,6 @@ from typing_extensions import Self, override
from agenton.layers import LayerDeps, PydanticAILayer, PydanticAIPrompt, PydanticAITool
from dify_agent.agent_stub.server.shell_agent_stub_env import ShellAgentStubTokenFactory, build_shell_agent_stub_env
-from dify_agent.layers.drive.layer import DifyDriveLayer
from dify_agent.layers.execution_context.layer import DifyExecutionContextLayer
from dify_agent.layers.shell.configs import DIFY_SHELL_LAYER_TYPE_ID, DifyShellLayerConfig
@@ -173,11 +172,11 @@ type ShellInterruptToolResult = ShellJobStatusObservation | ShellToolErrorObserv
class DifyShellLayerDeps(LayerDeps):
"""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.
+ The execution context supplies the token principal. The drive ref used for
+ Agent Stub CLI commands is passed through config so the drive layer can
+ depend on shell for eager materialization without a dependency cycle.
"""
- drive: DifyDriveLayer | None # pyright: ignore[reportUninitializedInstanceVariable]
execution_context: DifyExecutionContextLayer | None # pyright: ignore[reportUninitializedInstanceVariable]
@@ -624,7 +623,13 @@ class DifyShellLayer(PydanticAILayer[DifyShellLayerDeps, object, DifyShellLayerC
timeout: float,
env: dict[str, str] | None,
) -> RemoteCommandResult:
- """Run a workspace-scoped script to completion and delete its job state."""
+ """Run a workspace-scoped script to completion and delete its job state.
+
+ Shellctl's ``truncated`` flag is per output window: it means the caller
+ should continue from the returned offset. After this helper drains those
+ windows, only the final window can describe whether output is still
+ unread, usually because the safety window cap was reached.
+ """
client = self._require_client()
job_id: str | None = None
try:
@@ -632,13 +637,11 @@ class DifyShellLayer(PydanticAILayer[DifyShellLayerDeps, object, DifyShellLayerC
job_id = result.job_id
self._track_job_result(result)
output_parts = [result.output]
- truncated = result.truncated
windows = 1
while (result.truncated or not result.done) and windows < _REMOTE_COMMAND_MAX_OUTPUT_WINDOWS:
result = await client.wait(result.job_id, offset=self._tracked_offset(result.job_id), timeout=timeout)
self._track_job_result(result)
output_parts.append(result.output)
- truncated = truncated or result.truncated
windows += 1
return RemoteCommandResult(
job_id=result.job_id,
@@ -647,7 +650,7 @@ class DifyShellLayer(PydanticAILayer[DifyShellLayerDeps, object, DifyShellLayerC
exit_code=result.exit_code,
output="".join(output_parts),
offset=result.offset,
- truncated=truncated,
+ truncated=result.truncated,
output_path=result.output_path,
)
finally:
@@ -768,10 +771,9 @@ class DifyShellLayer(PydanticAILayer[DifyShellLayerDeps, object, DifyShellLayerC
"""Build per-command Agent Stub env only for user-visible ``shell.run``."""
execution_context_layer = self.deps.execution_context
execution_context = execution_context_layer.config if execution_context_layer is not None else None
- drive_layer = self.deps.drive
return build_shell_agent_stub_env(
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,
+ agent_stub_drive_ref=self.config.agent_stub_drive_ref,
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.py
index 0cfab33ad0d..610733cff98 100644
--- a/dify-agent/src/dify_agent/runtime/compositor_factory.py
+++ b/dify-agent/src/dify_agent/runtime/compositor_factory.py
@@ -38,7 +38,6 @@ from dify_agent.agent_stub.server.tokens.agent_stub import AgentStubTokenCodec
from dify_agent.layers.ask_human.layer import DifyAskHumanLayer
from dify_agent.layers.dify_plugin.llm_layer import DifyPluginLLMLayer
from dify_agent.layers.dify_plugin.tools_layer import DifyPluginToolsLayer
-from dify_agent.layers.drive import DifyDriveLayerConfig
from dify_agent.layers.drive.layer import DifyDriveLayer
from dify_agent.layers.execution_context.configs import DifyExecutionContextLayerConfig
from dify_agent.layers.execution_context.layer import DifyExecutionContextLayer
@@ -90,14 +89,7 @@ def create_default_layer_providers(
LayerProvider.from_layer_type(PydanticAIHistoryLayer),
LayerProvider.from_layer_type(DifyOutputLayer),
LayerProvider.from_layer_type(DifyAskHumanLayer),
- 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_layer_type(DifyDriveLayer),
LayerProvider.from_factory(
layer_type=DifyExecutionContextLayer,
create=lambda config: DifyExecutionContextLayer.from_config_with_settings(
diff --git a/dify-agent/src/dify_agent/server/app.py b/dify-agent/src/dify_agent/server/app.py
index cc3760da393..50f27660e77 100644
--- a/dify-agent/src/dify_agent/server/app.py
+++ b/dify-agent/src/dify_agent/server/app.py
@@ -10,7 +10,9 @@ stay state-only: they borrow the lifespan-owned clients through the runner and
receive shell-layer server settings through provider construction rather than
reading environment variables themselves. The standard server always mounts the
HTTP Agent Stub router and additionally starts the optional grpclib Agent Stub
-server when ``DIFY_AGENT_STUB_API_BASE_URL`` uses ``grpc://``.
+server when ``DIFY_AGENT_STUB_API_BASE_URL`` uses ``grpc://``. Process-level
+Logfire instrumentation is configured at app construction time and only exports
+remotely when Logfire's default environment configuration provides a token.
"""
from collections.abc import AsyncGenerator
@@ -25,6 +27,7 @@ from dify_agent.agent_stub.server.grpc_runtime import start_agent_stub_grpc_serv
from dify_agent.agent_stub.server.router import create_agent_stub_router
from dify_agent.runtime.compositor_factory import create_default_layer_providers
from dify_agent.runtime.run_scheduler import RunScheduler
+from dify_agent.server.observability import configure_server_observability
from dify_agent.server.routes.runs import create_runs_router
from dify_agent.server.routes.sandbox_files import create_sandbox_files_router
from dify_agent.server.sandbox_files import SandboxFileService
@@ -94,6 +97,7 @@ def create_app(settings: ServerSettings | None = None) -> FastAPI:
await redis.aclose()
app = FastAPI(title="Dify Agent Run Server", version="0.1.0", lifespan=lifespan)
+ configure_server_observability(app)
def get_store() -> RedisRunStore:
return state["store"] # pyright: ignore[reportReturnType]
diff --git a/dify-agent/src/dify_agent/server/observability.py b/dify-agent/src/dify_agent/server/observability.py
new file mode 100644
index 00000000000..7893dfe4769
--- /dev/null
+++ b/dify-agent/src/dify_agent/server/observability.py
@@ -0,0 +1,47 @@
+"""Process-level Logfire setup for the Dify Agent run server.
+
+The run server performs observability setup at the FastAPI app boundary rather
+than inside agent runtime code. Global instrumentations cover shared HTTPX,
+Redis, and Pydantic AI clients once per process; the FastAPI instrumentation is
+applied per app instance because tests and embedded callers can build multiple
+apps in one Python process. Remote export remains token-gated through Logfire's
+``if-token-present`` mode and Logfire's default environment-variable handling,
+so development without a token only writes Logfire's console output locally.
+"""
+
+from __future__ import annotations
+
+import logfire
+from fastapi import FastAPI
+
+_global_instrumentation_ready = False
+
+
+def configure_server_observability(app: FastAPI) -> None:
+ """Configure Logfire and instrument the server's framework/client boundaries.
+
+ Instrumentation calls intentionally use Logfire's defaults instead of
+ re-exposing capture options through Dify settings. The only Dify-owned
+ policy here is that remote export stays token-gated while local console
+ output still works without a token.
+ """
+ global _global_instrumentation_ready
+
+ logfire.configure(
+ send_to_logfire="if-token-present",
+ inspect_arguments=False,
+ )
+
+ if not _global_instrumentation_ready:
+ logfire.instrument_httpx()
+ logfire.instrument_redis()
+ logfire.instrument_pydantic_ai()
+ _global_instrumentation_ready = True
+
+ if getattr(app.state, "dify_agent_logfire_instrumented", False):
+ return
+ logfire.instrument_fastapi(app)
+ app.state.dify_agent_logfire_instrumented = True
+
+
+__all__ = ["configure_server_observability"]
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.py
index 6e45e14a034..61ffcec9e3a 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
@@ -8,7 +8,9 @@ from zipfile import ZipFile, ZipInfo
import pytest
from dify_agent.agent_stub.cli._drive import (
- list_drive_from_environment,
+ DrivePullResult,
+ format_drive_manifest,
+ list_drive_manifest_from_environment,
pull_drive_from_environment,
push_drive_from_environment,
)
@@ -22,7 +24,7 @@ from dify_agent.agent_stub.protocol.agent_stub import (
)
-def test_list_drive_from_environment_returns_manifest_json_model(monkeypatch: pytest.MonkeyPatch) -> None:
+def test_list_drive_manifest_from_environment_returns_manifest_model(monkeypatch: pytest.MonkeyPatch) -> 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: dict[str, object] = {}
@@ -47,7 +49,7 @@ def test_list_drive_from_environment_returns_manifest_json_model(monkeypatch: py
fake_manifest,
)
- result = list_drive_from_environment(prefix="skills/", json_output=True)
+ result = list_drive_manifest_from_environment(prefix="skills/")
assert isinstance(result, AgentStubDriveManifestResponse)
assert result.items[0].key == "skills/example/SKILL.md"
@@ -55,7 +57,7 @@ def test_list_drive_from_environment_returns_manifest_json_model(monkeypatch: py
assert captured["include_download_url"] is False
-def test_list_drive_from_environment_returns_human_readable_listing(monkeypatch: pytest.MonkeyPatch) -> None:
+def test_format_drive_manifest_returns_human_readable_listing(monkeypatch: pytest.MonkeyPatch) -> 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: dict[str, object] = {}
@@ -88,7 +90,7 @@ def test_list_drive_from_environment_returns_human_readable_listing(monkeypatch:
fake_manifest,
)
- result = list_drive_from_environment(prefix="skills/", json_output=False)
+ result = format_drive_manifest(list_drive_manifest_from_environment(prefix="skills/"))
assert result == ("12\ttext/markdown\t-\tskills/example/SKILL.md\n-\t-\tsha256:abc\tskills/example/helper.py")
assert captured["prefix"] == "skills/"
@@ -128,10 +130,10 @@ def test_pull_drive_from_environment_writes_files_under_drive_base(
lambda **_kwargs: b"hello world",
)
- results = pull_drive_from_environment(targets=["skills/"], drive_base=str(tmp_path))
+ result = pull_drive_from_environment(targets=["skills/"], local_base=str(tmp_path))
- assert results == [tmp_path / "skills" / "example" / "SKILL.md"]
- assert results[0].read_bytes() == b"hello world"
+ assert result.model_dump() == {"items": [{"key": "skills/", "local_path": str(tmp_path / "skills")}]}
+ assert (tmp_path / "skills" / "example" / "SKILL.md").read_bytes() == b"hello world"
assert captured["prefix"] == "skills/"
assert captured["include_download_url"] is True
@@ -169,11 +171,11 @@ def test_pull_drive_from_environment_auto_extracts_skill_archive(
lambda **_kwargs: archive_bytes,
)
- results = pull_drive_from_environment(targets=["skills/foo"], drive_base=str(tmp_path))
+ result = pull_drive_from_environment(targets=["skills/foo"], local_base=str(tmp_path))
archive_path = tmp_path / "skills" / "foo" / ".DIFY-SKILL-FULL.zip"
- assert results == [archive_path]
- assert archive_path.read_bytes() == archive_bytes
+ assert result.model_dump() == {"items": [{"key": "skills/foo", "local_path": str(tmp_path / "skills" / "foo")}]}
+ assert not archive_path.exists()
assert (tmp_path / "skills" / "foo" / "SKILL.md").read_text(encoding="utf-8") == "# Example\n"
assert (tmp_path / "skills" / "foo" / "nested" / "helper.py").read_text(encoding="utf-8") == "print('x')\n"
@@ -202,7 +204,7 @@ def test_pull_drive_from_environment_rejects_traversal_keys(
)
with pytest.raises(AgentStubValidationError, match="outside the drive base"):
- _ = pull_drive_from_environment(targets=[""], drive_base=str(tmp_path))
+ _ = pull_drive_from_environment(targets=[""], local_base=str(tmp_path))
def test_pull_drive_from_environment_rejects_skill_archive_path_traversal(
@@ -239,7 +241,7 @@ def test_pull_drive_from_environment_rejects_skill_archive_path_traversal(
)
with pytest.raises(AgentStubValidationError, match="path traversal"):
- _ = pull_drive_from_environment(targets=["skills/foo"], drive_base=str(tmp_path))
+ _ = pull_drive_from_environment(targets=["skills/foo"], local_base=str(tmp_path))
assert not (tmp_path / "skills" / "foo" / "SKILL.md").exists()
@@ -276,7 +278,7 @@ def test_pull_drive_from_environment_rejects_skill_archive_absolute_entry(
)
with pytest.raises(AgentStubValidationError, match="absolute path"):
- _ = pull_drive_from_environment(targets=["skills/foo"], drive_base=str(tmp_path))
+ _ = pull_drive_from_environment(targets=["skills/foo"], local_base=str(tmp_path))
def test_pull_drive_from_environment_rejects_skill_archive_symlink_entry(
@@ -314,7 +316,7 @@ def test_pull_drive_from_environment_rejects_skill_archive_symlink_entry(
)
with pytest.raises(AgentStubValidationError, match="symlink entry"):
- _ = pull_drive_from_environment(targets=["skills/foo"], drive_base=str(tmp_path))
+ _ = pull_drive_from_environment(targets=["skills/foo"], local_base=str(tmp_path))
def test_pull_drive_from_environment_rejects_invalid_skill_archive(
@@ -347,7 +349,7 @@ def test_pull_drive_from_environment_rejects_invalid_skill_archive(
)
with pytest.raises(AgentStubTransferError, match="downloaded skill archive is invalid"):
- _ = pull_drive_from_environment(targets=["skills/foo"], drive_base=str(tmp_path))
+ _ = pull_drive_from_environment(targets=["skills/foo"], local_base=str(tmp_path))
def test_pull_drive_from_environment_rejects_missing_download_url(
@@ -373,7 +375,7 @@ def test_pull_drive_from_environment_rejects_missing_download_url(
)
with pytest.raises(AgentStubValidationError, match="missing download_url"):
- _ = pull_drive_from_environment(targets=["skills/"], drive_base=str(tmp_path))
+ _ = pull_drive_from_environment(targets=["skills/"], local_base=str(tmp_path))
def test_pull_drive_from_environment_rejects_size_mismatch(
@@ -404,7 +406,7 @@ def test_pull_drive_from_environment_rejects_size_mismatch(
)
with pytest.raises(AgentStubTransferError, match="size mismatch"):
- _ = pull_drive_from_environment(targets=["skills/"], drive_base=str(tmp_path))
+ _ = pull_drive_from_environment(targets=["skills/"], local_base=str(tmp_path))
def test_pull_drive_from_environment_requests_multiple_targets_and_deduplicates_overlaps(
@@ -463,11 +465,16 @@ def test_pull_drive_from_environment_requests_multiple_targets_and_deduplicates_
),
)
- results = pull_drive_from_environment(targets=["skills/foo", "files/a.txt"], drive_base=str(tmp_path))
+ result = pull_drive_from_environment(targets=["skills/foo", "files/a.txt"], local_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"]
+ assert set(captured_prefixes) == {"skills/foo", "files/a.txt"}
+ assert len(captured_prefixes) == 2
+ assert {(item.key, item.local_path) for item in result.items} == {
+ ("files/a.txt", str(tmp_path / "files" / "a.txt")),
+ ("skills/foo", str(tmp_path / "skills" / "foo")),
+ }
+ assert set(downloaded_urls) == {"https://files.example.com/a-txt", "https://files.example.com/skill-md"}
+ assert len(downloaded_urls) == 2
def test_pull_drive_from_environment_without_targets_preserves_whole_drive_pull(
@@ -482,10 +489,44 @@ def test_pull_drive_from_environment_without_targets_preserves_whole_drive_pull(
lambda **kwargs: captured_prefixes.append(kwargs["prefix"]) or AgentStubDriveManifestResponse(items=[]),
)
- assert pull_drive_from_environment(drive_base=str(tmp_path)) == []
+ assert pull_drive_from_environment(local_base=str(tmp_path)).model_dump() == {"items": []}
assert captured_prefixes == [""]
+def test_pull_drive_from_environment_returns_json_result(
+ 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")
+ monkeypatch.setattr(
+ "dify_agent.agent_stub.cli._drive.request_agent_stub_drive_manifest_sync",
+ lambda **_kwargs: AgentStubDriveManifestResponse(
+ items=[
+ AgentStubDriveItem(
+ key="files/a.txt",
+ size=1,
+ hash=None,
+ mime_type="text/plain",
+ file_kind="tool_file",
+ file_id="tool-file-1",
+ download_url="https://files.example.com/a-txt",
+ )
+ ]
+ ),
+ )
+ monkeypatch.setattr(
+ "dify_agent.agent_stub.cli._drive.download_file_bytes_from_signed_url_sync",
+ lambda **_kwargs: b"a",
+ )
+
+ result = pull_drive_from_environment(targets=["files/a.txt"], local_base=str(tmp_path))
+
+ assert isinstance(result, DrivePullResult)
+ assert result.model_dump() == {"items": [{"key": "files/a.txt", "local_path": str(tmp_path / "files" / "a.txt")}]}
+ assert (tmp_path / "files" / "a.txt").read_bytes() == b"a"
+
+
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")
@@ -518,21 +559,46 @@ def test_push_drive_from_environment_commits_single_file(monkeypatch: pytest.Mon
monkeypatch.setattr("dify_agent.agent_stub.cli._drive.request_agent_stub_drive_commit_sync", fake_commit)
- response = push_drive_from_environment(local_path=str(source), drive_path="files/report.pdf", recursive=False)
+ response = push_drive_from_environment(local_path=str(source), drive_path="files/report.pdf", kind=None)
assert response.items[0].key == "files/report.pdf"
request = captured["request"]
assert isinstance(request, AgentStubDriveCommitRequest)
- assert request.items[0].model_dump(mode="json") == {
- "key": "files/report.pdf",
- "file_ref": {"kind": "tool_file", "id": "tool-file-1"},
- "value_owned_by_drive": True,
- "is_skill": False,
- "skill_metadata": None,
- }
+ assert request.items[0].key == "files/report.pdf"
+ assert request.items[0].file_ref is not None
+ assert request.items[0].file_ref.kind == "tool_file"
+ assert request.items[0].file_ref.id == "tool-file-1"
+
+
+def test_push_drive_from_environment_rejects_file_with_kind_skill(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ source = tmp_path / "report.pdf"
+ source.write_bytes(b"report")
+ 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="--kind skill requires a directory containing SKILL.md"):
+ _ = push_drive_from_environment(local_path=str(source), drive_path="files/report.pdf", kind="skill")
+
+
+def test_push_drive_from_environment_rejects_symlinked_file_root(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ source = tmp_path / "report.pdf"
+ source.write_bytes(b"report")
+ symlink_path = tmp_path / "report-link.pdf"
+ symlink_path.symlink_to(source)
+ 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"):
+ _ = push_drive_from_environment(local_path=str(symlink_path), drive_path="files/report.pdf", kind=None)
-def test_push_drive_from_environment_requires_skill_md_for_non_recursive_directory(
+def test_push_drive_from_environment_requires_kind_for_directory(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
@@ -541,11 +607,24 @@ def test_push_drive_from_environment_requires_skill_md_for_non_recursive_directo
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"):
- _ = push_drive_from_environment(local_path=str(skill_dir), drive_path="skills/example", recursive=False)
+ with pytest.raises(AgentStubValidationError, match="requires --kind skill or --kind dir"):
+ _ = push_drive_from_environment(local_path=str(skill_dir), drive_path="skills/example", kind=None)
-def test_push_drive_from_environment_standardizes_non_recursive_skill_directory(
+def test_push_drive_from_environment_kind_skill_requires_skill_md(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ skill_dir = tmp_path / "skill"
+ skill_dir.mkdir()
+ 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="requires a directory containing SKILL.md"):
+ _ = push_drive_from_environment(local_path=str(skill_dir), drive_path="skills/example", kind="skill")
+
+
+def test_push_drive_from_environment_kind_skill_standardizes_skill_directory(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
@@ -584,7 +663,7 @@ def test_push_drive_from_environment_standardizes_non_recursive_skill_directory(
),
)
- response = push_drive_from_environment(local_path=str(skill_dir), drive_path="skills/example", recursive=False)
+ response = push_drive_from_environment(local_path=str(skill_dir), drive_path="skills/example", kind="skill")
assert set(uploaded_paths) == {"SKILL.md", ".DIFY-SKILL-FULL.zip"}
assert {item.key for item in response.items} == {
@@ -593,7 +672,7 @@ def test_push_drive_from_environment_standardizes_non_recursive_skill_directory(
}
-def test_push_drive_from_environment_non_recursive_archive_excludes_transient_entries(
+def test_push_drive_from_environment_kind_skill_archive_excludes_transient_entries(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
@@ -641,7 +720,7 @@ def test_push_drive_from_environment_non_recursive_archive_excludes_transient_en
),
)
- _ = push_drive_from_environment(local_path=str(skill_dir), drive_path="skills/example", recursive=False)
+ _ = push_drive_from_environment(local_path=str(skill_dir), drive_path="skills/example", kind="skill")
assert {"SKILL.md", "helper.py"}.issubset(archive_entries)
assert ".git/config" not in archive_entries
@@ -649,7 +728,7 @@ def test_push_drive_from_environment_non_recursive_archive_excludes_transient_en
assert ".DIFY-SKILL-FULL.zip" not in archive_entries
-def test_push_drive_from_environment_non_recursive_rejects_symlinked_archive_entries(
+def test_push_drive_from_environment_kind_skill_rejects_symlinked_archive_entries(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
@@ -663,10 +742,52 @@ def test_push_drive_from_environment_non_recursive_rejects_symlinked_archive_ent
monkeypatch.setenv("DIFY_AGENT_STUB_AUTH_JWE", "test-jwe")
with pytest.raises(AgentStubValidationError, match="symlink"):
- _ = push_drive_from_environment(local_path=str(skill_dir), drive_path="skills/example", recursive=False)
+ _ = push_drive_from_environment(local_path=str(skill_dir), drive_path="skills/example", kind="skill")
+
+
+def test_push_drive_from_environment_kind_dir_requires_directory(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ source = tmp_path / "report.pdf"
+ source.write_bytes(b"report")
+ 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="--kind dir requires a directory"):
+ _ = push_drive_from_environment(local_path=str(source), drive_path="files/report.pdf", kind="dir")
+
+
+def test_push_drive_from_environment_kind_file_requires_file(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ skill_dir = tmp_path / "skill"
+ skill_dir.mkdir()
+ 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="--kind file requires a file"):
+ _ = push_drive_from_environment(local_path=str(skill_dir), drive_path="skills/example", kind="file")
+
+
+def test_push_drive_from_environment_rejects_symlinked_directory_root(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ source_dir = tmp_path / "skill"
+ source_dir.mkdir()
+ (source_dir / "SKILL.md").write_text("# Example\n", encoding="utf-8")
+ symlink_path = tmp_path / "skill-link"
+ symlink_path.symlink_to(source_dir, target_is_directory=True)
+ 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"):
+ _ = push_drive_from_environment(local_path=str(symlink_path), drive_path="skills/example", kind="skill")
-def test_push_drive_from_environment_rejects_symlinked_recursive_files(
+def test_push_drive_from_environment_kind_dir_rejects_symlinked_files(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
@@ -679,10 +800,10 @@ def test_push_drive_from_environment_rejects_symlinked_recursive_files(
monkeypatch.setenv("DIFY_AGENT_STUB_AUTH_JWE", "test-jwe")
with pytest.raises(AgentStubValidationError, match="symlink"):
- _ = push_drive_from_environment(local_path=str(root), drive_path="skills/example", recursive=True)
+ _ = push_drive_from_environment(local_path=str(root), drive_path="skills/example", kind="dir")
-def test_push_drive_from_environment_recursive_keeps_user_files_that_skill_packaging_skips(
+def test_push_drive_from_environment_kind_dir_keeps_user_files_that_skill_packaging_skips(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
@@ -723,7 +844,7 @@ def test_push_drive_from_environment_recursive_keeps_user_files_that_skill_packa
),
)
- response = push_drive_from_environment(local_path=str(root), drive_path="skills/example", recursive=True)
+ response = push_drive_from_environment(local_path=str(root), drive_path="skills/example", kind="dir")
assert set(uploaded_paths) == {".DIFY-SKILL-FULL.zip", "node_modules/module.js"}
assert {item.key for item in response.items} == {
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.py
index f2de6e8edc5..c2f2d44afb4 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
@@ -11,7 +11,7 @@ from dify_agent.agent_stub.cli._files import (
upload_file_from_environment,
upload_tool_file_resource_from_environment,
)
-from dify_agent.agent_stub.client._errors import AgentStubTransferError
+from dify_agent.agent_stub.client._errors import AgentStubTransferError, AgentStubValidationError
def _reference(record_id: str) -> str:
@@ -120,7 +120,7 @@ def test_download_file_from_environment_saves_bytes_and_renames_on_collision(
result = download_file_from_environment(
transfer_method="tool_file",
reference_or_url=_reference("tool-file-1"),
- directory=str(target_dir),
+ local_dir=str(target_dir),
)
assert result.path.name == "report (1).pdf"
@@ -157,7 +157,7 @@ def test_download_file_from_environment_sanitizes_server_filename(
result = download_file_from_environment(
transfer_method="tool_file",
reference_or_url=_reference("tool-file-1"),
- directory=str(target_dir),
+ local_dir=str(target_dir),
)
assert result.path.parent == target_dir
@@ -187,6 +187,62 @@ def test_upload_file_from_environment_rejects_non_canonical_reference(
_ = upload_file_from_environment(path=str(source))
+def test_download_file_from_environment_supports_mapping_json(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ target_dir = tmp_path / "inputs"
+ 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] = {}
+
+ def fake_request_download(**kwargs):
+ captured["file"] = kwargs["file"]
+ return type(
+ "Response",
+ (),
+ {
+ "filename": "report.pdf",
+ "mime_type": "application/pdf",
+ "size": 12,
+ "download_url": "https://files.example.com/download",
+ },
+ )()
+
+ monkeypatch.setattr("dify_agent.agent_stub.cli._files.request_agent_stub_file_download_sync", fake_request_download)
+ monkeypatch.setattr(
+ "dify_agent.agent_stub.cli._files.download_file_bytes_from_signed_url_sync",
+ lambda **_kwargs: b"downloaded",
+ )
+
+ result = download_file_from_environment(
+ mapping=json.dumps({"transfer_method": "tool_file", "reference": _reference("tool-file-1")}),
+ local_dir=str(target_dir),
+ )
+
+ assert captured["file"].model_dump() == {
+ "transfer_method": "tool_file",
+ "reference": _reference("tool-file-1"),
+ "url": None,
+ }
+ assert result.path == target_dir / "report.pdf"
+ assert result.path.read_bytes() == b"downloaded"
+
+
+def test_download_file_from_environment_requires_mapping_or_positional_pair() -> None:
+ with pytest.raises(AgentStubValidationError, match="requires either --mapping or TRANSFER_METHOD REFERENCE_OR_URL"):
+ _ = download_file_from_environment()
+
+
+def test_download_file_from_environment_rejects_mapping_mixed_with_positionals() -> None:
+ with pytest.raises(AgentStubValidationError, match="cannot be combined"):
+ _ = download_file_from_environment(
+ transfer_method="tool_file",
+ reference_or_url=_reference("tool-file-1"),
+ mapping=json.dumps({"transfer_method": "tool_file", "reference": _reference("tool-file-1")}),
+ )
+
+
def test_upload_tool_file_resource_from_environment_rejects_missing_id(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
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.py
index d66b801778c..8bdb8b2106d 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
@@ -6,6 +6,7 @@ from pathlib import Path
import pytest
+from dify_agent.agent_stub.cli._drive import DrivePullResult
from dify_agent.agent_stub.cli.main import main
from dify_agent.agent_stub.protocol.agent_stub import (
AgentStubDriveCommitResponse,
@@ -194,20 +195,81 @@ def test_cli_file_download_prints_saved_path(
)
with pytest.raises(SystemExit) as exc_info:
- main(["file", "download", "tool_file", _reference("tool-file-1"), "/tmp"])
+ main(["file", "download", "tool_file", _reference("tool-file-1"), "--to", "/tmp"])
captured = capsys.readouterr()
assert exc_info.value.code == 0
assert captured.out.strip() == "/tmp/report.pdf"
+def test_cli_file_download_supports_mapping_json(
+ monkeypatch: pytest.MonkeyPatch,
+ capsys: pytest.CaptureFixture[str],
+) -> None:
+ captured_kwargs: dict[str, object] = {}
+
+ def fake_download_file_from_environment(**kwargs):
+ captured_kwargs.update(kwargs)
+ return type("Response", (), {"path": Path("/tmp/inputs/report.pdf")})()
+
+ monkeypatch.setattr(
+ "dify_agent.agent_stub.cli.main.download_file_from_environment", fake_download_file_from_environment
+ )
+
+ with pytest.raises(SystemExit) as exc_info:
+ main(
+ [
+ "file",
+ "download",
+ "--mapping",
+ json.dumps({"transfer_method": "tool_file", "reference": _reference("tool-file-1")}),
+ "--to",
+ "/tmp/inputs",
+ ]
+ )
+
+ captured = capsys.readouterr()
+ assert exc_info.value.code == 0
+ assert captured_kwargs == {
+ "transfer_method": None,
+ "reference_or_url": None,
+ "mapping": json.dumps({"transfer_method": "tool_file", "reference": _reference("tool-file-1")}),
+ "local_dir": "/tmp/inputs",
+ }
+ assert captured.out.strip() == "/tmp/inputs/report.pdf"
+
+
+def test_cli_file_download_rejects_legacy_positional_directory(
+ monkeypatch: pytest.MonkeyPatch,
+ capsys: pytest.CaptureFixture[str],
+) -> None:
+ called = False
+
+ def fake_download_file_from_environment(**_kwargs):
+ nonlocal called
+ called = True
+ return type("Response", (), {"path": Path("/tmp/report.pdf")})()
+
+ monkeypatch.setattr(
+ "dify_agent.agent_stub.cli.main.download_file_from_environment", fake_download_file_from_environment
+ )
+
+ with pytest.raises(SystemExit) as exc_info:
+ main(["file", "download", "tool_file", _reference("tool-file-1"), "/tmp"])
+
+ captured = capsys.readouterr()
+ assert exc_info.value.code == 2
+ assert called is False
+ assert "/tmp" in captured.err
+
+
def test_cli_drive_list_prints_manifest_json(
monkeypatch: pytest.MonkeyPatch,
capsys: pytest.CaptureFixture[str],
) -> None:
monkeypatch.setattr(
- "dify_agent.agent_stub.cli.main.list_drive_from_environment",
- lambda *, prefix, json_output: AgentStubDriveManifestResponse(
+ "dify_agent.agent_stub.cli.main.list_drive_manifest_from_environment",
+ lambda *, prefix: AgentStubDriveManifestResponse(
items=[
AgentStubDriveItem(
key=prefix + "example/SKILL.md",
@@ -234,8 +296,19 @@ def test_cli_drive_list_prints_human_readable_listing(
capsys: pytest.CaptureFixture[str],
) -> None:
monkeypatch.setattr(
- "dify_agent.agent_stub.cli.main.list_drive_from_environment",
- lambda *, prefix, json_output: f"12\ttext/markdown\t-\t{prefix}example/SKILL.md",
+ "dify_agent.agent_stub.cli.main.list_drive_manifest_from_environment",
+ lambda *, prefix: AgentStubDriveManifestResponse(
+ items=[
+ AgentStubDriveItem(
+ key=f"{prefix}example/SKILL.md",
+ size=12,
+ hash=None,
+ mime_type="text/markdown",
+ file_kind="tool_file",
+ file_id="tool-file-1",
+ )
+ ]
+ ),
)
with pytest.raises(SystemExit) as exc_info:
@@ -252,14 +325,20 @@ def test_cli_drive_pull_prints_downloaded_paths(
) -> None:
monkeypatch.setattr(
"dify_agent.agent_stub.cli.main.pull_drive_from_environment",
- lambda *, targets, drive_base: [
- Path(drive_base) / targets[0] / "SKILL.md",
- Path(drive_base) / targets[0] / "helper.py",
- ],
+ lambda *, targets, local_base: DrivePullResult(
+ items=[
+ DrivePullResult.Item(
+ key=f"{targets[0]}/SKILL.md", local_path=str(Path(local_base) / targets[0] / "SKILL.md")
+ ),
+ DrivePullResult.Item(
+ key=f"{targets[0]}/helper.py", local_path=str(Path(local_base) / targets[0] / "helper.py")
+ ),
+ ]
+ ),
)
with pytest.raises(SystemExit) as exc_info:
- main(["drive", "pull", "skills/example", "--drive-base", "/tmp/drive"])
+ main(["drive", "pull", "skills/example", "--to", "/tmp/drive"])
captured = capsys.readouterr()
assert exc_info.value.code == 0
@@ -269,16 +348,49 @@ def test_cli_drive_pull_prints_downloaded_paths(
]
+def test_cli_drive_pull_prints_json_result(
+ monkeypatch: pytest.MonkeyPatch,
+ capsys: pytest.CaptureFixture[str],
+) -> None:
+ monkeypatch.setattr(
+ "dify_agent.agent_stub.cli.main.pull_drive_from_environment",
+ lambda *, targets, local_base: DrivePullResult(
+ items=[
+ DrivePullResult.Item(key="files/a.txt", local_path=f"{local_base}/files/a.txt"),
+ DrivePullResult.Item(key="skills/foo/SKILL.md", local_path=f"{local_base}/skills/foo/SKILL.md"),
+ ]
+ ),
+ )
+
+ with pytest.raises(SystemExit) as exc_info:
+ main(["drive", "pull", "files/a.txt", "--to", "/tmp/drive", "--json"])
+
+ captured = capsys.readouterr()
+ assert exc_info.value.code == 0
+ assert json.loads(captured.out) == {
+ "items": [
+ {"key": "files/a.txt", "local_path": "/tmp/drive/files/a.txt"},
+ {"key": "skills/foo/SKILL.md", "local_path": "/tmp/drive/skills/foo/SKILL.md"},
+ ]
+ }
+
+
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):
+ def fake_pull_drive_from_environment(*, targets, local_base):
captured_kwargs["targets"] = targets
- captured_kwargs["drive_base"] = drive_base
- return [Path(drive_base) / "skills" / "foo" / "SKILL.md"]
+ captured_kwargs["local_base"] = local_base
+ return DrivePullResult(
+ items=[
+ DrivePullResult.Item(
+ key="skills/foo/SKILL.md", local_path=str(Path(local_base) / "skills" / "foo" / "SKILL.md")
+ )
+ ]
+ )
monkeypatch.setattr(
"dify_agent.agent_stub.cli.main.pull_drive_from_environment",
@@ -286,11 +398,11 @@ def test_cli_drive_pull_forwards_multiple_targets(
)
with pytest.raises(SystemExit) as exc_info:
- main(["drive", "pull", "skills/foo", "files/a.txt", "--drive-base", "/tmp/drive"])
+ main(["drive", "pull", "skills/foo", "files/a.txt", "--to", "/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_kwargs == {"targets": ["skills/foo", "files/a.txt"], "local_base": "/tmp/drive"}
assert captured.out.strip() == "/tmp/drive/skills/foo/SKILL.md"
@@ -301,10 +413,16 @@ def test_cli_drive_pull_uses_environment_drive_base_default(
monkeypatch.setenv("DIFY_AGENT_STUB_DRIVE_BASE", "/env/drive")
captured_kwargs: dict[str, object] = {}
- def fake_pull_drive_from_environment(*, targets, drive_base):
+ def fake_pull_drive_from_environment(*, targets, local_base):
captured_kwargs["targets"] = targets
- captured_kwargs["drive_base"] = drive_base
- return [Path(drive_base) / "skills" / "foo" / "SKILL.md"]
+ captured_kwargs["local_base"] = local_base
+ return DrivePullResult(
+ items=[
+ DrivePullResult.Item(
+ key="skills/foo/SKILL.md", local_path=str(Path(local_base) / "skills" / "foo" / "SKILL.md")
+ )
+ ]
+ )
monkeypatch.setattr(
"dify_agent.agent_stub.cli.main.pull_drive_from_environment",
@@ -316,7 +434,7 @@ def test_cli_drive_pull_uses_environment_drive_base_default(
captured = capsys.readouterr()
assert exc_info.value.code == 0
- assert captured_kwargs == {"targets": ["skills/foo"], "drive_base": "/env/drive"}
+ assert captured_kwargs == {"targets": ["skills/foo"], "local_base": "/env/drive"}
assert captured.out.strip() == "/env/drive/skills/foo/SKILL.md"
@@ -327,10 +445,16 @@ def test_cli_drive_pull_keeps_historical_drive_base_when_env_is_missing(
monkeypatch.delenv("DIFY_AGENT_STUB_DRIVE_BASE", raising=False)
captured_kwargs: dict[str, object] = {}
- def fake_pull_drive_from_environment(*, targets, drive_base):
+ def fake_pull_drive_from_environment(*, targets, local_base):
captured_kwargs["targets"] = targets
- captured_kwargs["drive_base"] = drive_base
- return [Path(drive_base) / "skills" / "foo" / "SKILL.md"]
+ captured_kwargs["local_base"] = local_base
+ return DrivePullResult(
+ items=[
+ DrivePullResult.Item(
+ key="skills/foo/SKILL.md", local_path=str(Path(local_base) / "skills" / "foo" / "SKILL.md")
+ )
+ ]
+ )
monkeypatch.setattr(
"dify_agent.agent_stub.cli.main.pull_drive_from_environment",
@@ -342,17 +466,44 @@ def test_cli_drive_pull_keeps_historical_drive_base_when_env_is_missing(
captured = capsys.readouterr()
assert exc_info.value.code == 0
- assert captured_kwargs == {"targets": ["skills/foo"], "drive_base": "/mnt/drive"}
+ assert captured_kwargs == {"targets": ["skills/foo"], "local_base": "/mnt/drive"}
assert captured.out.strip() == "/mnt/drive/skills/foo/SKILL.md"
+def test_cli_drive_pull_without_targets_pulls_whole_visible_drive(
+ monkeypatch: pytest.MonkeyPatch,
+ capsys: pytest.CaptureFixture[str],
+) -> None:
+ captured_kwargs: dict[str, object] = {}
+
+ def fake_pull_drive_from_environment(*, targets, local_base):
+ captured_kwargs["targets"] = targets
+ captured_kwargs["local_base"] = local_base
+ return DrivePullResult(
+ items=[DrivePullResult.Item(key="files/a.txt", local_path=str(Path(local_base) / "files" / "a.txt"))]
+ )
+
+ 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", "--to", "/tmp/drive"])
+
+ captured = capsys.readouterr()
+ assert exc_info.value.code == 0
+ assert captured_kwargs == {"targets": None, "local_base": "/tmp/drive"}
+ assert captured.out.strip() == "/tmp/drive/files/a.txt"
+
+
def test_cli_drive_push_prints_commit_json(
monkeypatch: pytest.MonkeyPatch,
capsys: pytest.CaptureFixture[str],
) -> None:
monkeypatch.setattr(
"dify_agent.agent_stub.cli.main.push_drive_from_environment",
- lambda *, local_path, drive_path, recursive: AgentStubDriveCommitResponse(
+ lambda *, local_path, drive_path, kind: AgentStubDriveCommitResponse(
items=[
AgentStubDriveItem(
key=drive_path,
@@ -361,7 +512,7 @@ def test_cli_drive_push_prints_commit_json(
mime_type="text/markdown",
file_kind="tool_file",
file_id=Path(local_path).name,
- value_owned_by_drive=recursive is False,
+ value_owned_by_drive=kind != "dir",
)
]
),
@@ -373,3 +524,87 @@ def test_cli_drive_push_prints_commit_json(
captured = capsys.readouterr()
assert exc_info.value.code == 0
assert json.loads(captured.out)["items"][0]["key"] == "skills/example/SKILL.md"
+
+
+def test_cli_drive_push_forwards_kind(
+ monkeypatch: pytest.MonkeyPatch,
+ capsys: pytest.CaptureFixture[str],
+) -> None:
+ captured_kwargs: dict[str, object] = {}
+
+ def fake_push_drive_from_environment(*, local_path, drive_path, kind):
+ captured_kwargs["local_path"] = local_path
+ captured_kwargs["drive_path"] = drive_path
+ captured_kwargs["kind"] = kind
+ return AgentStubDriveCommitResponse(items=[])
+
+ monkeypatch.setattr(
+ "dify_agent.agent_stub.cli.main.push_drive_from_environment",
+ fake_push_drive_from_environment,
+ )
+
+ with pytest.raises(SystemExit) as exc_info:
+ main(["drive", "push", "/tmp/skill", "skills/example", "--kind", "skill"])
+
+ capsys.readouterr()
+ assert exc_info.value.code == 0
+ assert captured_kwargs == {
+ "local_path": "/tmp/skill",
+ "drive_path": "skills/example",
+ "kind": "skill",
+ }
+
+
+def test_cli_drive_push_accepts_json_flag(
+ monkeypatch: pytest.MonkeyPatch,
+ capsys: pytest.CaptureFixture[str],
+) -> None:
+ captured_kwargs: dict[str, object] = {}
+
+ def fake_push_drive_from_environment(*, local_path, drive_path, kind):
+ captured_kwargs["local_path"] = local_path
+ captured_kwargs["drive_path"] = drive_path
+ captured_kwargs["kind"] = kind
+ return AgentStubDriveCommitResponse(items=[])
+
+ monkeypatch.setattr(
+ "dify_agent.agent_stub.cli.main.push_drive_from_environment",
+ fake_push_drive_from_environment,
+ )
+
+ with pytest.raises(SystemExit) as exc_info:
+ main(["drive", "push", "/tmp/report.md", "files/report.md", "--json"])
+
+ captured = capsys.readouterr()
+ assert exc_info.value.code == 0
+ assert json.loads(captured.out) == {"items": []}
+ assert captured_kwargs == {
+ "local_path": "/tmp/report.md",
+ "drive_path": "files/report.md",
+ "kind": None,
+ }
+
+
+def test_cli_drive_push_rejects_recursive_option(
+ monkeypatch: pytest.MonkeyPatch,
+ capsys: pytest.CaptureFixture[str],
+) -> None:
+ called = False
+
+ def fake_push_drive_from_environment(*, local_path, drive_path, kind):
+ nonlocal called
+ called = True
+ return AgentStubDriveCommitResponse(items=[])
+
+ monkeypatch.setattr(
+ "dify_agent.agent_stub.cli.main.push_drive_from_environment",
+ fake_push_drive_from_environment,
+ )
+
+ with pytest.raises(SystemExit) as exc_info:
+ main(["drive", "push", "/tmp/dir", "files/dir", "--recursive"])
+
+ captured = capsys.readouterr()
+ assert exc_info.value.code == 2
+ assert called is False
+ assert "--recursive" in captured.err
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.py
index dcca5144607..7722ff940bd 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
@@ -196,6 +196,7 @@ def test_request_agent_stub_drive_manifest_sync_gets_manifest_request() -> None:
"items": [
{
"key": "skills/example/SKILL.md",
+ "name": "SKILL.md",
"size": 12,
"hash": "sha256:abc",
"mime_type": "text/markdown",
@@ -220,6 +221,7 @@ def test_request_agent_stub_drive_manifest_sync_gets_manifest_request() -> None:
http_client.close()
assert response.items[0].key == "skills/example/SKILL.md"
+ assert response.items[0].model_extra == {"name": "SKILL.md"}
def test_request_agent_stub_drive_commit_sync_posts_commit_request() -> None:
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.py
index f4bc75291fc..0c16cf8bccf 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
@@ -11,6 +11,7 @@ from dify_agent.agent_stub.protocol.agent_stub import (
AgentStubDriveCommitItem,
AgentStubDriveCommitRequest,
AgentStubDriveFileRef,
+ AgentStubDriveManifestResponse,
AgentStubFileMapping,
agent_stub_connections_url,
agent_stub_drive_base_for_ref,
@@ -159,6 +160,7 @@ def test_agent_stub_drive_commit_request_validates_file_refs() -> None:
]
)
+ assert request.items[0].file_ref is not None
assert request.items[0].file_ref.kind == "tool_file"
with pytest.raises(ValidationError, match="tool_file"):
@@ -168,6 +170,15 @@ def test_agent_stub_drive_commit_request_validates_file_refs() -> None:
assert item_without_file_ref.file_ref is None
+def test_agent_stub_drive_manifest_response_preserves_extra_item_fields() -> None:
+ response = AgentStubDriveManifestResponse.model_validate(
+ {"items": [{"key": "skills/example/SKILL.md", "name": "SKILL.md"}]}
+ )
+
+ assert response.items[0].model_extra == {"name": "SKILL.md"}
+ assert response.items[0].model_dump(mode="json")["name"] == "SKILL.md"
+
+
@pytest.mark.parametrize("transfer_method", ["tool_file", "local_file", "datasource_file"])
def test_agent_stub_file_mapping_rejects_non_remote_with_url(
transfer_method: Literal["tool_file", "local_file", "datasource_file"],
diff --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.py
index 7de8faa8d58..11e56f62d67 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
@@ -57,6 +57,7 @@ def test_dify_api_agent_stub_drive_handler_injects_execution_context_for_manifes
"items": [
{
"key": "skills/example/SKILL.md",
+ "name": "SKILL.md",
"size": 12,
"hash": "sha256:abc",
"mime_type": "text/markdown",
@@ -82,6 +83,7 @@ def test_dify_api_agent_stub_drive_handler_injects_execution_context_for_manifes
include_download_url=True,
)
assert response.items[0].download_url == "https://files.example.com/download"
+ assert response.items[0].model_extra == {"name": "SKILL.md"}
asyncio.run(scenario())
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.py
index 96d781caa72..05ddad3543c 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
@@ -48,10 +48,8 @@ def test_layer_config_rejects_unknown_fields() -> None:
def test_drive_layer_is_registered_and_constructible_from_config() -> None:
- layer = DifyDriveLayer.from_config_with_settings(
+ layer = DifyDriveLayer.from_config(
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)
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.py
index c95526f046d..f9abc8e718b 100644
--- a/dify-agent/tests/local/dify_agent/layers/drive/test_layer.py
+++ b/dify-agent/tests/local/dify_agent/layers/drive/test_layer.py
@@ -2,27 +2,30 @@
from __future__ import annotations
-from pathlib import Path
+from typing import cast
+
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
-
+from dify_agent.layers.drive.layer import DifyDriveLayer, DifyDriveLayerError
+from dify_agent.layers.shell import DifyShellLayerConfig
+from dify_agent.layers.shell.layer import DifyShellLayer, RemoteCommandResult, ShellctlClientFactory
-class _FakeExecutionContextConfig(LayerConfig):
- tenant_id: str
+def _unused_client_factory(_entrypoint: str):
+ raise AssertionError("shellctl client should not be used by these drive-layer tests")
-class _FakeExecutionContextLayer(PlainLayer[NoLayerDeps, _FakeExecutionContextConfig, EmptyRuntimeState]):
- type_id = None
- def __init__(self, tenant_id: str) -> None:
- self.config = _FakeExecutionContextConfig(tenant_id=tenant_id)
+def _shell_layer() -> DifyShellLayer:
+ return DifyShellLayer.from_config_with_settings(
+ DifyShellLayerConfig(agent_stub_drive_ref="agent-1"),
+ shellctl_entrypoint="http://shellctl",
+ shellctl_client_factory=cast(ShellctlClientFactory, _unused_client_factory),
+ )
-def _build_layer(tmp_path: Path) -> DifyDriveLayer:
- layer = DifyDriveLayer.from_config_with_settings(
+def _build_layer() -> DifyDriveLayer:
+ layer = DifyDriveLayer.from_config(
DifyDriveLayerConfig(
drive_ref="agent-1",
skills=[
@@ -43,158 +46,210 @@ def _build_layer(tmp_path: Path) -> DifyDriveLayer:
],
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")})
+ layer.bind_deps({"shell": _shell_layer()})
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)
+def _remote_result(
+ output: str,
+ *,
+ exit_code: int | None = 0,
+ truncated: bool = False,
+) -> RemoteCommandResult:
+ return RemoteCommandResult(
+ job_id="remote-drive-pull",
+ status="exited",
+ done=True,
+ exit_code=exit_code,
+ output=output,
+ offset=len(output),
+ truncated=truncated,
+ output_path="/tmp/output.log",
+ )
- 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
+def _pulled_output() -> str:
+ return (
+ "/mnt/drive/agent-1/tender-analyzer\n"
+ "/mnt/drive/agent-1/files/report.pdf\n"
+ "__DIFY_DRIVE_MENTIONED_PATH__\ttender-analyzer/SKILL.md\t/mnt/drive/agent-1/tender-analyzer/SKILL.md\n"
+ "__DIFY_DRIVE_SKILL_BEGIN__\ttender-analyzer/SKILL.md\n"
+ "# Tender Analyzer\n"
+ "Use carefully.\n"
+ "__DIFY_DRIVE_SKILL_END__\ttender-analyzer/SKILL.md\n"
+ "__DIFY_DRIVE_MENTIONED_PATH__\tfiles/report.pdf\t/mnt/drive/agent-1/files/report.pdf\n"
+ )
+
+
+def test_drive_layer_exposes_agent_stub_cli_usage_suffix_prompt() -> None:
+ layer = _build_layer()
+
+ assert len(layer.suffix_prompts) == 1
+ prompt = layer.suffix_prompts[0]
assert "Other available skills" in prompt
assert "other-skill: Other Skill — Fallback catalog entry." in prompt
+ assert "`dify-agent drive pull other-skill/`" not in prompt
+ assert (
+ '`skill_dir="$(dify-agent drive pull <SKILL_PATH> --to /tmp/drive)"; '
+ 'printf "%s\\n" "$skill_dir"; cat "$skill_dir/SKILL.md"`'
+ ) in prompt
+ assert "dify-agent drive list [REMOTE_PREFIX]" in prompt
+ assert "dify-agent drive pull [REMOTE ...] [--to LOCAL_DIR]" in prompt
+ assert "--to ." in prompt
+ assert "dify-agent drive push LOCAL_FILE REMOTE_PATH" in prompt
+ assert "dify-agent drive push LOCAL_DIR REMOTE_PATH --kind skill" in prompt
+ assert "dify-agent drive push LOCAL_DIR REMOTE_PATH --kind dir" in prompt
+ assert "dify-agent file download TRANSFER_METHOD REFERENCE_OR_URL [--to LOCAL_DIR]" in prompt
+ assert "dify-agent file download --mapping" in prompt
+ assert "dify-agent file upload PATH" in prompt
+ assert '{"transfer_method":"tool_file","reference":"..."}' in prompt
+ assert "--recursive" not in prompt
+ assert "--drive-base" not in prompt
@pytest.mark.anyio
-async def test_on_context_resume_loads_mentioned_targets_into_prompt(
- monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+async def test_on_context_create_pulls_mentioned_targets_through_shell(
+ monkeypatch: pytest.MonkeyPatch,
) -> 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)
+ layer = _build_layer()
+ captured: dict[str, object] = {}
+
+ async def fake_run_remote_script(
+ self: DifyShellLayer,
+ script: str,
+ *,
+ timeout: float = 10.0,
+ inject_agent_stub_env: bool = False,
+ ) -> RemoteCommandResult:
+ del self, timeout
+ captured["script"] = script
+ captured["inject_agent_stub_env"] = inject_agent_stub_env
+ return _remote_result(_pulled_output())
+
+ monkeypatch.setattr(DifyShellLayer, "run_remote_script", fake_run_remote_script)
- await layer.on_context_resume()
+ await layer.on_context_create()
+ script = captured["script"]
+ assert isinstance(script, str)
+ assert captured["inject_agent_stub_env"] is True
+ assert "base=/mnt/drive/agent-1" in script
+ assert 'dify-agent drive pull tender-analyzer/ files/report.pdf --to "$base"' in script
+ assert "cat /mnt/drive/agent-1/tender-analyzer/SKILL.md" in script
prompt = layer.build_prompt_context()
assert "Loaded mentioned skills" in prompt
+ assert "Path: tender-analyzer" in prompt
+ assert "Local path: /mnt/drive/agent-1/tender-analyzer" in prompt
+ assert "Name: Tender Analyzer" not 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
+ assert "files/report.pdf -> /mnt/drive/agent-1/files/report.pdf" in prompt
+ assert "Other available skills" not in prompt
@pytest.mark.anyio
-async def test_on_context_create_raises_when_mentioned_file_is_missing(
+async def test_on_context_resume_repulls_mentioned_targets_through_shell(
monkeypatch: pytest.MonkeyPatch,
- tmp_path: Path,
) -> None:
- layer = _build_layer(tmp_path)
+ layer = _build_layer()
+ calls = 0
+
+ async def fake_run_remote_script(
+ self: DifyShellLayer,
+ script: str,
+ *,
+ timeout: float = 10.0,
+ inject_agent_stub_env: bool = False,
+ ) -> RemoteCommandResult:
+ del self, script, timeout
+ nonlocal calls
+ calls += 1
+ assert inject_agent_stub_env is True
+ return _remote_result(_pulled_output())
+
+ monkeypatch.setattr(DifyShellLayer, "run_remote_script", fake_run_remote_script)
+
+ await layer.on_context_resume()
- 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")]
+ assert calls == 1
+ assert "Loaded mentioned skills" in layer.build_prompt_context()
- 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)
+async def test_on_context_create_raises_when_mentioned_file_is_missing(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ layer = _build_layer()
+
+ async def fake_run_remote_script(
+ self: DifyShellLayer,
+ script: str,
+ *,
+ timeout: float = 10.0,
+ inject_agent_stub_env: bool = False,
+ ) -> RemoteCommandResult:
+ del self, script, timeout, inject_agent_stub_env
+ output = (
+ "__DIFY_DRIVE_MENTIONED_PATH__\ttender-analyzer/SKILL.md\t/mnt/drive/agent-1/tender-analyzer/SKILL.md\n"
+ "__DIFY_DRIVE_SKILL_BEGIN__\ttender-analyzer/SKILL.md\n"
+ "# Tender Analyzer\n"
+ "__DIFY_DRIVE_SKILL_END__\ttender-analyzer/SKILL.md\n"
+ )
+ return _remote_result(output)
+
+ monkeypatch.setattr(DifyShellLayer, "run_remote_script", fake_run_remote_script)
with pytest.raises(DifyDriveLayerError, match="missing pulled file"):
await layer.on_context_create()
@pytest.mark.anyio
-async def test_on_context_resume_raises_when_mentioned_targets_are_missing(
+async def test_on_context_create_raises_when_shell_pull_fails(
monkeypatch: pytest.MonkeyPatch,
- tmp_path: Path,
) -> None:
- layer = _build_layer(tmp_path)
+ layer = _build_layer()
- async def _fetch_manifest_items(*, tenant_id: str, targets: list[tuple[str, bool]]) -> list[_DriveManifestItem]:
- del tenant_id, targets
- return []
+ async def fake_run_remote_script(
+ self: DifyShellLayer,
+ script: str,
+ *,
+ timeout: float = 10.0,
+ inject_agent_stub_env: bool = False,
+ ) -> RemoteCommandResult:
+ del self, script, timeout, inject_agent_stub_env
+ return _remote_result("permission denied\n", exit_code=1)
- async def _download_items(items: list[_DriveManifestItem]) -> dict[str, str]:
- assert items == []
- return {}
+ monkeypatch.setattr(DifyShellLayer, "run_remote_script", fake_run_remote_script)
- 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()
+ with pytest.raises(DifyDriveLayerError, match="drive mentioned pull failed in shell"):
+ await layer.on_context_create()
@pytest.mark.anyio
-async def test_on_context_create_raises_when_manifest_is_empty_for_mentioned_targets(
+async def test_on_context_create_raises_when_shell_output_is_truncated(
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 []
+ layer = _build_layer()
- async def _download_items(items: list[_DriveManifestItem]) -> dict[str, str]:
- assert items == []
- return {}
+ async def fake_run_remote_script(
+ self: DifyShellLayer,
+ script: str,
+ *,
+ timeout: float = 10.0,
+ inject_agent_stub_env: bool = False,
+ ) -> RemoteCommandResult:
+ del self, script, timeout, inject_agent_stub_env
+ return _remote_result(_pulled_output(), truncated=True)
- monkeypatch.setattr(layer, "_fetch_manifest_items", _fetch_manifest_items)
- monkeypatch.setattr(layer, "_download_items", _download_items)
+ monkeypatch.setattr(DifyShellLayer, "run_remote_script", fake_run_remote_script)
- with pytest.raises(DifyDriveLayerError, match="missing pulled file"):
+ with pytest.raises(DifyDriveLayerError, match="output was truncated"):
await layer.on_context_create()
+
+
+def test_parse_shell_pull_output_rejects_unclosed_skill_marker() -> None:
+ layer = _build_layer()
+
+ with pytest.raises(DifyDriveLayerError, match="omitted SKILL.md end marker"):
+ layer._parse_shell_pull_output("__DIFY_DRIVE_SKILL_BEGIN__\ttender-analyzer/SKILL.md\n# Tender\n")
diff --git a/dify-agent/tests/local/dify_agent/layers/knowledge/test_configs.py b/dify-agent/tests/local/dify_agent/layers/knowledge/test_configs.py
index f28939e329b..dbe8fddcbec 100644
--- a/dify-agent/tests/local/dify_agent/layers/knowledge/test_configs.py
+++ b/dify-agent/tests/local/dify_agent/layers/knowledge/test_configs.py
@@ -6,46 +6,142 @@ from dify_agent.layers.knowledge import DifyKnowledgeBaseLayerConfig
def _valid_config() -> dict[str, object]:
return {
- "dataset_ids": ["dataset-1"],
- "retrieval": {
- "mode": "multiple",
- "top_k": 4,
- },
+ "sets": [
+ {
+ "id": "support",
+ "name": "Support KB",
+ "datasets": [{"id": "dataset-1"}],
+ "query": {"mode": "generated_query"},
+ "retrieval": {
+ "mode": "multiple",
+ "top_k": 4,
+ },
+ }
+ ],
}
def test_knowledge_base_config_accepts_valid_multiple_mode() -> None:
config = DifyKnowledgeBaseLayerConfig.model_validate(_valid_config())
- assert config.dataset_ids == ["dataset-1"]
- assert config.retrieval.top_k == 4
- assert config.metadata_filtering.mode == "disabled"
+ assert config.sets[0].dataset_ids == ["dataset-1"]
+ assert config.sets[0].retrieval.top_k == 4
+ assert config.sets[0].metadata_filtering.mode == "disabled"
@pytest.mark.parametrize(
"payload, expected_message",
[
- ({"dataset_ids": [], "retrieval": {"mode": "multiple", "top_k": 4}}, "dataset_ids"),
+ ({"sets": []}, "sets"),
({"tool_name": "knowledge_base_search", **_valid_config()}, "Extra inputs are not permitted"),
({"tool_description": "Search knowledge", **_valid_config()}, "Extra inputs are not permitted"),
- ({"dataset_ids": ["dataset-1"], "retrieval": {"mode": "multiple"}}, "top_k"),
- ({"dataset_ids": ["dataset-1"], "retrieval": {"mode": "single"}}, "retrieval.model"),
(
{
- "dataset_ids": ["dataset-1"],
- "retrieval": {"mode": "multiple", "top_k": 4},
- "metadata_filtering": {"mode": "automatic"},
+ "sets": [
+ {
+ "id": "support",
+ "name": "Support KB",
+ "datasets": [{"id": ""}],
+ "query": {"mode": "generated_query"},
+ "retrieval": {"mode": "multiple", "top_k": 4},
+ }
+ ]
+ },
+ "dataset id",
+ ),
+ (
+ {
+ "sets": [
+ {
+ "id": "support",
+ "name": "Support KB",
+ "datasets": [{"id": "dataset-1"}],
+ "query": {"mode": "user_query"},
+ "retrieval": {"mode": "multiple", "top_k": 4},
+ }
+ ]
+ },
+ "query.value",
+ ),
+ (
+ {
+ "sets": [
+ {
+ "id": "support",
+ "name": "Support KB",
+ "datasets": [{"id": "dataset-1"}],
+ "query": {"mode": "generated_query"},
+ "retrieval": {"mode": "multiple"},
+ }
+ ]
+ },
+ "top_k",
+ ),
+ (
+ {
+ "sets": [
+ {
+ "id": "support",
+ "name": "Support KB",
+ "datasets": [{"id": "dataset-1"}],
+ "query": {"mode": "generated_query"},
+ "retrieval": {"mode": "single"},
+ }
+ ]
+ },
+ "retrieval.model",
+ ),
+ (
+ {
+ "sets": [
+ {
+ "id": "support",
+ "name": "Support KB",
+ "datasets": [{"id": "dataset-1"}],
+ "query": {"mode": "generated_query"},
+ "retrieval": {"mode": "multiple", "top_k": 4},
+ "metadata_filtering": {"mode": "automatic"},
+ }
+ ],
},
"metadata_filtering.model_config",
),
(
{
- "dataset_ids": ["dataset-1"],
- "retrieval": {"mode": "multiple", "top_k": 4},
- "metadata_filtering": {"mode": "manual"},
+ "sets": [
+ {
+ "id": "support",
+ "name": "Support KB",
+ "datasets": [{"id": "dataset-1"}],
+ "query": {"mode": "generated_query"},
+ "retrieval": {"mode": "multiple", "top_k": 4},
+ "metadata_filtering": {"mode": "manual"},
+ }
+ ],
},
"metadata_filtering.conditions",
),
+ (
+ {
+ "sets": [
+ {
+ "id": "support",
+ "name": "Support KB",
+ "datasets": [{"id": "dataset-1"}],
+ "query": {"mode": "generated_query"},
+ "retrieval": {"mode": "multiple", "top_k": 4},
+ },
+ {
+ "id": "docs",
+ "name": "support kb",
+ "datasets": [{"id": "dataset-2"}],
+ "query": {"mode": "generated_query"},
+ "retrieval": {"mode": "multiple", "top_k": 4},
+ },
+ ]
+ },
+ "names must be unique",
+ ),
],
)
def test_knowledge_base_config_rejects_invalid_inputs(payload: dict[str, object], expected_message: str) -> None:
@@ -57,8 +153,7 @@ def test_knowledge_base_config_rejects_observation_limit_smaller_than_result_lim
with pytest.raises(ValidationError, match="max_observation_chars"):
_ = DifyKnowledgeBaseLayerConfig.model_validate(
{
- "dataset_ids": ["dataset-1"],
- "retrieval": {"mode": "multiple", "top_k": 4},
+ **_valid_config(),
"max_result_content_chars": 50,
"max_observation_chars": 20,
}
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.py
index 28fadcb903b..ed6c798b409 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
@@ -8,7 +8,11 @@ from pydantic_ai import Tool
from agenton.compositor import Compositor, LayerNode, LayerProvider
from dify_agent.layers.execution_context import DifyExecutionContextLayerConfig
from dify_agent.layers.execution_context.layer import DifyExecutionContextLayer
-from dify_agent.layers.knowledge.client import DifyKnowledgeBaseClientError
+from dify_agent.layers.knowledge.client import (
+ DifyKnowledgeBaseClient,
+ DifyKnowledgeBaseClientError,
+ DifyKnowledgeRetrieveResponse,
+)
from dify_agent.layers.knowledge.configs import DifyKnowledgeBaseLayerConfig
from dify_agent.layers.knowledge.layer import (
BLANK_QUERY_OBSERVATION,
@@ -32,10 +36,23 @@ def _execution_context_config(**overrides: object) -> DifyExecutionContextLayerC
def _knowledge_config(**overrides: object) -> DifyKnowledgeBaseLayerConfig:
- payload: dict[str, object] = {
- "dataset_ids": ["dataset-1"],
+ set_payload: dict[str, object] = {
+ "id": "support",
+ "name": "Support KB",
+ "datasets": [{"id": "dataset-1"}],
+ "query": {"mode": "generated_query"},
"retrieval": {"mode": "multiple", "top_k": 4},
}
+ for key in ("id", "name", "description", "datasets", "query", "retrieval", "metadata_filtering"):
+ if key in overrides:
+ set_payload[key] = overrides.pop(key)
+ if "dataset_ids" in overrides:
+ dataset_ids = overrides.pop("dataset_ids")
+ assert isinstance(dataset_ids, list)
+ set_payload["datasets"] = [{"id": dataset_id} for dataset_id in dataset_ids]
+ payload: dict[str, object] = {
+ "sets": [set_payload],
+ }
payload.update(overrides)
return DifyKnowledgeBaseLayerConfig.model_validate(payload)
@@ -62,7 +79,7 @@ def _knowledge_provider() -> LayerProvider[DifyKnowledgeBaseLayer]:
)
-def test_knowledge_layer_exposes_one_query_only_tool_definition() -> None:
+def test_knowledge_layer_exposes_one_set_scoped_tool_definition() -> None:
async def scenario() -> None:
compositor = Compositor(
[
@@ -82,20 +99,23 @@ def test_knowledge_layer_exposes_one_query_only_tool_definition() -> None:
tool_def = await tool.prepare_tool_def(None) # pyright: ignore[reportArgumentType]
assert isinstance(tool, Tool)
assert tool.name == "knowledge_base_search"
- assert tool.description == "Search configured knowledge bases for information relevant to the query."
+ assert "Pick one configured set_name" in tool.description
assert tool_def is not None
- assert (
- tool_def.description == "Search configured knowledge bases for information relevant to the query."
- )
+ assert "Pick one configured set_name" in tool_def.description
assert tool_def.parameters_json_schema == {
"type": "object",
"properties": {
+ "set_name": {
+ "type": "string",
+ "enum": ["Support KB"],
+ "description": "Knowledge set to search.",
+ },
"query": {
"type": "string",
- "description": "Search query for the configured knowledge bases.",
- }
+ "description": "Search query for the selected knowledge set.",
+ },
},
- "required": ["query"],
+ "required": ["set_name", "query"],
"additionalProperties": False,
}
@@ -119,12 +139,105 @@ def test_knowledge_layer_rejects_blank_query_locally() -> None:
) as run:
knowledge_layer = run.get_layer("knowledge", DifyKnowledgeBaseLayer)
tool = (await knowledge_layer.get_tools(http_client=http_client))[0]
- result = await tool.function_schema.call({"query": " "}, None) # pyright: ignore[reportArgumentType]
+ result = await tool.function_schema.call( # pyright: ignore[reportArgumentType]
+ {"set_name": "Support KB", "query": " "}, None
+ )
assert result == BLANK_QUERY_OBSERVATION
asyncio.run(scenario())
+def test_knowledge_layer_exposes_no_tool_when_all_sets_are_user_query(monkeypatch: pytest.MonkeyPatch) -> None:
+ async def fake_retrieve(self: DifyKnowledgeBaseClient, **_kwargs: object) -> DifyKnowledgeRetrieveResponse:
+ del self
+ return DifyKnowledgeRetrieveResponse.model_validate({"results": [], "usage": {}})
+
+ monkeypatch.setattr(DifyKnowledgeBaseClient, "retrieve", fake_retrieve)
+
+ async def scenario() -> None:
+ compositor = Compositor(
+ [
+ LayerNode("execution_context", _execution_context_provider()),
+ LayerNode("knowledge", _knowledge_provider(), deps={"execution_context": "execution_context"}),
+ ]
+ )
+ async with httpx.AsyncClient() as http_client:
+ async with compositor.enter(
+ configs={
+ "execution_context": _execution_context_config(),
+ "knowledge": _knowledge_config(query={"mode": "user_query", "value": "release notes"}),
+ }
+ ) as run:
+ knowledge_layer = run.get_layer("knowledge", DifyKnowledgeBaseLayer)
+ assert await knowledge_layer.get_tools(http_client=http_client) == []
+
+ asyncio.run(scenario())
+
+
+def test_knowledge_layer_fetches_user_query_sets_on_context_entry(monkeypatch: pytest.MonkeyPatch) -> None:
+ seen_requests: list[dict[str, object]] = []
+
+ async def fake_retrieve(self: DifyKnowledgeBaseClient, **kwargs: object) -> DifyKnowledgeRetrieveResponse:
+ del self
+ seen_requests.append(kwargs)
+ return DifyKnowledgeRetrieveResponse.model_validate(
+ {
+ "results": [
+ {
+ "metadata": {
+ "_source": "knowledge",
+ "dataset_name": "Docs",
+ "document_name": "Release.md",
+ "score": 0.8,
+ },
+ "title": "Release",
+ "files": [],
+ "content": "Version notes",
+ "summary": None,
+ }
+ ],
+ "usage": {},
+ }
+ )
+
+ monkeypatch.setattr(DifyKnowledgeBaseClient, "retrieve", fake_retrieve)
+
+ async def scenario() -> None:
+ compositor = Compositor(
+ [
+ LayerNode("execution_context", _execution_context_provider()),
+ LayerNode("knowledge", _knowledge_provider(), deps={"execution_context": "execution_context"}),
+ ]
+ )
+ async with compositor.enter(
+ configs={
+ "execution_context": _execution_context_config(),
+ "knowledge": _knowledge_config(query={"mode": "user_query", "value": "release notes"}),
+ }
+ ) as run:
+ knowledge_layer = run.get_layer("knowledge", DifyKnowledgeBaseLayer)
+ assert len(seen_requests) == 1
+ assert seen_requests[0]["query"] == "release notes"
+ assert seen_requests[0]["dataset_ids"] == ["dataset-1"]
+ assert knowledge_layer.runtime_state.eager_config_fingerprint
+ assert knowledge_layer.runtime_state.eager_results[0].status == "success"
+ assert knowledge_layer.user_prompts == [
+ "Knowledge retrieval results:\n\n"
+ "Set: Support KB\n"
+ "Query: release notes\n"
+ "Results:\n"
+ "1. Title: Release\n"
+ " Dataset: Docs\n"
+ " Document: Release.md\n"
+ " Score: 0.8\n"
+ " Content: Version notes"
+ ]
+ await knowledge_layer.on_context_resume()
+ assert len(seen_requests) == 1
+
+ asyncio.run(scenario())
+
+
@pytest.mark.parametrize(
("field_name", "field_value"),
[
@@ -199,7 +312,9 @@ def test_knowledge_layer_formats_results_and_truncates_observation() -> None:
) as run:
knowledge_layer = run.get_layer("knowledge", DifyKnowledgeBaseLayer)
tool = (await knowledge_layer.get_tools(http_client=http_client))[0]
- result = await tool.function_schema.call({"query": "reset"}, None) # pyright: ignore[reportArgumentType]
+ result = await tool.function_schema.call( # pyright: ignore[reportArgumentType]
+ {"set_name": "Support KB", "query": "reset"}, None
+ )
assert result.startswith("Knowledge base search results:\n1. Title: Guide")
assert "Dataset: Docs" in result
assert "Document: Guide.md" in result
@@ -229,7 +344,9 @@ def test_knowledge_layer_returns_no_results_observation() -> None:
) as run:
knowledge_layer = run.get_layer("knowledge", DifyKnowledgeBaseLayer)
tool = (await knowledge_layer.get_tools(http_client=http_client))[0]
- result = await tool.function_schema.call({"query": "reset"}, None) # pyright: ignore[reportArgumentType]
+ result = await tool.function_schema.call( # pyright: ignore[reportArgumentType]
+ {"set_name": "Support KB", "query": "reset"}, None
+ )
assert result == NO_RESULTS_OBSERVATION
asyncio.run(scenario())
@@ -256,7 +373,9 @@ def test_knowledge_layer_converts_retryable_failures_into_observation() -> None:
) as run:
knowledge_layer = run.get_layer("knowledge", DifyKnowledgeBaseLayer)
tool = (await knowledge_layer.get_tools(http_client=http_client))[0]
- result = await tool.function_schema.call({"query": "reset"}, None) # pyright: ignore[reportArgumentType]
+ result = await tool.function_schema.call( # pyright: ignore[reportArgumentType]
+ {"set_name": "Support KB", "query": "reset"}, None
+ )
assert result == TEMPORARY_UNAVAILABLE_OBSERVATION
asyncio.run(scenario())
@@ -289,7 +408,9 @@ def test_knowledge_layer_converts_retryable_transport_failures_into_observation(
) as run:
knowledge_layer = run.get_layer("knowledge", DifyKnowledgeBaseLayer)
tool = (await knowledge_layer.get_tools(http_client=http_client))[0]
- result = await tool.function_schema.call({"query": "reset"}, None) # pyright: ignore[reportArgumentType]
+ result = await tool.function_schema.call( # pyright: ignore[reportArgumentType]
+ {"set_name": "Support KB", "query": "reset"}, None
+ )
assert result == TEMPORARY_UNAVAILABLE_OBSERVATION
asyncio.run(scenario())
@@ -317,7 +438,9 @@ def test_knowledge_layer_raises_non_retryable_client_errors() -> None:
knowledge_layer = run.get_layer("knowledge", DifyKnowledgeBaseLayer)
tool = (await knowledge_layer.get_tools(http_client=http_client))[0]
with pytest.raises(DifyKnowledgeBaseClientError) as exc_info:
- await tool.function_schema.call({"query": "reset"}, None) # pyright: ignore[reportArgumentType]
+ await tool.function_schema.call( # pyright: ignore[reportArgumentType]
+ {"set_name": "Support KB", "query": "reset"}, None
+ )
assert exc_info.value.status_code == 403
asyncio.run(scenario())
@@ -343,7 +466,9 @@ def test_knowledge_layer_raises_for_malformed_success_responses() -> None:
knowledge_layer = run.get_layer("knowledge", DifyKnowledgeBaseLayer)
tool = (await knowledge_layer.get_tools(http_client=http_client))[0]
with pytest.raises(DifyKnowledgeBaseClientError) as exc_info:
- await tool.function_schema.call({"query": "reset"}, None) # pyright: ignore[reportArgumentType]
+ await tool.function_schema.call( # pyright: ignore[reportArgumentType]
+ {"set_name": "Support KB", "query": "reset"}, None
+ )
assert exc_info.value.error_code == "invalid_response"
assert exc_info.value.retryable is False
@@ -411,7 +536,9 @@ def test_knowledge_layer_sends_execution_context_and_static_config_to_inner_api(
) as run:
knowledge_layer = run.get_layer("knowledge", DifyKnowledgeBaseLayer)
tool = (await knowledge_layer.get_tools(http_client=http_client))[0]
- result = await tool.function_schema.call({"query": "reset"}, None) # pyright: ignore[reportArgumentType]
+ result = await tool.function_schema.call( # pyright: ignore[reportArgumentType]
+ {"set_name": "Support KB", "query": "reset"}, None
+ )
assert result == NO_RESULTS_OBSERVATION
asyncio.run(scenario())
diff --git a/dify-agent/tests/local/dify_agent/layers/shell/test_configs.py b/dify-agent/tests/local/dify_agent/layers/shell/test_configs.py
index c15b15ee284..ec429f94339 100644
--- a/dify-agent/tests/local/dify_agent/layers/shell/test_configs.py
+++ b/dify-agent/tests/local/dify_agent/layers/shell/test_configs.py
@@ -29,6 +29,7 @@ def test_shell_layer_config_defaults_and_forbids_unknown_fields() -> None:
config = DifyShellLayerConfig()
assert config.model_dump() == {
+ "agent_stub_drive_ref": None,
"cli_tools": [],
"env": [],
"secret_refs": [],
@@ -51,6 +52,7 @@ def test_shell_layer_config_accepts_agent_soul_shell_settings() -> None:
],
env=[DifyShellEnvVarConfig(name="PROJECT_NAME", value="demo")],
secret_refs=[DifyShellSecretRefConfig(name="OPENAI_API_KEY", ref="credential-1")],
+ agent_stub_drive_ref="agent-1",
sandbox=DifyShellSandboxConfig(provider="independent", config={"cpu": 2}),
)
@@ -59,6 +61,7 @@ def test_shell_layer_config_accepts_agent_soul_shell_settings() -> None:
assert config.cli_tools[0].secret_refs[0].ref == "credential-2"
assert config.env[0].name == "PROJECT_NAME"
assert config.secret_refs[0].ref == "credential-1"
+ assert config.agent_stub_drive_ref == "agent-1"
assert config.sandbox is not None
assert config.sandbox.config == {"cpu": 2}
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.py
index c7d2599b63c..df24f856b21 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
@@ -14,8 +14,6 @@ from dify_agent.agent_stub.server.shell_agent_stub_env import (
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 DifyDriveLayer
from dify_agent.layers.execution_context import DifyExecutionContextLayerConfig
from dify_agent.layers.execution_context.layer import DifyExecutionContextLayer
from dify_agent.layers.shell import (
@@ -238,14 +236,6 @@ 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,
@@ -666,7 +656,7 @@ def test_shell_layer_injects_agent_stub_env_only_for_user_visible_shell_run() ->
client = FakeShellctlClient(run_handler=run_handler)
layer = DifyShellLayer.from_config_with_settings(
- DifyShellLayerConfig(),
+ DifyShellLayerConfig(agent_stub_drive_ref="agent-1"),
shellctl_entrypoint="http://shellctl",
shellctl_client_factory=lambda _entrypoint: client,
agent_stub_api_base_url="https://agent.example.com/agent-stub",
@@ -674,7 +664,7 @@ def test_shell_layer_injects_agent_stub_env_only_for_user_visible_shell_run() ->
f"token-for:{execution_context.tenant_id}:{session_id}"
),
)
- layer.deps = layer.deps_type(drive=_drive_layer(), execution_context=_execution_context_layer())
+ layer.deps = layer.deps_type(execution_context=_execution_context_layer())
tools = {tool.name: tool for tool in layer.tools}
async def scenario() -> None:
@@ -738,6 +728,7 @@ def test_run_remote_script_uses_workspace_cwd_accumulates_output_and_deletes_job
result = await layer.run_remote_script("printf 'hello world'", timeout=7.5)
assert result.output == "hello world"
assert result.exit_code == 0
+ assert result.truncated is False
asyncio.run(scenario())
@@ -793,7 +784,7 @@ def test_run_remote_script_can_inject_agent_stub_env_for_server_owned_uploads()
client = FakeShellctlClient(run_handler=run_handler)
layer = DifyShellLayer.from_config_with_settings(
- DifyShellLayerConfig(),
+ DifyShellLayerConfig(agent_stub_drive_ref="agent-1"),
shellctl_entrypoint="http://shellctl",
shellctl_client_factory=lambda _entrypoint: client,
agent_stub_api_base_url="https://agent.example.com/agent-stub",
@@ -801,7 +792,7 @@ def test_run_remote_script_can_inject_agent_stub_env_for_server_owned_uploads()
f"token-for:{execution_context.tenant_id}:{session_id}"
),
)
- layer.deps = layer.deps_type(drive=_drive_layer(), execution_context=_execution_context_layer())
+ layer.deps = layer.deps_type(execution_context=_execution_context_layer())
async def scenario() -> None:
async with layer.resource_context():
diff --git a/dify-agent/tests/local/dify_agent/runtime/test_runner.py b/dify-agent/tests/local/dify_agent/runtime/test_runner.py
index f5ddeb72367..4a64fe9090d 100644
--- a/dify-agent/tests/local/dify_agent/runtime/test_runner.py
+++ b/dify-agent/tests/local/dify_agent/runtime/test_runner.py
@@ -995,7 +995,7 @@ def test_runner_passes_dynamic_dify_knowledge_tools_to_agent(monkeypatch: pytest
return TestModel(custom_output_text="done") # pyright: ignore[reportReturnType]
async def fake_get_tools(self: DifyKnowledgeBaseLayer, *, http_client: httpx.AsyncClient) -> list[Tool[object]]:
- assert self.config.dataset_ids == ["dataset-1"]
+ assert self.config.sets[0].dataset_ids == ["dataset-1"]
assert http_client.headers.get("X-Test-Client") == "dify-api"
return [Tool(knowledge_tool, name="knowledge_base_search")]
@@ -1055,8 +1055,15 @@ def test_runner_passes_dynamic_dify_knowledge_tools_to_agent(monkeypatch: pytest
deps={"execution_context": "execution_context"},
config=DifyKnowledgeBaseLayerConfig.model_validate(
{
- "dataset_ids": ["dataset-1"],
- "retrieval": {"mode": "multiple", "top_k": 4},
+ "sets": [
+ {
+ "id": "support",
+ "name": "Support KB",
+ "datasets": [{"id": "dataset-1"}],
+ "query": {"mode": "generated_query"},
+ "retrieval": {"mode": "multiple", "top_k": 4},
+ }
+ ],
}
),
),
diff --git a/dify-agent/tests/local/dify_agent/server/test_app.py b/dify-agent/tests/local/dify_agent/server/test_app.py
index 8e40bd683b9..ea0bc3b2977 100644
--- a/dify-agent/tests/local/dify_agent/server/test_app.py
+++ b/dify-agent/tests/local/dify_agent/server/test_app.py
@@ -231,8 +231,15 @@ def test_create_app_creates_scheduler_and_closes_after_shutdown(monkeypatch: pyt
knowledge_layer = knowledge_provider.create_layer(
DifyKnowledgeBaseLayerConfig.model_validate(
{
- "dataset_ids": ["dataset-1"],
- "retrieval": {"mode": "multiple", "top_k": 2},
+ "sets": [
+ {
+ "id": "support",
+ "name": "Support KB",
+ "datasets": [{"id": "dataset-1"}],
+ "query": {"mode": "generated_query"},
+ "retrieval": {"mode": "multiple", "top_k": 2},
+ }
+ ],
}
)
)
diff --git a/dify-agent/tests/local/dify_agent/server/test_observability.py b/dify-agent/tests/local/dify_agent/server/test_observability.py
new file mode 100644
index 00000000000..534298415ba
--- /dev/null
+++ b/dify-agent/tests/local/dify_agent/server/test_observability.py
@@ -0,0 +1,81 @@
+from __future__ import annotations
+
+from typing import ClassVar
+
+from fastapi import FastAPI
+
+import dify_agent.server.observability as observability
+from dify_agent.server.observability import configure_server_observability
+
+
+class FakeLogfireModule:
+ configure_calls: ClassVar[list[dict[str, object]]] = []
+ fastapi_calls: ClassVar[list[dict[str, object]]] = []
+ httpx_calls: ClassVar[list[dict[str, object]]] = []
+ redis_calls: ClassVar[list[dict[str, object]]] = []
+ pydantic_ai_calls: ClassVar[list[dict[str, object]]] = []
+
+ @classmethod
+ def reset(cls) -> None:
+ cls.configure_calls.clear()
+ cls.fastapi_calls.clear()
+ cls.httpx_calls.clear()
+ cls.redis_calls.clear()
+ cls.pydantic_ai_calls.clear()
+
+ @classmethod
+ def configure(cls, **kwargs: object) -> None:
+ cls.configure_calls.append(kwargs)
+
+ @classmethod
+ def instrument_fastapi(cls, app: FastAPI, **kwargs: object) -> None:
+ cls.fastapi_calls.append({"app": app, **kwargs})
+
+ @classmethod
+ def instrument_httpx(cls, **kwargs: object) -> None:
+ cls.httpx_calls.append(kwargs)
+
+ @classmethod
+ def instrument_redis(cls, **kwargs: object) -> None:
+ cls.redis_calls.append(kwargs)
+
+ @classmethod
+ def instrument_pydantic_ai(cls, **kwargs: object) -> None:
+ cls.pydantic_ai_calls.append(kwargs)
+
+
+def test_configure_server_observability_keeps_remote_export_token_gated_by_logfire_env(monkeypatch) -> None:
+ FakeLogfireModule.reset()
+ monkeypatch.setattr(observability, "logfire", FakeLogfireModule)
+ monkeypatch.setattr(observability, "_global_instrumentation_ready", False)
+ app = FastAPI()
+
+ configure_server_observability(app)
+
+ assert FakeLogfireModule.configure_calls == [
+ {
+ "send_to_logfire": "if-token-present",
+ "inspect_arguments": False,
+ }
+ ]
+
+
+def test_configure_server_observability_instruments_server_boundaries_once(monkeypatch) -> None:
+ FakeLogfireModule.reset()
+ monkeypatch.setattr(observability, "logfire", FakeLogfireModule)
+ monkeypatch.setattr(observability, "_global_instrumentation_ready", False)
+ first_app = FastAPI()
+ second_app = FastAPI()
+
+ configure_server_observability(first_app)
+ configure_server_observability(second_app)
+
+ assert FakeLogfireModule.httpx_calls == [{}]
+ assert FakeLogfireModule.redis_calls == [{}]
+ assert FakeLogfireModule.pydantic_ai_calls == [{}]
+ assert FakeLogfireModule.fastapi_calls == [
+ {"app": first_app},
+ {"app": second_app},
+ ]
+ assert first_app.state.dify_agent_logfire_instrumented is True
+ assert second_app.state.dify_agent_logfire_instrumented is True
diff --git a/dify-agent/tests/local/dify_agent/test_import_boundaries.py b/dify-agent/tests/local/dify_agent/test_import_boundaries.py
index 104f12031f0..c24941fae7f 100644
--- a/dify-agent/tests/local/dify_agent/test_import_boundaries.py
+++ b/dify-agent/tests/local/dify_agent/test_import_boundaries.py
@@ -115,7 +115,7 @@ def test_protocol_and_dify_plugin_exports_do_not_import_server_only_modules() ->
"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']",
- "assert dify_agent_layers_knowledge.__all__ == ['DIFY_KNOWLEDGE_BASE_LAYER_TYPE_ID', 'DifyKnowledgeBaseLayerConfig', 'DifyKnowledgeMetadataCondition', 'DifyKnowledgeMetadataConditions', 'DifyKnowledgeMetadataFilteringConfig', 'DifyKnowledgeModelConfig', 'DifyKnowledgeRerankingModelConfig', 'DifyKnowledgeRetrievalConfig']",
+ "assert dify_agent_layers_knowledge.__all__ == ['DIFY_KNOWLEDGE_BASE_LAYER_TYPE_ID', 'DifyKnowledgeBaseLayerConfig', 'DifyKnowledgeDatasetConfig', 'DifyKnowledgeEagerResult', 'DifyKnowledgeMetadataCondition', 'DifyKnowledgeMetadataConditions', 'DifyKnowledgeMetadataFilteringConfig', 'DifyKnowledgeModelConfig', 'DifyKnowledgeQueryConfig', 'DifyKnowledgeRerankingModelConfig', 'DifyKnowledgeRetrievalConfig', 'DifyKnowledgeRuntimeState', 'DifyKnowledgeSetConfig']",
"assert dify_agent_layers_output.__all__ == ['DIFY_OUTPUT_LAYER_TYPE_ID', 'DifyOutputLayerConfig']",
"assert dify_agent_layers_shell.__all__ == ['DIFY_SHELL_LAYER_TYPE_ID', 'DifyShellCliToolConfig', 'DifyShellEnvVarConfig', 'DifyShellLayerConfig', 'DifyShellSandboxConfig', 'DifyShellSecretRefConfig']",
],
diff --git a/dify-agent/tests/local/test_packaging.py b/dify-agent/tests/local/test_packaging.py
index b2e6b24dc38..84ee53ba2dd 100644
--- a/dify-agent/tests/local/test_packaging.py
+++ b/dify-agent/tests/local/test_packaging.py
@@ -19,6 +19,7 @@ SERVER_RUNTIME_DEPENDENCIES = {
"graphon==0.5.2",
"jsonschema>=4.23.0,<5.0.0",
"jwcrypto>=1.5.6,<2",
+ "logfire[fastapi,httpx,redis]>=4.37.0,<5.0.0",
"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",
diff --git a/dify-agent/uv.lock b/dify-agent/uv.lock
index bc20927b44e..d9a151cb209 100644
--- a/dify-agent/uv.lock
+++ b/dify-agent/uv.lock
@@ -78,6 +78,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/da/42/e921fccf5015463e32a3cf6ee7f980a6ed0f395ceeaa45060b61d86486c2/anyio-4.13.0-py3-none-any.whl", hash = "sha256:08b310f9e24a9594186fd75b4f73f4a4152069e3853f1ed8bfbf58369f4ad708", size = 114353, upload-time = "2026-03-24T12:59:08.246Z" },
]
+[[package]]
+name = "asgiref"
+version = "3.11.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/63/40/f03da1264ae8f7cfdbf9146542e5e7e8100a4c66ab48e791df9a03d3f6c0/asgiref-3.11.1.tar.gz", hash = "sha256:5f184dc43b7e763efe848065441eac62229c9f7b0475f41f80e207a114eda4ce", size = 38550, upload-time = "2026-02-03T13:30:14.33Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/5c/0a/a72d10ed65068e115044937873362e6e32fab1b7dce0046aeb224682c989/asgiref-3.11.1-py3-none-any.whl", hash = "sha256:e8667a091e69529631969fd45dc268fa79b99c92c5fcdda727757e52146ec133", size = 24345, upload-time = "2026-02-03T13:30:13.039Z" },
+]
+
[[package]]
name = "attrs"
version = "26.1.0"
@@ -601,6 +610,7 @@ server = [
{ name = "graphon" },
{ name = "jsonschema" },
{ name = "jwcrypto" },
+ { name = "logfire", extra = ["fastapi", "httpx", "redis"] },
{ name = "pydantic-ai-slim", extra = ["anthropic", "google", "openai"] },
{ name = "pydantic-settings" },
{ name = "redis" },
@@ -633,6 +643,7 @@ requires-dist = [
{ name = "httpx", specifier = "==0.28.1" },
{ name = "jsonschema", marker = "extra == 'server'", specifier = ">=4.23.0,<5.0.0" },
{ name = "jwcrypto", marker = "extra == 'server'", specifier = ">=1.5.6,<2" },
+ { name = "logfire", extras = ["fastapi", "httpx", "redis"], marker = "extra == 'server'", specifier = ">=4.37.0,<5.0.0" },
{ name = "protobuf", marker = "extra == 'grpc'", specifier = ">=6.33.5,<7.0.0" },
{ name = "pydantic", specifier = ">=2.12.5,<2.13" },
{ name = "pydantic-ai-slim", specifier = ">=1.85.1,<2.0.0" },
@@ -699,6 +710,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/c1/8b/5fe2cc11fee489817272089c4203e679c63b570a5aaeb18d852ae3cbba6a/et_xmlfile-2.0.0-py3-none-any.whl", hash = "sha256:7a91720bc756843502c3b7504c77b8fe44217c85c537d85037f0f536151b2caa", size = 18059, upload-time = "2024-10-25T17:25:39.051Z" },
]
+[[package]]
+name = "executing"
+version = "2.2.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/cc/28/c14e053b6762b1044f34a13aab6859bbf40456d37d23aa286ac24cfd9a5d/executing-2.2.1.tar.gz", hash = "sha256:3632cc370565f6648cc328b32435bd120a1e4ebb20c77e3fdde9a13cd1e533c4", size = 1129488, upload-time = "2025-09-01T09:48:10.866Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/c1/ea/53f2148663b321f21b5a606bd5f191517cf40b7072c0497d3c92c4a13b1e/executing-2.2.1-py2.py3-none-any.whl", hash = "sha256:760643d3452b4d777d295bb167ccc74c64a81df23fb5e08eff250c425a4b2017", size = 28317, upload-time = "2025-09-01T09:48:08.5Z" },
+]
+
[[package]]
name = "fastapi"
version = "0.136.0"
@@ -806,6 +826,18 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/65/af/508e0528015240d710c6763f7c89ff44fab9a94a80b4377e265d692cbfd6/google_genai-1.73.1-py3-none-any.whl", hash = "sha256:af2d2287d25e42a187de19811ef33beb2e347c7e2bdb4dc8c467d78254e43a2c", size = 783595, upload-time = "2026-04-14T21:06:17.464Z" },
]
+[[package]]
+name = "googleapis-common-protos"
+version = "1.75.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "protobuf" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/b5/c8/f439cffde755cffa462bfbb156278fa6f9d09119719af9814b858fd4f81f/googleapis_common_protos-1.75.0.tar.gz", hash = "sha256:53a062ff3c32552fbd62c11fe23768b78e4ddf0494d5e5fd97d3f4689c75fbbd", size = 151035, upload-time = "2026-05-07T08:04:49.423Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/e7/c8/e2645aa8ed02fd4c7a2f59d68783b65b1f3cbdfe39a6308e156509d1fee8/googleapis_common_protos-1.75.0-py3-none-any.whl", hash = "sha256:961ed60399c457ceb0ee8f285a84c870aabc9c6a832b9d37bb281b5bebde43ed", size = 300631, upload-time = "2026-05-07T08:03:30.345Z" },
+]
+
[[package]]
name = "graphon"
version = "0.5.2"
@@ -1367,6 +1399,35 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/4f/79/d3bbab197e86e0ff4f9c07122895b66a3e0d024247fcff7f12c473cb36d9/llvmlite-0.47.0-cp314-cp314t-win_amd64.whl", hash = "sha256:6842cf6f707ec4be3d985a385ad03f72b2d724439e118fcbe99b2929964f0453", size = 39153839, upload-time = "2026-03-31T18:29:51.004Z" },
]
+[[package]]
+name = "logfire"
+version = "4.37.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "executing" },
+ { name = "opentelemetry-exporter-otlp-proto-http" },
+ { name = "opentelemetry-instrumentation" },
+ { name = "opentelemetry-sdk" },
+ { name = "protobuf" },
+ { name = "rich" },
+ { name = "typing-extensions" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/c2/f2/34b8ebbd6bbd82c71055d6b881b24d8ada79a0e6692d3dd8cca5e86fadb3/logfire-4.37.0.tar.gz", hash = "sha256:7ee0cb64b59c356a41a1701fb84597037f8db1fa15df7a3715ef363e5a1de06a", size = 1212176, upload-time = "2026-06-12T20:47:06.904Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/7a/08/1805d2f26955671115aae555d78cc4c72a6fe733f332d44d69756bc1737b/logfire-4.37.0-py3-none-any.whl", hash = "sha256:a20823e6dbb3204614a3ea5e79c91df42405c5112393ec9d8e34ef45b60d315f", size = 378930, upload-time = "2026-06-12T20:47:03.674Z" },
+]
+
+[package.optional-dependencies]
+fastapi = [
+ { name = "opentelemetry-instrumentation-fastapi" },
+]
+httpx = [
+ { name = "opentelemetry-instrumentation-httpx" },
+]
+redis = [
+ { name = "opentelemetry-instrumentation-redis" },
+]
+
[[package]]
name = "logfire-api"
version = "4.32.1"
@@ -2007,6 +2068,162 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/cf/df/d3f1ddf4bb4cb50ed9b1139cc7b1c54c34a1e7ce8fd1b9a37c0d1551a6bd/opentelemetry_api-1.39.1-py3-none-any.whl", hash = "sha256:2edd8463432a7f8443edce90972169b195e7d6a05500cd29e6d13898187c9950", size = 66356, upload-time = "2025-12-11T13:32:17.304Z" },
]
+[[package]]
+name = "opentelemetry-exporter-otlp-proto-common"
+version = "1.39.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "opentelemetry-proto" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/e9/9d/22d241b66f7bbde88a3bfa6847a351d2c46b84de23e71222c6aae25c7050/opentelemetry_exporter_otlp_proto_common-1.39.1.tar.gz", hash = "sha256:763370d4737a59741c89a67b50f9e39271639ee4afc999dadfe768541c027464", size = 20409, upload-time = "2025-12-11T13:32:40.885Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/8c/02/ffc3e143d89a27ac21fd557365b98bd0653b98de8a101151d5805b5d4c33/opentelemetry_exporter_otlp_proto_common-1.39.1-py3-none-any.whl", hash = "sha256:08f8a5862d64cc3435105686d0216c1365dc5701f86844a8cd56597d0c764fde", size = 18366, upload-time = "2025-12-11T13:32:20.2Z" },
+]
+
+[[package]]
+name = "opentelemetry-exporter-otlp-proto-http"
+version = "1.39.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "googleapis-common-protos" },
+ { name = "opentelemetry-api" },
+ { name = "opentelemetry-exporter-otlp-proto-common" },
+ { name = "opentelemetry-proto" },
+ { name = "opentelemetry-sdk" },
+ { name = "requests" },
+ { name = "typing-extensions" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/80/04/2a08fa9c0214ae38880df01e8bfae12b067ec0793446578575e5080d6545/opentelemetry_exporter_otlp_proto_http-1.39.1.tar.gz", hash = "sha256:31bdab9745c709ce90a49a0624c2bd445d31a28ba34275951a6a362d16a0b9cb", size = 17288, upload-time = "2025-12-11T13:32:42.029Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/95/f1/b27d3e2e003cd9a3592c43d099d2ed8d0a947c15281bf8463a256db0b46c/opentelemetry_exporter_otlp_proto_http-1.39.1-py3-none-any.whl", hash = "sha256:d9f5207183dd752a412c4cd564ca8875ececba13be6e9c6c370ffb752fd59985", size = 19641, upload-time = "2025-12-11T13:32:22.248Z" },
+]
+
+[[package]]
+name = "opentelemetry-instrumentation"
+version = "0.60b1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "opentelemetry-api" },
+ { name = "opentelemetry-semantic-conventions" },
+ { name = "packaging" },
+ { name = "wrapt" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/41/0f/7e6b713ac117c1f5e4e3300748af699b9902a2e5e34c9cf443dde25a01fa/opentelemetry_instrumentation-0.60b1.tar.gz", hash = "sha256:57ddc7974c6eb35865af0426d1a17132b88b2ed8586897fee187fd5b8944bd6a", size = 31706, upload-time = "2025-12-11T13:36:42.515Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/77/d2/6788e83c5c86a2690101681aeef27eeb2a6bf22df52d3f263a22cee20915/opentelemetry_instrumentation-0.60b1-py3-none-any.whl", hash = "sha256:04480db952b48fb1ed0073f822f0ee26012b7be7c3eac1a3793122737c78632d", size = 33096, upload-time = "2025-12-11T13:35:33.067Z" },
+]
+
+[[package]]
+name = "opentelemetry-instrumentation-asgi"
+version = "0.60b1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "asgiref" },
+ { name = "opentelemetry-api" },
+ { name = "opentelemetry-instrumentation" },
+ { name = "opentelemetry-semantic-conventions" },
+ { name = "opentelemetry-util-http" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/77/db/851fa88db7441da82d50bd80f2de5ee55213782e25dc858e04d0c9961d60/opentelemetry_instrumentation_asgi-0.60b1.tar.gz", hash = "sha256:16bfbe595cd24cda309a957456d0fc2523f41bc7b076d1f2d7e98a1ad9876d6f", size = 26107, upload-time = "2025-12-11T13:36:47.015Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/76/76/1fb94367cef64420d2171157a6b9509582873bd09a6afe08a78a8d1f59d9/opentelemetry_instrumentation_asgi-0.60b1-py3-none-any.whl", hash = "sha256:d48def2dbed10294c99cfcf41ebbd0c414d390a11773a41f472d20000fcddc25", size = 16933, upload-time = "2025-12-11T13:35:40.462Z" },
+]
+
+[[package]]
+name = "opentelemetry-instrumentation-fastapi"
+version = "0.60b1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "opentelemetry-api" },
+ { name = "opentelemetry-instrumentation" },
+ { name = "opentelemetry-instrumentation-asgi" },
+ { name = "opentelemetry-semantic-conventions" },
+ { name = "opentelemetry-util-http" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/9c/e7/e7e5e50218cf488377209d85666b182fa2d4928bf52389411ceeee1b2b60/opentelemetry_instrumentation_fastapi-0.60b1.tar.gz", hash = "sha256:de608955f7ff8eecf35d056578346a5365015fd7d8623df9b1f08d1c74769c01", size = 24958, upload-time = "2025-12-11T13:36:59.35Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/7d/cc/6e808328ba54662e50babdcab21138eae4250bc0fddf67d55526a615a2ca/opentelemetry_instrumentation_fastapi-0.60b1-py3-none-any.whl", hash = "sha256:af94b7a239ad1085fc3a820ecf069f67f579d7faf4c085aaa7bd9b64eafc8eaf", size = 13478, upload-time = "2025-12-11T13:36:00.811Z" },
+]
+
+[[package]]
+name = "opentelemetry-instrumentation-httpx"
+version = "0.60b1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "opentelemetry-api" },
+ { name = "opentelemetry-instrumentation" },
+ { name = "opentelemetry-semantic-conventions" },
+ { name = "opentelemetry-util-http" },
+ { name = "wrapt" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/86/08/11208bcfcab4fc2023252c3f322aa397fd9ad948355fea60f5fc98648603/opentelemetry_instrumentation_httpx-0.60b1.tar.gz", hash = "sha256:a506ebaf28c60112cbe70ad4f0338f8603f148938cb7b6794ce1051cd2b270ae", size = 20611, upload-time = "2025-12-11T13:37:01.661Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/43/59/b98e84eebf745ffc75397eaad4763795bff8a30cbf2373a50ed4e70646c5/opentelemetry_instrumentation_httpx-0.60b1-py3-none-any.whl", hash = "sha256:f37636dd742ad2af83d896ba69601ed28da51fa4e25d1ab62fde89ce413e275b", size = 15701, upload-time = "2025-12-11T13:36:04.56Z" },
+]
+
+[[package]]
+name = "opentelemetry-instrumentation-redis"
+version = "0.60b1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "opentelemetry-api" },
+ { name = "opentelemetry-instrumentation" },
+ { name = "opentelemetry-semantic-conventions" },
+ { name = "wrapt" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/6a/1e/225364fab4db793f6f5024ed9f3dd53774fd7c7c21fa242460234dcdf8d9/opentelemetry_instrumentation_redis-0.60b1.tar.gz", hash = "sha256:ecafa8f81c88917b59f0d842fb3d157f3a8edc71fb4b85bebca3bc19432ce7b8", size = 14774, upload-time = "2025-12-11T13:37:11.201Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/05/bd/d55d3b34fd49df08d9d9fa3701dff0051b216e2c7e9adaaa4ff6aa1de8d7/opentelemetry_instrumentation_redis-0.60b1-py3-none-any.whl", hash = "sha256:33bef0ff9af6f2d88de90c1cd7e25675c10a16d4f9ee5ae7592b28bb08b78139", size = 15502, upload-time = "2025-12-11T13:36:21.481Z" },
+]
+
+[[package]]
+name = "opentelemetry-proto"
+version = "1.39.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "protobuf" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/49/1d/f25d76d8260c156c40c97c9ed4511ec0f9ce353f8108ca6e7561f82a06b2/opentelemetry_proto-1.39.1.tar.gz", hash = "sha256:6c8e05144fc0d3ed4d22c2289c6b126e03bcd0e6a7da0f16cedd2e1c2772e2c8", size = 46152, upload-time = "2025-12-11T13:32:48.681Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/51/95/b40c96a7b5203005a0b03d8ce8cd212ff23f1793d5ba289c87a097571b18/opentelemetry_proto-1.39.1-py3-none-any.whl", hash = "sha256:22cdc78efd3b3765d09e68bfbd010d4fc254c9818afd0b6b423387d9dee46007", size = 72535, upload-time = "2025-12-11T13:32:33.866Z" },
+]
+
+[[package]]
+name = "opentelemetry-sdk"
+version = "1.39.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "opentelemetry-api" },
+ { name = "opentelemetry-semantic-conventions" },
+ { name = "typing-extensions" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/eb/fb/c76080c9ba07e1e8235d24cdcc4d125ef7aa3edf23eb4e497c2e50889adc/opentelemetry_sdk-1.39.1.tar.gz", hash = "sha256:cf4d4563caf7bff906c9f7967e2be22d0d6b349b908be0d90fb21c8e9c995cc6", size = 171460, upload-time = "2025-12-11T13:32:49.369Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/7c/98/e91cf858f203d86f4eccdf763dcf01cf03f1dae80c3750f7e635bfa206b6/opentelemetry_sdk-1.39.1-py3-none-any.whl", hash = "sha256:4d5482c478513ecb0a5d938dcc61394e647066e0cc2676bee9f3af3f3f45f01c", size = 132565, upload-time = "2025-12-11T13:32:35.069Z" },
+]
+
+[[package]]
+name = "opentelemetry-semantic-conventions"
+version = "0.60b1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "opentelemetry-api" },
+ { name = "typing-extensions" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/91/df/553f93ed38bf22f4b999d9be9c185adb558982214f33eae539d3b5cd0858/opentelemetry_semantic_conventions-0.60b1.tar.gz", hash = "sha256:87c228b5a0669b748c76d76df6c364c369c28f1c465e50f661e39737e84bc953", size = 137935, upload-time = "2025-12-11T13:32:50.487Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/7a/5e/5958555e09635d09b75de3c4f8b9cae7335ca545d77392ffe7331534c402/opentelemetry_semantic_conventions-0.60b1-py3-none-any.whl", hash = "sha256:9fa8c8b0c110da289809292b0591220d3a7b53c1526a23021e977d68597893fb", size = 219982, upload-time = "2025-12-11T13:32:36.955Z" },
+]
+
+[[package]]
+name = "opentelemetry-util-http"
+version = "0.60b1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/50/fc/c47bb04a1d8a941a4061307e1eddfa331ed4d0ab13d8a9781e6db256940a/opentelemetry_util_http-0.60b1.tar.gz", hash = "sha256:0d97152ca8c8a41ced7172d29d3622a219317f74ae6bb3027cfbdcf22c3cc0d6", size = 11053, upload-time = "2025-12-11T13:37:25.115Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/16/5c/d3f1733665f7cd582ef0842fb1d2ed0bc1fba10875160593342d22bba375/opentelemetry_util_http-0.60b1-py3-none-any.whl", hash = "sha256:66381ba28550c91bee14dcba8979ace443444af1ed609226634596b4b0faf199", size = 8947, upload-time = "2025-12-11T13:36:37.151Z" },
+]
+
[[package]]
name = "orjson"
version = "3.11.8"
diff --git a/eslint-suppressions.json b/eslint-suppressions.json
index dd17f02f97c..99b50aeb1a3 100644
--- a/eslint-suppressions.json
+++ b/eslint-suppressions.json
@@ -886,11 +886,6 @@
"count": 1
}
},
- "web/app/components/app/overview/customize/index.tsx": {
- "jsx-a11y/anchor-has-content": {
- "count": 3
- }
- },
"web/app/components/app/overview/workflow-hidden-input-fields.tsx": {
"no-restricted-imports": {
"count": 1
@@ -1203,14 +1198,6 @@
"count": 1
}
},
- "web/app/components/base/chat/chat/chat-input-area/index.tsx": {
- "jsx-a11y/no-autofocus": {
- "count": 1
- },
- "ts/no-explicit-any": {
- "count": 3
- }
- },
"web/app/components/base/chat/chat/check-input-forms-hooks.ts": {
"ts/no-explicit-any": {
"count": 1
@@ -1241,14 +1228,6 @@
"count": 17
}
},
- "web/app/components/base/chat/chat/index.tsx": {
- "ts/no-explicit-any": {
- "count": 2
- },
- "ts/no-non-null-asserted-optional-chain": {
- "count": 1
- }
- },
"web/app/components/base/chat/chat/log/index.tsx": {
"jsx-a11y/click-events-have-key-events": {
"count": 1
@@ -4554,9 +4533,6 @@
"web/app/components/workflow-app/hooks/use-nodes-sync-draft.ts": {
"no-restricted-imports": {
"count": 1
- },
- "ts/no-explicit-any": {
- "count": 2
}
},
"web/app/components/workflow-app/hooks/use-workflow-init.ts": {
@@ -6283,9 +6259,6 @@
"web/app/components/workflow/operator/add-block.tsx": {
"no-restricted-imports": {
"count": 1
- },
- "ts/no-explicit-any": {
- "count": 1
}
},
"web/app/components/workflow/operator/hooks.ts": {
diff --git a/packages/contracts/generated/api/console/agent/orpc.gen.ts b/packages/contracts/generated/api/console/agent/orpc.gen.ts
index 5e4a692f244..f8f9ccaa785 100644
--- a/packages/contracts/generated/api/console/agent/orpc.gen.ts
+++ b/packages/contracts/generated/api/console/agent/orpc.gen.ts
@@ -6,6 +6,8 @@ import * as z from 'zod'
import {
zDeleteAgentByAgentIdApiKeysByApiKeyIdPath,
zDeleteAgentByAgentIdApiKeysByApiKeyIdResponse,
+ zDeleteAgentByAgentIdBuildDraftPath,
+ zDeleteAgentByAgentIdBuildDraftResponse,
zDeleteAgentByAgentIdFilesPath,
zDeleteAgentByAgentIdFilesQuery,
zDeleteAgentByAgentIdFilesResponse,
@@ -17,6 +19,8 @@ import {
zGetAgentByAgentIdApiAccessResponse,
zGetAgentByAgentIdApiKeysPath,
zGetAgentByAgentIdApiKeysResponse,
+ zGetAgentByAgentIdBuildDraftPath,
+ zGetAgentByAgentIdBuildDraftResponse,
zGetAgentByAgentIdChatMessagesByMessageIdSuggestedQuestionsPath,
zGetAgentByAgentIdChatMessagesByMessageIdSuggestedQuestionsResponse,
zGetAgentByAgentIdChatMessagesPath,
@@ -76,6 +80,11 @@ import {
zPostAgentByAgentIdApiEnableResponse,
zPostAgentByAgentIdApiKeysPath,
zPostAgentByAgentIdApiKeysResponse,
+ zPostAgentByAgentIdBuildDraftApplyPath,
+ zPostAgentByAgentIdBuildDraftApplyResponse,
+ zPostAgentByAgentIdBuildDraftCheckoutBody,
+ zPostAgentByAgentIdBuildDraftCheckoutPath,
+ zPostAgentByAgentIdBuildDraftCheckoutResponse,
zPostAgentByAgentIdChatMessagesByTaskIdStopPath,
zPostAgentByAgentIdChatMessagesByTaskIdStopResponse,
zPostAgentByAgentIdComposerValidateBody,
@@ -95,6 +104,9 @@ import {
zPostAgentByAgentIdFilesBody,
zPostAgentByAgentIdFilesPath,
zPostAgentByAgentIdFilesResponse,
+ zPostAgentByAgentIdPublishBody,
+ zPostAgentByAgentIdPublishPath,
+ zPostAgentByAgentIdPublishResponse,
zPostAgentByAgentIdSandboxFilesUploadBody,
zPostAgentByAgentIdSandboxFilesUploadPath,
zPostAgentByAgentIdSandboxFilesUploadResponse,
@@ -107,6 +119,9 @@ import {
zPostAgentByAgentIdVersionsByVersionIdRestoreResponse,
zPostAgentResponse,
zPutAgentByAgentIdBody,
+ zPutAgentByAgentIdBuildDraftBody,
+ zPutAgentByAgentIdBuildDraftPath,
+ zPutAgentByAgentIdBuildDraftResponse,
zPutAgentByAgentIdComposerBody,
zPutAgentByAgentIdComposerPath,
zPutAgentByAgentIdComposerResponse,
@@ -206,10 +221,88 @@ export const apiKeys = {
byApiKeyId,
}
+export const post3 = oc
+ .route({
+ inputStructure: 'detailed',
+ method: 'POST',
+ operationId: 'postAgentByAgentIdBuildDraftApply',
+ path: '/agent/{agent_id}/build-draft/apply',
+ tags: ['console'],
+ })
+ .input(z.object({ params: zPostAgentByAgentIdBuildDraftApplyPath }))
+ .output(zPostAgentByAgentIdBuildDraftApplyResponse)
+
+export const apply = {
+ post: post3,
+}
+
+export const post4 = oc
+ .route({
+ inputStructure: 'detailed',
+ method: 'POST',
+ operationId: 'postAgentByAgentIdBuildDraftCheckout',
+ path: '/agent/{agent_id}/build-draft/checkout',
+ tags: ['console'],
+ })
+ .input(
+ z.object({
+ body: zPostAgentByAgentIdBuildDraftCheckoutBody,
+ params: zPostAgentByAgentIdBuildDraftCheckoutPath,
+ }),
+ )
+ .output(zPostAgentByAgentIdBuildDraftCheckoutResponse)
+
+export const checkout = {
+ post: post4,
+}
+
+export const delete2 = oc
+ .route({
+ inputStructure: 'detailed',
+ method: 'DELETE',
+ operationId: 'deleteAgentByAgentIdBuildDraft',
+ path: '/agent/{agent_id}/build-draft',
+ tags: ['console'],
+ })
+ .input(z.object({ params: zDeleteAgentByAgentIdBuildDraftPath }))
+ .output(zDeleteAgentByAgentIdBuildDraftResponse)
+
+export const get4 = oc
+ .route({
+ inputStructure: 'detailed',
+ method: 'GET',
+ operationId: 'getAgentByAgentIdBuildDraft',
+ path: '/agent/{agent_id}/build-draft',
+ tags: ['console'],
+ })
+ .input(z.object({ params: zGetAgentByAgentIdBuildDraftPath }))
+ .output(zGetAgentByAgentIdBuildDraftResponse)
+
+export const put = oc
+ .route({
+ inputStructure: 'detailed',
+ method: 'PUT',
+ operationId: 'putAgentByAgentIdBuildDraft',
+ path: '/agent/{agent_id}/build-draft',
+ tags: ['console'],
+ })
+ .input(
+ z.object({ body: zPutAgentByAgentIdBuildDraftBody, params: zPutAgentByAgentIdBuildDraftPath }),
+ )
+ .output(zPutAgentByAgentIdBuildDraftResponse)
+
+export const buildDraft = {
+ delete: delete2,
+ get: get4,
+ put,
+ apply,
+ checkout,
+}
+
/**
* Get suggested questions for an Agent App message
*/
-export const get4 = oc
+export const get5 = oc
.route({
description: 'Get suggested questions for an Agent App message',
inputStructure: 'detailed',
@@ -222,7 +315,7 @@ export const get4 = oc
.output(zGetAgentByAgentIdChatMessagesByMessageIdSuggestedQuestionsResponse)
export const suggestedQuestions = {
- get: get4,
+ get: get5,
}
export const byMessageId = {
@@ -232,7 +325,7 @@ export const byMessageId = {
/**
* Stop a running Agent App chat message generation
*/
-export const post3 = oc
+export const post5 = oc
.route({
description: 'Stop a running Agent App chat message generation',
inputStructure: 'detailed',
@@ -245,7 +338,7 @@ export const post3 = oc
.output(zPostAgentByAgentIdChatMessagesByTaskIdStopResponse)
export const stop = {
- post: post3,
+ post: post5,
}
export const byTaskId = {
@@ -255,7 +348,7 @@ export const byTaskId = {
/**
* Get Agent App chat messages for a conversation with pagination
*/
-export const get5 = oc
+export const get6 = oc
.route({
description: 'Get Agent App chat messages for a conversation with pagination',
inputStructure: 'detailed',
@@ -273,12 +366,12 @@ export const get5 = oc
.output(zGetAgentByAgentIdChatMessagesResponse)
export const chatMessages = {
- get: get5,
+ get: get6,
byMessageId,
byTaskId,
}
-export const get6 = oc
+export const get7 = oc
.route({
inputStructure: 'detailed',
method: 'GET',
@@ -290,10 +383,10 @@ export const get6 = oc
.output(zGetAgentByAgentIdComposerCandidatesResponse)
export const candidates = {
- get: get6,
+ get: get7,
}
-export const post4 = oc
+export const post6 = oc
.route({
inputStructure: 'detailed',
method: 'POST',
@@ -310,10 +403,10 @@ export const post4 = oc
.output(zPostAgentByAgentIdComposerValidateResponse)
export const validate = {
- post: post4,
+ post: post6,
}
-export const get7 = oc
+export const get8 = oc
.route({
inputStructure: 'detailed',
method: 'GET',
@@ -324,7 +417,7 @@ export const get7 = oc
.input(z.object({ params: zGetAgentByAgentIdComposerPath }))
.output(zGetAgentByAgentIdComposerResponse)
-export const put = oc
+export const put2 = oc
.route({
inputStructure: 'detailed',
method: 'PUT',
@@ -336,13 +429,13 @@ export const put = oc
.output(zPutAgentByAgentIdComposerResponse)
export const composer = {
- get: get7,
- put,
+ get: get8,
+ put: put2,
candidates,
validate,
}
-export const post5 = oc
+export const post7 = oc
.route({
inputStructure: 'detailed',
method: 'POST',
@@ -355,10 +448,10 @@ export const post5 = oc
.output(zPostAgentByAgentIdCopyResponse)
export const copy = {
- post: post5,
+ post: post7,
}
-export const post6 = oc
+export const post8 = oc
.route({
inputStructure: 'detailed',
method: 'POST',
@@ -370,7 +463,7 @@ export const post6 = oc
.output(zPostAgentByAgentIdDebugConversationRefreshResponse)
export const refresh = {
- post: post6,
+ post: post8,
}
export const debugConversation = {
@@ -380,7 +473,7 @@ export const debugConversation = {
/**
* Time-limited external signed URL for one Agent App drive value
*/
-export const get8 = oc
+export const get9 = oc
.route({
description: 'Time-limited external signed URL for one Agent App drive value',
inputStructure: 'detailed',
@@ -398,13 +491,13 @@ export const get8 = oc
.output(zGetAgentByAgentIdDriveFilesDownloadResponse)
export const download = {
- get: get8,
+ get: get9,
}
/**
* Truncated text preview of one Agent App drive value
*/
-export const get9 = oc
+export const get10 = oc
.route({
description: 'Truncated text preview of one Agent App drive value',
inputStructure: 'detailed',
@@ -422,13 +515,13 @@ export const get9 = oc
.output(zGetAgentByAgentIdDriveFilesPreviewResponse)
export const preview = {
- get: get9,
+ get: get10,
}
/**
* List agent drive entries for an Agent App
*/
-export const get10 = oc
+export const get11 = oc
.route({
description: 'List agent drive entries for an Agent App',
inputStructure: 'detailed',
@@ -446,7 +539,7 @@ export const get10 = oc
.output(zGetAgentByAgentIdDriveFilesResponse)
export const files = {
- get: get10,
+ get: get11,
download,
preview,
}
@@ -454,7 +547,7 @@ export const files = {
/**
* Inspect one drive-backed skill for slash-menu hover/detail UI
*/
-export const get11 = oc
+export const get12 = oc
.route({
description: 'Inspect one drive-backed skill for slash-menu hover/detail UI',
inputStructure: 'detailed',
@@ -467,7 +560,7 @@ export const get11 = oc
.output(zGetAgentByAgentIdDriveSkillsBySkillPathInspectResponse)
export const inspect = {
- get: get11,
+ get: get12,
}
export const bySkillPath = {
@@ -477,7 +570,7 @@ export const bySkillPath = {
/**
* List drive-backed skills for an Agent App
*/
-export const get12 = oc
+export const get13 = oc
.route({
description: 'List drive-backed skills for an Agent App',
inputStructure: 'detailed',
@@ -490,7 +583,7 @@ export const get12 = oc
.output(zGetAgentByAgentIdDriveSkillsResponse)
export const skills = {
- get: get12,
+ get: get13,
bySkillPath,
}
@@ -502,7 +595,7 @@ export const drive = {
/**
* Update an Agent App's presentation features (opener, follow-up, citations, ...)
*/
-export const post7 = oc
+export const post9 = oc
.route({
description: 'Update an Agent App\'s presentation features (opener, follow-up, citations, ...)',
inputStructure: 'detailed',
@@ -517,13 +610,13 @@ export const post7 = oc
.output(zPostAgentByAgentIdFeaturesResponse)
export const features = {
- post: post7,
+ post: post9,
}
/**
* Create or update Agent App message feedback
*/
-export const post8 = oc
+export const post10 = oc
.route({
description: 'Create or update Agent App message feedback',
inputStructure: 'detailed',
@@ -538,13 +631,13 @@ export const post8 = oc
.output(zPostAgentByAgentIdFeedbacksResponse)
export const feedbacks = {
- post: post8,
+ post: post10,
}
/**
* Delete one Agent App drive file by key
*/
-export const delete2 = oc
+export const delete3 = oc
.route({
description: 'Delete one Agent App drive file by key',
inputStructure: 'detailed',
@@ -561,7 +654,7 @@ export const delete2 = oc
/**
* Commit an uploaded file into the Agent App drive under files/<name>
*/
-export const post9 = oc
+export const post11 = oc
.route({
description: 'Commit an uploaded file into the Agent App drive under files/<name>',
inputStructure: 'detailed',
@@ -575,11 +668,11 @@ export const post9 = oc
.output(zPostAgentByAgentIdFilesResponse)
export const files2 = {
- delete: delete2,
- post: post9,
+ delete: delete3,
+ post: post11,
}
-export const get13 = oc
+export const get14 = oc
.route({
inputStructure: 'detailed',
method: 'GET',
@@ -591,10 +684,10 @@ export const get13 = oc
.output(zGetAgentByAgentIdLogSourcesResponse)
export const logSources = {
- get: get13,
+ get: get14,
}
-export const get14 = oc
+export const get15 = oc
.route({
inputStructure: 'detailed',
method: 'GET',
@@ -611,14 +704,14 @@ export const get14 = oc
.output(zGetAgentByAgentIdLogsByConversationIdMessagesResponse)
export const messages = {
- get: get14,
+ get: get15,
}
export const byConversationId = {
messages,
}
-export const get15 = oc
+export const get16 = oc
.route({
inputStructure: 'detailed',
method: 'GET',
@@ -632,14 +725,14 @@ export const get15 = oc
.output(zGetAgentByAgentIdLogsResponse)
export const logs = {
- get: get15,
+ get: get16,
byConversationId,
}
/**
* Get Agent App message details by ID
*/
-export const get16 = oc
+export const get17 = oc
.route({
description: 'Get Agent App message details by ID',
inputStructure: 'detailed',
@@ -652,17 +745,32 @@ export const get16 = oc
.output(zGetAgentByAgentIdMessagesByMessageIdResponse)
export const byMessageId2 = {
- get: get16,
+ get: get17,
}
export const messages2 = {
byMessageId: byMessageId2,
}
+export const post12 = oc
+ .route({
+ inputStructure: 'detailed',
+ method: 'POST',
+ operationId: 'postAgentByAgentIdPublish',
+ path: '/agent/{agent_id}/publish',
+ tags: ['console'],
+ })
+ .input(z.object({ body: zPostAgentByAgentIdPublishBody, params: zPostAgentByAgentIdPublishPath }))
+ .output(zPostAgentByAgentIdPublishResponse)
+
+export const publish = {
+ post: post12,
+}
+
/**
* List workflow apps that reference this Agent App's bound Agent (read-only)
*/
-export const get17 = oc
+export const get18 = oc
.route({
description: 'List workflow apps that reference this Agent App\'s bound Agent (read-only)',
inputStructure: 'detailed',
@@ -675,13 +783,13 @@ export const get17 = oc
.output(zGetAgentByAgentIdReferencingWorkflowsResponse)
export const referencingWorkflows = {
- get: get17,
+ get: get18,
}
/**
* Read a text/binary preview file in an Agent App conversation sandbox
*/
-export const get18 = oc
+export const get19 = oc
.route({
description: 'Read a text/binary preview file in an Agent App conversation sandbox',
inputStructure: 'detailed',
@@ -699,13 +807,13 @@ export const get18 = oc
.output(zGetAgentByAgentIdSandboxFilesReadResponse)
export const read = {
- get: get18,
+ get: get19,
}
/**
* Upload one Agent App sandbox file as a Dify ToolFile mapping
*/
-export const post10 = oc
+export const post13 = oc
.route({
description: 'Upload one Agent App sandbox file as a Dify ToolFile mapping',
inputStructure: 'detailed',
@@ -723,13 +831,13 @@ export const post10 = oc
.output(zPostAgentByAgentIdSandboxFilesUploadResponse)
export const upload = {
- post: post10,
+ post: post13,
}
/**
* List a directory in an Agent App conversation sandbox
*/
-export const get19 = oc
+export const get20 = oc
.route({
description: 'List a directory in an Agent App conversation sandbox',
inputStructure: 'detailed',
@@ -747,7 +855,7 @@ export const get19 = oc
.output(zGetAgentByAgentIdSandboxFilesResponse)
export const files3 = {
- get: get19,
+ get: get20,
read,
upload,
}
@@ -759,7 +867,7 @@ export const sandbox = {
/**
* Upload + standardize a Skill into an Agent App drive
*/
-export const post11 = oc
+export const post14 = oc
.route({
description: 'Upload + standardize a Skill into an Agent App drive',
inputStructure: 'detailed',
@@ -778,13 +886,13 @@ export const post11 = oc
.output(zPostAgentByAgentIdSkillsUploadResponse)
export const upload2 = {
- post: post11,
+ post: post14,
}
/**
* Infer CLI tool + ENV suggestions from a standardized Agent App skill
*/
-export const post12 = oc
+export const post15 = oc
.route({
description: 'Infer CLI tool + ENV suggestions from a standardized Agent App skill',
inputStructure: 'detailed',
@@ -797,13 +905,13 @@ export const post12 = oc
.output(zPostAgentByAgentIdSkillsBySlugInferToolsResponse)
export const inferTools = {
- post: post12,
+ post: post15,
}
/**
* Delete a standardized skill from an Agent App drive
*/
-export const delete3 = oc
+export const delete4 = oc
.route({
description: 'Delete a standardized skill from an Agent App drive',
inputStructure: 'detailed',
@@ -816,7 +924,7 @@ export const delete3 = oc
.output(zDeleteAgentByAgentIdSkillsBySlugResponse)
export const bySlug = {
- delete: delete3,
+ delete: delete4,
inferTools,
}
@@ -825,7 +933,7 @@ export const skills2 = {
bySlug,
}
-export const get20 = oc
+export const get21 = oc
.route({
inputStructure: 'detailed',
method: 'GET',
@@ -842,14 +950,14 @@ export const get20 = oc
.output(zGetAgentByAgentIdStatisticsSummaryResponse)
export const summary = {
- get: get20,
+ get: get21,
}
export const statistics = {
summary,
}
-export const post13 = oc
+export const post16 = oc
.route({
inputStructure: 'detailed',
method: 'POST',
@@ -861,10 +969,10 @@ export const post13 = oc
.output(zPostAgentByAgentIdVersionsByVersionIdRestoreResponse)
export const restore = {
- post: post13,
+ post: post16,
}
-export const get21 = oc
+export const get22 = oc
.route({
inputStructure: 'detailed',
method: 'GET',
@@ -876,11 +984,11 @@ export const get21 = oc
.output(zGetAgentByAgentIdVersionsByVersionIdResponse)
export const byVersionId = {
- get: get21,
+ get: get22,
restore,
}
-export const get22 = oc
+export const get23 = oc
.route({
inputStructure: 'detailed',
method: 'GET',
@@ -892,11 +1000,11 @@ export const get22 = oc
.output(zGetAgentByAgentIdVersionsResponse)
export const versions = {
- get: get22,
+ get: get23,
byVersionId,
}
-export const delete4 = oc
+export const delete5 = oc
.route({
inputStructure: 'detailed',
method: 'DELETE',
@@ -908,7 +1016,7 @@ export const delete4 = oc
.input(z.object({ params: zDeleteAgentByAgentIdPath }))
.output(zDeleteAgentByAgentIdResponse)
-export const get23 = oc
+export const get24 = oc
.route({
inputStructure: 'detailed',
method: 'GET',
@@ -919,7 +1027,7 @@ export const get23 = oc
.input(z.object({ params: zGetAgentByAgentIdPath }))
.output(zGetAgentByAgentIdResponse)
-export const put2 = oc
+export const put3 = oc
.route({
inputStructure: 'detailed',
method: 'PUT',
@@ -931,12 +1039,13 @@ export const put2 = oc
.output(zPutAgentByAgentIdResponse)
export const byAgentId = {
- delete: delete4,
- get: get23,
- put: put2,
+ delete: delete5,
+ get: get24,
+ put: put3,
apiAccess,
apiEnable,
apiKeys,
+ buildDraft,
chatMessages,
composer,
copy,
@@ -948,6 +1057,7 @@ export const byAgentId = {
logSources,
logs,
messages: messages2,
+ publish,
referencingWorkflows,
sandbox,
skills: skills2,
@@ -955,7 +1065,7 @@ export const byAgentId = {
versions,
}
-export const get24 = oc
+export const get25 = oc
.route({
inputStructure: 'detailed',
method: 'GET',
@@ -966,7 +1076,7 @@ export const get24 = oc
.input(z.object({ query: zGetAgentQuery.optional() }))
.output(zGetAgentResponse)
-export const post14 = oc
+export const post17 = oc
.route({
inputStructure: 'detailed',
method: 'POST',
@@ -979,8 +1089,8 @@ export const post14 = oc
.output(zPostAgentResponse)
export const agent = {
- get: get24,
- post: post14,
+ get: get25,
+ post: post17,
inviteOptions,
byAgentId,
}
diff --git a/packages/contracts/generated/api/console/agent/types.gen.ts b/packages/contracts/generated/api/console/agent/types.gen.ts
index 60f760ca76e..bd4918a22ce 100644
--- a/packages/contracts/generated/api/console/agent/types.gen.ts
+++ b/packages/contracts/generated/api/console/agent/types.gen.ts
@@ -26,6 +26,7 @@ export type AgentAppDetailWithSite = {
active_config_is_published?: boolean
api_base_url?: string | null
app_id?: string | null
+ backing_app_id?: string | null
bound_agent_id?: string | null
created_at?: number | null
created_by?: string | null
@@ -34,6 +35,7 @@ export type AgentAppDetailWithSite = {
description?: string | null
enable_api: boolean
enable_site: boolean
+ hidden_app_backed?: boolean
icon?: string | null
icon_background?: string | null
icon_type?: string | null
@@ -46,7 +48,7 @@ export type AgentAppDetailWithSite = {
name: string
permission_keys?: Array<string>
role?: string | null
- site?: Site | null
+ site?: AppDetailSiteResponse | null
tags?: Array<Tag>
tracing?: JsonValue | null
updated_at?: number | null
@@ -107,27 +109,18 @@ export type ApiKeyItem = {
type: string
}
-export type MessageInfiniteScrollPaginationResponse = {
- data: Array<MessageDetailResponse>
- has_more: boolean
- limit: number
-}
-
-export type SuggestedQuestionsResponse = {
- data: Array<string>
-}
-
-export type SimpleResultResponse = {
+export type AgentSimpleResultResponse = {
result: string
}
-export type AgentAppComposerResponse = {
- active_config_snapshot: AgentConfigSnapshotSummaryResponse
- agent: AgentComposerAgentResponse
- agent_soul: AgentSoulConfig
- save_options: Array<ComposerSaveStrategy>
- validation?: ComposerValidationFindingsResponse | null
- variant: 'agent_app'
+export type AgentBuildDraftResponse = {
+ agent_soul: {
+ [key: string]: unknown
+ }
+ draft: {
+ [key: string]: unknown
+ }
+ variant: string
}
export type ComposerSavePayload = {
@@ -148,6 +141,45 @@ export type ComposerSavePayload = {
version_note?: string | null
}
+export type AgentBuildDraftApplyResponse = {
+ draft: {
+ [key: string]: unknown
+ }
+ result: string
+}
+
+export type AgentBuildDraftCheckoutPayload = {
+ force?: boolean
+}
+
+export type MessageInfiniteScrollPaginationResponse = {
+ data: Array<MessageDetailResponse>
+ has_more: boolean
+ limit: number
+}
+
+export type SuggestedQuestionsResponse = {
+ data: Array<string>
+}
+
+export type SimpleResultResponse = {
+ result: string
+}
+
+export type AgentAppComposerResponse = {
+ active_config_snapshot?: AgentConfigSnapshotSummaryResponse | null
+ agent: AgentComposerAgentResponse
+ agent_soul: AgentSoulConfig
+ app_id?: string | null
+ backing_app_id?: string | null
+ chat_endpoint?: string | null
+ draft?: AgentConfigDraftSummaryResponse | null
+ hidden_app_backed?: boolean
+ save_options: Array<ComposerSaveStrategy>
+ validation?: ComposerValidationFindingsResponse | null
+ variant: 'agent_app'
+}
+
export type AgentComposerCandidatesResponse = {
allowed_node_job_candidates?: AgentComposerNodeJobCandidatesResponse
allowed_soul_candidates?: AgentComposerSoulCandidatesResponse
@@ -294,6 +326,21 @@ export type MessageDetailResponse = {
workflow_run_id?: string | null
}
+export type AgentPublishPayload = {
+ version_note?: string | null
+}
+
+export type AgentPublishResponse = {
+ active_config_snapshot?: {
+ [key: string]: unknown
+ } | null
+ active_config_snapshot_id: string
+ draft?: {
+ [key: string]: unknown
+ } | null
+ result: string
+}
+
export type AgentReferencingWorkflowsResponse = {
data?: Array<AgentReferencingWorkflowResponse>
}
@@ -359,6 +406,8 @@ export type AgentConfigSnapshotDetailResponse = {
export type AgentConfigSnapshotRestoreResponse = {
active_config_snapshot_id: string
+ draft_config_id?: string | null
+ restored_version_id?: string | null
result: 'success'
}
@@ -367,6 +416,7 @@ export type AgentAppPartial = {
active_config_is_published?: boolean
app_id?: string | null
author_name?: string | null
+ backing_app_id?: string | null
bound_agent_id?: string | null
create_user_name?: string | null
created_at?: number | null
@@ -374,6 +424,7 @@ export type AgentAppPartial = {
debug_conversation_id?: string | null
description?: string | null
has_draft_trigger?: boolean | null
+ hidden_app_backed?: boolean
icon?: string | null
icon_background?: string | null
icon_type?: string | null
@@ -413,22 +464,32 @@ export type ModelConfig = {
provider: string
}
-export type Site = {
+export type AppDetailSiteResponse = {
+ access_token?: string | null
+ app_base_url?: string | null
chat_color_theme?: string | null
- chat_color_theme_inverted: boolean
+ chat_color_theme_inverted?: boolean | null
+ code?: string | null
copyright?: string | null
+ created_at?: number | null
+ created_by?: string | null
custom_disclaimer?: string | null
- default_language: string
+ customize_domain?: string | null
+ customize_token_strategy?: string | null
+ default_language?: string | null
description?: string | null
icon?: string | null
icon_background?: string | null
- icon_type?: string | null
+ icon_type?: string | IconType | null
readonly icon_url: string | null
input_placeholder?: string | null
privacy_policy?: string | null
- show_workflow_steps: boolean
- title: string
- use_icon_as_answer_icon: boolean
+ prompt_public?: boolean | null
+ show_workflow_steps?: boolean | null
+ title?: string | null
+ updated_at?: number | null
+ updated_by?: string | null
+ use_icon_as_answer_icon?: boolean | null
}
export type Tag = {
@@ -464,10 +525,12 @@ export type AgentInviteOptionResponse = {
app_id?: string | null
archived_at?: number | null
archived_by?: string | null
+ backing_app_id?: string | null
created_at?: number | null
created_by?: string | null
description: string
existing_node_ids?: Array<string>
+ hidden_app_backed?: boolean
icon?: string | null
icon_background?: string | null
icon_type?: AgentIconType | null
@@ -488,31 +551,11 @@ export type AgentInviteOptionResponse = {
workflow_node_id?: string | null
}
-export type AgentConfigSnapshotSummaryResponse = {
- agent_id?: string | null
- created_at?: number | null
- created_by?: string | null
- display_version?: number | null
- id: string
- snapshot_version?: number | null
- summary?: string | null
- version: number
- version_note?: string | null
-}
-
-export type AgentComposerAgentResponse = {
- active_config_snapshot_id?: string | null
- description: string
- id: string
- name: string
- scope: AgentScope
- status: AgentStatus
-}
-
export type AgentSoulConfig = {
app_features?: AgentSoulAppFeaturesConfig
app_variables?: Array<AppVariableConfig>
env?: AgentSoulEnvConfig
+ files?: AgentSoulFilesConfig
human?: AgentSoulHumanConfig
knowledge?: AgentSoulKnowledgeConfig
memory?: AgentSoulMemoryConfig
@@ -524,18 +567,6 @@ export type AgentSoulConfig = {
tools?: AgentSoulToolsConfig
}
-export type ComposerSaveStrategy
- = | 'node_job_only'
- | 'save_as_new_agent'
- | 'save_as_new_version'
- | 'save_to_current_version'
- | 'save_to_roster'
-
-export type ComposerValidationFindingsResponse = {
- knowledge_retrieval_placeholder?: Array<ComposerKnowledgePlaceholderResponse>
- warnings?: Array<ComposerValidationWarningResponse>
-}
-
export type ComposerBindingPayload = {
agent_id?: string | null
binding_type: 'inline_agent' | 'roster_agent'
@@ -554,6 +585,13 @@ export type WorkflowNodeJobConfig = {
workflow_prompt?: string
}
+export type ComposerSaveStrategy
+ = | 'node_job_only'
+ | 'save_as_new_agent'
+ | 'save_as_new_version'
+ | 'save_to_current_version'
+ | 'save_to_roster'
+
export type ComposerSoulLockPayload = {
locked?: boolean
unlocked_from_version_id?: string | null
@@ -561,6 +599,52 @@ export type ComposerSoulLockPayload = {
export type ComposerVariant = 'agent_app' | 'workflow'
+export type AgentConfigSnapshotSummaryResponse = {
+ agent_id?: string | null
+ created_at?: number | null
+ created_by?: string | null
+ display_version?: number | null
+ id: string
+ snapshot_version?: number | null
+ summary?: string | null
+ version: number
+ version_note?: string | null
+}
+
+export type AgentComposerAgentResponse = {
+ active_config_snapshot_id?: string | null
+ app_id?: string | null
+ backing_app_id?: string | null
+ description: string
+ hidden_app_backed?: boolean
+ icon?: string | null
+ icon_background?: string | null
+ icon_type?: string | null
+ id: string
+ name: string
+ role?: string | null
+ scope: AgentScope
+ source?: AgentSource | null
+ status: AgentStatus
+}
+
+export type AgentConfigDraftSummaryResponse = {
+ account_id?: string | null
+ agent_id: string
+ base_snapshot_id?: string | null
+ created_at?: number | null
+ created_by?: string | null
+ draft_type: AgentConfigDraftType
+ id: string
+ updated_at?: number | null
+ updated_by?: string | null
+}
+
+export type ComposerValidationFindingsResponse = {
+ knowledge_retrieval_placeholder?: Array<ComposerKnowledgePlaceholderResponse>
+ warnings?: Array<ComposerValidationWarningResponse>
+}
+
export type AgentComposerNodeJobCandidatesResponse = {
declare_output_types?: Array<DeclaredOutputType>
human_contacts?: Array<AgentHumanContactConfig>
@@ -571,7 +655,7 @@ export type AgentComposerSoulCandidatesResponse = {
cli_tools?: Array<AgentCliToolConfig>
dify_tools?: Array<AgentComposerDifyToolCandidateResponse>
human_contacts?: Array<AgentHumanContactConfig>
- knowledge_datasets?: Array<AgentKnowledgeDatasetConfig>
+ knowledge_sets?: Array<AgentComposerKnowledgeSetCandidateResponse>
}
export type ComposerCandidateCapabilities = {
@@ -925,15 +1009,18 @@ export type AgentSoulEnvConfig = {
variables?: Array<AgentEnvVariableConfig>
}
+export type AgentSoulFilesConfig = {
+ files?: Array<AgentFileRefConfig>
+ skills?: Array<AgentSkillRefConfig>
+}
+
export type AgentSoulHumanConfig = {
contacts?: Array<AgentHumanContactConfig>
tools?: Array<AgentHumanToolConfig>
}
export type AgentSoulKnowledgeConfig = {
- datasets?: Array<AgentKnowledgeDatasetConfig>
- query_config?: AgentKnowledgeQueryConfig
- query_mode?: AgentKnowledgeQueryMode | null
+ sets?: Array<AgentKnowledgeSetConfig>
}
export type AgentSoulMemoryConfig = {
@@ -1030,6 +1117,8 @@ export type WorkflowPreviousNodeOutputRef = {
[key: string]: unknown
}
+export type AgentConfigDraftType = 'debug_build' | 'draft'
+
export type DeclaredOutputType = 'array' | 'boolean' | 'file' | 'number' | 'object' | 'string'
export type AgentCliToolConfig = {
@@ -1074,11 +1163,12 @@ export type AgentComposerDifyToolCandidateResponse = {
tools_count?: number | null
}
-export type AgentKnowledgeDatasetConfig = {
+export type AgentComposerKnowledgeSetCandidateResponse = {
+ datasets?: Array<AgentComposerKnowledgeDatasetCandidateResponse>
description?: string | null
- id?: string | null
- name?: string | null
- [key: string]: unknown
+ id: string
+ missing_dataset_ids?: Array<string>
+ name: string
}
export type AgentModerationProviderConfig = {
@@ -1173,6 +1263,7 @@ export type AgentUserSatisfactionRateStatisticResponse = {
export type AgentConfigRevisionOperation
= | 'create_version'
+ | 'publish_draft'
| 'restore_version'
| 'save_current_version'
| 'save_new_agent'
@@ -1226,22 +1317,51 @@ export type AgentEnvVariableConfig = {
[key: string]: unknown
}
-export type AgentHumanToolConfig = {
+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 AgentSkillRefConfig = {
description?: string | null
- enabled?: boolean
+ 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 AgentKnowledgeQueryConfig = {
- query?: string | null
- score_threshold?: number | null
- score_threshold_enabled?: boolean | null
- top_k?: number | null
+export type AgentHumanToolConfig = {
+ description?: string | null
+ enabled?: boolean
+ name?: string | null
[key: string]: unknown
}
-export type AgentKnowledgeQueryMode = 'generated_query' | 'user_query'
+export type AgentKnowledgeSetConfig = {
+ datasets: Array<AgentKnowledgeDatasetConfig>
+ description?: string | null
+ id: string
+ metadata_filtering?: AgentKnowledgeMetadataFilteringConfig
+ name: string
+ query: AgentKnowledgeQueryConfig
+ retrieval: AgentKnowledgeRetrievalConfig
+}
export type AgentMemoryArtifactConfig = {
id?: string | null
@@ -1343,21 +1463,6 @@ 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'
@@ -1381,6 +1486,13 @@ export type AgentPermissionConfig = {
export type AgentCliToolRiskLevel = 'dangerous' | 'safe' | 'unknown'
+export type AgentComposerKnowledgeDatasetCandidateResponse = {
+ description?: string | null
+ id?: string | null
+ missing?: boolean
+ name?: string | null
+}
+
export type AgentModerationIoConfig = {
enabled?: boolean
preset_response?: string | null
@@ -1409,6 +1521,34 @@ export type FormInputConfig
export type JsonValue2 = unknown
+export type AgentKnowledgeDatasetConfig = {
+ description?: string | null
+ id?: string | null
+ name?: string | null
+}
+
+export type AgentKnowledgeMetadataFilteringConfig = {
+ conditions?: AgentKnowledgeMetadataConditions | null
+ mode?: 'automatic' | 'disabled' | 'manual'
+ model_config?: AgentKnowledgeModelConfig | null
+}
+
+export type AgentKnowledgeQueryConfig = {
+ mode: AgentKnowledgeQueryMode
+ value?: string | null
+}
+
+export type AgentKnowledgeRetrievalConfig = {
+ mode: 'multiple' | 'single'
+ model?: AgentKnowledgeModelConfig | null
+ reranking_enable?: boolean
+ reranking_mode?: string
+ reranking_model?: AgentKnowledgeRerankingModelConfig | null
+ score_threshold?: number | null
+ top_k?: number | null
+ weights?: AgentKnowledgeWeightedScoreConfig | null
+}
+
export type AgentModelResponseFormatConfig = {
type?: string | null
[key: string]: unknown
@@ -1459,6 +1599,38 @@ export type FileListInputConfig = {
type?: 'file-list'
}
+export type AgentKnowledgeMetadataConditions = {
+ conditions?: Array<AgentKnowledgeMetadataCondition>
+ logical_operator?: 'and' | 'or'
+}
+
+export type AgentKnowledgeModelConfig = {
+ completion_params?: {
+ [key: string]: unknown
+ }
+ mode: string
+ name: string
+ provider: string
+}
+
+export type AgentKnowledgeQueryMode = 'generated_query' | 'user_query'
+
+export type AgentKnowledgeRerankingModelConfig = {
+ model: string
+ provider: string
+}
+
+export type AgentKnowledgeWeightedScoreConfig = {
+ keyword_setting?: {
+ [key: string]: unknown
+ } | null
+ vector_setting?: {
+ [key: string]: unknown
+ } | null
+ weight_type?: string | null
+ [key: string]: unknown
+}
+
export type StringSource = {
selector?: Array<string>
type: ValueSourceType
@@ -1475,6 +1647,30 @@ export type FileType = 'audio' | 'custom' | 'document' | 'image' | 'video'
export type FileTransferMethod = 'datasource_file' | 'local_file' | 'remote_url' | 'tool_file'
+export type AgentKnowledgeMetadataCondition = {
+ comparison_operator:
+ | '<'
+ | '='
+ | '>'
+ | 'after'
+ | 'before'
+ | 'contains'
+ | 'empty'
+ | 'end with'
+ | 'in'
+ | 'is'
+ | 'is not'
+ | 'not contains'
+ | 'not empty'
+ | 'not in'
+ | 'start with'
+ | '≠'
+ | '≤'
+ | '≥'
+ name: string
+ value?: string | Array<string> | number | null
+}
+
export type ValueSourceType = 'constant' | 'variable'
export type AgentAppPaginationWritable = {
@@ -1490,6 +1686,7 @@ export type AgentAppDetailWithSiteWritable = {
active_config_is_published?: boolean
api_base_url?: string | null
app_id?: string | null
+ backing_app_id?: string | null
bound_agent_id?: string | null
created_at?: number | null
created_by?: string | null
@@ -1498,6 +1695,7 @@ export type AgentAppDetailWithSiteWritable = {
description?: string | null
enable_api: boolean
enable_site: boolean
+ hidden_app_backed?: boolean
icon?: string | null
icon_background?: string | null
icon_type?: string | null
@@ -1509,7 +1707,7 @@ export type AgentAppDetailWithSiteWritable = {
name: string
permission_keys?: Array<string>
role?: string | null
- site?: SiteWritable | null
+ site?: AppDetailSiteResponseWritable | null
tags?: Array<Tag>
tracing?: JsonValue | null
updated_at?: number | null
@@ -1523,6 +1721,7 @@ export type AgentAppPartialWritable = {
active_config_is_published?: boolean
app_id?: string | null
author_name?: string | null
+ backing_app_id?: string | null
bound_agent_id?: string | null
create_user_name?: string | null
created_at?: number | null
@@ -1530,6 +1729,7 @@ export type AgentAppPartialWritable = {
debug_conversation_id?: string | null
description?: string | null
has_draft_trigger?: boolean | null
+ hidden_app_backed?: boolean
icon?: string | null
icon_background?: string | null
icon_type?: string | null
@@ -1551,21 +1751,31 @@ export type AgentAppPartialWritable = {
workflow?: WorkflowPartial | null
}
-export type SiteWritable = {
+export type AppDetailSiteResponseWritable = {
+ access_token?: string | null
+ app_base_url?: string | null
chat_color_theme?: string | null
- chat_color_theme_inverted: boolean
+ chat_color_theme_inverted?: boolean | null
+ code?: string | null
copyright?: string | null
+ created_at?: number | null
+ created_by?: string | null
custom_disclaimer?: string | null
- default_language: string
+ customize_domain?: string | null
+ customize_token_strategy?: string | null
+ default_language?: string | null
description?: string | null
icon?: string | null
icon_background?: string | null
- icon_type?: string | null
+ icon_type?: string | IconType | null
input_placeholder?: string | null
privacy_policy?: string | null
- show_workflow_steps: boolean
- title: string
- use_icon_as_answer_icon: boolean
+ prompt_public?: boolean | null
+ show_workflow_steps?: boolean | null
+ title?: string | null
+ updated_at?: number | null
+ updated_by?: string | null
+ use_icon_as_answer_icon?: boolean | null
}
export type GetAgentData = {
@@ -1779,6 +1989,86 @@ export type DeleteAgentByAgentIdApiKeysByApiKeyIdResponses = {
export type DeleteAgentByAgentIdApiKeysByApiKeyIdResponse
= DeleteAgentByAgentIdApiKeysByApiKeyIdResponses[keyof DeleteAgentByAgentIdApiKeysByApiKeyIdResponses]
+export type DeleteAgentByAgentIdBuildDraftData = {
+ body?: never
+ path: {
+ agent_id: string
+ }
+ query?: never
+ url: '/agent/{agent_id}/build-draft'
+}
+
+export type DeleteAgentByAgentIdBuildDraftResponses = {
+ 200: AgentSimpleResultResponse
+}
+
+export type DeleteAgentByAgentIdBuildDraftResponse
+ = DeleteAgentByAgentIdBuildDraftResponses[keyof DeleteAgentByAgentIdBuildDraftResponses]
+
+export type GetAgentByAgentIdBuildDraftData = {
+ body?: never
+ path: {
+ agent_id: string
+ }
+ query?: never
+ url: '/agent/{agent_id}/build-draft'
+}
+
+export type GetAgentByAgentIdBuildDraftResponses = {
+ 200: AgentBuildDraftResponse
+}
+
+export type GetAgentByAgentIdBuildDraftResponse
+ = GetAgentByAgentIdBuildDraftResponses[keyof GetAgentByAgentIdBuildDraftResponses]
+
+export type PutAgentByAgentIdBuildDraftData = {
+ body: ComposerSavePayload
+ path: {
+ agent_id: string
+ }
+ query?: never
+ url: '/agent/{agent_id}/build-draft'
+}
+
+export type PutAgentByAgentIdBuildDraftResponses = {
+ 200: AgentBuildDraftResponse
+}
+
+export type PutAgentByAgentIdBuildDraftResponse
+ = PutAgentByAgentIdBuildDraftResponses[keyof PutAgentByAgentIdBuildDraftResponses]
+
+export type PostAgentByAgentIdBuildDraftApplyData = {
+ body?: never
+ path: {
+ agent_id: string
+ }
+ query?: never
+ url: '/agent/{agent_id}/build-draft/apply'
+}
+
+export type PostAgentByAgentIdBuildDraftApplyResponses = {
+ 200: AgentBuildDraftApplyResponse
+}
+
+export type PostAgentByAgentIdBuildDraftApplyResponse
+ = PostAgentByAgentIdBuildDraftApplyResponses[keyof PostAgentByAgentIdBuildDraftApplyResponses]
+
+export type PostAgentByAgentIdBuildDraftCheckoutData = {
+ body: AgentBuildDraftCheckoutPayload
+ path: {
+ agent_id: string
+ }
+ query?: never
+ url: '/agent/{agent_id}/build-draft/checkout'
+}
+
+export type PostAgentByAgentIdBuildDraftCheckoutResponses = {
+ 200: AgentBuildDraftResponse
+}
+
+export type PostAgentByAgentIdBuildDraftCheckoutResponse
+ = PostAgentByAgentIdBuildDraftCheckoutResponses[keyof PostAgentByAgentIdBuildDraftCheckoutResponses]
+
export type GetAgentByAgentIdChatMessagesData = {
body?: never
path: {
@@ -2202,6 +2492,26 @@ export type GetAgentByAgentIdMessagesByMessageIdResponses = {
export type GetAgentByAgentIdMessagesByMessageIdResponse
= GetAgentByAgentIdMessagesByMessageIdResponses[keyof GetAgentByAgentIdMessagesByMessageIdResponses]
+export type PostAgentByAgentIdPublishData = {
+ body: AgentPublishPayload
+ path: {
+ agent_id: string
+ }
+ query?: never
+ url: '/agent/{agent_id}/publish'
+}
+
+export type PostAgentByAgentIdPublishErrors = {
+ 403: unknown
+}
+
+export type PostAgentByAgentIdPublishResponses = {
+ 200: AgentPublishResponse
+}
+
+export type PostAgentByAgentIdPublishResponse
+ = PostAgentByAgentIdPublishResponses[keyof PostAgentByAgentIdPublishResponses]
+
export type GetAgentByAgentIdReferencingWorkflowsData = {
body?: never
path: {
diff --git a/packages/contracts/generated/api/console/agent/zod.gen.ts b/packages/contracts/generated/api/console/agent/zod.gen.ts
index 1e188dd5e73..712f9c54a08 100644
--- a/packages/contracts/generated/api/console/agent/zod.gen.ts
+++ b/packages/contracts/generated/api/console/agent/zod.gen.ts
@@ -47,6 +47,37 @@ export const zApiKeyList = z.object({
data: z.array(zApiKeyItem),
})
+/**
+ * AgentSimpleResultResponse
+ */
+export const zAgentSimpleResultResponse = z.object({
+ result: z.string(),
+})
+
+/**
+ * AgentBuildDraftResponse
+ */
+export const zAgentBuildDraftResponse = z.object({
+ agent_soul: z.record(z.string(), z.unknown()),
+ draft: z.record(z.string(), z.unknown()),
+ variant: z.string(),
+})
+
+/**
+ * AgentBuildDraftApplyResponse
+ */
+export const zAgentBuildDraftApplyResponse = z.object({
+ draft: z.record(z.string(), z.unknown()),
+ result: z.string(),
+})
+
+/**
+ * AgentBuildDraftCheckoutPayload
+ */
+export const zAgentBuildDraftCheckoutPayload = z.object({
+ force: z.boolean().optional().default(false),
+})
+
/**
* SuggestedQuestionsResponse
*/
@@ -110,6 +141,23 @@ export const zAgentDriveFilePayload = z.object({
upload_file_id: z.string(),
})
+/**
+ * AgentPublishPayload
+ */
+export const zAgentPublishPayload = z.object({
+ version_note: z.string().nullish(),
+})
+
+/**
+ * AgentPublishResponse
+ */
+export const zAgentPublishResponse = z.object({
+ active_config_snapshot: z.record(z.string(), z.unknown()).nullish(),
+ active_config_snapshot_id: z.string(),
+ draft: z.record(z.string(), z.unknown()).nullish(),
+ result: z.string(),
+})
+
/**
* SandboxReadResponse
*/
@@ -134,6 +182,8 @@ export const zAgentSandboxUploadPayload = z.object({
*/
export const zAgentConfigSnapshotRestoreResponse = z.object({
active_config_snapshot_id: z.string(),
+ draft_config_id: z.string().nullish(),
+ restored_version_id: z.string().nullish(),
result: z.literal('success'),
})
@@ -190,24 +240,34 @@ export const zDeletedTool = z.object({
})
/**
- * Site
+ * AppDetailSiteResponse
*/
-export const zSite = z.object({
+export const zAppDetailSiteResponse = z.object({
+ access_token: z.string().nullish(),
+ app_base_url: z.string().nullish(),
chat_color_theme: z.string().nullish(),
- chat_color_theme_inverted: z.boolean(),
+ chat_color_theme_inverted: z.boolean().nullish(),
+ code: z.string().nullish(),
copyright: z.string().nullish(),
+ created_at: z.int().nullish(),
+ created_by: z.string().nullish(),
custom_disclaimer: z.string().nullish(),
- default_language: z.string(),
+ customize_domain: z.string().nullish(),
+ customize_token_strategy: z.string().nullish(),
+ default_language: z.string().nullish(),
description: z.string().nullish(),
icon: z.string().nullish(),
icon_background: z.string().nullish(),
- icon_type: z.string().nullish(),
+ icon_type: z.union([z.string(), zIconType]).nullish(),
icon_url: z.string().nullable(),
input_placeholder: z.string().nullish(),
privacy_policy: z.string().nullish(),
- show_workflow_steps: z.boolean(),
- title: z.string(),
- use_icon_as_answer_icon: z.boolean(),
+ prompt_public: z.boolean().nullish(),
+ show_workflow_steps: z.boolean().nullish(),
+ title: z.string().nullish(),
+ updated_at: z.int().nullish(),
+ updated_by: z.string().nullish(),
+ use_icon_as_answer_icon: z.boolean().nullish(),
})
/**
@@ -242,26 +302,20 @@ export const zWorkflowPartial = z.object({
})
/**
- * AgentConfigSnapshotSummaryResponse
+ * ComposerBindingPayload
*/
-export const zAgentConfigSnapshotSummaryResponse = z.object({
+export const zComposerBindingPayload = z.object({
agent_id: z.string().nullish(),
- created_at: z.int().nullish(),
- created_by: z.string().nullish(),
- display_version: z.int().nullish(),
- id: z.string(),
- snapshot_version: z.int().nullish(),
- summary: z.string().nullish(),
- version: z.int(),
- version_note: z.string().nullish(),
+ binding_type: z.enum(['inline_agent', 'roster_agent']),
+ current_snapshot_id: z.string().nullish(),
})
/**
- * AgentConfigSnapshotListResponse
+ * AgentIconType
+ *
+ * Supported icon storage formats for Agent roster entries.
*/
-export const zAgentConfigSnapshotListResponse = z.object({
- data: z.array(zAgentConfigSnapshotSummaryResponse),
-})
+export const zAgentIconType = z.enum(['emoji', 'image', 'link'])
/**
* ComposerSaveStrategy
@@ -275,33 +329,39 @@ export const zComposerSaveStrategy = z.enum([
])
/**
- * ComposerBindingPayload
+ * ComposerSoulLockPayload
*/
-export const zComposerBindingPayload = z.object({
- agent_id: z.string().nullish(),
- binding_type: z.enum(['inline_agent', 'roster_agent']),
- current_snapshot_id: z.string().nullish(),
+export const zComposerSoulLockPayload = z.object({
+ locked: z.boolean().optional().default(true),
+ unlocked_from_version_id: z.string().nullish(),
})
/**
- * AgentIconType
- *
- * Supported icon storage formats for Agent roster entries.
+ * ComposerVariant
*/
-export const zAgentIconType = z.enum(['emoji', 'image', 'link'])
+export const zComposerVariant = z.enum(['agent_app', 'workflow'])
/**
- * ComposerSoulLockPayload
+ * AgentConfigSnapshotSummaryResponse
*/
-export const zComposerSoulLockPayload = z.object({
- locked: z.boolean().optional().default(true),
- unlocked_from_version_id: z.string().nullish(),
+export const zAgentConfigSnapshotSummaryResponse = z.object({
+ agent_id: z.string().nullish(),
+ created_at: z.int().nullish(),
+ created_by: z.string().nullish(),
+ display_version: z.int().nullish(),
+ id: z.string(),
+ snapshot_version: z.int().nullish(),
+ summary: z.string().nullish(),
+ version: z.int(),
+ version_note: z.string().nullish(),
})
/**
- * ComposerVariant
+ * AgentConfigSnapshotListResponse
*/
-export const zComposerVariant = z.enum(['agent_app', 'workflow'])
+export const zAgentConfigSnapshotListResponse = z.object({
+ data: z.array(zAgentConfigSnapshotSummaryResponse),
+})
/**
* ComposerCandidateCapabilities
@@ -733,6 +793,7 @@ export const zAgentAppPartial = z.object({
active_config_is_published: z.boolean().optional().default(false),
app_id: z.string().nullish(),
author_name: z.string().nullish(),
+ backing_app_id: z.string().nullish(),
bound_agent_id: z.string().nullish(),
create_user_name: z.string().nullish(),
created_at: z.int().nullish(),
@@ -740,6 +801,7 @@ export const zAgentAppPartial = z.object({
debug_conversation_id: z.string().nullish(),
description: z.string().nullish(),
has_draft_trigger: z.boolean().nullish(),
+ hidden_app_backed: z.boolean().optional().default(false),
icon: z.string().nullish(),
icon_background: z.string().nullish(),
icon_type: z.string().nullish(),
@@ -798,6 +860,7 @@ export const zAgentAppDetailWithSite = z.object({
active_config_is_published: z.boolean().optional().default(false),
api_base_url: z.string().nullish(),
app_id: z.string().nullish(),
+ backing_app_id: z.string().nullish(),
bound_agent_id: z.string().nullish(),
created_at: z.int().nullish(),
created_by: z.string().nullish(),
@@ -806,6 +869,7 @@ export const zAgentAppDetailWithSite = z.object({
description: z.string().nullish(),
enable_api: z.boolean(),
enable_site: z.boolean(),
+ hidden_app_backed: z.boolean().optional().default(false),
icon: z.string().nullish(),
icon_background: z.string().nullish(),
icon_type: z.string().nullish(),
@@ -818,7 +882,7 @@ export const zAgentAppDetailWithSite = z.object({
name: z.string(),
permission_keys: z.array(z.string()).optional(),
role: z.string().nullish(),
- site: zSite.nullish(),
+ site: zAppDetailSiteResponse.nullish(),
tags: z.array(zTag).optional(),
tracing: zJsonValue.nullish(),
updated_at: z.int().nullish(),
@@ -885,10 +949,12 @@ export const zAgentInviteOptionResponse = z.object({
app_id: z.string().nullish(),
archived_at: z.int().nullish(),
archived_by: z.string().nullish(),
+ backing_app_id: z.string().nullish(),
created_at: z.int().nullish(),
created_by: z.string().nullish(),
description: z.string(),
existing_node_ids: z.array(z.string()).optional(),
+ hidden_app_backed: z.boolean().optional().default(false),
icon: z.string().nullish(),
icon_background: z.string().nullish(),
icon_type: zAgentIconType.nullish(),
@@ -925,10 +991,18 @@ export const zAgentInviteOptionsResponse = z.object({
*/
export const zAgentComposerAgentResponse = z.object({
active_config_snapshot_id: z.string().nullish(),
+ app_id: z.string().nullish(),
+ backing_app_id: z.string().nullish(),
description: z.string(),
+ hidden_app_backed: z.boolean().optional().default(false),
+ icon: z.string().nullish(),
+ icon_background: z.string().nullish(),
+ icon_type: z.string().nullish(),
id: z.string(),
name: z.string(),
+ role: z.string().nullish(),
scope: zAgentScope,
+ source: zAgentSource.nullish(),
status: zAgentStatus,
})
@@ -987,6 +1061,28 @@ export const zWorkflowPreviousNodeOutputRef = z.object({
.nullish(),
})
+/**
+ * AgentConfigDraftType
+ *
+ * Editable Agent Soul draft workspace type.
+ */
+export const zAgentConfigDraftType = z.enum(['debug_build', 'draft'])
+
+/**
+ * AgentConfigDraftSummaryResponse
+ */
+export const zAgentConfigDraftSummaryResponse = z.object({
+ account_id: z.string().nullish(),
+ agent_id: z.string(),
+ base_snapshot_id: z.string().nullish(),
+ created_at: z.int().nullish(),
+ created_by: z.string().nullish(),
+ draft_type: zAgentConfigDraftType,
+ id: z.string(),
+ updated_at: z.int().nullish(),
+ updated_by: z.string().nullish(),
+})
+
/**
* DeclaredOutputType
*/
@@ -1022,15 +1118,6 @@ export const zAgentComposerDifyToolCandidateResponse = z.object({
tools_count: z.int().nullish(),
})
-/**
- * AgentKnowledgeDatasetConfig
- */
-export const zAgentKnowledgeDatasetConfig = z.object({
- description: z.string().nullish(),
- id: z.string().max(255).nullish(),
- name: z.string().max(255).nullish(),
-})
-
/**
* SimpleAccount
*/
@@ -1204,6 +1291,7 @@ export const zAgentStatisticSummaryEnvelopeResponse = z.object({
*/
export const zAgentConfigRevisionOperation = z.enum([
'create_version',
+ 'publish_draft',
'restore_version',
'save_current_version',
'save_new_agent',
@@ -1263,44 +1351,69 @@ export const zAgentEnvVariableConfig = z.object({
})
/**
- * AgentHumanToolConfig
+ * AgentFileRefConfig
*/
-export const zAgentHumanToolConfig = z.object({
- description: z.string().nullish(),
- enabled: z.boolean().optional().default(true),
+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(),
})
/**
- * AgentSoulHumanConfig
+ * WorkflowNodeJobMetadata
*/
-export const zAgentSoulHumanConfig = z.object({
- contacts: z.array(zAgentHumanContactConfig).optional(),
- tools: z.array(zAgentHumanToolConfig).optional(),
+export const zWorkflowNodeJobMetadata = z.object({
+ agent_soul: z.record(z.string(), z.unknown()).nullish(),
+ file_refs: z.array(zAgentFileRefConfig).nullish(),
})
/**
- * AgentKnowledgeQueryConfig
+ * AgentSkillRefConfig
*/
-export const zAgentKnowledgeQueryConfig = z.object({
- query: z.string().nullish(),
- score_threshold: z.number().gte(0).lte(1).nullish(),
- score_threshold_enabled: z.boolean().nullish(),
- top_k: z.int().gte(1).nullish(),
+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(),
})
/**
- * AgentKnowledgeQueryMode
+ * AgentSoulFilesConfig
*/
-export const zAgentKnowledgeQueryMode = z.enum(['generated_query', 'user_query'])
+export const zAgentSoulFilesConfig = z.object({
+ files: z.array(zAgentFileRefConfig).optional(),
+ skills: z.array(zAgentSkillRefConfig).optional(),
+})
/**
- * AgentSoulKnowledgeConfig
+ * AgentHumanToolConfig
*/
-export const zAgentSoulKnowledgeConfig = z.object({
- datasets: z.array(zAgentKnowledgeDatasetConfig).optional(),
- query_config: zAgentKnowledgeQueryConfig.optional(),
- query_mode: zAgentKnowledgeQueryMode.nullish(),
+export const zAgentHumanToolConfig = z.object({
+ description: z.string().nullish(),
+ enabled: z.boolean().optional().default(true),
+ name: z.string().max(255).nullish(),
+})
+
+/**
+ * AgentSoulHumanConfig
+ */
+export const zAgentSoulHumanConfig = z.object({
+ contacts: z.array(zAgentHumanContactConfig).optional(),
+ tools: z.array(zAgentHumanToolConfig).optional(),
})
/**
@@ -1394,31 +1507,6 @@ 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
*
@@ -1521,6 +1609,27 @@ export const zAgentCliToolConfig = z.object({
tool_name: z.string().max(255).nullish(),
})
+/**
+ * AgentComposerKnowledgeDatasetCandidateResponse
+ */
+export const zAgentComposerKnowledgeDatasetCandidateResponse = z.object({
+ description: z.string().nullish(),
+ id: z.string().max(255).nullish(),
+ missing: z.boolean().optional().default(false),
+ name: z.string().max(255).nullish(),
+})
+
+/**
+ * AgentComposerKnowledgeSetCandidateResponse
+ */
+export const zAgentComposerKnowledgeSetCandidateResponse = z.object({
+ datasets: z.array(zAgentComposerKnowledgeDatasetCandidateResponse).optional(),
+ description: z.string().nullish(),
+ id: z.string(),
+ missing_dataset_ids: z.array(z.string()).optional(),
+ name: z.string(),
+})
+
/**
* AgentComposerSoulCandidatesResponse
*/
@@ -1528,7 +1637,7 @@ export const zAgentComposerSoulCandidatesResponse = z.object({
cli_tools: z.array(zAgentCliToolConfig).optional(),
dify_tools: z.array(zAgentComposerDifyToolCandidateResponse).optional(),
human_contacts: z.array(zAgentHumanContactConfig).optional(),
- knowledge_datasets: z.array(zAgentKnowledgeDatasetConfig).optional(),
+ knowledge_sets: z.array(zAgentComposerKnowledgeSetCandidateResponse).optional(),
})
/**
@@ -1583,6 +1692,15 @@ export const zHumanInputFormSubmissionData = z.object({
submitted_data: z.record(z.string(), zJsonValue2).nullish(),
})
+/**
+ * AgentKnowledgeDatasetConfig
+ */
+export const zAgentKnowledgeDatasetConfig = z.object({
+ description: z.string().nullish(),
+ id: z.string().max(255).nullish(),
+ name: z.string().max(255).nullish(),
+})
+
/**
* AgentModelResponseFormatConfig
*/
@@ -1733,53 +1851,6 @@ export const zAgentSoulToolsConfig = z.object({
dify_tools: z.array(zAgentSoulDifyToolConfig).optional(),
})
-/**
- * AgentSoulConfig
- */
-export const zAgentSoulConfig = z.object({
- app_features: zAgentSoulAppFeaturesConfig.optional(),
- app_variables: z.array(zAppVariableConfig).optional(),
- env: zAgentSoulEnvConfig.optional(),
- human: zAgentSoulHumanConfig.optional(),
- knowledge: zAgentSoulKnowledgeConfig.optional(),
- memory: zAgentSoulMemoryConfig.optional(),
- misc_legacy: zAgentSoulAppFeaturesConfig.optional(),
- model: zAgentSoulModelConfig.nullish(),
- prompt: zAgentSoulPromptConfig.optional(),
- sandbox: zAgentSoulSandboxConfig.optional(),
- schema_version: z.int().optional().default(1),
- tools: zAgentSoulToolsConfig.optional(),
-})
-
-/**
- * AgentAppComposerResponse
- */
-export const zAgentAppComposerResponse = z.object({
- active_config_snapshot: zAgentConfigSnapshotSummaryResponse,
- agent: zAgentComposerAgentResponse,
- agent_soul: zAgentSoulConfig,
- save_options: z.array(zComposerSaveStrategy),
- validation: zComposerValidationFindingsResponse.nullish(),
- variant: z.literal('agent_app'),
-})
-
-/**
- * AgentConfigSnapshotDetailResponse
- */
-export const zAgentConfigSnapshotDetailResponse = z.object({
- agent_id: z.string().nullish(),
- config_snapshot: zAgentSoulConfig,
- created_at: z.int().nullish(),
- created_by: z.string().nullish(),
- display_version: z.int().nullish(),
- id: z.string(),
- revisions: z.array(zAgentConfigRevisionResponse).optional(),
- snapshot_version: z.int().nullish(),
- summary: z.string().nullish(),
- version: z.int(),
- version_note: z.string().nullish(),
-})
-
/**
* OutputErrorStrategy
*
@@ -1869,27 +1940,6 @@ export const zWorkflowNodeJobConfig = z.object({
workflow_prompt: z.string().optional().default(''),
})
-/**
- * ComposerSavePayload
- */
-export const zComposerSavePayload = z.object({
- agent_soul: zAgentSoulConfig.nullish(),
- binding: zComposerBindingPayload.nullish(),
- client_revision_id: z.string().nullish(),
- description: z.string().nullish(),
- icon: z.string().max(255).nullish(),
- icon_background: z.string().max(255).nullish(),
- icon_type: zAgentIconType.nullish(),
- idempotency_key: z.string().nullish(),
- new_agent_name: z.string().min(1).max(255).nullish(),
- node_job: zWorkflowNodeJobConfig.nullish(),
- role: z.string().max(255).nullish(),
- save_strategy: zComposerSaveStrategy,
- soul_lock: zComposerSoulLockPayload.optional(),
- variant: zComposerVariant,
- version_note: z.string().nullish(),
-})
-
/**
* ButtonStyle
*
@@ -1908,6 +1958,73 @@ export const zUserActionConfig = z.object({
title: z.string().max(100),
})
+/**
+ * AgentKnowledgeModelConfig
+ */
+export const zAgentKnowledgeModelConfig = z.object({
+ completion_params: z.record(z.string(), z.unknown()).optional(),
+ mode: z.string().min(1).max(64),
+ name: z.string().min(1).max(255),
+ provider: z.string().min(1).max(255),
+})
+
+/**
+ * AgentKnowledgeQueryMode
+ */
+export const zAgentKnowledgeQueryMode = z.enum(['generated_query', 'user_query'])
+
+/**
+ * AgentKnowledgeQueryConfig
+ *
+ * Per-set query policy for Agent v2 knowledge retrieval.
+ *
+ * Agent v2 stores knowledge as explicit ``knowledge.sets`` rather than the
+ * legacy flat ``datasets`` / ``query_mode`` / ``query_config`` shape. Each
+ * set owns its own query policy, so ``user_query`` must carry an explicit
+ * ``value`` while ``generated_query`` leaves that value empty.
+ */
+export const zAgentKnowledgeQueryConfig = z.object({
+ mode: zAgentKnowledgeQueryMode,
+ value: z.string().nullish(),
+})
+
+/**
+ * AgentKnowledgeRerankingModelConfig
+ */
+export const zAgentKnowledgeRerankingModelConfig = z.object({
+ model: z.string().min(1).max(255),
+ provider: z.string().min(1).max(255),
+})
+
+/**
+ * AgentKnowledgeWeightedScoreConfig
+ */
+export const zAgentKnowledgeWeightedScoreConfig = z.object({
+ keyword_setting: z.record(z.string(), z.unknown()).nullish(),
+ vector_setting: z.record(z.string(), z.unknown()).nullish(),
+ weight_type: z.string().max(64).nullish(),
+})
+
+/**
+ * AgentKnowledgeRetrievalConfig
+ *
+ * Per-set retrieval policy for Agent v2 knowledge retrieval.
+ *
+ * Retrieval settings now live on each knowledge set instead of one shared
+ * flat config. A set may use either ``multiple`` retrieval with ``top_k`` or
+ * ``single`` retrieval with a required model config.
+ */
+export const zAgentKnowledgeRetrievalConfig = z.object({
+ mode: z.enum(['multiple', 'single']),
+ model: zAgentKnowledgeModelConfig.nullish(),
+ reranking_enable: z.boolean().optional().default(true),
+ reranking_mode: z.string().optional().default('reranking_model'),
+ reranking_model: zAgentKnowledgeRerankingModelConfig.nullish(),
+ score_threshold: z.number().gte(0).lte(1).nullish(),
+ top_k: z.int().gte(1).nullish(),
+ weights: zAgentKnowledgeWeightedScoreConfig.nullish(),
+})
+
/**
* FileType
*/
@@ -1946,6 +2063,166 @@ export const zFileListInputConfig = z.object({
type: z.literal('file-list').optional().default('file-list'),
})
+/**
+ * AgentKnowledgeMetadataCondition
+ */
+export const zAgentKnowledgeMetadataCondition = z.object({
+ comparison_operator: z.enum([
+ '<',
+ '=',
+ '>',
+ 'after',
+ 'before',
+ 'contains',
+ 'empty',
+ 'end with',
+ 'in',
+ 'is',
+ 'is not',
+ 'not contains',
+ 'not empty',
+ 'not in',
+ 'start with',
+ '≠',
+ '≤',
+ '≥',
+ ]),
+ name: z.string().min(1).max(255),
+ value: z.union([z.string(), z.array(z.string()), z.number()]).nullish(),
+})
+
+/**
+ * AgentKnowledgeMetadataConditions
+ */
+export const zAgentKnowledgeMetadataConditions = z.object({
+ conditions: z.array(zAgentKnowledgeMetadataCondition).optional(),
+ logical_operator: z.enum(['and', 'or']).optional().default('and'),
+})
+
+/**
+ * AgentKnowledgeMetadataFilteringConfig
+ *
+ * Per-set metadata filtering policy.
+ *
+ * The Python attribute uses ``metadata_model_config`` for clarity because the
+ * model belongs to metadata filtering specifically, while the external API and
+ * generated schema keep the historical ``model_config`` field name via alias.
+ */
+export const zAgentKnowledgeMetadataFilteringConfig = z.object({
+ conditions: zAgentKnowledgeMetadataConditions.nullish(),
+ mode: z.enum(['automatic', 'disabled', 'manual']).optional().default('disabled'),
+ model_config: zAgentKnowledgeModelConfig.nullish(),
+})
+
+/**
+ * AgentKnowledgeSetConfig
+ *
+ * One explicit knowledge set in Agent v2.
+ *
+ * ``knowledge.sets`` replaces the old flat knowledge config. Each set owns
+ * its datasets plus query, retrieval, and metadata policies. An individual
+ * set must contain at least one dataset id even though the overall knowledge
+ * section may be empty, which is how callers express "no knowledge layer".
+ */
+export const zAgentKnowledgeSetConfig = z.object({
+ datasets: z.array(zAgentKnowledgeDatasetConfig),
+ description: z.string().nullish(),
+ id: z.string().min(1).max(255),
+ metadata_filtering: zAgentKnowledgeMetadataFilteringConfig.optional(),
+ name: z.string().min(1).max(255),
+ query: zAgentKnowledgeQueryConfig,
+ retrieval: zAgentKnowledgeRetrievalConfig,
+})
+
+/**
+ * AgentSoulKnowledgeConfig
+ *
+ * Top-level Agent v2 knowledge config.
+ *
+ * Agent v2 models knowledge as explicit sets instead of one flat
+ * ``datasets`` / ``query_mode`` / ``query_config`` block. An empty ``sets``
+ * list means no knowledge layer should be emitted at runtime, while set-name
+ * uniqueness stays case-insensitive because runtime selection addresses sets
+ * by name.
+ */
+export const zAgentSoulKnowledgeConfig = z.object({
+ sets: z.array(zAgentKnowledgeSetConfig).optional(),
+})
+
+/**
+ * AgentSoulConfig
+ */
+export const zAgentSoulConfig = z.object({
+ app_features: zAgentSoulAppFeaturesConfig.optional(),
+ app_variables: z.array(zAppVariableConfig).optional(),
+ env: zAgentSoulEnvConfig.optional(),
+ files: zAgentSoulFilesConfig.optional(),
+ human: zAgentSoulHumanConfig.optional(),
+ knowledge: zAgentSoulKnowledgeConfig.optional(),
+ memory: zAgentSoulMemoryConfig.optional(),
+ misc_legacy: zAgentSoulAppFeaturesConfig.optional(),
+ model: zAgentSoulModelConfig.nullish(),
+ prompt: zAgentSoulPromptConfig.optional(),
+ sandbox: zAgentSoulSandboxConfig.optional(),
+ schema_version: z.int().optional().default(1),
+ tools: zAgentSoulToolsConfig.optional(),
+})
+
+/**
+ * ComposerSavePayload
+ */
+export const zComposerSavePayload = z.object({
+ agent_soul: zAgentSoulConfig.nullish(),
+ binding: zComposerBindingPayload.nullish(),
+ client_revision_id: z.string().nullish(),
+ description: z.string().nullish(),
+ icon: z.string().max(255).nullish(),
+ icon_background: z.string().max(255).nullish(),
+ icon_type: zAgentIconType.nullish(),
+ idempotency_key: z.string().nullish(),
+ new_agent_name: z.string().min(1).max(255).nullish(),
+ node_job: zWorkflowNodeJobConfig.nullish(),
+ role: z.string().max(255).nullish(),
+ save_strategy: zComposerSaveStrategy,
+ soul_lock: zComposerSoulLockPayload.optional(),
+ variant: zComposerVariant,
+ version_note: z.string().nullish(),
+})
+
+/**
+ * AgentAppComposerResponse
+ */
+export const zAgentAppComposerResponse = z.object({
+ active_config_snapshot: zAgentConfigSnapshotSummaryResponse.nullish(),
+ agent: zAgentComposerAgentResponse,
+ agent_soul: zAgentSoulConfig,
+ app_id: z.string().nullish(),
+ backing_app_id: z.string().nullish(),
+ chat_endpoint: z.string().nullish(),
+ draft: zAgentConfigDraftSummaryResponse.nullish(),
+ hidden_app_backed: z.boolean().optional().default(false),
+ save_options: z.array(zComposerSaveStrategy),
+ validation: zComposerValidationFindingsResponse.nullish(),
+ variant: z.literal('agent_app'),
+})
+
+/**
+ * AgentConfigSnapshotDetailResponse
+ */
+export const zAgentConfigSnapshotDetailResponse = z.object({
+ agent_id: z.string().nullish(),
+ config_snapshot: zAgentSoulConfig,
+ created_at: z.int().nullish(),
+ created_by: z.string().nullish(),
+ display_version: z.int().nullish(),
+ id: z.string(),
+ revisions: z.array(zAgentConfigRevisionResponse).optional(),
+ snapshot_version: z.int().nullish(),
+ summary: z.string().nullish(),
+ version: z.int(),
+ version_note: z.string().nullish(),
+})
+
/**
* ValueSourceType
*
@@ -2075,6 +2352,7 @@ export const zAgentAppPartialWritable = z.object({
active_config_is_published: z.boolean().optional().default(false),
app_id: z.string().nullish(),
author_name: z.string().nullish(),
+ backing_app_id: z.string().nullish(),
bound_agent_id: z.string().nullish(),
create_user_name: z.string().nullish(),
created_at: z.int().nullish(),
@@ -2082,6 +2360,7 @@ export const zAgentAppPartialWritable = z.object({
debug_conversation_id: z.string().nullish(),
description: z.string().nullish(),
has_draft_trigger: z.boolean().nullish(),
+ hidden_app_backed: z.boolean().optional().default(false),
icon: z.string().nullish(),
icon_background: z.string().nullish(),
icon_type: z.string().nullish(),
@@ -2115,23 +2394,33 @@ export const zAgentAppPaginationWritable = z.object({
})
/**
- * Site
+ * AppDetailSiteResponse
*/
-export const zSiteWritable = z.object({
+export const zAppDetailSiteResponseWritable = z.object({
+ access_token: z.string().nullish(),
+ app_base_url: z.string().nullish(),
chat_color_theme: z.string().nullish(),
- chat_color_theme_inverted: z.boolean(),
+ chat_color_theme_inverted: z.boolean().nullish(),
+ code: z.string().nullish(),
copyright: z.string().nullish(),
+ created_at: z.int().nullish(),
+ created_by: z.string().nullish(),
custom_disclaimer: z.string().nullish(),
- default_language: z.string(),
+ customize_domain: z.string().nullish(),
+ customize_token_strategy: z.string().nullish(),
+ default_language: z.string().nullish(),
description: z.string().nullish(),
icon: z.string().nullish(),
icon_background: z.string().nullish(),
- icon_type: z.string().nullish(),
+ icon_type: z.union([z.string(), zIconType]).nullish(),
input_placeholder: z.string().nullish(),
privacy_policy: z.string().nullish(),
- show_workflow_steps: z.boolean(),
- title: z.string(),
- use_icon_as_answer_icon: z.boolean(),
+ prompt_public: z.boolean().nullish(),
+ show_workflow_steps: z.boolean().nullish(),
+ title: z.string().nullish(),
+ updated_at: z.int().nullish(),
+ updated_by: z.string().nullish(),
+ use_icon_as_answer_icon: z.boolean().nullish(),
})
/**
@@ -2142,6 +2431,7 @@ export const zAgentAppDetailWithSiteWritable = z.object({
active_config_is_published: z.boolean().optional().default(false),
api_base_url: z.string().nullish(),
app_id: z.string().nullish(),
+ backing_app_id: z.string().nullish(),
bound_agent_id: z.string().nullish(),
created_at: z.int().nullish(),
created_by: z.string().nullish(),
@@ -2150,6 +2440,7 @@ export const zAgentAppDetailWithSiteWritable = z.object({
description: z.string().nullish(),
enable_api: z.boolean(),
enable_site: z.boolean(),
+ hidden_app_backed: z.boolean().optional().default(false),
icon: z.string().nullish(),
icon_background: z.string().nullish(),
icon_type: z.string().nullish(),
@@ -2161,7 +2452,7 @@ export const zAgentAppDetailWithSiteWritable = z.object({
name: z.string(),
permission_keys: z.array(z.string()).optional(),
role: z.string().nullish(),
- site: zSiteWritable.nullish(),
+ site: zAppDetailSiteResponseWritable.nullish(),
tags: z.array(zTag).optional(),
tracing: zJsonValue.nullish(),
updated_at: z.int().nullish(),
@@ -2297,6 +2588,55 @@ export const zDeleteAgentByAgentIdApiKeysByApiKeyIdPath = z.object({
*/
export const zDeleteAgentByAgentIdApiKeysByApiKeyIdResponse = z.void()
+export const zDeleteAgentByAgentIdBuildDraftPath = z.object({
+ agent_id: z.uuid(),
+})
+
+/**
+ * Agent build draft discarded
+ */
+export const zDeleteAgentByAgentIdBuildDraftResponse = zAgentSimpleResultResponse
+
+export const zGetAgentByAgentIdBuildDraftPath = z.object({
+ agent_id: z.uuid(),
+})
+
+/**
+ * Agent build draft
+ */
+export const zGetAgentByAgentIdBuildDraftResponse = zAgentBuildDraftResponse
+
+export const zPutAgentByAgentIdBuildDraftBody = zComposerSavePayload
+
+export const zPutAgentByAgentIdBuildDraftPath = z.object({
+ agent_id: z.uuid(),
+})
+
+/**
+ * Agent build draft saved
+ */
+export const zPutAgentByAgentIdBuildDraftResponse = zAgentBuildDraftResponse
+
+export const zPostAgentByAgentIdBuildDraftApplyPath = z.object({
+ agent_id: z.uuid(),
+})
+
+/**
+ * Agent build draft applied
+ */
+export const zPostAgentByAgentIdBuildDraftApplyResponse = zAgentBuildDraftApplyResponse
+
+export const zPostAgentByAgentIdBuildDraftCheckoutBody = zAgentBuildDraftCheckoutPayload
+
+export const zPostAgentByAgentIdBuildDraftCheckoutPath = z.object({
+ agent_id: z.uuid(),
+})
+
+/**
+ * Agent build draft checked out
+ */
+export const zPostAgentByAgentIdBuildDraftCheckoutResponse = zAgentBuildDraftResponse
+
export const zGetAgentByAgentIdChatMessagesPath = z.object({
agent_id: z.uuid(),
})
@@ -2565,6 +2905,17 @@ export const zGetAgentByAgentIdMessagesByMessageIdPath = z.object({
*/
export const zGetAgentByAgentIdMessagesByMessageIdResponse = zMessageDetailResponse
+export const zPostAgentByAgentIdPublishBody = zAgentPublishPayload
+
+export const zPostAgentByAgentIdPublishPath = z.object({
+ agent_id: z.uuid(),
+})
+
+/**
+ * Agent draft published
+ */
+export const zPostAgentByAgentIdPublishResponse = zAgentPublishResponse
+
export const zGetAgentByAgentIdReferencingWorkflowsPath = z.object({
agent_id: z.uuid(),
})
diff --git a/packages/contracts/generated/api/console/apps/orpc.gen.ts b/packages/contracts/generated/api/console/apps/orpc.gen.ts
index ea72df28458..59783646462 100644
--- a/packages/contracts/generated/api/console/apps/orpc.gen.ts
+++ b/packages/contracts/generated/api/console/apps/orpc.gen.ts
@@ -185,6 +185,7 @@ import {
zGetAppsByAppIdWorkflowsDraftNodesByNodeIdAgentComposerCandidatesPath,
zGetAppsByAppIdWorkflowsDraftNodesByNodeIdAgentComposerCandidatesResponse,
zGetAppsByAppIdWorkflowsDraftNodesByNodeIdAgentComposerPath,
+ zGetAppsByAppIdWorkflowsDraftNodesByNodeIdAgentComposerQuery,
zGetAppsByAppIdWorkflowsDraftNodesByNodeIdAgentComposerResponse,
zGetAppsByAppIdWorkflowsDraftNodesByNodeIdLastRunPath,
zGetAppsByAppIdWorkflowsDraftNodesByNodeIdLastRunResponse,
@@ -3569,7 +3570,12 @@ export const get62 = oc
path: '/apps/{app_id}/workflows/draft/nodes/{node_id}/agent-composer',
tags: ['console'],
})
- .input(z.object({ params: zGetAppsByAppIdWorkflowsDraftNodesByNodeIdAgentComposerPath }))
+ .input(
+ z.object({
+ params: zGetAppsByAppIdWorkflowsDraftNodesByNodeIdAgentComposerPath,
+ query: zGetAppsByAppIdWorkflowsDraftNodesByNodeIdAgentComposerQuery.optional(),
+ }),
+ )
.output(zGetAppsByAppIdWorkflowsDraftNodesByNodeIdAgentComposerResponse)
export const put4 = oc
diff --git a/packages/contracts/generated/api/console/apps/types.gen.ts b/packages/contracts/generated/api/console/apps/types.gen.ts
index 0c9d22ed995..b8f44b27f12 100644
--- a/packages/contracts/generated/api/console/apps/types.gen.ts
+++ b/packages/contracts/generated/api/console/apps/types.gen.ts
@@ -43,7 +43,7 @@ export type AppDetailWithSite = {
model_config?: ModelConfig | null
name: string
permission_keys?: Array<string>
- site?: Site | null
+ site?: AppDetailSiteResponse | null
tags?: Array<Tag>
tracing?: JsonValue | null
updated_at?: number | null
@@ -972,8 +972,11 @@ export type WorkflowAgentComposerResponse = {
agent?: AgentComposerAgentResponse | null
agent_soul: AgentSoulConfig
app_id?: string | null
+ backing_app_id?: string | null
binding?: AgentComposerBindingResponse | null
+ chat_endpoint?: string | null
effective_declared_outputs?: Array<DeclaredOutputConfig>
+ hidden_app_backed?: boolean
impact_summary?: AgentComposerImpactResponse | null
node_id?: string | null
node_job: WorkflowNodeJobConfig
@@ -1233,22 +1236,32 @@ export type ModelConfig = {
provider: string
}
-export type Site = {
+export type AppDetailSiteResponse = {
+ access_token?: string | null
+ app_base_url?: string | null
chat_color_theme?: string | null
- chat_color_theme_inverted: boolean
+ chat_color_theme_inverted?: boolean | null
+ code?: string | null
copyright?: string | null
+ created_at?: number | null
+ created_by?: string | null
custom_disclaimer?: string | null
- default_language: string
+ customize_domain?: string | null
+ customize_token_strategy?: string | null
+ default_language?: string | null
description?: string | null
icon?: string | null
icon_background?: string | null
- icon_type?: string | null
+ icon_type?: string | IconType | null
readonly icon_url: string | null
input_placeholder?: string | null
privacy_policy?: string | null
- show_workflow_steps: boolean
- title: string
- use_icon_as_answer_icon: boolean
+ prompt_public?: boolean | null
+ show_workflow_steps?: boolean | null
+ title?: string | null
+ updated_at?: number | null
+ updated_by?: string | null
+ use_icon_as_answer_icon?: boolean | null
}
export type Tag = {
@@ -1789,10 +1802,18 @@ export type AgentConfigSnapshotSummaryResponse = {
export type AgentComposerAgentResponse = {
active_config_snapshot_id?: string | null
+ app_id?: string | null
+ backing_app_id?: string | null
description: string
+ hidden_app_backed?: boolean
+ icon?: string | null
+ icon_background?: string | null
+ icon_type?: string | null
id: string
name: string
+ role?: string | null
scope: AgentScope
+ source?: AgentSource | null
status: AgentStatus
}
@@ -1800,6 +1821,7 @@ export type AgentSoulConfig = {
app_features?: AgentSoulAppFeaturesConfig
app_variables?: Array<AppVariableConfig>
env?: AgentSoulEnvConfig
+ files?: AgentSoulFilesConfig
human?: AgentSoulHumanConfig
knowledge?: AgentSoulKnowledgeConfig
memory?: AgentSoulMemoryConfig
@@ -1905,7 +1927,7 @@ export type AgentComposerSoulCandidatesResponse = {
cli_tools?: Array<AgentCliToolConfig>
dify_tools?: Array<AgentComposerDifyToolCandidateResponse>
human_contacts?: Array<AgentHumanContactConfig>
- knowledge_datasets?: Array<AgentKnowledgeDatasetConfig>
+ knowledge_sets?: Array<AgentComposerKnowledgeSetCandidateResponse>
}
export type ComposerCandidateCapabilities = {
@@ -2108,6 +2130,8 @@ export type WorkflowRunForArchivedLogResponse = {
export type AgentScope = 'roster' | 'workflow_only'
+export type AgentSource = 'agent_app' | 'imported' | 'roster' | 'system' | 'workflow'
+
export type AgentStatus = 'active' | 'archived'
export type AgentSoulAppFeaturesConfig = {
@@ -2133,15 +2157,18 @@ export type AgentSoulEnvConfig = {
variables?: Array<AgentEnvVariableConfig>
}
+export type AgentSoulFilesConfig = {
+ files?: Array<AgentFileRefConfig>
+ skills?: Array<AgentSkillRefConfig>
+}
+
export type AgentSoulHumanConfig = {
contacts?: Array<AgentHumanContactConfig>
tools?: Array<AgentHumanToolConfig>
}
export type AgentSoulKnowledgeConfig = {
- datasets?: Array<AgentKnowledgeDatasetConfig>
- query_config?: AgentKnowledgeQueryConfig
- query_mode?: AgentKnowledgeQueryMode | null
+ sets?: Array<AgentKnowledgeSetConfig>
}
export type AgentSoulMemoryConfig = {
@@ -2293,11 +2320,12 @@ export type AgentComposerDifyToolCandidateResponse = {
tools_count?: number | null
}
-export type AgentKnowledgeDatasetConfig = {
+export type AgentComposerKnowledgeSetCandidateResponse = {
+ datasets?: Array<AgentComposerKnowledgeDatasetCandidateResponse>
description?: string | null
- id?: string | null
- name?: string | null
- [key: string]: unknown
+ id: string
+ missing_dataset_ids?: Array<string>
+ name: string
}
export type CheckResultView = {
@@ -2401,22 +2429,51 @@ export type AgentEnvVariableConfig = {
[key: string]: unknown
}
-export type AgentHumanToolConfig = {
+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 AgentSkillRefConfig = {
description?: string | null
- enabled?: boolean
+ 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 AgentKnowledgeQueryConfig = {
- query?: string | null
- score_threshold?: number | null
- score_threshold_enabled?: boolean | null
- top_k?: number | null
+export type AgentHumanToolConfig = {
+ description?: string | null
+ enabled?: boolean
+ name?: string | null
[key: string]: unknown
}
-export type AgentKnowledgeQueryMode = 'generated_query' | 'user_query'
+export type AgentKnowledgeSetConfig = {
+ datasets: Array<AgentKnowledgeDatasetConfig>
+ description?: string | null
+ id: string
+ metadata_filtering?: AgentKnowledgeMetadataFilteringConfig
+ name: string
+ query: AgentKnowledgeQueryConfig
+ retrieval: AgentKnowledgeRetrievalConfig
+}
export type AgentMemoryArtifactConfig = {
id?: string | null
@@ -2475,21 +2532,6 @@ 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 = {
@@ -2521,6 +2563,13 @@ export type AgentPermissionConfig = {
export type AgentCliToolRiskLevel = 'dangerous' | 'safe' | 'unknown'
+export type AgentComposerKnowledgeDatasetCandidateResponse = {
+ description?: string | null
+ id?: string | null
+ missing?: boolean
+ name?: string | null
+}
+
export type ButtonStyle = 'accent' | 'default' | 'ghost' | 'primary'
export type ParagraphInputConfig = {
@@ -2560,6 +2609,34 @@ export type AgentModerationProviderConfig = {
[key: string]: unknown
}
+export type AgentKnowledgeDatasetConfig = {
+ description?: string | null
+ id?: string | null
+ name?: string | null
+}
+
+export type AgentKnowledgeMetadataFilteringConfig = {
+ conditions?: AgentKnowledgeMetadataConditions | null
+ mode?: 'automatic' | 'disabled' | 'manual'
+ model_config?: AgentKnowledgeModelConfig | null
+}
+
+export type AgentKnowledgeQueryConfig = {
+ mode: AgentKnowledgeQueryMode
+ value?: string | null
+}
+
+export type AgentKnowledgeRetrievalConfig = {
+ mode: 'multiple' | 'single'
+ model?: AgentKnowledgeModelConfig | null
+ reranking_enable?: boolean
+ reranking_mode?: string
+ reranking_model?: AgentKnowledgeRerankingModelConfig | null
+ score_threshold?: number | null
+ top_k?: number | null
+ weights?: AgentKnowledgeWeightedScoreConfig | null
+}
+
export type AgentModelResponseFormatConfig = {
type?: string | null
[key: string]: unknown
@@ -2593,8 +2670,64 @@ export type AgentModerationIoConfig = {
[key: string]: unknown
}
+export type AgentKnowledgeMetadataConditions = {
+ conditions?: Array<AgentKnowledgeMetadataCondition>
+ logical_operator?: 'and' | 'or'
+}
+
+export type AgentKnowledgeModelConfig = {
+ completion_params?: {
+ [key: string]: unknown
+ }
+ mode: string
+ name: string
+ provider: string
+}
+
+export type AgentKnowledgeQueryMode = 'generated_query' | 'user_query'
+
+export type AgentKnowledgeRerankingModelConfig = {
+ model: string
+ provider: string
+}
+
+export type AgentKnowledgeWeightedScoreConfig = {
+ keyword_setting?: {
+ [key: string]: unknown
+ } | null
+ vector_setting?: {
+ [key: string]: unknown
+ } | null
+ weight_type?: string | null
+ [key: string]: unknown
+}
+
export type ValueSourceType = 'constant' | 'variable'
+export type AgentKnowledgeMetadataCondition = {
+ comparison_operator:
+ | '<'
+ | '='
+ | '>'
+ | 'after'
+ | 'before'
+ | 'contains'
+ | 'empty'
+ | 'end with'
+ | 'in'
+ | 'is'
+ | 'is not'
+ | 'not contains'
+ | 'not empty'
+ | 'not in'
+ | 'start with'
+ | '≠'
+ | '≤'
+ | '≥'
+ name: string
+ value?: string | Array<string> | number | null
+}
+
export type AppPaginationWritable = {
data: Array<AppPartialWritable>
has_more: boolean
@@ -2624,7 +2757,7 @@ export type AppDetailWithSiteWritable = {
model_config?: ModelConfig | null
name: string
permission_keys?: Array<string>
- site?: SiteWritable | null
+ site?: AppDetailSiteResponseWritable | null
tags?: Array<Tag>
tracing?: JsonValue | null
updated_at?: number | null
@@ -2684,21 +2817,31 @@ export type AppPartialWritable = {
workflow?: WorkflowPartial | null
}
-export type SiteWritable = {
+export type AppDetailSiteResponseWritable = {
+ access_token?: string | null
+ app_base_url?: string | null
chat_color_theme?: string | null
- chat_color_theme_inverted: boolean
+ chat_color_theme_inverted?: boolean | null
+ code?: string | null
copyright?: string | null
+ created_at?: number | null
+ created_by?: string | null
custom_disclaimer?: string | null
- default_language: string
+ customize_domain?: string | null
+ customize_token_strategy?: string | null
+ default_language?: string | null
description?: string | null
icon?: string | null
icon_background?: string | null
- icon_type?: string | null
+ icon_type?: string | IconType | null
input_placeholder?: string | null
privacy_policy?: string | null
- show_workflow_steps: boolean
- title: string
- use_icon_as_answer_icon: boolean
+ prompt_public?: boolean | null
+ show_workflow_steps?: boolean | null
+ title?: string | null
+ updated_at?: number | null
+ updated_by?: string | null
+ use_icon_as_answer_icon?: boolean | null
}
export type WorkflowCommentBasicWritable = {
@@ -5389,7 +5532,9 @@ export type GetAppsByAppIdWorkflowsDraftNodesByNodeIdAgentComposerData = {
app_id: string
node_id: string
}
- query?: never
+ query?: {
+ snapshot_id?: string
+ }
url: '/apps/{app_id}/workflows/draft/nodes/{node_id}/agent-composer'
}
diff --git a/packages/contracts/generated/api/console/apps/zod.gen.ts b/packages/contracts/generated/api/console/apps/zod.gen.ts
index 73e98b8837a..89afe8f3ddf 100644
--- a/packages/contracts/generated/api/console/apps/zod.gen.ts
+++ b/packages/contracts/generated/api/console/apps/zod.gen.ts
@@ -847,24 +847,34 @@ export const zDeletedTool = z.object({
})
/**
- * Site
+ * AppDetailSiteResponse
*/
-export const zSite = z.object({
+export const zAppDetailSiteResponse = z.object({
+ access_token: z.string().nullish(),
+ app_base_url: z.string().nullish(),
chat_color_theme: z.string().nullish(),
- chat_color_theme_inverted: z.boolean(),
+ chat_color_theme_inverted: z.boolean().nullish(),
+ code: z.string().nullish(),
copyright: z.string().nullish(),
+ created_at: z.int().nullish(),
+ created_by: z.string().nullish(),
custom_disclaimer: z.string().nullish(),
- default_language: z.string(),
+ customize_domain: z.string().nullish(),
+ customize_token_strategy: z.string().nullish(),
+ default_language: z.string().nullish(),
description: z.string().nullish(),
icon: z.string().nullish(),
icon_background: z.string().nullish(),
- icon_type: z.string().nullish(),
+ icon_type: z.union([z.string(), zIconType]).nullish(),
icon_url: z.string().nullable(),
input_placeholder: z.string().nullish(),
privacy_policy: z.string().nullish(),
- show_workflow_steps: z.boolean(),
- title: z.string(),
- use_icon_as_answer_icon: z.boolean(),
+ prompt_public: z.boolean().nullish(),
+ show_workflow_steps: z.boolean().nullish(),
+ title: z.string().nullish(),
+ updated_at: z.int().nullish(),
+ updated_by: z.string().nullish(),
+ use_icon_as_answer_icon: z.boolean().nullish(),
})
/**
@@ -2100,7 +2110,7 @@ export const zAppDetailWithSite = z.object({
model_config: zModelConfig.nullish(),
name: z.string(),
permission_keys: z.array(z.string()).optional(),
- site: zSite.nullish(),
+ site: zAppDetailSiteResponse.nullish(),
tags: z.array(zTag).optional(),
tracing: zJsonValue.nullish(),
updated_at: z.int().nullish(),
@@ -2488,6 +2498,13 @@ export const zWorkflowArchivedLogPaginationResponse = z.object({
*/
export const zAgentScope = z.enum(['roster', 'workflow_only'])
+/**
+ * AgentSource
+ *
+ * Origin that created or imported the Agent.
+ */
+export const zAgentSource = z.enum(['agent_app', 'imported', 'roster', 'system', 'workflow'])
+
/**
* AgentStatus
*
@@ -2500,10 +2517,18 @@ export const zAgentStatus = z.enum(['active', 'archived'])
*/
export const zAgentComposerAgentResponse = z.object({
active_config_snapshot_id: z.string().nullish(),
+ app_id: z.string().nullish(),
+ backing_app_id: z.string().nullish(),
description: z.string(),
+ hidden_app_backed: z.boolean().optional().default(false),
+ icon: z.string().nullish(),
+ icon_background: z.string().nullish(),
+ icon_type: z.string().nullish(),
id: z.string(),
name: z.string(),
+ role: z.string().nullish(),
scope: zAgentScope,
+ source: zAgentSource.nullish(),
status: zAgentStatus,
})
@@ -2647,15 +2672,6 @@ export const zAgentComposerDifyToolCandidateResponse = z.object({
tools_count: z.int().nullish(),
})
-/**
- * AgentKnowledgeDatasetConfig
- */
-export const zAgentKnowledgeDatasetConfig = z.object({
- description: z.string().nullish(),
- id: z.string().max(255).nullish(),
- name: z.string().max(255).nullish(),
-})
-
/**
* CheckResultView
*
@@ -2769,44 +2785,69 @@ export const zAgentEnvVariableConfig = z.object({
})
/**
- * AgentHumanToolConfig
+ * AgentFileRefConfig
*/
-export const zAgentHumanToolConfig = z.object({
- description: z.string().nullish(),
- enabled: z.boolean().optional().default(true),
+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(),
})
/**
- * AgentSoulHumanConfig
+ * WorkflowNodeJobMetadata
*/
-export const zAgentSoulHumanConfig = z.object({
- contacts: z.array(zAgentHumanContactConfig).optional(),
- tools: z.array(zAgentHumanToolConfig).optional(),
+export const zWorkflowNodeJobMetadata = z.object({
+ agent_soul: z.record(z.string(), z.unknown()).nullish(),
+ file_refs: z.array(zAgentFileRefConfig).nullish(),
})
/**
- * AgentKnowledgeQueryConfig
+ * AgentSkillRefConfig
*/
-export const zAgentKnowledgeQueryConfig = z.object({
- query: z.string().nullish(),
- score_threshold: z.number().gte(0).lte(1).nullish(),
- score_threshold_enabled: z.boolean().nullish(),
- top_k: z.int().gte(1).nullish(),
+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(),
})
/**
- * AgentKnowledgeQueryMode
+ * AgentSoulFilesConfig
*/
-export const zAgentKnowledgeQueryMode = z.enum(['generated_query', 'user_query'])
+export const zAgentSoulFilesConfig = z.object({
+ files: z.array(zAgentFileRefConfig).optional(),
+ skills: z.array(zAgentSkillRefConfig).optional(),
+})
/**
- * AgentSoulKnowledgeConfig
+ * AgentHumanToolConfig
*/
-export const zAgentSoulKnowledgeConfig = z.object({
- datasets: z.array(zAgentKnowledgeDatasetConfig).optional(),
- query_config: zAgentKnowledgeQueryConfig.optional(),
- query_mode: zAgentKnowledgeQueryMode.nullish(),
+export const zAgentHumanToolConfig = z.object({
+ description: z.string().nullish(),
+ enabled: z.boolean().optional().default(true),
+ name: z.string().max(255).nullish(),
+})
+
+/**
+ * AgentSoulHumanConfig
+ */
+export const zAgentSoulHumanConfig = z.object({
+ contacts: z.array(zAgentHumanContactConfig).optional(),
+ tools: z.array(zAgentHumanToolConfig).optional(),
})
/**
@@ -2857,31 +2898,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(),
-})
-
-/**
- * WorkflowNodeJobMetadata
- */
-export const zWorkflowNodeJobMetadata = z.object({
- agent_soul: z.record(z.string(), z.unknown()).nullish(),
- file_refs: z.array(zAgentFileRefConfig).nullish(),
-})
-
/**
* OutputErrorStrategy
*
@@ -3020,6 +3036,27 @@ export const zAgentCliToolConfig = z.object({
tool_name: z.string().max(255).nullish(),
})
+/**
+ * AgentComposerKnowledgeDatasetCandidateResponse
+ */
+export const zAgentComposerKnowledgeDatasetCandidateResponse = z.object({
+ description: z.string().nullish(),
+ id: z.string().max(255).nullish(),
+ missing: z.boolean().optional().default(false),
+ name: z.string().max(255).nullish(),
+})
+
+/**
+ * AgentComposerKnowledgeSetCandidateResponse
+ */
+export const zAgentComposerKnowledgeSetCandidateResponse = z.object({
+ datasets: z.array(zAgentComposerKnowledgeDatasetCandidateResponse).optional(),
+ description: z.string().nullish(),
+ id: z.string(),
+ missing_dataset_ids: z.array(z.string()).optional(),
+ name: z.string(),
+})
+
/**
* AgentComposerSoulCandidatesResponse
*/
@@ -3027,7 +3064,7 @@ export const zAgentComposerSoulCandidatesResponse = z.object({
cli_tools: z.array(zAgentCliToolConfig).optional(),
dify_tools: z.array(zAgentComposerDifyToolCandidateResponse).optional(),
human_contacts: z.array(zAgentHumanContactConfig).optional(),
- knowledge_datasets: z.array(zAgentKnowledgeDatasetConfig).optional(),
+ knowledge_sets: z.array(zAgentComposerKnowledgeSetCandidateResponse).optional(),
})
/**
@@ -3059,6 +3096,15 @@ export const zUserActionConfig = z.object({
title: z.string().max(100),
})
+/**
+ * AgentKnowledgeDatasetConfig
+ */
+export const zAgentKnowledgeDatasetConfig = z.object({
+ description: z.string().nullish(),
+ id: z.string().max(255).nullish(),
+ name: z.string().max(255).nullish(),
+})
+
/**
* AgentModelResponseFormatConfig
*/
@@ -3310,62 +3356,70 @@ export const zAgentSoulAppFeaturesConfig = z.object({
})
/**
- * AgentSoulConfig
+ * AgentKnowledgeModelConfig
*/
-export const zAgentSoulConfig = z.object({
- app_features: zAgentSoulAppFeaturesConfig.optional(),
- app_variables: z.array(zAppVariableConfig).optional(),
- env: zAgentSoulEnvConfig.optional(),
- human: zAgentSoulHumanConfig.optional(),
- knowledge: zAgentSoulKnowledgeConfig.optional(),
- memory: zAgentSoulMemoryConfig.optional(),
- misc_legacy: zAgentSoulAppFeaturesConfig.optional(),
- model: zAgentSoulModelConfig.nullish(),
- prompt: zAgentSoulPromptConfig.optional(),
- sandbox: zAgentSoulSandboxConfig.optional(),
- schema_version: z.int().optional().default(1),
- tools: zAgentSoulToolsConfig.optional(),
+export const zAgentKnowledgeModelConfig = z.object({
+ completion_params: z.record(z.string(), z.unknown()).optional(),
+ mode: z.string().min(1).max(64),
+ name: z.string().min(1).max(255),
+ provider: z.string().min(1).max(255),
})
/**
- * WorkflowAgentComposerResponse
+ * AgentKnowledgeQueryMode
*/
-export const zWorkflowAgentComposerResponse = z.object({
- active_config_snapshot: zAgentConfigSnapshotSummaryResponse.nullish(),
- agent: zAgentComposerAgentResponse.nullish(),
- agent_soul: zAgentSoulConfig,
- app_id: z.string().nullish(),
- binding: zAgentComposerBindingResponse.nullish(),
- effective_declared_outputs: z.array(zDeclaredOutputConfig).optional(),
- impact_summary: zAgentComposerImpactResponse.nullish(),
- node_id: z.string().nullish(),
- node_job: zWorkflowNodeJobConfig,
- save_options: z.array(zComposerSaveStrategy),
- soul_lock: zAgentComposerSoulLockResponse,
- validation: zComposerValidationFindingsResponse.nullish(),
- variant: z.literal('workflow'),
- workflow_id: z.string().nullish(),
+export const zAgentKnowledgeQueryMode = z.enum(['generated_query', 'user_query'])
+
+/**
+ * AgentKnowledgeQueryConfig
+ *
+ * Per-set query policy for Agent v2 knowledge retrieval.
+ *
+ * Agent v2 stores knowledge as explicit ``knowledge.sets`` rather than the
+ * legacy flat ``datasets`` / ``query_mode`` / ``query_config`` shape. Each
+ * set owns its own query policy, so ``user_query`` must carry an explicit
+ * ``value`` while ``generated_query`` leaves that value empty.
+ */
+export const zAgentKnowledgeQueryConfig = z.object({
+ mode: zAgentKnowledgeQueryMode,
+ value: z.string().nullish(),
})
/**
- * ComposerSavePayload
+ * AgentKnowledgeRerankingModelConfig
*/
-export const zComposerSavePayload = z.object({
- agent_soul: zAgentSoulConfig.nullish(),
- binding: zComposerBindingPayload.nullish(),
- client_revision_id: z.string().nullish(),
- description: z.string().nullish(),
- icon: z.string().max(255).nullish(),
- icon_background: z.string().max(255).nullish(),
- icon_type: zAgentIconType.nullish(),
- idempotency_key: z.string().nullish(),
- new_agent_name: z.string().min(1).max(255).nullish(),
- node_job: zWorkflowNodeJobConfig.nullish(),
- role: z.string().max(255).nullish(),
- save_strategy: zComposerSaveStrategy,
- soul_lock: zComposerSoulLockPayload.optional(),
- variant: zComposerVariant,
- version_note: z.string().nullish(),
+export const zAgentKnowledgeRerankingModelConfig = z.object({
+ model: z.string().min(1).max(255),
+ provider: z.string().min(1).max(255),
+})
+
+/**
+ * AgentKnowledgeWeightedScoreConfig
+ */
+export const zAgentKnowledgeWeightedScoreConfig = z.object({
+ keyword_setting: z.record(z.string(), z.unknown()).nullish(),
+ vector_setting: z.record(z.string(), z.unknown()).nullish(),
+ weight_type: z.string().max(64).nullish(),
+})
+
+/**
+ * AgentKnowledgeRetrievalConfig
+ *
+ * Per-set retrieval policy for Agent v2 knowledge retrieval.
+ *
+ * Retrieval settings now live on each knowledge set instead of one shared
+ * flat config. A set may use either ``multiple`` retrieval with ``top_k`` or
+ * ``single`` retrieval with a required model config.
+ */
+export const zAgentKnowledgeRetrievalConfig = z.object({
+ mode: z.enum(['multiple', 'single']),
+ model: zAgentKnowledgeModelConfig.nullish(),
+ reranking_enable: z.boolean().optional().default(true),
+ reranking_mode: z.string().optional().default('reranking_model'),
+ reranking_model: zAgentKnowledgeRerankingModelConfig.nullish(),
+ score_threshold: z.number().gte(0).lte(1).nullish(),
+ top_k: z.int().gte(1).nullish(),
+ weights: zAgentKnowledgeWeightedScoreConfig.nullish(),
})
/**
@@ -3489,6 +3543,155 @@ export const zMessageInfiniteScrollPaginationResponse = z.object({
limit: z.int(),
})
+/**
+ * AgentKnowledgeMetadataCondition
+ */
+export const zAgentKnowledgeMetadataCondition = z.object({
+ comparison_operator: z.enum([
+ '<',
+ '=',
+ '>',
+ 'after',
+ 'before',
+ 'contains',
+ 'empty',
+ 'end with',
+ 'in',
+ 'is',
+ 'is not',
+ 'not contains',
+ 'not empty',
+ 'not in',
+ 'start with',
+ '≠',
+ '≤',
+ '≥',
+ ]),
+ name: z.string().min(1).max(255),
+ value: z.union([z.string(), z.array(z.string()), z.number()]).nullish(),
+})
+
+/**
+ * AgentKnowledgeMetadataConditions
+ */
+export const zAgentKnowledgeMetadataConditions = z.object({
+ conditions: z.array(zAgentKnowledgeMetadataCondition).optional(),
+ logical_operator: z.enum(['and', 'or']).optional().default('and'),
+})
+
+/**
+ * AgentKnowledgeMetadataFilteringConfig
+ *
+ * Per-set metadata filtering policy.
+ *
+ * The Python attribute uses ``metadata_model_config`` for clarity because the
+ * model belongs to metadata filtering specifically, while the external API and
+ * generated schema keep the historical ``model_config`` field name via alias.
+ */
+export const zAgentKnowledgeMetadataFilteringConfig = z.object({
+ conditions: zAgentKnowledgeMetadataConditions.nullish(),
+ mode: z.enum(['automatic', 'disabled', 'manual']).optional().default('disabled'),
+ model_config: zAgentKnowledgeModelConfig.nullish(),
+})
+
+/**
+ * AgentKnowledgeSetConfig
+ *
+ * One explicit knowledge set in Agent v2.
+ *
+ * ``knowledge.sets`` replaces the old flat knowledge config. Each set owns
+ * its datasets plus query, retrieval, and metadata policies. An individual
+ * set must contain at least one dataset id even though the overall knowledge
+ * section may be empty, which is how callers express "no knowledge layer".
+ */
+export const zAgentKnowledgeSetConfig = z.object({
+ datasets: z.array(zAgentKnowledgeDatasetConfig),
+ description: z.string().nullish(),
+ id: z.string().min(1).max(255),
+ metadata_filtering: zAgentKnowledgeMetadataFilteringConfig.optional(),
+ name: z.string().min(1).max(255),
+ query: zAgentKnowledgeQueryConfig,
+ retrieval: zAgentKnowledgeRetrievalConfig,
+})
+
+/**
+ * AgentSoulKnowledgeConfig
+ *
+ * Top-level Agent v2 knowledge config.
+ *
+ * Agent v2 models knowledge as explicit sets instead of one flat
+ * ``datasets`` / ``query_mode`` / ``query_config`` block. An empty ``sets``
+ * list means no knowledge layer should be emitted at runtime, while set-name
+ * uniqueness stays case-insensitive because runtime selection addresses sets
+ * by name.
+ */
+export const zAgentSoulKnowledgeConfig = z.object({
+ sets: z.array(zAgentKnowledgeSetConfig).optional(),
+})
+
+/**
+ * AgentSoulConfig
+ */
+export const zAgentSoulConfig = z.object({
+ app_features: zAgentSoulAppFeaturesConfig.optional(),
+ app_variables: z.array(zAppVariableConfig).optional(),
+ env: zAgentSoulEnvConfig.optional(),
+ files: zAgentSoulFilesConfig.optional(),
+ human: zAgentSoulHumanConfig.optional(),
+ knowledge: zAgentSoulKnowledgeConfig.optional(),
+ memory: zAgentSoulMemoryConfig.optional(),
+ misc_legacy: zAgentSoulAppFeaturesConfig.optional(),
+ model: zAgentSoulModelConfig.nullish(),
+ prompt: zAgentSoulPromptConfig.optional(),
+ sandbox: zAgentSoulSandboxConfig.optional(),
+ schema_version: z.int().optional().default(1),
+ tools: zAgentSoulToolsConfig.optional(),
+})
+
+/**
+ * WorkflowAgentComposerResponse
+ */
+export const zWorkflowAgentComposerResponse = z.object({
+ active_config_snapshot: zAgentConfigSnapshotSummaryResponse.nullish(),
+ agent: zAgentComposerAgentResponse.nullish(),
+ agent_soul: zAgentSoulConfig,
+ app_id: z.string().nullish(),
+ backing_app_id: z.string().nullish(),
+ binding: zAgentComposerBindingResponse.nullish(),
+ chat_endpoint: z.string().nullish(),
+ effective_declared_outputs: z.array(zDeclaredOutputConfig).optional(),
+ hidden_app_backed: z.boolean().optional().default(false),
+ impact_summary: zAgentComposerImpactResponse.nullish(),
+ node_id: z.string().nullish(),
+ node_job: zWorkflowNodeJobConfig,
+ save_options: z.array(zComposerSaveStrategy),
+ soul_lock: zAgentComposerSoulLockResponse,
+ validation: zComposerValidationFindingsResponse.nullish(),
+ variant: z.literal('workflow'),
+ workflow_id: z.string().nullish(),
+})
+
+/**
+ * ComposerSavePayload
+ */
+export const zComposerSavePayload = z.object({
+ agent_soul: zAgentSoulConfig.nullish(),
+ binding: zComposerBindingPayload.nullish(),
+ client_revision_id: z.string().nullish(),
+ description: z.string().nullish(),
+ icon: z.string().max(255).nullish(),
+ icon_background: z.string().max(255).nullish(),
+ icon_type: zAgentIconType.nullish(),
+ idempotency_key: z.string().nullish(),
+ new_agent_name: z.string().min(1).max(255).nullish(),
+ node_job: zWorkflowNodeJobConfig.nullish(),
+ role: z.string().max(255).nullish(),
+ save_strategy: zComposerSaveStrategy,
+ soul_lock: zComposerSoulLockPayload.optional(),
+ variant: zComposerVariant,
+ version_note: z.string().nullish(),
+})
+
/**
* GeneratedAppResponse
*/
@@ -3537,23 +3740,33 @@ export const zAppPaginationWritable = z.object({
})
/**
- * Site
+ * AppDetailSiteResponse
*/
-export const zSiteWritable = z.object({
+export const zAppDetailSiteResponseWritable = z.object({
+ access_token: z.string().nullish(),
+ app_base_url: z.string().nullish(),
chat_color_theme: z.string().nullish(),
- chat_color_theme_inverted: z.boolean(),
+ chat_color_theme_inverted: z.boolean().nullish(),
+ code: z.string().nullish(),
copyright: z.string().nullish(),
+ created_at: z.int().nullish(),
+ created_by: z.string().nullish(),
custom_disclaimer: z.string().nullish(),
- default_language: z.string(),
+ customize_domain: z.string().nullish(),
+ customize_token_strategy: z.string().nullish(),
+ default_language: z.string().nullish(),
description: z.string().nullish(),
icon: z.string().nullish(),
icon_background: z.string().nullish(),
- icon_type: z.string().nullish(),
+ icon_type: z.union([z.string(), zIconType]).nullish(),
input_placeholder: z.string().nullish(),
privacy_policy: z.string().nullish(),
- show_workflow_steps: z.boolean(),
- title: z.string(),
- use_icon_as_answer_icon: z.boolean(),
+ prompt_public: z.boolean().nullish(),
+ show_workflow_steps: z.boolean().nullish(),
+ title: z.string().nullish(),
+ updated_at: z.int().nullish(),
+ updated_by: z.string().nullish(),
+ use_icon_as_answer_icon: z.boolean().nullish(),
})
/**
@@ -3580,7 +3793,7 @@ export const zAppDetailWithSiteWritable = z.object({
model_config: zModelConfig.nullish(),
name: z.string(),
permission_keys: z.array(z.string()).optional(),
- site: zSiteWritable.nullish(),
+ site: zAppDetailSiteResponseWritable.nullish(),
tags: z.array(zTag).optional(),
tracing: zJsonValue.nullish(),
updated_at: z.int().nullish(),
@@ -5336,6 +5549,10 @@ export const zGetAppsByAppIdWorkflowsDraftNodesByNodeIdAgentComposerPath = z.obj
node_id: z.string(),
})
+export const zGetAppsByAppIdWorkflowsDraftNodesByNodeIdAgentComposerQuery = z.object({
+ snapshot_id: z.string().max(255).optional(),
+})
+
/**
* Workflow agent composer state
*/
diff --git a/packages/contracts/generated/api/console/installed-apps/types.gen.ts b/packages/contracts/generated/api/console/installed-apps/types.gen.ts
index ce366c9e102..47274cf6795 100644
--- a/packages/contracts/generated/api/console/installed-apps/types.gen.ts
+++ b/packages/contracts/generated/api/console/installed-apps/types.gen.ts
@@ -31,6 +31,7 @@ export type AudioTranscriptResponse = {
export type ChatMessagePayload = {
conversation_id?: string | null
+ draft_type?: 'debug_build' | 'draft'
files?: Array<unknown> | null
inputs: {
[key: string]: unknown
diff --git a/packages/contracts/generated/api/console/installed-apps/zod.gen.ts b/packages/contracts/generated/api/console/installed-apps/zod.gen.ts
index 2899942c8f8..a502514baa7 100644
--- a/packages/contracts/generated/api/console/installed-apps/zod.gen.ts
+++ b/packages/contracts/generated/api/console/installed-apps/zod.gen.ts
@@ -43,6 +43,7 @@ export const zAudioTranscriptResponse = z.object({
*/
export const zChatMessagePayload = z.object({
conversation_id: z.string().nullish(),
+ draft_type: z.enum(['debug_build', 'draft']).optional().default('draft'),
files: z.array(z.unknown()).nullish(),
inputs: z.record(z.string(), z.unknown()),
model_config: z.record(z.string(), z.unknown()).optional(),
diff --git a/packages/iconify-collections/assets/vender/agent-v2/configure-active.svg b/packages/iconify-collections/assets/vender/agent-v2/configure-active.svg
new file mode 100644
index 00000000000..9ad5ce5db2d
--- /dev/null
+++ b/packages/iconify-collections/assets/vender/agent-v2/configure-active.svg
@@ -0,0 +1,3 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="14" height="16" viewBox="0 0 14 16" fill="none">
+ <path d="M7.5 2.2912C10.875 2.66428 13.5 5.52559 13.5 9V15.75H0V9C0 5.52559 2.62504 2.66428 6 2.2912V0H7.5V2.2912ZM6.75 12.75C8.82105 12.75 10.5 11.071 10.5 9C10.5 6.92895 8.82105 5.25 6.75 5.25C4.67893 5.25 3 6.92895 3 9C3 11.071 4.67893 12.75 6.75 12.75ZM6.75 11.25C5.50732 11.25 4.5 10.2427 4.5 9C4.5 7.75732 5.50732 6.75 6.75 6.75C7.99268 6.75 9 7.75732 9 9C9 10.2427 7.99268 11.25 6.75 11.25ZM6.75 9.75C7.16422 9.75 7.5 9.41422 7.5 9C7.5 8.58578 7.16422 8.25 6.75 8.25C6.33578 8.25 6 8.58578 6 9C6 9.41422 6.33578 9.75 6.75 9.75Z" fill="currentColor" />
+</svg>
diff --git a/packages/iconify-collections/assets/vender/agent-v2/configure-build.svg b/packages/iconify-collections/assets/vender/agent-v2/configure-build.svg
new file mode 100644
index 00000000000..fa32db16d8d
--- /dev/null
+++ b/packages/iconify-collections/assets/vender/agent-v2/configure-build.svg
@@ -0,0 +1,3 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" fill="none">
+ <path fill-rule="evenodd" clip-rule="evenodd" d="M9.66661 1.33333C9.8434 1.33335 10.013 1.40364 10.138 1.52865L11.4713 2.86198C11.5963 2.987 11.6666 3.15654 11.6666 3.33333C11.6666 3.51012 11.5963 3.67967 11.4713 3.80469L9.10932 6.16667L14.3046 11.362C14.5649 11.6223 14.5649 12.0443 14.3046 12.3047L12.3046 14.3047C12.0443 14.565 11.6223 14.565 11.3619 14.3047L6.16661 9.10938L4.4713 10.8047C4.3463 10.9297 4.17673 11 3.99995 11C3.82316 11 3.65361 10.9297 3.52859 10.8047L0.695261 7.97136C0.434913 7.71101 0.434913 7.289 0.695261 7.02865L6.19526 1.52865L6.24409 1.48438C6.36272 1.38718 6.51191 1.33333 6.66661 1.33333H9.66661ZM7.10932 8.16667L11.8333 12.8906L12.8906 11.8333L8.16661 7.10938L7.10932 8.16667ZM2.10932 7.5L3.99995 9.39063L10.0572 3.33333L9.39057 2.66667H6.94266L2.10932 7.5Z" fill="currentColor" />
+</svg>
diff --git a/packages/iconify-collections/assets/vender/agent-v2/configure-preview.svg b/packages/iconify-collections/assets/vender/agent-v2/configure-preview.svg
new file mode 100644
index 00000000000..7973118a153
--- /dev/null
+++ b/packages/iconify-collections/assets/vender/agent-v2/configure-preview.svg
@@ -0,0 +1,3 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 15 15" fill="none">
+ <path d="M12.4756 4.75207L12.3112 5.12919C12.1909 5.40528 11.8091 5.40528 11.6887 5.12919L11.5244 4.75207C11.2314 4.07965 10.7037 3.54427 10.0451 3.25139L9.53867 3.02615C9.26487 2.90435 9.26487 2.50587 9.53867 2.38408L10.0168 2.17143C10.6923 1.87101 11.2295 1.31582 11.5174 0.620554L11.6862 0.21302C11.8039 -0.0710068 12.1961 -0.0710068 12.3137 0.21302L12.4825 0.620554C12.7705 1.31582 13.3077 1.87101 13.9832 2.17143L14.4613 2.38408C14.7351 2.50587 14.7351 2.90435 14.4613 3.02615L13.9549 3.25139C13.2963 3.54427 12.7686 4.07965 12.4756 4.75207ZM5.33333 1.33333H8V2.66667H5.33333C3.12419 2.66667 1.33333 4.45753 1.33333 6.66667C1.33333 9.07333 2.97472 10.6437 6.66667 12.3199V10.6667H8C10.2091 10.6667 12 8.8758 12 6.66667H13.3333C13.3333 9.6122 10.9455 12 8 12V14.3333C4.66667 13 0 11 0 6.66667C0 3.72115 2.38781 1.33333 5.33333 1.33333Z" fill="currentColor" />
+</svg>
diff --git a/packages/iconify-collections/assets/vender/agent-v2/configure.svg b/packages/iconify-collections/assets/vender/agent-v2/configure.svg
new file mode 100644
index 00000000000..c8da02e46f3
--- /dev/null
+++ b/packages/iconify-collections/assets/vender/agent-v2/configure.svg
@@ -0,0 +1,3 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="14" height="16" viewBox="0 0 14 16" fill="none">
+ <path d="M7.5 2.2912C10.875 2.66428 13.5 5.52559 13.5 9V15.75H0V9C0 5.52559 2.62504 2.66428 6 2.2912V0H7.5V2.2912ZM12 14.25V9C12 6.10051 9.6495 3.75 6.75 3.75C3.85051 3.75 1.5 6.10051 1.5 9V14.25H12ZM6.75 12.75C4.67893 12.75 3 11.071 3 9C3 6.92895 4.67893 5.25 6.75 5.25C8.82105 5.25 10.5 6.92895 10.5 9C10.5 11.071 8.82105 12.75 6.75 12.75ZM6.75 11.25C7.99268 11.25 9 10.2427 9 9C9 7.75732 7.99268 6.75 6.75 6.75C5.50732 6.75 4.5 7.75732 4.5 9C4.5 10.2427 5.50732 11.25 6.75 11.25ZM6.75 9.75C6.33578 9.75 6 9.41422 6 9C6 8.58578 6.33578 8.25 6.75 8.25C7.16422 8.25 7.5 8.58578 7.5 9C7.5 9.41422 7.16422 9.75 6.75 9.75Z" fill="currentColor" />
+</svg>
diff --git a/packages/iconify-collections/custom-public/icons.json b/packages/iconify-collections/custom-public/icons.json
index 0f83cf3b3e8..bba5a879707 100644
--- a/packages/iconify-collections/custom-public/icons.json
+++ b/packages/iconify-collections/custom-public/icons.json
@@ -1,6 +1,6 @@
{
"prefix": "custom-public",
- "lastModified": 1781515983,
+ "lastModified": 1782215796,
"icons": {
"agent-building-blocks": {
"body": "<path fill=\"#155AEF\" fill-rule=\"evenodd\" d=\"M8.303 1.546c.178-.045.364-.051.544-.017c.23.043.432.167.573.246l3.757 2.113c.12.067.29.156.433.289l.06.06c.12.131.21.288.267.457c.07.215.063.445.063.6V9.56c0 .146.007.36-.056.563q-.055.181-.162.338l-.075.1c-.137.163-.32.274-.442.353l-5.013 3.259c-.135.088-.33.224-.556.282a1.3 1.3 0 0 1-.543.017c-.23-.043-.433-.166-.573-.245l-3.757-2.114c-.136-.077-.34-.182-.493-.35a1.3 1.3 0 0 1-.267-.456C1.993 11.09 2 10.86 2 10.704V6.441c0-.146-.007-.36.055-.563l.043-.118a1.3 1.3 0 0 1 .195-.32l.053-.059c.128-.131.282-.225.389-.294L7.86 1.755c.122-.078.273-.165.443-.209m-4.97 9.158l.001.164l.033.02l.11.062l3.264 1.836v-1.137L3.333 9.732zm4.741.917v1.076l4.464-2.901l.098-.065l.029-.02v-.034l.001-.118v-.923zm-4.74-3.419L6.74 10.12V8.982L3.333 7.066zm4.74.752v1.076l4.592-2.985V5.969zm.51-6.08l-4.631 3.01l3.429 1.93l4.664-3.032l-3.28-1.846l-.15-.082z\" clip-rule=\"evenodd\"/>"
diff --git a/packages/iconify-collections/custom-vender/icons.json b/packages/iconify-collections/custom-vender/icons.json
index 048c5af7553..f1aa8be7d73 100644
--- a/packages/iconify-collections/custom-vender/icons.json
+++ b/packages/iconify-collections/custom-vender/icons.json
@@ -1,14 +1,32 @@
{
"prefix": "custom-vender",
- "lastModified": 1781515983,
+ "lastModified": 1782365697,
"icons": {
"agent-v2-access-point": {
"body": "<g fill=\"none\"><path d=\"M7.5 11.25C7.91421 11.25 8.25 11.5858 8.25 12V14.25C8.25 14.6642 7.91421 15 7.5 15C7.08579 15 6.75 14.6642 6.75 14.25V12C6.75 11.5858 7.08579 11.25 7.5 11.25Z\" fill=\"currentColor\"/><path d=\"M2.19653 2.19653C2.48937 1.90372 2.96418 1.90382 3.25708 2.19653L8.03027 6.96973C8.09162 7.03108 8.13966 7.10082 8.17529 7.1748C8.19164 7.20869 8.20587 7.24378 8.21704 7.28027C8.24638 7.37633 8.25641 7.477 8.24634 7.57617C8.23743 7.66451 8.21216 7.74788 8.17529 7.82446C8.13963 7.89868 8.09176 7.96874 8.03027 8.03027L3.25708 12.8035C2.96419 13.096 2.48932 13.0962 2.19653 12.8035C1.90394 12.5107 1.90405 12.0358 2.19653 11.7429L5.68945 8.25H0.75C0.335786 8.25 0 7.91421 0 7.5C0 7.08579 0.335786 6.75 0.75 6.75H5.68945L2.19653 3.25708C1.90389 2.96423 1.90388 2.48937 2.19653 2.19653Z\" fill=\"currentColor\"/><path d=\"M10.1521 10.1521C10.445 9.85921 10.9198 9.85921 11.2126 10.1521L12.8035 11.7429C13.096 12.0358 13.0962 12.5107 12.8035 12.8035C12.5107 13.0962 12.0358 13.096 11.7429 12.8035L10.1521 11.2126C9.85921 10.9198 9.85922 10.445 10.1521 10.1521Z\" fill=\"currentColor\"/><path d=\"M14.25 6.75C14.6642 6.75 15 7.08579 15 7.5C15 7.91421 14.6642 8.25 14.25 8.25H12C11.5858 8.25 11.25 7.91421 11.25 7.5C11.25 7.08579 11.5858 6.75 12 6.75H14.25Z\" fill=\"currentColor\"/><path d=\"M11.7422 2.19653C12.035 1.90387 12.5098 1.90406 12.8027 2.19653C13.0956 2.4894 13.0955 2.96419 12.8027 3.25708L11.2119 4.8479C10.919 5.14079 10.4443 5.1408 10.1514 4.8479C9.85883 4.55497 9.85858 4.08013 10.1514 3.78735L11.7422 2.19653Z\" fill=\"currentColor\"/><path d=\"M7.5 0C7.91421 0 8.25 0.335786 8.25 0.75V3C8.25 3.41421 7.91421 3.75 7.5 3.75C7.08579 3.75 6.75 3.41421 6.75 3V0.75C6.75 0.335786 7.08579 0 7.5 0Z\" fill=\"currentColor\"/></g>",
"width": 15,
"height": 15
},
+ "agent-v2-configure": {
+ "body": "<g fill=\"none\"><path d=\"M7.5 2.2912C10.875 2.66428 13.5 5.52559 13.5 9V15.75H0V9C0 5.52559 2.62504 2.66428 6 2.2912V0H7.5V2.2912ZM12 14.25V9C12 6.10051 9.6495 3.75 6.75 3.75C3.85051 3.75 1.5 6.10051 1.5 9V14.25H12ZM6.75 12.75C4.67893 12.75 3 11.071 3 9C3 6.92895 4.67893 5.25 6.75 5.25C8.82105 5.25 10.5 6.92895 10.5 9C10.5 11.071 8.82105 12.75 6.75 12.75ZM6.75 11.25C7.99268 11.25 9 10.2427 9 9C9 7.75732 7.99268 6.75 6.75 6.75C5.50732 6.75 4.5 7.75732 4.5 9C4.5 10.2427 5.50732 11.25 6.75 11.25ZM6.75 9.75C6.33578 9.75 6 9.41422 6 9C6 8.58578 6.33578 8.25 6.75 8.25C7.16422 8.25 7.5 8.58578 7.5 9C7.5 9.41422 7.16422 9.75 6.75 9.75Z\" fill=\"currentColor\"/></g>",
+ "width": 14
+ },
+ "agent-v2-configure-active": {
+ "body": "<g fill=\"none\"><path d=\"M7.5 2.2912C10.875 2.66428 13.5 5.52559 13.5 9V15.75H0V9C0 5.52559 2.62504 2.66428 6 2.2912V0H7.5V2.2912ZM6.75 12.75C8.82105 12.75 10.5 11.071 10.5 9C10.5 6.92895 8.82105 5.25 6.75 5.25C4.67893 5.25 3 6.92895 3 9C3 11.071 4.67893 12.75 6.75 12.75ZM6.75 11.25C5.50732 11.25 4.5 10.2427 4.5 9C4.5 7.75732 5.50732 6.75 6.75 6.75C7.99268 6.75 9 7.75732 9 9C9 10.2427 7.99268 11.25 6.75 11.25ZM6.75 9.75C7.16422 9.75 7.5 9.41422 7.5 9C7.5 8.58578 7.16422 8.25 6.75 8.25C6.33578 8.25 6 8.58578 6 9C6 9.41422 6.33578 9.75 6.75 9.75Z\" fill=\"currentColor\"/></g>",
+ "width": 14
+ },
+ "agent-v2-configure-build": {
+ "body": "<g fill=\"none\"><path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M9.66661 1.33333C9.8434 1.33335 10.013 1.40364 10.138 1.52865L11.4713 2.86198C11.5963 2.987 11.6666 3.15654 11.6666 3.33333C11.6666 3.51012 11.5963 3.67967 11.4713 3.80469L9.10932 6.16667L14.3046 11.362C14.5649 11.6223 14.5649 12.0443 14.3046 12.3047L12.3046 14.3047C12.0443 14.565 11.6223 14.565 11.3619 14.3047L6.16661 9.10938L4.4713 10.8047C4.3463 10.9297 4.17673 11 3.99995 11C3.82316 11 3.65361 10.9297 3.52859 10.8047L0.695261 7.97136C0.434913 7.71101 0.434913 7.289 0.695261 7.02865L6.19526 1.52865L6.24409 1.48438C6.36272 1.38718 6.51191 1.33333 6.66661 1.33333H9.66661ZM7.10932 8.16667L11.8333 12.8906L12.8906 11.8333L8.16661 7.10938L7.10932 8.16667ZM2.10932 7.5L3.99995 9.39063L10.0572 3.33333L9.39057 2.66667H6.94266L2.10932 7.5Z\" fill=\"currentColor\"/></g>",
+ "width": 16
+ },
+ "agent-v2-configure-preview": {
+ "body": "<g fill=\"none\"><path d=\"M12.4756 4.75207L12.3112 5.12919C12.1909 5.40528 11.8091 5.40528 11.6887 5.12919L11.5244 4.75207C11.2314 4.07965 10.7037 3.54427 10.0451 3.25139L9.53867 3.02615C9.26487 2.90435 9.26487 2.50587 9.53867 2.38408L10.0168 2.17143C10.6923 1.87101 11.2295 1.31582 11.5174 0.620554L11.6862 0.21302C11.8039-0.0710068 12.1961-0.0710068 12.3137 0.21302L12.4825 0.620554C12.7705 1.31582 13.3077 1.87101 13.9832 2.17143L14.4613 2.38408C14.7351 2.50587 14.7351 2.90435 14.4613 3.02615L13.9549 3.25139C13.2963 3.54427 12.7686 4.07965 12.4756 4.75207ZM5.33333 1.33333H8V2.66667H5.33333C3.12419 2.66667 1.33333 4.45753 1.33333 6.66667C1.33333 9.07333 2.97472 10.6437 6.66667 12.3199V10.6667H8C10.2091 10.6667 12 8.8758 12 6.66667H13.3333C13.3333 9.6122 10.9455 12 8 12V14.3333C4.66667 13 0 11 0 6.66667C0 3.72115 2.38781 1.33333 5.33333 1.33333Z\" fill=\"currentColor\"/></g>",
+ "width": 15,
+ "height": 15
+ },
"agent-v2-end-user-auth": {
- "body": "<g fill=\"none\"><path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M12 7.33325C13.1046 7.33325 14 8.22865 14 9.33325C14 10.1403 13.5218 10.8356 12.8333 11.1516V11.9999L12.3333 12.4999L12.8333 12.9511V13.6666L12 14.3333L11.1667 13.6666V11.1516C10.4782 10.8356 10 10.1403 10 9.33325C10 8.22865 10.8954 7.33325 12 7.33325ZM12 8.66659C11.6318 8.66659 11.3333 8.96505 11.3333 9.33325C11.3333 9.70145 11.6318 9.99992 12 9.99992C12.3682 9.99992 12.6667 9.70145 12.6667 9.33325C12.6667 8.96505 12.3682 8.66659 12 8.66659Z\" fill=\"currentColor\"/><path d=\"M8 7.99992C8.2545 7.99992 8.50382 8.01506 8.7474 8.04484L8.58594 9.36841C8.39687 9.34527 8.20127 9.33325 8 9.33325C5.8465 9.33325 4.25915 10.7274 3.78646 12.6666H10V13.9999H2.26758L2.33594 13.2708C2.61081 10.3473 4.82817 7.99992 8 7.99992Z\" fill=\"currentColor\"/><path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M8 1.33325C9.65687 1.33325 11 2.6764 11 4.33325C11 5.99011 9.65687 7.33325 8 7.33325C6.34315 7.33325 5 5.99011 5 4.33325C5 2.6764 6.34315 1.33325 8 1.33325ZM8 2.66659C7.07953 2.66659 6.33333 3.41278 6.33333 4.33325C6.33333 5.25373 7.07953 5.99992 8 5.99992C8.92047 5.99992 9.66667 5.25373 9.66667 4.33325C9.66667 3.41278 8.92047 2.66659 8 2.66659Z\" fill=\"currentColor\"/></g>"
+ "body": "<g fill=\"none\"><path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M12 7.33325C13.1046 7.33325 14 8.22865 14 9.33325C14 10.1403 13.5218 10.8356 12.8333 11.1516V11.9999L12.3333 12.4999L12.8333 12.9511V13.6666L12 14.3333L11.1667 13.6666V11.1516C10.4782 10.8356 10 10.1403 10 9.33325C10 8.22865 10.8954 7.33325 12 7.33325ZM12 8.66659C11.6318 8.66659 11.3333 8.96505 11.3333 9.33325C11.3333 9.70145 11.6318 9.99992 12 9.99992C12.3682 9.99992 12.6667 9.70145 12.6667 9.33325C12.6667 8.96505 12.3682 8.66659 12 8.66659Z\" fill=\"currentColor\"/><path d=\"M8 7.99992C8.2545 7.99992 8.50382 8.01506 8.7474 8.04484L8.58594 9.36841C8.39687 9.34527 8.20127 9.33325 8 9.33325C5.8465 9.33325 4.25915 10.7274 3.78646 12.6666H10V13.9999H2.26758L2.33594 13.2708C2.61081 10.3473 4.82817 7.99992 8 7.99992Z\" fill=\"currentColor\"/><path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M8 1.33325C9.65687 1.33325 11 2.6764 11 4.33325C11 5.99011 9.65687 7.33325 8 7.33325C6.34315 7.33325 5 5.99011 5 4.33325C5 2.6764 6.34315 1.33325 8 1.33325ZM8 2.66659C7.07953 2.66659 6.33333 3.41278 6.33333 4.33325C6.33333 5.25373 7.07953 5.99992 8 5.99992C8.92047 5.99992 9.66667 5.25373 9.66667 4.33325C9.66667 3.41278 8.92047 2.66659 8 2.66659Z\" fill=\"currentColor\"/></g>",
+ "width": 16
},
"agent-v2-plan": {
"body": "<g fill=\"none\"><path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M17 0C17.5523 0 18 0.447715 18 1V6C18 6.55228 17.5523 7 17 7H12C11.4477 7 11 6.55228 11 6V4.5H6.94629C5.92438 4.50039 5.56101 5.85276 6.44531 6.36523L12.5576 9.90332C15.2116 11.4402 14.1206 15.4996 11.0537 15.5H7V17C7 17.5523 6.55228 18 6 18H1C0.447715 18 0 17.5523 0 17V12C0 11.4477 0.447715 11 1 11H6C6.55228 11 7 11.4477 7 12V13.5H11.0537C12.0756 13.4996 12.4394 12.1472 11.5557 11.6348L5.44336 8.09668C2.789 6.55983 3.87917 2.50039 6.94629 2.5H11V1C11 0.447715 11.4477 0 12 0H17ZM2 16H5V13H2V16ZM13 5H16V2H13V5Z\" fill=\"currentColor\"/></g>",
@@ -17,8 +35,8 @@
},
"agent-v2-prompt-insert": {
"body": "<g fill=\"none\"><path d=\"M2.91669 1.16669C1.95019 1.16669 1.16669 1.95019 1.16669 2.91669V11.0834C1.16669 12.0499 1.95019 12.8334 2.91669 12.8334H11.0834C12.0499 12.8334 12.8334 12.0499 12.8334 11.0834V2.91669C12.8334 1.95019 12.0499 1.16669 11.0834 1.16669H2.91669ZM2.33335 2.91669C2.33335 2.59452 2.59452 2.33335 2.91669 2.33335H11.0834C11.4055 2.33335 11.6667 2.59452 11.6667 2.91669V11.0834C11.6667 11.4055 11.4055 11.6667 11.0834 11.6667H2.91669C2.59452 11.6667 2.33335 11.4055 2.33335 11.0834V2.91669ZM5.67188 10.5L9.67186 3.50002H8.32815L4.32817 10.5H5.67188Z\" fill=\"currentColor\"/></g>",
- "width": 14,
- "height": 14
+ "height": 14,
+ "width": 14
},
"agent-v2-robot-3": {
"body": "<g fill=\"none\"><path d=\"M6.25 6.875C6.82523 6.875 7.29167 7.34128 7.29167 7.91667V9.16667C7.29167 9.74205 6.82523 10.2083 6.25 10.2083C5.67477 10.2083 5.20833 9.74205 5.20833 9.16667V7.91667C5.20833 7.34128 5.67477 6.875 6.25 6.875Z\" fill=\"currentColor\"/><path d=\"M10.4167 6.875C10.992 6.875 11.4583 7.34135 11.4583 7.91667V9.16667C11.4583 9.74199 10.992 10.2083 10.4167 10.2083C9.84135 10.2083 9.375 9.74199 9.375 9.16667V7.91667C9.375 7.34135 9.84135 6.875 10.4167 6.875Z\" fill=\"currentColor\"/><path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M8.33333 0C9.13875 0 9.79167 0.652918 9.79167 1.45833C9.79167 2.02329 9.46964 2.51173 8.99984 2.75391V3.33822C9.38912 3.34279 9.77995 3.35006 10.175 3.36263C11.6983 3.41112 12.7377 3.42425 13.6401 3.90951C14.375 4.30477 15.0255 4.97655 15.3971 5.72347C15.5468 6.02442 15.6427 6.33532 15.7056 6.66667H15.8333C16.2936 6.66667 16.6667 7.03976 16.6667 7.5V10C16.6667 10.4602 16.2936 10.8333 15.8333 10.8333H15.8285C15.8235 11.2254 15.813 11.5735 15.7869 11.8831C15.7386 12.4571 15.6361 12.9628 15.3971 13.4432C15.0254 14.1901 14.3749 14.8619 13.6401 15.2572C12.7377 15.7424 11.6982 15.7556 10.175 15.804C8.93336 15.8436 7.73328 15.8436 6.4917 15.804C4.96843 15.7556 3.92896 15.7424 3.02653 15.2572C2.29178 14.8619 1.64121 14.1902 1.26953 13.4432C1.03058 12.9628 0.928072 12.4571 0.87972 11.8831C0.853642 11.5735 0.843216 11.2254 0.838216 10.8333H0.833333C0.373096 10.8333 0 10.4602 0 10V7.5C0 7.03976 0.373096 6.66667 0.833333 6.66667H0.9611C1.02392 6.33532 1.11984 6.02442 1.26953 5.72347C1.64119 4.97649 2.29177 4.30475 3.02653 3.90951C3.92895 3.42425 4.96837 3.41112 6.4917 3.36263C6.88671 3.35006 7.27754 3.34279 7.66683 3.33822V2.75391C7.19703 2.51173 6.875 2.02329 6.875 1.45833C6.875 0.652918 7.52792 0 8.33333 0ZM10.1213 5.02848C8.91522 4.9901 7.75142 4.9901 6.54541 5.02848C4.85908 5.08217 4.29323 5.12091 3.81592 5.3776C3.38476 5.60954 2.98015 6.02734 2.76204 6.46566C2.65217 6.68652 2.57959 6.96168 2.54069 7.4235C2.50069 7.89854 2.5 8.50363 2.5 9.37825V9.78841C2.5 10.663 2.50069 11.2681 2.54069 11.7432C2.57959 12.205 2.65215 12.4801 2.76204 12.701C2.98015 13.1393 3.38475 13.5571 3.81592 13.7891C4.29321 14.0458 4.85904 14.0845 6.54541 14.1382C7.75141 14.1766 8.91523 14.1766 10.1213 14.1382C11.8075 14.0845 12.3734 14.0458 12.8507 13.7891C13.2819 13.5572 13.6865 13.1394 13.9046 12.701C14.0145 12.4801 14.0871 12.205 14.126 11.7432C14.166 11.2681 14.1667 10.663 14.1667 9.78841V9.37825C14.1667 8.50363 14.166 7.89854 14.126 7.4235C14.0871 6.96168 14.0145 6.68652 13.9046 6.46566C13.6865 6.02729 13.2819 5.60951 12.8507 5.3776C12.3734 5.12091 11.8075 5.08217 10.1213 5.02848Z\" fill=\"currentColor\"/></g>",
diff --git a/packages/iconify-collections/custom-vender/info.json b/packages/iconify-collections/custom-vender/info.json
index 608b5020f04..57770b38ddc 100644
--- a/packages/iconify-collections/custom-vender/info.json
+++ b/packages/iconify-collections/custom-vender/info.json
@@ -1,7 +1,7 @@
{
"prefix": "custom-vender",
"name": "Dify Custom Vender",
- "total": 326,
+ "total": 330,
"version": "0.0.0-private",
"author": {
"name": "LangGenius, Inc.",
@@ -14,11 +14,11 @@
},
"samples": [
"agent-v2-access-point",
- "agent-v2-end-user-auth",
- "agent-v2-plan",
- "agent-v2-prompt-insert",
- "agent-v2-robot-3",
- "features-citations"
+ "agent-v2-configure",
+ "agent-v2-configure-active",
+ "agent-v2-configure-build",
+ "agent-v2-configure-preview",
+ "agent-v2-end-user-auth"
],
"palette": false
}
diff --git a/web/__tests__/proxy-frame-options.spec.ts b/web/__tests__/proxy-frame-options.spec.ts
new file mode 100644
index 00000000000..f6f6abe160c
--- /dev/null
+++ b/web/__tests__/proxy-frame-options.spec.ts
@@ -0,0 +1,20 @@
+import { describe, expect, it } from 'vitest'
+import { canEmbedPath } from '@/proxy'
+
+describe('proxy frame options', () => {
+ it('should allow embedded share routes', () => {
+ expect(canEmbedPath('/chatbot/token')).toBe(true)
+ expect(canEmbedPath('/workflow/token')).toBe(true)
+ expect(canEmbedPath('/completion/token')).toBe(true)
+ expect(canEmbedPath('/webapp-signin')).toBe(true)
+ expect(canEmbedPath('/agent/token')).toBe(true)
+ })
+
+ it('should deny non-embedded console routes by default', () => {
+ expect(canEmbedPath('/agents')).toBe(false)
+ expect(canEmbedPath('/agent-settings')).toBe(false)
+ expect(canEmbedPath('/agentic')).toBe(false)
+ expect(canEmbedPath('/roster/agent/agent-1/access')).toBe(false)
+ expect(canEmbedPath('/apps')).toBe(false)
+ })
+})
diff --git a/web/app/components/app-sidebar/nav-link/index.tsx b/web/app/components/app-sidebar/nav-link/index.tsx
index ab7ec49acca..1f4e17cfec0 100644
--- a/web/app/components/app-sidebar/nav-link/index.tsx
+++ b/web/app/components/app-sidebar/nav-link/index.tsx
@@ -47,10 +47,12 @@ const NavLink = ({
const NavIcon = isActive ? iconMap.selected : iconMap.normal
const isCollapsed = mode !== 'expand'
+ const borderClassName = 'border-t-[0.75px] border-r-[0.25px] border-b-[0.25px] border-l-[0.75px]'
const linkClassName = cn(
+ borderClassName,
isActive
- ? 'border-t-[0.75px] border-r-[0.25px] border-b-[0.25px] border-l-[0.75px] border-effects-highlight-lightmode-off bg-components-menu-item-bg-active system-sm-semibold text-text-accent-light-mode-only'
- : 'system-sm-medium text-components-menu-item-text hover:bg-components-menu-item-bg-hover hover:text-components-menu-item-text-hover',
+ ? 'border-effects-highlight-lightmode-off bg-components-menu-item-bg-active system-sm-semibold text-text-accent-light-mode-only'
+ : 'border-transparent system-sm-medium text-components-menu-item-text hover:bg-components-menu-item-bg-hover hover:text-components-menu-item-text-hover',
isCollapsed ? 'flex size-8 items-center justify-center p-1.5' : 'flex h-8 items-center rounded-lg pr-1 pl-3',
'rounded-lg',
)
@@ -68,7 +70,9 @@ const NavLink = ({
type="button"
disabled
className={cn(
+ borderClassName,
'cursor-not-allowed rounded-lg system-sm-medium text-components-menu-item-text opacity-30 hover:bg-components-menu-item-bg-hover',
+ 'border-transparent',
isCollapsed ? 'flex size-8 items-center justify-center p-1.5' : 'flex h-8 items-center pr-1 pl-3',
)}
title={mode === 'collapse' ? name : ''}
diff --git a/web/app/components/app/overview/__tests__/app-card-utils.spec.ts b/web/app/components/app/overview/__tests__/app-card-utils.spec.ts
index 11c2dd54bb1..694a9aec7ba 100644
--- a/web/app/components/app/overview/__tests__/app-card-utils.spec.ts
+++ b/web/app/components/app/overview/__tests__/app-card-utils.spec.ts
@@ -285,6 +285,18 @@ describe('app-card-utils', () => {
expect(snippet).not.toContain('isDev: true')
})
+ it('should generate an agent embedded script route when requested', () => {
+ const snippet = getEmbeddedScriptSnippet({
+ url: 'https://example.com',
+ token: 'agent-token',
+ webAppRoute: 'agent',
+ primaryColor: '#1C64F2',
+ inputValues: {},
+ })
+
+ expect(snippet).toContain('routeSegment: \'agent\'')
+ })
+
it('should compress and encode base64 using CompressionStream when available', async () => {
const result = await compressAndEncodeBase64('hello')
expect(typeof result).toBe('string')
diff --git a/web/app/components/app/overview/app-card-utils.ts b/web/app/components/app/overview/app-card-utils.ts
index 9475da4300a..acca7e162a0 100644
--- a/web/app/components/app/overview/app-card-utils.ts
+++ b/web/app/components/app/overview/app-card-utils.ts
@@ -11,6 +11,7 @@ type OverviewCardType = 'api' | 'webapp'
export type OverviewOperationKey = 'launch' | 'embedded' | 'customize' | 'settings' | 'develop'
export type WorkflowLaunchInputValue = string | boolean
+export type EmbeddedWebAppRoute = 'chatbot' | 'agent'
export type WorkflowHiddenStartVariable = Pick<
InputVar,
'default' | 'hide' | 'label' | 'max_length' | 'options' | 'required' | 'type' | 'variable'
@@ -156,12 +157,14 @@ ${entries.map(([key, value]) => ` ${key}: ${JSON.stringify(value)},`).join('\
export const getEmbeddedScriptSnippet = ({
url,
token,
+ webAppRoute = 'chatbot',
primaryColor,
isTestEnv,
inputValues,
}: {
url: string
token: string
+ webAppRoute?: EmbeddedWebAppRoute
primaryColor: string
isTestEnv?: boolean
inputValues: Record<string, WorkflowLaunchInputValue>
@@ -174,6 +177,9 @@ export const getEmbeddedScriptSnippet = ({
: ''}${IS_CE_EDITION
? `,
baseUrl: '${url}${basePath}'`
+ : ''}${webAppRoute !== 'chatbot'
+ ? `,
+ routeSegment: '${webAppRoute}'`
: ''},
inputs: ${getScriptInputsContent(inputValues)},
systemVariables: {
diff --git a/web/app/components/app/overview/customize/index.tsx b/web/app/components/app/overview/customize/index.tsx
index 3affa339bf3..98b67db112c 100644
--- a/web/app/components/app/overview/customize/index.tsx
+++ b/web/app/components/app/overview/customize/index.tsx
@@ -13,7 +13,8 @@ type IShareLinkProps = {
onClose: () => void
api_base_url: string
appId: string
- mode: AppModeEnum
+ mode?: AppModeEnum
+ sourceCodeRepository?: 'webapp-conversation' | 'webapp-text-generator'
}
const StepNum: FC<{ children: React.ReactNode }> = ({ children }) => (
@@ -38,10 +39,12 @@ const CustomizeModal: FC<IShareLinkProps> = ({
appId,
api_base_url,
mode,
+ sourceCodeRepository,
}) => {
const { t } = useTranslation()
const docLink = useDocLink()
const isChatApp = mode === AppModeEnum.CHAT || mode === AppModeEnum.ADVANCED_CHAT
+ const repository = sourceCodeRepository ?? (isChatApp ? 'webapp-conversation' : 'webapp-text-generator')
const apiDocLink = docLink('/use-dify/publish/developing-with-apis')
return (
@@ -67,7 +70,7 @@ const CustomizeModal: FC<IShareLinkProps> = ({
<div className="flex flex-col">
<div className="text-text-primary">{t(`${prefixCustomize}.way1.step1`, { ns: 'appOverview' })}</div>
<div className="mt-1 mb-2 text-xs text-text-tertiary">{t(`${prefixCustomize}.way1.step1Tip`, { ns: 'appOverview' })}</div>
- <Button nativeButton={false} render={<a href={`https://github.com/langgenius/${isChatApp ? 'webapp-conversation' : 'webapp-text-generator'}`} target="_blank" rel="noopener noreferrer" />}>
+ <Button nativeButton={false} render={<a href={`https://github.com/langgenius/${repository}`} target="_blank" rel="noopener noreferrer" aria-label={t(`${prefixCustomize}.way1.step1Operation`, { ns: 'appOverview' })} />}>
<GithubIcon className="mr-2 text-text-secondary" />
{t(`${prefixCustomize}.way1.step1Operation`, { ns: 'appOverview' })}
</Button>
@@ -78,7 +81,7 @@ const CustomizeModal: FC<IShareLinkProps> = ({
<div className="flex flex-col">
<div className="text-text-primary">{t(`${prefixCustomize}.way1.step2`, { ns: 'appOverview' })}</div>
<div className="mt-1 mb-2 text-xs text-text-tertiary">{t(`${prefixCustomize}.way1.step2Tip`, { ns: 'appOverview' })}</div>
- <Button nativeButton={false} render={<a href="https://vercel.com/docs/concepts/deployments/git/vercel-for-github" target="_blank" rel="noopener noreferrer" />}>
+ <Button nativeButton={false} render={<a href="https://vercel.com/docs/concepts/deployments/git/vercel-for-github" target="_blank" rel="noopener noreferrer" aria-label={t(`${prefixCustomize}.way1.step2Operation`, { ns: 'appOverview' })} />}>
<div className="mr-1.5 border-t-0 border-r-[7px] border-b-12 border-l-[7px] border-solid border-text-primary border-t-transparent border-r-transparent border-l-transparent"></div>
<span>{t(`${prefixCustomize}.way1.step2Operation`, { ns: 'appOverview' })}</span>
</Button>
@@ -114,7 +117,7 @@ const CustomizeModal: FC<IShareLinkProps> = ({
<p className="my-2 system-sm-medium text-text-secondary">{t(`${prefixCustomize}.way2.name`, { ns: 'appOverview' })}</p>
<Button
nativeButton={false}
- render={<a href={apiDocLink} target="_blank" rel="noopener noreferrer" />}
+ render={<a href={apiDocLink} target="_blank" rel="noopener noreferrer" aria-label={t(`${prefixCustomize}.way2.operation`, { ns: 'appOverview' })} />}
className="mt-2"
>
<span className="text-sm text-text-secondary">{t(`${prefixCustomize}.way2.operation`, { ns: 'appOverview' })}</span>
diff --git a/web/app/components/app/overview/embedded/index.tsx b/web/app/components/app/overview/embedded/index.tsx
index 70b90c3cc04..fd36938af79 100644
--- a/web/app/components/app/overview/embedded/index.tsx
+++ b/web/app/components/app/overview/embedded/index.tsx
@@ -1,13 +1,9 @@
import type { MutableRefObject } from 'react'
-import type { WorkflowHiddenStartVariable, WorkflowLaunchInputValue } from '../app-card-utils'
+import type { EmbeddedWebAppRoute, WorkflowHiddenStartVariable, WorkflowLaunchInputValue } from '../app-card-utils'
import type { SiteInfo } from '@/models/share'
import { cn } from '@langgenius/dify-ui/cn'
import { Dialog, DialogCloseButton, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
-import {
- RiArrowDownSLine,
- RiArrowRightSLine,
-} from '@remixicon/react'
import copy from 'copy-to-clipboard'
import { Suspense, use, useEffect, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
@@ -33,6 +29,7 @@ type Props = Readonly<{
onClose: () => void
accessToken?: string
appBaseUrl?: string
+ webAppRoute?: EmbeddedWebAppRoute
hiddenInputs?: WorkflowHiddenStartVariable[]
className?: string
}>
@@ -62,15 +59,17 @@ const getSerializedHiddenInputValue = (
const buildEmbeddedIframeUrl = async ({
appBaseUrl,
accessToken,
+ webAppRoute,
variables,
values,
}: {
appBaseUrl: string
accessToken: string
+ webAppRoute: EmbeddedWebAppRoute
variables: WorkflowHiddenStartVariable[]
values: Record<string, WorkflowLaunchInputValue>
}) => {
- const iframeUrl = new URL(`${appBaseUrl}${basePath}/chatbot/${accessToken}`, window.location.origin)
+ const iframeUrl = new URL(`${appBaseUrl}${basePath}/${webAppRoute}/${accessToken}`, window.location.origin)
await Promise.all(variables.map(async (variable) => {
iframeUrl.searchParams.set(variable.variable, await compressAndEncodeBase64(getSerializedHiddenInputValue(variable, values)))
@@ -101,8 +100,9 @@ const EmbeddedContent = ({
siteInfo,
appBaseUrl,
accessToken,
+ webAppRoute = 'chatbot',
hiddenInputs,
-}: Required<Pick<Props, 'accessToken' | 'appBaseUrl'>> & Pick<Props, 'siteInfo' | 'hiddenInputs'>) => {
+}: Required<Pick<Props, 'accessToken' | 'appBaseUrl'>> & Pick<Props, 'siteInfo' | 'webAppRoute' | 'hiddenInputs'>) => {
const { t } = useTranslation()
const supportedHiddenInputs = useMemo<WorkflowHiddenStartVariable[]>(
() => (hiddenInputs ?? []).filter(isWorkflowLaunchInputSupported),
@@ -122,6 +122,7 @@ const EmbeddedContent = ({
() => buildEmbeddedIframeUrl({
appBaseUrl,
accessToken,
+ webAppRoute,
variables: supportedHiddenInputs,
values: initialHiddenInputValues,
}),
@@ -143,6 +144,7 @@ const EmbeddedContent = ({
setPreviewIframeUrlPromise(buildEmbeddedIframeUrl({
appBaseUrl,
accessToken,
+ webAppRoute,
variables: supportedHiddenInputs,
values: nextHiddenInputValues,
}))
@@ -150,15 +152,17 @@ const EmbeddedContent = ({
const scriptsContent = useMemo(() => getEmbeddedScriptSnippet({
url: appBaseUrl,
token: accessToken,
+ webAppRoute,
primaryColor: themeBuilder.theme?.primaryColor ?? '#1C64F2',
isTestEnv,
inputValues: hiddenInputValues,
- }), [accessToken, appBaseUrl, hiddenInputValues, isTestEnv, themeBuilder.theme?.primaryColor])
+ }), [accessToken, appBaseUrl, hiddenInputValues, isTestEnv, themeBuilder.theme?.primaryColor, webAppRoute])
const onClickCopy = async () => {
const latestIframeUrl = await buildEmbeddedIframeUrl({
appBaseUrl,
accessToken,
+ webAppRoute,
variables: supportedHiddenInputs,
values: hiddenInputValues,
})
@@ -211,8 +215,8 @@ const EmbeddedContent = ({
</div>
</div>
{hiddenInputsCollapsed
- ? <RiArrowRightSLine className="size-4 shrink-0 text-text-tertiary" />
- : <RiArrowDownSLine className="size-4 shrink-0 text-text-tertiary" />}
+ ? <span aria-hidden className="i-ri-arrow-right-s-line size-4 shrink-0 text-text-tertiary" />
+ : <span aria-hidden className="i-ri-arrow-down-s-line size-4 shrink-0 text-text-tertiary" />}
</button>
{!hiddenInputsCollapsed && (
<div className="max-h-72 space-y-4 overflow-y-auto border-t-[0.5px] border-divider-subtle px-4 py-4">
@@ -307,7 +311,7 @@ const EmbeddedContent = ({
)
}
-const Embedded = ({ siteInfo, isShow, onClose, appBaseUrl, accessToken, hiddenInputs, className }: Props) => {
+const Embedded = ({ siteInfo, isShow, onClose, appBaseUrl, accessToken, webAppRoute = 'chatbot', hiddenInputs, className }: Props) => {
const { t } = useTranslation()
return (
@@ -327,10 +331,11 @@ const Embedded = ({ siteInfo, isShow, onClose, appBaseUrl, accessToken, hiddenIn
<div className="min-h-0 flex-1 overflow-y-auto overscroll-contain">
{isShow && (
<EmbeddedContent
- key={`${appBaseUrl ?? ''}:${accessToken ?? ''}:${JSON.stringify(hiddenInputs ?? [])}`}
+ key={`${appBaseUrl ?? ''}:${accessToken ?? ''}:${webAppRoute}:${JSON.stringify(hiddenInputs ?? [])}`}
siteInfo={siteInfo}
appBaseUrl={appBaseUrl ?? ''}
accessToken={accessToken ?? ''}
+ webAppRoute={webAppRoute}
hiddenInputs={hiddenInputs}
/>
)}
diff --git a/web/app/components/app/overview/settings/__tests__/index.spec.tsx b/web/app/components/app/overview/settings/__tests__/index.spec.tsx
index 280b35c5437..facebf0b91c 100644
--- a/web/app/components/app/overview/settings/__tests__/index.spec.tsx
+++ b/web/app/components/app/overview/settings/__tests__/index.spec.tsx
@@ -228,15 +228,15 @@ describe('SettingsModal', () => {
expect(mockOnClose).toHaveBeenCalled()
})
- it('should collapse the expanded settings section immediately when closing', () => {
+ it('should keep one show-more trigger while toggling the advanced section', () => {
renderSettingsModal()
- fireEvent.click(screen.getByText('appOverview.overview.appInfo.settings.more.entry'))
- expect(screen.getByPlaceholderText('appOverview.overview.appInfo.settings.more.privacyPolicyPlaceholder')).toBeInTheDocument()
+ expect(screen.getAllByText('appOverview.overview.appInfo.settings.more.entry')).toHaveLength(1)
- fireEvent.click(screen.getByText('common.operation.cancel'))
+ fireEvent.click(screen.getByText('appOverview.overview.appInfo.settings.more.entry'))
- expect(screen.getByText('appOverview.overview.appInfo.settings.more.entry')).toBeInTheDocument()
+ expect(screen.getAllByText('appOverview.overview.appInfo.settings.more.entry')).toHaveLength(1)
+ expect(screen.getByPlaceholderText('appOverview.overview.appInfo.settings.more.privacyPolicyPlaceholder')).toBeInTheDocument()
})
it('should reset local form state when the controlled dialog reopens', () => {
@@ -273,6 +273,7 @@ describe('SettingsModal', () => {
)
expect(screen.getByText('appOverview.overview.appInfo.settings.more.entry')).toBeInTheDocument()
+ expect(screen.queryByPlaceholderText('appOverview.overview.appInfo.settings.more.privacyPolicyPlaceholder')).not.toBeInTheDocument()
})
it('should reset the input placeholder when app info changes while open', () => {
diff --git a/web/app/components/app/overview/settings/index.tsx b/web/app/components/app/overview/settings/index.tsx
index 5c1a52304ef..e621a5aaacd 100644
--- a/web/app/components/app/overview/settings/index.tsx
+++ b/web/app/components/app/overview/settings/index.tsx
@@ -1,12 +1,15 @@
'use client'
import type { FC } from 'react'
import type { AppIconSelection } from '@/app/components/base/app-icon-picker'
-import type { AppDetailResponse } from '@/models/app'
-import type { AppIconType, AppSSO, Language } from '@/types/app'
+import type { AppIconType, Language, SiteConfig } from '@/types/app'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
+import { CollapsiblePanel, CollapsibleRoot, CollapsibleTrigger } from '@langgenius/dify-ui/collapsible'
import { Dialog, DialogCloseButton, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
+import { FieldControl, FieldDescription, FieldLabel, FieldRoot } from '@langgenius/dify-ui/field'
+import { Form } from '@langgenius/dify-ui/form'
import { Input } from '@langgenius/dify-ui/input'
+import { ScrollArea } from '@langgenius/dify-ui/scroll-area'
import { Select, SelectContent, SelectItem, SelectItemIndicator, SelectItemText, SelectTrigger } from '@langgenius/dify-ui/select'
import { Switch } from '@langgenius/dify-ui/switch'
import { Textarea } from '@langgenius/dify-ui/textarea'
@@ -28,13 +31,39 @@ import { AppModeEnum } from '@/types/app'
type ISettingsModalProps = {
isChat: boolean
- appInfo: AppDetailResponse & Partial<AppSSO>
+ appInfo: SettingsAppInfo
isShow: boolean
defaultValue?: string
onClose: () => void
onSave?: (params: ConfigParams) => Promise<void>
}
+type SettingsSiteInfo = Pick<
+ SiteConfig,
+ | 'title'
+ | 'description'
+ | 'default_language'
+ | 'chat_color_theme'
+ | 'chat_color_theme_inverted'
+ | 'copyright'
+ | 'privacy_policy'
+ | 'custom_disclaimer'
+ | 'input_placeholder'
+ | 'icon_type'
+ | 'icon'
+ | 'icon_background'
+ | 'icon_url'
+ | 'show_workflow_steps'
+ | 'use_icon_as_answer_icon'
+>
+
+export type SettingsAppInfo = {
+ id: string
+ mode: AppModeEnum
+ enable_sso?: boolean
+ site: SettingsSiteInfo
+}
+
export type ConfigParams = {
title: string
description: string
@@ -156,10 +185,8 @@ const SettingsModal: FC<ISettingsModalProps> = ({
const selectedLanguage = LANGUAGE_OPTIONS.find(item => item.value === language)
const inputPlaceholderLabelId = React.useId()
const inputPlaceholderDescriptionId = React.useId()
-
const inputPlaceholderValue = isCloudSandboxPlan ? '' : (inputInfo.inputPlaceholder ?? '')
const copyrightSwitchValue = isCloudSandboxPlan ? false : inputInfo.copyrightSwitchValue
- // Editable + has value + blurred -> preview as gray placeholder text (matches how it'll render in chat).
const showInputPlaceholderPreview = !isCloudSandboxPlan && inputPlaceholderValue.trim().length > 0 && !inputPlaceholderFocused
const inputPlaceholderField = (
<div
@@ -218,12 +245,12 @@ const SettingsModal: FC<ISettingsModalProps> = ({
}
}
- const onHide = () => {
- onClose()
+ const handleClose = () => {
setIsShowMore(false)
+ onClose()
}
- const onClickSave = async () => {
+ const handleFormSubmit = async () => {
if (!inputInfo.title) {
toast.error(t('newApp.nameNotEmpty', { ns: 'app' }))
return
@@ -283,7 +310,7 @@ const SettingsModal: FC<ISettingsModalProps> = ({
}
await onSave?.(params)
setSaveLoading(false)
- onHide()
+ handleClose()
}
const onChange = (field: string) => {
@@ -304,8 +331,8 @@ const SettingsModal: FC<ISettingsModalProps> = ({
return (
<>
- <Dialog open={isShow} onOpenChange={open => !open && onHide()}>
- <DialogContent className="flex max-h-[calc(100dvh-2rem)] w-[520px] flex-col overflow-hidden! p-0!">
+ <Dialog open={isShow} onOpenChange={open => !open && handleClose()} disablePointerDismissal>
+ <DialogContent className="grid max-h-[calc(100dvh-2rem)] w-[520px] grid-rows-[auto_minmax(0,1fr)] overflow-hidden p-0">
{/* header */}
<div className="shrink-0 pt-5 pr-5 pb-3 pl-6">
<div className="flex items-center gap-1">
@@ -316,262 +343,264 @@ const SettingsModal: FC<ISettingsModalProps> = ({
<span>{t(`${prefixSettings}.modalTip`, { ns: 'appOverview' })}</span>
</div>
</div>
- {/* form body */}
- <div className="min-h-0 flex-1 space-y-5 overflow-y-auto overscroll-contain px-6 py-3">
- {/* name & icon */}
- <div className="flex gap-4">
- <div className="grow">
- <div className={cn('mb-1 py-1 system-sm-semibold text-text-secondary')}>{t(`${prefixSettings}.webName`, { ns: 'appOverview' })}</div>
- <Input
- className="w-full"
- value={inputInfo.title}
- onChange={onChange('title')}
- placeholder={t('appNamePlaceholder', { ns: 'app' }) || ''}
- />
- </div>
- <AppIcon
- size="xxl"
- onClick={() => { setShowAppIconPicker(true) }}
- className="mt-2 cursor-pointer"
- iconType={appIcon.type}
- icon={appIcon.type === 'image' ? appIcon.fileId : appIcon.icon}
- background={appIcon.type === 'image' ? undefined : appIcon.background}
- imageUrl={appIcon.type === 'image' ? appIcon.url : undefined}
- />
- </div>
- {/* description */}
- <div className="relative">
- <div className={cn('py-1 system-sm-semibold text-text-secondary')}>{t(`${prefixSettings}.webDesc`, { ns: 'appOverview' })}</div>
- <Textarea
- aria-label={t(`${prefixSettings}.webDesc`, { ns: 'appOverview' })}
- className="mt-1"
- value={inputInfo.desc}
- onValueChange={onDesChange}
- placeholder={t(`${prefixSettings}.webDescPlaceholder`, { ns: 'appOverview' }) as string}
- />
- <p className={cn('pb-0.5 body-xs-regular text-text-tertiary')}>{t(`${prefixSettings}.webDescTip`, { ns: 'appOverview' })}</p>
- </div>
- <Divider className="my-0 h-px" />
- {/* answer icon */}
- {isChat && (
- <div className="w-full">
- <div className="flex items-center justify-between">
- <div className={cn('py-1 system-sm-semibold text-text-secondary')}>{t('answerIcon.title', { ns: 'app' })}</div>
- <Switch
- checked={inputInfo.use_icon_as_answer_icon}
- onCheckedChange={v => setInputInfo({ ...inputInfo, use_icon_as_answer_icon: v })}
+ <Form className="grid min-h-0 grid-rows-[minmax(0,1fr)_auto]" onFormSubmit={handleFormSubmit}>
+ {/* form body */}
+ <ScrollArea
+ className="relative min-h-0"
+ slotClassNames={{
+ viewport: 'overscroll-contain',
+ content: 'min-w-0 space-y-5 px-6 py-3',
+ }}
+ >
+ {/* name & icon */}
+ <div className="flex gap-4">
+ <FieldRoot name="title" className="grow">
+ <FieldLabel>{t(`${prefixSettings}.webName`, { ns: 'appOverview' })}</FieldLabel>
+ <FieldControl
+ value={inputInfo.title}
+ onValueChange={value => setInputInfo(item => ({ ...item, title: value }))}
+ placeholder={t('appNamePlaceholder', { ns: 'app' }) || ''}
/>
- </div>
- <p className="pb-0.5 body-xs-regular text-text-tertiary">{t('answerIcon.description', { ns: 'app' })}</p>
+ </FieldRoot>
+ <AppIcon
+ size="xxl"
+ onClick={() => { setShowAppIconPicker(true) }}
+ className="mt-2 cursor-pointer"
+ iconType={appIcon.type}
+ icon={appIcon.type === 'image' ? appIcon.fileId : appIcon.icon}
+ background={appIcon.type === 'image' ? undefined : appIcon.background}
+ imageUrl={appIcon.type === 'image' ? appIcon.url : undefined}
+ />
</div>
- )}
- {/* language */}
- <div className="flex items-center">
- <div className={cn('grow py-1 system-sm-semibold text-text-secondary')}>{t(`${prefixSettings}.language`, { ns: 'appOverview' })}</div>
- <Select
- value={selectedLanguage?.value ?? null}
- onValueChange={handleLanguageChange}
- >
- <SelectTrigger
- aria-label={t(`${prefixSettings}.language`, { ns: 'appOverview' })}
- size="large"
- className="w-[200px]"
- >
- {selectedLanguage?.name ?? t('placeholder.select', { ns: 'common' })}
- </SelectTrigger>
- <SelectContent>
- {LANGUAGE_OPTIONS.map(item => (
- <SelectItem key={item.value} value={item.value}>
- <SelectItemText>{item.name}</SelectItemText>
- <SelectItemIndicator />
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </div>
- {/* theme color */}
- {isChat && (
+ {/* description */}
+ <FieldRoot name="description">
+ <FieldLabel>{t(`${prefixSettings}.webDesc`, { ns: 'appOverview' })}</FieldLabel>
+ <Textarea
+ value={inputInfo.desc}
+ onValueChange={onDesChange}
+ placeholder={t(`${prefixSettings}.webDescPlaceholder`, { ns: 'appOverview' }) as string}
+ />
+ <FieldDescription>{t(`${prefixSettings}.webDescTip`, { ns: 'appOverview' })}</FieldDescription>
+ </FieldRoot>
+ <Divider className="my-0 h-px" />
+ {/* answer icon */}
+ {isChat && (
+ <FieldRoot name="use_icon_as_answer_icon" className="w-full">
+ <div className="flex items-center justify-between gap-3">
+ <FieldLabel>{t('answerIcon.title', { ns: 'app' })}</FieldLabel>
+ <Switch
+ checked={inputInfo.use_icon_as_answer_icon}
+ onCheckedChange={v => setInputInfo({ ...inputInfo, use_icon_as_answer_icon: v })}
+ />
+ </div>
+ <FieldDescription>{t('answerIcon.description', { ns: 'app' })}</FieldDescription>
+ </FieldRoot>
+ )}
+ {/* language */}
<div className="flex items-center">
- <div className="grow">
- <div className={cn('py-1 system-sm-semibold text-text-secondary')}>{t(`${prefixSettings}.chatColorTheme`, { ns: 'appOverview' })}</div>
- <div className="pb-0.5 body-xs-regular text-text-tertiary">{t(`${prefixSettings}.chatColorThemeDesc`, { ns: 'appOverview' })}</div>
- </div>
- <div className="shrink-0">
- <Input
- className="mb-1 w-[200px]"
- value={inputInfo.chatColorTheme ?? ''}
- onChange={onChange('chatColorTheme')}
- placeholder="E.g #A020F0"
- />
- <div className="flex items-center justify-between">
- <p className={cn('body-xs-regular text-text-tertiary')}>{t(`${prefixSettings}.chatColorThemeInverted`, { ns: 'appOverview' })}</p>
- <Switch checked={inputInfo.chatColorThemeInverted} onCheckedChange={v => setInputInfo({ ...inputInfo, chatColorThemeInverted: v })}></Switch>
+ <div className={cn('grow py-1 system-sm-semibold text-text-secondary')}>{t(`${prefixSettings}.language`, { ns: 'appOverview' })}</div>
+ <Select
+ value={selectedLanguage?.value ?? null}
+ onValueChange={handleLanguageChange}
+ >
+ <SelectTrigger
+ aria-label={t(`${prefixSettings}.language`, { ns: 'appOverview' })}
+ size="medium"
+ className="w-[200px]"
+ >
+ {selectedLanguage?.name ?? t('placeholder.select', { ns: 'common' })}
+ </SelectTrigger>
+ <SelectContent>
+ {LANGUAGE_OPTIONS.map(item => (
+ <SelectItem key={item.value} value={item.value}>
+ <SelectItemText>{item.name}</SelectItemText>
+ <SelectItemIndicator />
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ {/* theme color */}
+ {isChat && (
+ <div className="flex items-center">
+ <div className="grow">
+ <div className={cn('py-1 system-sm-semibold text-text-secondary')}>{t(`${prefixSettings}.chatColorTheme`, { ns: 'appOverview' })}</div>
+ <div className="pb-0.5 body-xs-regular text-text-tertiary">{t(`${prefixSettings}.chatColorThemeDesc`, { ns: 'appOverview' })}</div>
</div>
+ <FieldRoot name="chat_color_theme" className="w-[200px] shrink-0">
+ <FieldControl
+ className="mb-1"
+ value={inputInfo.chatColorTheme ?? ''}
+ onValueChange={value => setInputInfo(item => ({ ...item, chatColorTheme: value }))}
+ placeholder="E.g #A020F0"
+ />
+ <div className="flex items-center justify-between gap-2 body-xs-regular text-text-tertiary">
+ <span>{t(`${prefixSettings}.chatColorThemeInverted`, { ns: 'appOverview' })}</span>
+ <Switch checked={inputInfo.chatColorThemeInverted} onCheckedChange={v => setInputInfo({ ...inputInfo, chatColorThemeInverted: v })}></Switch>
+ </div>
+ </FieldRoot>
</div>
- </div>
- )}
- {/* workflow detail */}
- <div className="w-full">
- <div className="flex items-center justify-between">
- <div className={cn('py-1 system-sm-semibold text-text-secondary')}>{t(`${prefixSettings}.workflow.subTitle`, { ns: 'appOverview' })}</div>
- <Switch
- disabled={!(appInfo.mode === AppModeEnum.WORKFLOW || appInfo.mode === AppModeEnum.ADVANCED_CHAT)}
- checked={inputInfo.show_workflow_steps}
- onCheckedChange={v => setInputInfo({ ...inputInfo, show_workflow_steps: v })}
- />
- </div>
- <p className="pb-0.5 body-xs-regular text-text-tertiary">{t(`${prefixSettings}.workflow.showDesc`, { ns: 'appOverview' })}</p>
- </div>
- {/* more settings switch */}
- <Divider className="my-0 h-px" />
- {!isShowMore && (
- <button type="button" className="flex w-full cursor-pointer items-center text-left" onClick={() => setIsShowMore(true)}>
- <div className="grow">
- <div className={cn('py-1 system-sm-semibold text-text-secondary')}>{t(`${prefixSettings}.more.entry`, { ns: 'appOverview' })}</div>
- <p className={cn('pb-0.5 body-xs-regular text-text-tertiary')}>
- {t(`${prefixSettings}.more.copyRightPlaceholder`, { ns: 'appOverview' })}
- {' '}
- &
- {' '}
- {t(`${prefixSettings}.more.privacyPolicyPlaceholder`, { ns: 'appOverview' })}
- </p>
+ )}
+ {/* workflow detail */}
+ <FieldRoot name="show_workflow_steps" className="w-full">
+ <div className="flex items-center justify-between gap-3">
+ <FieldLabel>{t(`${prefixSettings}.workflow.subTitle`, { ns: 'appOverview' })}</FieldLabel>
+ <Switch
+ disabled={!(appInfo.mode === AppModeEnum.WORKFLOW || appInfo.mode === AppModeEnum.ADVANCED_CHAT)}
+ checked={inputInfo.show_workflow_steps}
+ onCheckedChange={v => setInputInfo({ ...inputInfo, show_workflow_steps: v })}
+ />
</div>
- <span aria-hidden="true" className="ml-1 i-ri-arrow-right-s-line size-4 shrink-0 text-text-secondary" />
- </button>
- )}
- {/* more settings */}
- {isShowMore && (
- <>
- {/* input placeholder — Chatbot / Agent / Chatflow only */}
- {INPUT_PLACEHOLDER_SUPPORTED_MODES.includes(appInfo.mode) && (
- <div className="w-full">
- <div className="flex items-center">
- <div className="flex grow items-center">
- <div id={inputPlaceholderLabelId} className={cn('mr-1 py-1 system-sm-semibold text-text-secondary')}>{t(`${prefixSettings}.more.inputPlaceholder`, { ns: 'appOverview' })}</div>
- {isCloudSandboxPlan && (
- <div className="h-[18px] select-none">
- <PremiumBadgeButton size="s" color="blue" onClick={handlePlanClick}>
- <span aria-hidden="true" className="i-custom-public-common-sparkles-soft flex h-3.5 w-3.5 items-center py-px pl-[3px] text-components-premium-badge-indigo-text-stop-0" />
- <div className="system-xs-medium">
- <span className="p-1">
- {t('upgradeBtn.encourageShort', { ns: 'billing' })}
- </span>
+ <FieldDescription>{t(`${prefixSettings}.workflow.showDesc`, { ns: 'appOverview' })}</FieldDescription>
+ </FieldRoot>
+ <CollapsibleRoot open={isShowMore} onOpenChange={setIsShowMore}>
+ <Divider className="my-0 h-px" />
+ <CollapsibleTrigger className="-mx-2 mt-2 min-h-11 px-2 py-1.5 hover:not-data-disabled:bg-components-panel-on-panel-item-bg-hover focus-visible:ring-inset data-panel-open:text-text-secondary">
+ <div className="min-w-0 grow">
+ <div className="system-sm-semibold text-text-secondary">{t(`${prefixSettings}.more.entry`, { ns: 'appOverview' })}</div>
+ <p className="truncate body-xs-regular text-text-tertiary">
+ {t(`${prefixSettings}.more.copyRightPlaceholder`, { ns: 'appOverview' })}
+ {' '}
+ &
+ {' '}
+ {t(`${prefixSettings}.more.privacyPolicyPlaceholder`, { ns: 'appOverview' })}
+ </p>
+ </div>
+ <span aria-hidden="true" className="i-ri-arrow-right-s-line size-4 shrink-0 text-text-secondary transition-transform group-data-panel-open:rotate-90" />
+ </CollapsibleTrigger>
+ <CollapsiblePanel>
+ <div className="space-y-5 pt-5">
+ {INPUT_PLACEHOLDER_SUPPORTED_MODES.includes(appInfo.mode) && (
+ <div className="w-full">
+ <div className="flex items-center">
+ <div className="flex grow items-center">
+ <div id={inputPlaceholderLabelId} className={cn('mr-1 py-1 system-sm-semibold text-text-secondary')}>{t(`${prefixSettings}.more.inputPlaceholder`, { ns: 'appOverview' })}</div>
+ {isCloudSandboxPlan && (
+ <div className="h-[18px] select-none">
+ <PremiumBadgeButton size="s" color="blue" onClick={handlePlanClick}>
+ <span aria-hidden="true" className="i-custom-public-common-sparkles-soft flex h-3.5 w-3.5 items-center py-px pl-[3px] text-components-premium-badge-indigo-text-stop-0" />
+ <div className="system-xs-medium">
+ <span className="p-1">
+ {t('upgradeBtn.encourageShort', { ns: 'billing' })}
+ </span>
+ </div>
+ </PremiumBadgeButton>
</div>
- </PremiumBadgeButton>
+ )}
+ </div>
+ </div>
+ <p id={inputPlaceholderDescriptionId} className="pb-0.5 body-xs-regular text-text-tertiary">{t(`${prefixSettings}.more.inputPlaceholderTip`, { ns: 'appOverview' })}</p>
+ {isCloudSandboxPlan
+ ? (
+ <Tooltip>
+ <TooltipTrigger render={inputPlaceholderField} />
+ <TooltipContent className="w-[180px]">
+ {t(`${prefixSettings}.more.inputPlaceholderTooltip`, { ns: 'appOverview' })}
+ </TooltipContent>
+ </Tooltip>
+ )
+ : inputPlaceholderField}
+ {!isCloudSandboxPlan && (
+ <div className="mt-1 text-right body-xs-regular text-text-tertiary">
+ {`${inputInfo.inputPlaceholder?.length ?? 0} / ${INPUT_PLACEHOLDER_MAX_LENGTH}`}
</div>
)}
</div>
- </div>
- <p id={inputPlaceholderDescriptionId} className="pb-0.5 body-xs-regular text-text-tertiary">{t(`${prefixSettings}.more.inputPlaceholderTip`, { ns: 'appOverview' })}</p>
- {isCloudSandboxPlan
- ? (
- <Tooltip>
- <TooltipTrigger render={inputPlaceholderField} />
- <TooltipContent className="w-[180px]">
- {t(`${prefixSettings}.more.inputPlaceholderTooltip`, { ns: 'appOverview' })}
- </TooltipContent>
- </Tooltip>
- )
- : inputPlaceholderField}
- {!isCloudSandboxPlan && (
- <div className="mt-1 text-right body-xs-regular text-text-tertiary">
- {`${inputInfo.inputPlaceholder?.length ?? 0} / ${INPUT_PLACEHOLDER_MAX_LENGTH}`}
- </div>
)}
- </div>
- )}
- {/* copyright */}
- <div className="w-full">
- <div className="flex items-center">
- <div className="flex grow items-center">
- <div className={cn('mr-1 py-1 system-sm-semibold text-text-secondary')}>{t(`${prefixSettings}.more.copyright`, { ns: 'appOverview' })}</div>
- {/* upgrade button */}
- {isCloudSandboxPlan && (
- <div className="h-[18px] select-none">
- <PremiumBadgeButton size="s" color="blue" onClick={handlePlanClick}>
- <span aria-hidden="true" className="i-custom-public-common-sparkles-soft flex h-3.5 w-3.5 items-center py-px pl-[3px] text-components-premium-badge-indigo-text-stop-0" />
- <div className="system-xs-medium">
- <span className="p-1">
- {t('upgradeBtn.encourageShort', { ns: 'billing' })}
- </span>
+ {/* copyright */}
+ <div className="w-full">
+ <div className="flex items-center">
+ <div className="flex grow items-center">
+ <div className={cn('mr-1 py-1 system-sm-semibold text-text-secondary')}>{t(`${prefixSettings}.more.copyright`, { ns: 'appOverview' })}</div>
+ {/* upgrade button */}
+ {isCloudSandboxPlan && (
+ <div className="h-[18px] select-none">
+ <PremiumBadgeButton size="s" color="blue" onClick={handlePlanClick}>
+ <span aria-hidden="true" className="i-custom-public-common-sparkles-soft flex h-3.5 w-3.5 items-center py-px pl-[3px] text-components-premium-badge-indigo-text-stop-0" />
+ <div className="system-xs-medium">
+ <span className="p-1">
+ {t('upgradeBtn.encourageShort', { ns: 'billing' })}
+ </span>
+ </div>
+ </PremiumBadgeButton>
</div>
- </PremiumBadgeButton>
+ )}
</div>
+ {webappCopyrightEnabled
+ ? (
+ <Switch
+ checked={copyrightSwitchValue}
+ onCheckedChange={v => setInputInfo({ ...inputInfo, copyrightSwitchValue: v })}
+ />
+ )
+ : (
+ <Tooltip>
+ <TooltipTrigger
+ render={(
+ <div>
+ <Switch
+ disabled
+ checked={copyrightSwitchValue}
+ onCheckedChange={v => setInputInfo({ ...inputInfo, copyrightSwitchValue: v })}
+ />
+ </div>
+ )}
+ />
+ <TooltipContent className="w-[180px]">
+ {t(`${prefixSettings}.more.copyrightTooltip`, { ns: 'appOverview' })}
+ </TooltipContent>
+ </Tooltip>
+ )}
+ </div>
+ <p className="pb-0.5 body-xs-regular text-text-tertiary">{t(`${prefixSettings}.more.copyrightTip`, { ns: 'appOverview' })}</p>
+ {copyrightSwitchValue && (
+ <Input
+ className="mt-2 h-10"
+ value={inputInfo.copyright}
+ onChange={onChange('copyright')}
+ placeholder={t(`${prefixSettings}.more.copyRightPlaceholder`, { ns: 'appOverview' }) as string}
+ />
)}
</div>
- {webappCopyrightEnabled
- ? (
- <Switch
- checked={copyrightSwitchValue}
- onCheckedChange={v => setInputInfo({ ...inputInfo, copyrightSwitchValue: v })}
- />
- )
- : (
- <Tooltip>
- <TooltipTrigger
- render={(
- <div>
- <Switch
- disabled
- checked={copyrightSwitchValue}
- onCheckedChange={v => setInputInfo({ ...inputInfo, copyrightSwitchValue: v })}
- />
- </div>
- )}
- />
- <TooltipContent className="w-[180px]">
- {t(`${prefixSettings}.more.copyrightTooltip`, { ns: 'appOverview' })}
- </TooltipContent>
- </Tooltip>
- )}
+ {/* privacy policy */}
+ <div className="w-full">
+ <div className={cn('py-1 system-sm-semibold text-text-secondary')}>{t(`${prefixSettings}.more.privacyPolicy`, { ns: 'appOverview' })}</div>
+ <p className={cn('pb-0.5 body-xs-regular text-text-tertiary')}>
+ <Trans
+ i18nKey={`${prefixSettings}.more.privacyPolicyTip`}
+ ns="appOverview"
+ components={{ privacyPolicyLink: <Link href="https://dify.ai/privacy" target="_blank" rel="noopener noreferrer" className="text-text-accent" /> }}
+ />
+ </p>
+ <Input
+ className="mt-1"
+ value={inputInfo.privacyPolicy}
+ onChange={onChange('privacyPolicy')}
+ placeholder={t(`${prefixSettings}.more.privacyPolicyPlaceholder`, { ns: 'appOverview' }) as string}
+ />
+ </div>
+ {/* custom disclaimer */}
+ <div className="w-full">
+ <div className={cn('py-1 system-sm-semibold text-text-secondary')}>{t(`${prefixSettings}.more.customDisclaimer`, { ns: 'appOverview' })}</div>
+ <p className={cn('pb-0.5 body-xs-regular text-text-tertiary')}>{t(`${prefixSettings}.more.customDisclaimerTip`, { ns: 'appOverview' })}</p>
+ <Textarea
+ aria-label={t(`${prefixSettings}.more.customDisclaimer`, { ns: 'appOverview' })}
+ className="mt-1"
+ value={inputInfo.customDisclaimer}
+ onValueChange={value => setInputInfo(item => ({ ...item, customDisclaimer: value }))}
+ placeholder={t(`${prefixSettings}.more.customDisclaimerPlaceholder`, { ns: 'appOverview' }) as string}
+ />
+ </div>
</div>
- <p className="pb-0.5 body-xs-regular text-text-tertiary">{t(`${prefixSettings}.more.copyrightTip`, { ns: 'appOverview' })}</p>
- {copyrightSwitchValue && (
- <Input
- className="mt-2 h-10"
- value={inputInfo.copyright}
- onChange={onChange('copyright')}
- placeholder={t(`${prefixSettings}.more.copyRightPlaceholder`, { ns: 'appOverview' }) as string}
- />
- )}
- </div>
- {/* privacy policy */}
- <div className="w-full">
- <div className={cn('py-1 system-sm-semibold text-text-secondary')}>{t(`${prefixSettings}.more.privacyPolicy`, { ns: 'appOverview' })}</div>
- <p className={cn('pb-0.5 body-xs-regular text-text-tertiary')}>
- <Trans
- i18nKey={`${prefixSettings}.more.privacyPolicyTip`}
- ns="appOverview"
- components={{ privacyPolicyLink: <Link href="https://dify.ai/privacy" target="_blank" rel="noopener noreferrer" className="text-text-accent" /> }}
- />
- </p>
- <Input
- className="mt-1"
- value={inputInfo.privacyPolicy}
- onChange={onChange('privacyPolicy')}
- placeholder={t(`${prefixSettings}.more.privacyPolicyPlaceholder`, { ns: 'appOverview' }) as string}
- />
- </div>
- {/* custom disclaimer */}
- <div className="w-full">
- <div className={cn('py-1 system-sm-semibold text-text-secondary')}>{t(`${prefixSettings}.more.customDisclaimer`, { ns: 'appOverview' })}</div>
- <p className={cn('pb-0.5 body-xs-regular text-text-tertiary')}>{t(`${prefixSettings}.more.customDisclaimerTip`, { ns: 'appOverview' })}</p>
- <Textarea
- aria-label={t(`${prefixSettings}.more.customDisclaimer`, { ns: 'appOverview' })}
- className="mt-1"
- value={inputInfo.customDisclaimer}
- onValueChange={value => setInputInfo(item => ({ ...item, customDisclaimer: value }))}
- placeholder={t(`${prefixSettings}.more.customDisclaimerPlaceholder`, { ns: 'appOverview' }) as string}
- />
- </div>
- </>
- )}
- </div>
- {/* footer */}
- <div className="flex shrink-0 justify-end p-6 pt-5">
- <Button className="mr-2" onClick={onHide}>{t('operation.cancel', { ns: 'common' })}</Button>
- <Button variant="primary" onClick={onClickSave} loading={saveLoading}>{t('operation.save', { ns: 'common' })}</Button>
- </div>
+ </CollapsiblePanel>
+ </CollapsibleRoot>
+ </ScrollArea>
+ {/* footer */}
+ <div className="flex shrink-0 justify-end p-6 pt-5">
+ <Button type="button" className="mr-2" onClick={handleClose}>{t('operation.cancel', { ns: 'common' })}</Button>
+ <Button type="submit" variant="primary" loading={saveLoading}>{t('operation.save', { ns: 'common' })}</Button>
+ </div>
+ </Form>
</DialogContent>
</Dialog>
<AppIconPicker
diff --git a/web/app/components/base/chat/chat-with-history/chat-wrapper.tsx b/web/app/components/base/chat/chat-with-history/chat-wrapper.tsx
index 6f1db936418..99faced13de 100644
--- a/web/app/components/base/chat/chat-with-history/chat-wrapper.tsx
+++ b/web/app/components/base/chat/chat-with-history/chat-wrapper.tsx
@@ -60,6 +60,9 @@ const ChatWrapper = () => {
} = useChatWithHistoryContext()
const appSourceType = isInstalledApp ? AppSourceType.installedApp : AppSourceType.webApp
+ const timezone = appSourceType === AppSourceType.webApp
+ ? Intl.DateTimeFormat().resolvedOptions().timeZone
+ : undefined
// Semantic variable for better code readability
const isHistoryConversation = !!currentConversationId
@@ -94,6 +97,8 @@ const ChatWrapper = () => {
taskId => stopChatMessageResponding('', taskId, appSourceType, appId),
clearChatList,
setClearChatList,
+ undefined,
+ { timezone },
)
const inputsFormValue = currentConversationId ? currentConversationInputs : newConversationInputsRef?.current
const inputDisabled = useMemo(() => {
diff --git a/web/app/components/base/chat/chat/__tests__/hooks.spec.tsx b/web/app/components/base/chat/chat/__tests__/hooks.spec.tsx
index cd0e4ea8c88..9b8eddbce25 100644
--- a/web/app/components/base/chat/chat/__tests__/hooks.spec.tsx
+++ b/web/app/components/base/chat/chat/__tests__/hooks.spec.tsx
@@ -6,6 +6,10 @@ import { useParams, usePathname } from '@/next/navigation'
import { sseGet, ssePost } from '@/service/base'
import { useChat } from '../hooks'
+const useTimestampMock = vi.hoisted(() =>
+ vi.fn(() => ({ formatTime: vi.fn().mockReturnValue('10:00 AM') })),
+)
+
vi.mock('@/service/base', () => ({
sseGet: vi.fn(),
ssePost: vi.fn(),
@@ -31,7 +35,7 @@ vi.mock('@langgenius/dify-ui/toast', () => ({
}))
vi.mock('@/hooks/use-timestamp', () => ({
- default: () => ({ formatTime: vi.fn().mockReturnValue('10:00 AM') }),
+ default: useTimestampMock,
}))
vi.mock('@/next/navigation', () => ({
@@ -91,6 +95,21 @@ describe('useChat', () => {
expect(result.current.suggestedQuestions).toEqual([])
})
+ it('should pass timestamp options to timestamp formatter', () => {
+ renderHook(() => useChat(
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ { timezone: 'UTC' },
+ ))
+
+ expect(useTimestampMock).toHaveBeenCalledWith({ timezone: 'UTC' })
+ })
+
it('should initialize with opening statement and suggested questions', () => {
const config = {
opening_statement: 'Hello {{name}}',
diff --git a/web/app/components/base/chat/chat/chat-input-area/__tests__/index.spec.tsx b/web/app/components/base/chat/chat/chat-input-area/__tests__/index.spec.tsx
index cdc5583daef..dbb11d9454c 100644
--- a/web/app/components/base/chat/chat/chat-input-area/__tests__/index.spec.tsx
+++ b/web/app/components/base/chat/chat/chat-input-area/__tests__/index.spec.tsx
@@ -329,6 +329,12 @@ describe('ChatInputArea', () => {
render(<ChatInputArea visionConfig={mockVisionConfig} />)
expect(screen.getByRole('button', { name: 'common.operation.send' })).toBeInTheDocument()
})
+
+ it('should render a custom send button label when provided', () => {
+ render(<ChatInputArea visionConfig={mockVisionConfig} sendButtonLabel="Start build" />)
+ expect(screen.getByRole('button', { name: 'Start build' })).toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'common.operation.send' })).not.toBeInTheDocument()
+ })
})
// -------------------------------------------------------------------------
@@ -542,14 +548,20 @@ describe('ChatInputArea', () => {
// -------------------------------------------------------------------------
describe('Validation & Constraints', () => {
- it('should notify and NOT send when query is blank', async () => {
+ it('should disable send when query is blank', async () => {
const user = userEvent.setup({ delay: null })
const onSend = vi.fn()
render(<ChatInputArea onSend={onSend} visionConfig={mockVisionConfig} />)
- await user.click(screen.getByRole('button', { name: 'common.operation.send' }))
+ const sendButton = screen.getByRole('button', { name: 'common.operation.send' })
+ expect(sendButton).toBeDisabled()
+
+ await user.click(sendButton)
expect(onSend).not.toHaveBeenCalled()
- expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({ type: 'info' }))
+ expect(mockNotify).not.toHaveBeenCalled()
+
+ await user.type(getTextarea()!, ' ')
+ expect(sendButton).toBeDisabled()
})
it('should notify and NOT send while bot is responding', async () => {
diff --git a/web/app/components/base/chat/chat/chat-input-area/__tests__/operation.spec.tsx b/web/app/components/base/chat/chat/chat-input-area/__tests__/operation.spec.tsx
index 5a34a7a7eaa..84787371eae 100644
--- a/web/app/components/base/chat/chat/chat-input-area/__tests__/operation.spec.tsx
+++ b/web/app/components/base/chat/chat/chat-input-area/__tests__/operation.spec.tsx
@@ -62,6 +62,24 @@ describe('Operation', () => {
expect(screen.getByRole('button', { name: 'common.operation.send' })).toBeInTheDocument()
})
+ it('should render file upload before voice input when both actions are enabled', () => {
+ const fileConfig: FileUpload = { enabled: true } as FileUpload
+ const speechConfig: EnableType = { enabled: true }
+
+ render(
+ <Operation
+ onSend={vi.fn()}
+ fileConfig={fileConfig}
+ speechToTextConfig={speechConfig}
+ />,
+ )
+
+ const fileUploader = screen.getByTestId('file-uploader')
+ const voiceButton = screen.getByRole('button', { name: 'common.voiceInput.start' })
+
+ expect(fileUploader.compareDocumentPosition(voiceButton) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
+ })
+
it('should not render voice input button when speechToTextConfig.enabled is false', () => {
const speechConfig: EnableType = { enabled: false }
diff --git a/web/app/components/base/chat/chat/chat-input-area/index.tsx b/web/app/components/base/chat/chat/chat-input-area/index.tsx
index 7b4be33f5e4..e05aa8648e3 100644
--- a/web/app/components/base/chat/chat/chat-input-area/index.tsx
+++ b/web/app/components/base/chat/chat/chat-input-area/index.tsx
@@ -20,6 +20,10 @@ import { useCheckInputsForms } from '../check-input-forms-hooks'
import { useTextAreaHeight } from './hooks'
import Operation from './operation'
+type AudioRecorderWithPermission = typeof Recorder & {
+ getPermission: () => Promise<void>
+}
+
type ChatInputAreaProps = {
readonly?: boolean
botName?: string
@@ -32,11 +36,12 @@ type ChatInputAreaProps = {
visionConfig?: FileUpload
speechToTextConfig?: EnableType
onSend?: OnSend
- inputs?: Record<string, any>
+ inputs?: Record<string, unknown>
inputsForm?: InputForm[]
theme?: Theme | null
isResponding?: boolean
disabled?: boolean
+ sendButtonLabel?: string
/**
* Controls whether pressing Enter sends the message.
* - true (default): Enter sends, Shift+Enter inserts newline
@@ -45,10 +50,11 @@ type ChatInputAreaProps = {
*/
sendOnEnter?: boolean
}
-const ChatInputArea = ({ readonly, botName, customPlaceholder, showFeatureBar, showFileUpload, featureBarReadonly = readonly, featureBarDisabled, onFeatureBarClick, visionConfig, speechToTextConfig = { enabled: true }, onSend, inputs = {}, inputsForm = [], theme, isResponding, disabled, sendOnEnter = true }: ChatInputAreaProps) => {
+const ChatInputArea = ({ readonly, botName, customPlaceholder, showFeatureBar, showFileUpload, featureBarReadonly = readonly, featureBarDisabled, onFeatureBarClick, visionConfig, speechToTextConfig = { enabled: true }, onSend, inputs = {}, inputsForm = [], theme, isResponding, disabled, sendButtonLabel, sendOnEnter = true }: ChatInputAreaProps) => {
const { t } = useTranslation()
const { wrapperRef, textareaRef, textValueRef, holdSpaceRef, handleTextareaResize, isMultipleLine } = useTextAreaHeight()
const [query, setQuery] = useState('')
+ const canSend = !!query.trim()
const [showVoiceInput, setShowVoiceInput] = useState(false)
const filesStore = useFileStore()
const { handleDragFileEnter, handleDragFileLeave, handleDragFileOver, handleDropFile, handleClipboardPasteFile, isDragActive } = useFile(visionConfig!, false)
@@ -61,6 +67,9 @@ const ChatInputArea = ({ readonly, botName, customPlaceholder, showFeatureBar, s
setTimeout(handleTextareaResize, 0)
}, [handleTextareaResize])
const handleSend = () => {
+ if (!canSend)
+ return
+
if (isResponding) {
toast.info(t('errorMessage.waitForResponse', { ns: 'appDebug' }))
return
@@ -71,10 +80,6 @@ const ChatInputArea = ({ readonly, botName, customPlaceholder, showFeatureBar, s
toast.info(t('errorMessage.waitForFileUpload', { ns: 'appDebug' }))
return
}
- if (!query || !query.trim()) {
- toast.info(t('errorMessage.queryRequired', { ns: 'appAnnotation' }))
- return
- }
if (checkInputsForm(inputs, inputsForm)) {
onSend(query, files)
handleQueryChange('')
@@ -131,13 +136,13 @@ const ChatInputArea = ({ readonly, botName, customPlaceholder, showFeatureBar, s
}
}
const handleShowVoiceInput = useCallback(() => {
- (Recorder as any).getPermission().then(() => {
+ ;(Recorder as AudioRecorderWithPermission).getPermission().then(() => {
setShowVoiceInput(true)
}, () => {
toast.error(t('voiceInput.notAllow', { ns: 'common' }))
})
}, [t])
- const operation = (<Operation ref={holdSpaceRef} readonly={readonly} fileConfig={visionConfig} speechToTextConfig={speechToTextConfig} onShowVoiceInput={handleShowVoiceInput} onSend={handleSend} theme={theme} />)
+ const operation = (<Operation ref={holdSpaceRef} readonly={readonly} fileConfig={visionConfig} speechToTextConfig={speechToTextConfig} onShowVoiceInput={handleShowVoiceInput} onSend={handleSend} sendButtonLabel={sendButtonLabel} disabled={!canSend} theme={theme} />)
return (
<>
<div className={cn('relative z-10 overflow-hidden rounded-xl border border-components-chat-input-border bg-components-panel-bg-blur pb-[9px] shadow-md', isDragActive && 'border border-dashed border-components-option-card-option-selected-border', disabled && 'pointer-events-none border-components-panel-border opacity-50 shadow-none')}>
@@ -148,7 +153,28 @@ const ChatInputArea = ({ readonly, botName, customPlaceholder, showFeatureBar, s
<div ref={textValueRef} className="pointer-events-none invisible absolute size-auto p-1 body-lg-regular leading-6 whitespace-pre">
{query}
</div>
- <Textarea ref={ref => textareaRef.current = ref as any} className={cn('w-full resize-none bg-transparent p-1 body-lg-regular leading-6 text-text-primary outline-hidden')} placeholder={!readonly && customPlaceholder?.trim() ? customPlaceholder : decode(t(readonly ? 'chat.inputDisabledPlaceholder' : 'chat.inputPlaceholder', { ns: 'common', botName }) || '')} autoFocus minRows={1} value={query} onChange={e => handleQueryChange(e.target.value)} onKeyDown={handleKeyDown} onCompositionStart={handleCompositionStart} onCompositionEnd={handleCompositionEnd} onPaste={handleClipboardPasteFile} onDragEnter={handleDragFileEnter} onDragLeave={handleDragFileLeave} onDragOver={handleDragFileOver} onDrop={handleDropFile} readOnly={readonly} />
+ <Textarea
+ ref={(ref) => {
+ textareaRef.current = ref ?? undefined
+ }}
+ className={cn('w-full resize-none bg-transparent p-1 body-lg-regular leading-6 text-text-primary outline-hidden')}
+ placeholder={!readonly && customPlaceholder?.trim() ? customPlaceholder : decode(t(readonly ? 'chat.inputDisabledPlaceholder' : 'chat.inputPlaceholder', { ns: 'common', botName }) || '')}
+ // Existing chat behavior focuses the composer as soon as it opens.
+ // eslint-disable-next-line jsx-a11y/no-autofocus
+ autoFocus
+ minRows={1}
+ value={query}
+ onChange={e => handleQueryChange(e.target.value)}
+ onKeyDown={handleKeyDown}
+ onCompositionStart={handleCompositionStart}
+ onCompositionEnd={handleCompositionEnd}
+ onPaste={handleClipboardPasteFile}
+ onDragEnter={handleDragFileEnter}
+ onDragLeave={handleDragFileLeave}
+ onDragOver={handleDragFileOver}
+ onDrop={handleDropFile}
+ readOnly={readonly}
+ />
</div>
{!isMultipleLine && operation}
</div>
diff --git a/web/app/components/base/chat/chat/chat-input-area/operation.tsx b/web/app/components/base/chat/chat/chat-input-area/operation.tsx
index 763071daf5e..542665cb574 100644
--- a/web/app/components/base/chat/chat/chat-input-area/operation.tsx
+++ b/web/app/components/base/chat/chat/chat-input-area/operation.tsx
@@ -6,11 +6,6 @@ import type {
import type { FileUpload } from '@/app/components/base/features/types'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
-import {
- RiMicLine,
- RiSendPlane2Fill,
-} from '@remixicon/react'
-import { noop } from 'es-toolkit/function'
import { memo } from 'react'
import { useTranslation } from 'react-i18next'
import ActionButton from '@/app/components/base/action-button'
@@ -22,6 +17,8 @@ type OperationProps = {
speechToTextConfig?: EnableType
onShowVoiceInput?: () => void
onSend: () => void
+ sendButtonLabel?: string
+ disabled?: boolean
theme?: Theme | null
ref?: Ref<HTMLDivElement>
}
@@ -32,6 +29,8 @@ const Operation: FC<OperationProps> = ({
speechToTextConfig,
onShowVoiceInput,
onSend,
+ sendButtonLabel,
+ disabled,
theme,
}) => {
const { t } = useTranslation()
@@ -46,7 +45,7 @@ const Operation: FC<OperationProps> = ({
className="flex items-center pl-1"
ref={ref}
>
- <div className="flex items-center space-x-1">
+ <div className="flex items-center gap-1">
{fileConfig?.enabled && <FileUploaderInChatInput readonly={readonly} fileConfig={fileConfig} />}
{
speechToTextConfig?.enabled && (
@@ -56,16 +55,20 @@ const Operation: FC<OperationProps> = ({
disabled={readonly}
onClick={onShowVoiceInput}
>
- <RiMicLine className="size-5" aria-hidden="true" />
+ <span className="i-ri-mic-line size-5" aria-hidden="true" />
</ActionButton>
)
}
</div>
<Button
- aria-label={t('operation.send', { ns: 'common' })}
- className="ml-3 w-8 px-0"
+ aria-label={sendButtonLabel ? undefined : t('operation.send', { ns: 'common' })}
+ className={cn(
+ 'ml-3 focus-visible:ring-inset',
+ sendButtonLabel ? 'px-3' : 'w-8 px-0',
+ )}
variant="primary"
- onClick={readonly ? noop : onSend}
+ disabled={readonly || disabled}
+ onClick={onSend}
style={
theme
? {
@@ -74,7 +77,7 @@ const Operation: FC<OperationProps> = ({
: {}
}
>
- <RiSendPlane2Fill className="size-4" aria-hidden="true" />
+ {sendButtonLabel || <span className="i-ri-send-plane-2-fill size-4" aria-hidden="true" />}
</Button>
</div>
</div>
diff --git a/web/app/components/base/chat/chat/hooks.ts b/web/app/components/base/chat/chat/hooks.ts
index 212c678b50f..72233118d12 100644
--- a/web/app/components/base/chat/chat/hooks.ts
+++ b/web/app/components/base/chat/chat/hooks.ts
@@ -55,6 +55,10 @@ type SendCallback = {
isPublicAPI?: boolean
}
+type UseChatOptions = {
+ timezone?: string
+}
+
export const useChat = (
config?: ChatConfig,
formSettings?: {
@@ -66,9 +70,10 @@ export const useChat = (
clearChatList?: boolean,
clearChatListCallback?: (state: boolean) => void,
initialConversationId?: string,
+ options: UseChatOptions = {},
) => {
const { t } = useTranslation()
- const { formatTime } = useTimestamp()
+ const { formatTime } = useTimestamp({ timezone: options.timezone })
const conversationIdRef = useRef(initialConversationId ?? '')
const initialConversationIdRef = useRef(initialConversationId ?? '')
const hasStopRespondedRef = useRef(false)
diff --git a/web/app/components/base/chat/chat/index.tsx b/web/app/components/base/chat/chat/index.tsx
index 3ecbaa1f156..32bf971b1ab 100644
--- a/web/app/components/base/chat/chat/index.tsx
+++ b/web/app/components/base/chat/chat/index.tsx
@@ -13,6 +13,8 @@ import type {
import type { HumanInputFormSubmitData } from './answer/human-input-content/type'
import type { InputForm } from './type'
import type { Emoji } from '@/app/components/tools/types'
+import type { HumanInputNodeType } from '@/app/components/workflow/nodes/human-input/types'
+import type { Node } from '@/app/components/workflow/types'
import type { AppData } from '@/models/share'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
@@ -39,7 +41,7 @@ export type ChatProps = {
onStopResponding?: () => void
noChatInput?: boolean
onSend?: OnSend
- inputs?: Record<string, any>
+ inputs?: Record<string, unknown>
inputsForm?: InputForm[]
onRegenerate?: OnRegenerate
chatContainerClassName?: string
@@ -68,11 +70,14 @@ export type ChatProps = {
onFeatureBarClick?: (state: boolean) => void
noSpacing?: boolean
inputDisabled?: boolean
+ inputPlaceholder?: string
+ inputPlaceholderBotName?: string
+ sendButtonLabel?: string
sidebarCollapseState?: boolean
hideAvatar?: boolean
sendOnEnter?: boolean
onHumanInputFormSubmit?: (formToken: string, formData: HumanInputFormSubmitData) => Promise<void>
- getHumanInputNodeData?: (nodeID: string) => any
+ getHumanInputNodeData?: (nodeID: string) => Node<HumanInputNodeType> | undefined
}
const Chat: FC<ChatProps> = ({
@@ -114,6 +119,9 @@ const Chat: FC<ChatProps> = ({
onFeatureBarClick,
noSpacing,
inputDisabled,
+ inputPlaceholder,
+ inputPlaceholderBotName,
+ sendButtonLabel,
sidebarCollapseState,
hideAvatar,
sendOnEnter,
@@ -180,7 +188,7 @@ const Chat: FC<ChatProps> = ({
appData={appData}
key={item.id}
item={item}
- question={chatList[index - 1]?.content!}
+ question={chatList[index - 1]?.content ?? ''}
index={index}
config={config}
answerIcon={answerIcon}
@@ -240,8 +248,8 @@ const Chat: FC<ChatProps> = ({
{
!noChatInput && (
<ChatInputArea
- botName={appData?.site?.title || 'Bot'}
- customPlaceholder={appData?.site?.input_placeholder}
+ botName={inputPlaceholderBotName || appData?.site?.title || 'Bot'}
+ customPlaceholder={inputPlaceholder ?? appData?.site?.input_placeholder}
disabled={inputDisabled}
showFeatureBar={showFeatureBar}
showFileUpload={showFileUpload}
@@ -256,6 +264,7 @@ const Chat: FC<ChatProps> = ({
theme={themeBuilder?.theme}
isResponding={isResponding}
readonly={readonly}
+ sendButtonLabel={sendButtonLabel}
sendOnEnter={sendOnEnter}
/>
)
diff --git a/web/app/components/base/chat/embedded-chatbot/chat-wrapper.tsx b/web/app/components/base/chat/embedded-chatbot/chat-wrapper.tsx
index 44da86a582c..124497f9588 100644
--- a/web/app/components/base/chat/embedded-chatbot/chat-wrapper.tsx
+++ b/web/app/components/base/chat/embedded-chatbot/chat-wrapper.tsx
@@ -84,6 +84,9 @@ const ChatWrapper = () => {
opening_statement: currentConversationItem?.introduction || (config as any).opening_statement,
} as ChatConfig
}, [appParams, currentConversationItem?.introduction])
+ const timezone = appSourceType === AppSourceType.webApp
+ ? Intl.DateTimeFormat().resolvedOptions().timeZone
+ : undefined
const {
chatList,
handleSend,
@@ -101,6 +104,8 @@ const ChatWrapper = () => {
taskId => stopChatMessageResponding('', taskId, appSourceType, appId),
clearChatList,
setClearChatList,
+ undefined,
+ { timezone },
)
const inputsFormValue = currentConversationId ? currentConversationInputs : newConversationInputsRef?.current
const inputDisabled = useMemo(() => {
diff --git a/web/app/components/base/file-uploader/file-uploader-in-chat-input/__tests__/index.spec.tsx b/web/app/components/base/file-uploader/file-uploader-in-chat-input/__tests__/index.spec.tsx
index 233dba7c8e3..783fc9fb359 100644
--- a/web/app/components/base/file-uploader/file-uploader-in-chat-input/__tests__/index.spec.tsx
+++ b/web/app/components/base/file-uploader/file-uploader-in-chat-input/__tests__/index.spec.tsx
@@ -42,11 +42,10 @@ describe('FileUploaderInChatInput', () => {
vi.clearAllMocks()
})
- it('should render an attachment icon SVG', () => {
+ it('should render a named attachment trigger', () => {
renderWithProvider(<FileUploaderInChatInput fileConfig={createFileConfig()} />)
- const button = screen.getByRole('button')
- expect(button.querySelector('svg')).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: /fileUploader\.uploadFromComputer/ })).toBeInTheDocument()
})
it('should render FileFromLinkOrLocal when not readonly', () => {
@@ -72,9 +71,8 @@ describe('FileUploaderInChatInput', () => {
/>,
)
- const button = screen.getByRole('button')
+ const button = screen.getByRole('button', { name: /fileUploader\.uploadFromComputer/ })
expect(button).toBeInTheDocument()
- expect(button.querySelector('svg')).toBeInTheDocument()
})
it('should render button with attachment icon for remote_url upload method', () => {
@@ -85,17 +83,24 @@ describe('FileUploaderInChatInput', () => {
/>,
)
- const button = screen.getByRole('button')
+ const button = screen.getByRole('button', { name: /fileUploader\.uploadFromComputer/ })
expect(button).toBeInTheDocument()
- expect(button.querySelector('svg')).toBeInTheDocument()
})
- it('should apply open state styling when trigger is activated', () => {
+ it('should keep stable focus and open-state styling on the trigger', () => {
renderWithProvider(<FileUploaderInChatInput fileConfig={createFileConfig()} />)
- const button = screen.getByRole('button')
+ const button = screen.getByRole('button', { name: /fileUploader\.uploadFromComputer/ })
fireEvent.click(button)
- expect(button).toBeInTheDocument()
+ expect(button).toHaveAttribute('data-popup-open')
+ expect(button).toHaveClass(
+ 'size-8',
+ 'outline-hidden',
+ 'focus-visible:ring-2',
+ 'focus-visible:ring-state-accent-solid',
+ 'focus-visible:ring-inset',
+ 'data-popup-open:bg-state-base-hover',
+ )
})
})
diff --git a/web/app/components/base/file-uploader/file-uploader-in-chat-input/index.tsx b/web/app/components/base/file-uploader/file-uploader-in-chat-input/index.tsx
index 4acf9bf64f4..eaa8f45402e 100644
--- a/web/app/components/base/file-uploader/file-uploader-in-chat-input/index.tsx
+++ b/web/app/components/base/file-uploader/file-uploader-in-chat-input/index.tsx
@@ -1,13 +1,10 @@
import type { FileUpload } from '@/app/components/base/features/types'
import { cn } from '@langgenius/dify-ui/cn'
-import {
- RiAttachmentLine,
-} from '@remixicon/react'
import {
memo,
useCallback,
} from 'react'
-import ActionButton from '@/app/components/base/action-button'
+import { useTranslation } from 'react-i18next'
import { TransferMethod } from '@/types/app'
import FileFromLinkOrLocal from '../file-from-link-or-local'
@@ -19,28 +16,41 @@ const FileUploaderInChatInput = ({
fileConfig,
readonly,
}: FileUploaderInChatInputProps) => {
- const renderTrigger = useCallback((open: boolean) => {
+ const { t } = useTranslation()
+ const renderTrigger = useCallback((_open: boolean) => {
return (
- <ActionButton
- size="l"
- className={cn(open && 'bg-state-base-hover')}
+ <button
+ type="button"
+ aria-label={t('fileUploader.uploadFromComputer', { ns: 'common' })}
+ className={cn(
+ 'inline-flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-lg p-1.5 text-text-tertiary outline-hidden',
+ 'hover:bg-state-base-hover hover:text-text-secondary',
+ 'focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:ring-inset',
+ 'data-popup-open:bg-state-base-hover',
+ 'disabled:cursor-not-allowed disabled:text-text-disabled disabled:hover:bg-transparent disabled:hover:text-text-disabled',
+ )}
disabled={readonly}
>
- <RiAttachmentLine className="size-5" />
- </ActionButton>
+ <span className="i-ri-attachment-line size-5" aria-hidden="true" />
+ </button>
)
- }, [])
-
- if (readonly)
- return renderTrigger(false)
+ }, [readonly, t])
return (
- <FileFromLinkOrLocal
- trigger={renderTrigger}
- fileConfig={fileConfig}
- showFromLocal={fileConfig?.allowed_file_upload_methods?.includes(TransferMethod.local_file)}
- showFromLink={fileConfig?.allowed_file_upload_methods?.includes(TransferMethod.remote_url)}
- />
+ <span className="inline-flex size-8 shrink-0 items-center justify-center">
+ {
+ readonly
+ ? renderTrigger(false)
+ : (
+ <FileFromLinkOrLocal
+ trigger={renderTrigger}
+ fileConfig={fileConfig}
+ showFromLocal={fileConfig?.allowed_file_upload_methods?.includes(TransferMethod.local_file)}
+ showFromLink={fileConfig?.allowed_file_upload_methods?.includes(TransferMethod.remote_url)}
+ />
+ )
+ }
+ </span>
)
}
diff --git a/web/app/components/base/infotip/index.tsx b/web/app/components/base/infotip/index.tsx
index fe47bc6d667..3a80d1f5c94 100644
--- a/web/app/components/base/infotip/index.tsx
+++ b/web/app/components/base/infotip/index.tsx
@@ -36,6 +36,8 @@ type InfotipProps = {
'aria-label': string
/** Placement of the popup relative to the trigger. Defaults to `top`. */
'placement'?: Placement
+ /** Distance between the trigger and popup. Defaults to the popover primitive spacing. */
+ 'sideOffset'?: number
/** Extra classes on the outer trigger wrapper (layout / margin). */
'className'?: string
/** Extra classes on the `?` icon itself (size / color overrides). */
@@ -52,6 +54,7 @@ export function Infotip({
children,
'aria-label': ariaLabel,
placement = 'top',
+ sideOffset,
className,
iconClassName,
popupClassName,
@@ -79,6 +82,7 @@ export function Infotip({
</PopoverTrigger>
<PopoverContent
placement={placement}
+ sideOffset={sideOffset}
popupClassName={cn('max-w-[300px] rounded-md px-3 py-2 system-xs-regular text-text-tertiary', popupClassName)}
>
{children}
diff --git a/web/app/components/main-nav/__tests__/index.spec.tsx b/web/app/components/main-nav/__tests__/index.spec.tsx
index b46cf22875c..9e528f6d1cc 100644
--- a/web/app/components/main-nav/__tests__/index.spec.tsx
+++ b/web/app/components/main-nav/__tests__/index.spec.tsx
@@ -23,7 +23,7 @@ import { AppModeEnum } from '@/types/app'
import MainNav from '../index'
import { DETAIL_SIDEBAR_STORAGE_KEY } from '../storage'
-const activeGradientMaskClassName = 'aria-[current=page]:main-nav-active-glass'
+const activeGradientMaskClassName = 'aria-[current=page]:dify-blue-glass-surface'
const activeStackingClassName = 'aria-[current=page]:z-1'
const { mockIsAgentV2Enabled, mockSwitchWorkspace, mockToastSuccess, hotkeyRegistrations } = vi.hoisted(() => ({
@@ -384,6 +384,7 @@ describe('MainNav', () => {
expect(screen.getByRole('link', { name: /common.mainNav.home/ })).toHaveAttribute('href', '/')
expect(screen.getByRole('link', { name: /common.menus.apps/ })).toHaveAttribute('href', '/apps')
expect(screen.getByRole('link', { name: /common.menus.roster/ })).toHaveAttribute('href', '/roster')
+ expect(screen.getByRole('link', { name: /common.menus.roster common.menus.status/ })).toBeInTheDocument()
expect(screen.getByRole('link', { name: /common.menus.datasets/ })).toHaveAttribute('href', '/datasets')
expect(screen.getByRole('link', { name: /common.mainNav.integrations/ })).toHaveAttribute('href', '/integrations/model-provider')
expect(screen.getByRole('link', { name: /common.mainNav.marketplace/ })).toHaveAttribute('href', '/marketplace')
diff --git a/web/app/components/main-nav/components/nav-link.tsx b/web/app/components/main-nav/components/nav-link.tsx
index 628be088263..de1a62bfbd0 100644
--- a/web/app/components/main-nav/components/nav-link.tsx
+++ b/web/app/components/main-nav/components/nav-link.tsx
@@ -1,5 +1,6 @@
'use client'
+import type { ReactNode } from 'react'
import type { MainNavItem } from '../types'
import { cn } from '@langgenius/dify-ui/cn'
import Link from '@/next/link'
@@ -17,11 +18,13 @@ const NavIcon = ({
type MainNavLinkProps = {
item: MainNavItem
pathname: string
+ children?: ReactNode
}
const MainNavLink = ({
item,
pathname,
+ children,
}: MainNavLinkProps) => {
const activated = item.active(pathname)
@@ -33,12 +36,13 @@ const MainNavLink = ({
className={cn(
'group relative flex h-8 w-full items-center gap-2 rounded-[10px] px-2 py-1.5 outline-hidden transition-colors focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:ring-inset',
'not-aria-[current=page]:bg-components-main-nav-nav-button-bg not-aria-[current=page]:system-md-medium not-aria-[current=page]:text-components-main-nav-nav-button-text not-aria-[current=page]:hover:bg-components-main-nav-nav-button-bg-hover not-aria-[current=page]:hover:text-components-main-nav-nav-button-text',
- 'aria-[current=page]:main-nav-active-glass aria-[current=page]:z-1',
+ 'aria-[current=page]:dify-blue-glass-surface aria-[current=page]:z-1',
)}
>
<NavIcon icon={item.icon} className="group-aria-[current=page]:hidden" />
<NavIcon icon={item.activeIcon} className="hidden group-aria-[current=page]:block" />
- <span className="truncate group-aria-[current=page]:text-shadow-[0px_0px_8px_var(--color-components-main-nav-glass-text-glow)]">{item.label}</span>
+ <span className="min-w-0 truncate group-aria-[current=page]:text-shadow-[0px_0px_8px_var(--color-components-main-nav-glass-text-glow)]">{item.label}</span>
+ {children}
</Link>
)
}
diff --git a/web/app/components/main-nav/index.tsx b/web/app/components/main-nav/index.tsx
index 3d0a83c4af9..fd304813280 100644
--- a/web/app/components/main-nav/index.tsx
+++ b/web/app/components/main-nav/index.tsx
@@ -12,6 +12,7 @@ import AppDetailTop from '@/app/components/app-sidebar/app-detail-top'
import DatasetDetailSection from '@/app/components/app-sidebar/dataset-detail-section'
import DatasetDetailTop from '@/app/components/app-sidebar/dataset-detail-top'
import { useStore as useAppStore } from '@/app/components/app/store'
+import Badge from '@/app/components/base/badge'
import DifyLogo from '@/app/components/base/logo/dify-logo'
import EnvNav from '@/app/components/header/env-nav'
import { useAppContext } from '@/context/app-context'
@@ -299,7 +300,16 @@ const MainNav = ({
<>
<nav className="isolate flex flex-col gap-px p-2">
{navItems.map(item => (
- <MainNavLink key={item.href} item={item} pathname={pathname} />
+ <MainNavLink key={item.href} item={item} pathname={pathname}>
+ {item.href === '/roster' && (
+ <Badge
+ size="xs"
+ variant="dimm"
+ text={t('menus.status', { ns: 'common' })}
+ className="ml-auto shrink-0"
+ />
+ )}
+ </MainNavLink>
))}
</nav>
{!isCurrentWorkspaceDatasetOperator && <WebAppsSection />}
diff --git a/web/app/components/workflow-app/hooks/__tests__/use-nodes-sync-draft.spec.ts b/web/app/components/workflow-app/hooks/__tests__/use-nodes-sync-draft.spec.ts
index 4b54a4e0da7..06428dcc2d3 100644
--- a/web/app/components/workflow-app/hooks/__tests__/use-nodes-sync-draft.spec.ts
+++ b/web/app/components/workflow-app/hooks/__tests__/use-nodes-sync-draft.spec.ts
@@ -270,6 +270,71 @@ describe('useNodesSyncDraft — handleRefreshWorkflowDraft(true) on 409', () =>
expect(callbacks.onSettled).toHaveBeenCalled()
})
+ it('should keep pending inline Agent v2 nodes in draft without incomplete bindings', async () => {
+ reactFlowState = {
+ ...reactFlowState,
+ edges: [
+ { id: 'edge-1', source: 'n1', target: 'pending-agent', data: { sourceType: BlockEnum.Start, targetType: BlockEnum.Agent } },
+ { id: 'temp-edge', source: 'temp-node', target: 'pending-agent', data: {} },
+ ],
+ }
+ mockGetNodes.mockReturnValue([
+ { id: 'n1', position: { x: 0, y: 0 }, data: { type: BlockEnum.Start } },
+ {
+ id: 'pending-agent',
+ position: { x: 1, y: 1 },
+ data: {
+ type: BlockEnum.Agent,
+ title: 'Agent',
+ desc: '',
+ agent_node_kind: 'dify_agent',
+ version: '2',
+ agent_binding: {
+ binding_type: 'inline_agent',
+ },
+ _isTempNode: true,
+ _openInlineAgentPanel: true,
+ selected: true,
+ },
+ },
+ { id: 'temp-node', position: { x: 2, y: 2 }, data: { type: BlockEnum.Answer, _isTempNode: true } },
+ ])
+
+ const { result } = renderUseNodesSyncDraft()
+
+ await act(async () => {
+ await result.current.doSyncWorkflowDraft(false)
+ })
+
+ expect(mockSyncWorkflowDraft).toHaveBeenCalledWith(expect.objectContaining({
+ params: expect.objectContaining({
+ graph: expect.objectContaining({
+ nodes: [
+ { id: 'n1', position: { x: 0, y: 0 }, data: { type: BlockEnum.Start } },
+ {
+ id: 'pending-agent',
+ position: { x: 1, y: 1 },
+ data: {
+ type: BlockEnum.Agent,
+ title: 'Agent',
+ desc: '',
+ agent_node_kind: 'dify_agent',
+ version: '2',
+ agent_binding: {
+ binding_type: 'inline_agent',
+ },
+ selected: true,
+ },
+ },
+ ],
+ edges: [
+ { id: 'edge-1', source: 'n1', target: 'pending-agent', data: { sourceType: BlockEnum.Start, targetType: BlockEnum.Agent } },
+ ],
+ }),
+ }),
+ }))
+ })
+
it('should post workflow draft with keepalive when the page closes', () => {
reactFlowState = {
...reactFlowState,
diff --git a/web/app/components/workflow-app/hooks/use-nodes-sync-draft.ts b/web/app/components/workflow-app/hooks/use-nodes-sync-draft.ts
index 980b2536546..47328410f10 100644
--- a/web/app/components/workflow-app/hooks/use-nodes-sync-draft.ts
+++ b/web/app/components/workflow-app/hooks/use-nodes-sync-draft.ts
@@ -8,6 +8,7 @@ import { useFeaturesStore } from '@/app/components/base/features/hooks'
import { collaborationManager } from '@/app/components/workflow/collaboration/core/collaboration-manager'
import { useSerialAsyncCallback } from '@/app/components/workflow/hooks/use-serial-async-callback'
import { useNodesReadOnly, useNodesReadOnlyByCanEdit } from '@/app/components/workflow/hooks/use-workflow'
+import { isAgentV2NodeData, needsInlineAgentBindingCreation } from '@/app/components/workflow/nodes/agent-v2/types'
import { useWorkflowStore } from '@/app/components/workflow/store'
import { BlockEnum } from '@/app/components/workflow/types'
import { API_PREFIX } from '@/config'
@@ -33,10 +34,26 @@ const useNodesSyncDraftBase = (getNodesReadOnly: () => boolean) => {
transform,
} = store.getState()
const allNodes = getNodes()
- const nodes = allNodes.filter(node => !node.data?._isTempNode && node.data?.type !== BlockEnum.StartPlaceholder)
+ const nodes = allNodes.filter((node) => {
+ if (node.data?.type === BlockEnum.StartPlaceholder)
+ return false
+
+ if (!node.data?._isTempNode)
+ return true
+
+ return isAgentV2NodeData(node.data) && needsInlineAgentBindingCreation(node.data)
+ })
const skippedNodeIds = new Set(
allNodes
- .filter(node => node.data?._isTempNode || node.data?.type === BlockEnum.StartPlaceholder)
+ .filter((node) => {
+ if (node.data?.type === BlockEnum.StartPlaceholder)
+ return true
+
+ if (!node.data?._isTempNode)
+ return false
+
+ return !(isAgentV2NodeData(node.data) && needsInlineAgentBindingCreation(node.data))
+ })
.map(node => node.id),
)
const [x, y, zoom] = transform
@@ -159,9 +176,10 @@ const useNodesSyncDraftBase = (getNodesReadOnly: () => boolean) => {
setDraftUpdatedAt(res.updated_at)
callback?.onSuccess?.()
}
- catch (error: any) {
- if (error && error.json && !error.bodyUsed) {
- error.json().then((err: any) => {
+ catch (error: unknown) {
+ const responseError = error as { bodyUsed?: boolean, json?: () => Promise<{ code?: string }> }
+ if (responseError.json && !responseError.bodyUsed) {
+ responseError.json().then((err) => {
if (err.code === 'draft_workflow_not_sync' && !notRefreshWhenSyncError)
handleRefreshWorkflowDraft(true)
})
diff --git a/web/app/components/workflow/__tests__/candidate-node-main.spec.tsx b/web/app/components/workflow/__tests__/candidate-node-main.spec.tsx
index 3b327d7cc98..24041815a3d 100644
--- a/web/app/components/workflow/__tests__/candidate-node-main.spec.tsx
+++ b/web/app/components/workflow/__tests__/candidate-node-main.spec.tsx
@@ -294,6 +294,7 @@ describe('CandidateNodeMain', () => {
agent_binding: {
binding_type: 'inline_agent',
},
+ selected: true,
_isTempNode: true,
}),
}),
@@ -307,6 +308,7 @@ describe('CandidateNodeMain', () => {
agent_id: 'inline-agent-1',
current_snapshot_id: 'inline-snapshot-1',
},
+ selected: true,
}),
}),
]))
diff --git a/web/app/components/workflow/candidate-node-main.tsx b/web/app/components/workflow/candidate-node-main.tsx
index d7473023891..968fefc9721 100644
--- a/web/app/components/workflow/candidate-node-main.tsx
+++ b/web/app/components/workflow/candidate-node-main.tsx
@@ -53,12 +53,18 @@ const CandidateNodeMain: FC<Props> = ({
const { x, y } = screenToFlowPosition({ x: mousePosition.pageX, y: mousePosition.pageY })
const shouldCreateInlineAgentBinding = isAgentV2NodeData(candidateNode.data) && needsInlineAgentBindingCreation(candidateNode.data)
const newNodes = produce(nodes, (draft) => {
+ if (shouldCreateInlineAgentBinding) {
+ draft.forEach((node) => {
+ node.data.selected = false
+ })
+ }
draft.push({
...candidateNode,
data: {
...candidateNode.data,
_isCandidate: false,
_isTempNode: shouldCreateInlineAgentBinding ? true : candidateNode.data._isTempNode,
+ selected: shouldCreateInlineAgentBinding ? true : candidateNode.data.selected,
},
position: {
x,
@@ -89,6 +95,8 @@ const CandidateNodeMain: FC<Props> = ({
}
if (shouldCreateInlineAgentBinding) {
+ workflowStore.getState().setOpenInlineAgentPanelNodeId(candidateNode.id)
+ handleSyncWorkflowDraft(true, true)
createInlineAgentBinding(candidateNode.id, {
onError: () => {
const { nodes, setNodes } = collaborativeWorkflow.getState()
@@ -105,7 +113,6 @@ const CandidateNodeMain: FC<Props> = ({
delete node.data._isTempNode
}
}))
- workflowStore.getState().setOpenInlineAgentPanelNodeId(candidateNode.id)
handleSyncWorkflowDraft(true, true)
},
})
diff --git a/web/app/components/workflow/hooks/use-nodes-interactions.ts b/web/app/components/workflow/hooks/use-nodes-interactions.ts
index 538c270692c..f06a0288edf 100644
--- a/web/app/components/workflow/hooks/use-nodes-interactions.ts
+++ b/web/app/components/workflow/hooks/use-nodes-interactions.ts
@@ -193,6 +193,8 @@ export const useNodesInteractions = () => {
const createInlineAgentBindingForNode = useCallback((nodeId: string, options?: {
onError?: () => void
}) => {
+ workflowStore.getState().setOpenInlineAgentPanelNodeId(nodeId)
+ handleSyncWorkflowDraft(true, true)
createInlineAgentBinding(nodeId, {
onError: () => {
options?.onError?.()
@@ -208,7 +210,6 @@ export const useNodesInteractions = () => {
delete node.data._isTempNode
}
}))
- workflowStore.getState().setOpenInlineAgentPanelNodeId(nodeId)
handleSyncWorkflowDraft(true, true)
},
})
diff --git a/web/app/components/workflow/nodes/agent-v2/__tests__/hooks.spec.tsx b/web/app/components/workflow/nodes/agent-v2/__tests__/hooks.spec.tsx
index 6031e3d8b41..089182565ba 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
@@ -156,6 +156,16 @@ describe('useCreateInlineAgentBinding', () => {
agent_id: 'inline-agent-1',
current_snapshot_id: 'inline-snapshot-1',
}))
+ expect(queryClient.getQueryData(['workflow-agent-composer', 'app-1', 'node-1'])).toEqual(expect.objectContaining({
+ agent_soul: expect.objectContaining({
+ schema_version: 1,
+ }),
+ binding: expect.objectContaining({
+ binding_type: 'inline_agent',
+ agent_id: 'inline-agent-1',
+ current_snapshot_id: 'inline-snapshot-1',
+ }),
+ }))
})
it('creates inline agent with a model-less initial soul before the default model loads', async () => {
@@ -212,6 +222,61 @@ describe('useCreateInlineAgentBinding', () => {
current_snapshot_id: 'inline-snapshot-1',
}))
})
+
+ it('finishes inline creation after the caller component unmounts', async () => {
+ let resolveComposerState!: (value: Awaited<ReturnType<typeof mockComposerMutationFn>>) => void
+ mockComposerMutationFn.mockImplementationOnce(async _variables =>
+ new Promise((resolve) => {
+ resolveComposerState = resolve as typeof resolveComposerState
+ }),
+ )
+ const onSuccess = vi.fn()
+ const queryClient = new QueryClient({
+ defaultOptions: {
+ mutations: {
+ retry: false,
+ },
+ },
+ })
+ const { result, unmount } = renderWorkflowHook(() => useCreateInlineAgentBinding(), {
+ queryClient,
+ hooksStoreProps: {
+ configsMap: {
+ flowId: 'app-1',
+ flowType: FlowType.appFlow,
+ fileSettings: {} as never,
+ },
+ },
+ })
+
+ act(() => {
+ void result.current.createInlineAgentBinding('node-1', { onSuccess })
+ })
+ await waitFor(() => expect(mockComposerMutationFn).toHaveBeenCalled())
+ unmount()
+ resolveComposerState({
+ agent_soul: {
+ schema_version: 1,
+ },
+ binding: {
+ binding_type: 'inline_agent',
+ agent_id: 'inline-agent-1',
+ current_snapshot_id: 'inline-snapshot-1',
+ },
+ variables: {},
+ })
+
+ await waitFor(() => expect(onSuccess).toHaveBeenCalledWith({
+ binding_type: 'inline_agent',
+ agent_id: 'inline-agent-1',
+ current_snapshot_id: 'inline-snapshot-1',
+ }))
+ expect(queryClient.getQueryData(['workflow-agent-composer', 'app-1', 'node-1'])).toEqual(expect.objectContaining({
+ agent_soul: expect.objectContaining({
+ schema_version: 1,
+ }),
+ }))
+ })
})
describe('useWorkflowInlineAgentConfigureSync', () => {
@@ -283,4 +348,52 @@ describe('useWorkflowInlineAgentConfigureSync', () => {
}),
}))
})
+
+ it('still saves manually when inline agent autosave is disabled', async () => {
+ const queryClient = new QueryClient({
+ defaultOptions: {
+ queries: {
+ retry: false,
+ },
+ mutations: {
+ retry: false,
+ },
+ },
+ })
+ const { result } = renderWorkflowHook(() => useWorkflowInlineAgentConfigureSync({
+ nodeId: 'node-1',
+ baseConfig: {
+ schema_version: 1,
+ },
+ autoSaveEnabled: false,
+ enabled: true,
+ }), {
+ queryClient,
+ hooksStoreProps: {
+ configsMap: {
+ flowId: 'app-1',
+ flowType: FlowType.appFlow,
+ fileSettings: {} as never,
+ },
+ },
+ })
+
+ await act(async () => {
+ await result.current.saveDraft()
+ })
+
+ expect(mockComposerMutationFn).toHaveBeenCalledWith({
+ params: {
+ app_id: 'app-1',
+ node_id: 'node-1',
+ },
+ body: expect.objectContaining({
+ variant: 'workflow',
+ save_strategy: 'node_job_only',
+ agent_soul: expect.objectContaining({
+ schema_version: 1,
+ }),
+ }),
+ }, expect.any(Object))
+ })
})
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.tsx
index 5b2a15c8ac1..25a5fae2762 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
@@ -123,9 +123,9 @@ describe('agent/node', () => {
expect(screen.getByText('workflow.nodes.agent.roster.inlineSetup.name')).toHaveClass('system-xs-regular', 'text-text-secondary')
expect(screen.getByText('workflow.nodes.agent.roster.inlineSetup.type')).toHaveClass('system-2xs-regular', 'text-text-tertiary')
- const robotIcon = container.querySelector('.i-custom-vender-agent-v2-robot-3')
- expect(robotIcon).toHaveClass('size-5')
- expect(robotIcon?.parentElement).toHaveClass('size-8', 'rounded-full', 'bg-background-default-burn')
+ const configureIcon = container.querySelector('.i-custom-vender-agent-v2-configure')
+ expect(configureIcon).toHaveClass('h-3.5', 'w-3')
+ expect(configureIcon?.parentElement).toHaveClass('size-8', 'rounded-full', 'bg-background-default-burn')
})
it('renders the fixed inline setup name when workflow composer state is loaded', () => {
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.tsx
index 1b824eb7510..c8a362ccda2 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
@@ -12,12 +12,15 @@ const {
mockHandleNodeDataUpdate,
mockHandleNodeDataUpdateWithSyncDraft,
mockInsertNodes,
- mockOrchestrateDrawerPanelProps,
+ mockOrchestratePanelContentProps,
mockPromptEditorProps,
+ mockCopyFromRosterMutate,
+ mockCopyFromRosterState,
mockCreateInlineAgentBinding,
mockSetInputs,
mockStoreState,
mockUseAgentRosterDetail,
+ mockWorkflowInlineAgentDetailRefetch,
mockUseWorkflowInlineAgentDetail,
mockUseNodeCrud,
} = vi.hoisted(() => ({
@@ -26,21 +29,27 @@ const {
mockHandleNodeDataUpdate: vi.fn(),
mockHandleNodeDataUpdateWithSyncDraft: vi.fn((_payload, options) => options?.callback?.onSuccess?.()),
mockInsertNodes: vi.fn(),
- mockOrchestrateDrawerPanelProps: [] as Array<{
- agentId: string
+ mockOrchestratePanelContentProps: [] as Array<{
+ agentId?: string
+ appId?: string
inlineComposerState?: unknown
- isInline: boolean
nodeId: string
open: boolean
}>,
mockPromptEditorProps: [] as PromptEditorProps[],
+ mockCopyFromRosterMutate: vi.fn(),
+ mockCopyFromRosterState: {
+ isPending: false,
+ },
mockCreateInlineAgentBinding: vi.fn(),
mockSetInputs: vi.fn(),
mockStoreState: {
+ appId: 'app-1',
openInlineAgentPanelNodeId: undefined as string | undefined,
setOpenInlineAgentPanelNodeId: vi.fn(),
},
mockUseAgentRosterDetail: vi.fn(),
+ mockWorkflowInlineAgentDetailRefetch: vi.fn(),
mockUseWorkflowInlineAgentDetail: vi.fn(),
mockUseNodeCrud: vi.fn(),
}))
@@ -80,6 +89,18 @@ vi.mock('@lexical/react/LexicalComposerContext', () => ({
}],
}))
+vi.mock('@tanstack/react-query', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@tanstack/react-query')>()
+
+ return {
+ ...actual,
+ useMutation: () => ({
+ isPending: mockCopyFromRosterState.isPending,
+ mutate: mockCopyFromRosterMutate,
+ }),
+ }
+})
+
vi.mock('lexical', async (importOriginal) => {
const actual = await importOriginal<typeof import('lexical')>()
@@ -148,23 +169,94 @@ vi.mock('../hooks', () => ({
useWorkflowInlineAgentDetail: (nodeId?: string, agentId?: string | null) => mockUseWorkflowInlineAgentDetail(nodeId, agentId),
}))
-vi.mock('../components/agent-orchestrate-drawer-panel', () => ({
- AgentOrchestrateDrawerPanel: (props: {
- agentId: string
+vi.mock('../components/agent-orchestrate-panel-content', () => ({
+ WorkflowRosterAgentOrchestratePanelContent: (props: {
+ agentId?: string
+ nodeId: string
+ open: boolean
+ }) => {
+ mockOrchestratePanelContentProps.push(props)
+
+ return (
+ <div role="region" aria-label="readonly-roster-orchestrate-panel" />
+ )
+ },
+ WorkflowInlineAgentConfigureWorkspace: (props: {
+ agentId?: string
appId?: string
inlineComposerState?: unknown
- isInline: boolean
nodeId: string
+ onClose?: () => void
+ onSaved?: (binding: {
+ agent_id?: string | null
+ binding_type: 'inline_agent' | 'roster_agent'
+ current_snapshot_id?: string | null
+ }) => void
+ onSaveInlineToRoster?: () => void
open: boolean
}) => {
- mockOrchestrateDrawerPanelProps.push(props)
+ mockOrchestratePanelContentProps.push(props)
return (
- <div role="region" aria-label={props.isInline ? 'inline-orchestrate-panel' : 'readonly-roster-orchestrate-panel'} />
+ <div role="region" aria-label="inline-orchestrate-panel">
+ <button
+ type="button"
+ onClick={props.onSaveInlineToRoster}
+ >
+ Inline workspace more
+ </button>
+ <button
+ type="button"
+ onClick={() => {
+ props.onSaved?.({
+ binding_type: 'inline_agent',
+ agent_id: 'inline-agent-1',
+ current_snapshot_id: 'latest-snapshot-2',
+ })
+ }}
+ >
+ Autosave inline workspace
+ </button>
+ </div>
)
},
}))
+vi.mock('../components/save-inline-agent-to-roster-dialog', () => ({
+ SaveInlineAgentToRosterDialog: ({
+ open,
+ onSaved,
+ }: {
+ open: boolean
+ onSaved: (binding: {
+ agent_id?: string | null
+ binding_type: 'inline_agent' | 'roster_agent'
+ current_snapshot_id?: string | null
+ id: string
+ node_id: string
+ workflow_id: string
+ }) => void
+ }) => open
+ ? (
+ <div role="dialog" aria-label="save-inline-agent-to-roster">
+ <button
+ type="button"
+ onClick={() => onSaved({
+ id: 'binding-1',
+ binding_type: 'roster_agent',
+ agent_id: 'saved-roster-agent',
+ current_snapshot_id: 'saved-snapshot',
+ workflow_id: 'workflow-1',
+ node_id: 'agent-node',
+ })}
+ >
+ Save inline agent to roster
+ </button>
+ </div>
+ )
+ : null,
+}))
+
vi.mock('../../_base/hooks/use-available-var-list', () => ({
default: () => ({
availableVars: [{
@@ -214,8 +306,33 @@ describe('agent/panel', () => {
beforeEach(() => {
vi.clearAllMocks()
mockPromptEditorProps.length = 0
- mockOrchestrateDrawerPanelProps.length = 0
+ mockOrchestratePanelContentProps.length = 0
+ mockStoreState.appId = 'app-1'
mockStoreState.openInlineAgentPanelNodeId = undefined
+ mockCopyFromRosterState.isPending = false
+ mockCopyFromRosterMutate.mockImplementation((_variables, options?: {
+ onSuccess?: (composerState: {
+ binding: {
+ agent_id: string
+ binding_type: 'inline_agent'
+ current_snapshot_id: string
+ id: string
+ node_id: string
+ workflow_id: string
+ }
+ }) => void
+ }) => {
+ options?.onSuccess?.({
+ binding: {
+ id: 'binding-1',
+ binding_type: 'inline_agent',
+ agent_id: 'inline-copy-agent',
+ current_snapshot_id: 'inline-copy-snapshot',
+ workflow_id: 'workflow-1',
+ node_id: 'agent-node',
+ },
+ })
+ })
mockCreateInlineAgentBinding.mockImplementation(() => {})
mockUseNodeCrud.mockImplementation((_id: string, data: AgentV2NodeType) => ({
inputs: data,
@@ -246,6 +363,8 @@ describe('agent/panel', () => {
},
}
: undefined,
+ isFetching: false,
+ refetch: mockWorkflowInlineAgentDetailRefetch,
}))
})
@@ -292,9 +411,8 @@ describe('agent/panel', () => {
expect(within(panel).getByRole('link', { name: 'workflow.nodes.agent.roster.editInConsole' })).toHaveAttribute('href', '/roster/agent/agent-1/configure')
expect(within(panel).getByRole('button', { name: 'workflow.nodes.agent.roster.makeCopy' })).toBeInTheDocument()
expect(within(panel).getByRole('region', { name: 'readonly-roster-orchestrate-panel' })).toBeInTheDocument()
- expect(mockOrchestrateDrawerPanelProps.at(-1)).toMatchObject({
+ expect(mockOrchestratePanelContentProps.at(-1)).toMatchObject({
agentId: 'agent-1',
- isInline: false,
nodeId: 'agent-node',
open: true,
})
@@ -304,6 +422,52 @@ describe('agent/panel', () => {
expect(screen.queryByRole('dialog', { name: 'Nadia' })).not.toBeInTheDocument()
})
+ it('copies a roster agent from the drawer into an inline agent for this node', () => {
+ render(
+ <AgentV2Panel
+ id="agent-node"
+ data={createData()}
+ panelProps={panelProps}
+ />,
+ )
+
+ fireEvent.click(screen.getByRole('button', { name: /^workflow\.nodes\.agent\.roster\.openPanel/ }))
+ fireEvent.click(screen.getByRole('button', { name: 'workflow.nodes.agent.roster.makeCopy' }))
+
+ expect(mockCopyFromRosterMutate).toHaveBeenCalledWith(
+ {
+ params: {
+ app_id: 'app-1',
+ node_id: 'agent-node',
+ },
+ body: {
+ source_agent_id: 'agent-1',
+ },
+ },
+ 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-copy-agent',
+ current_snapshot_id: 'inline-copy-snapshot',
+ },
+ _openInlineAgentPanel: true,
+ }),
+ },
+ expect.objectContaining({
+ sync: true,
+ notRefreshWhenSyncError: true,
+ }),
+ )
+ })
+
it('renders a required roster state when no roster agent is selected', () => {
render(
<AgentV2Panel
@@ -321,6 +485,7 @@ describe('agent/panel', () => {
})
it('renders a pending inline agent state while the binding is being created', () => {
+ mockStoreState.openInlineAgentPanelNodeId = 'agent-node'
const { container } = render(
<AgentV2Panel
id="agent-node"
@@ -336,12 +501,58 @@ describe('agent/panel', () => {
expect(screen.queryByText(/^workflow\.errorMsg\.fieldRequired/)).not.toBeInTheDocument()
expect(container.querySelector('[aria-busy="true"]')).toBeInTheDocument()
- expect(screen.getByRole('button', { name: 'workflow.nodes.agent.roster.change' })).toBeDisabled()
+ expect(screen.getByRole('button', { name: 'workflow.nodes.agent.roster.change', hidden: true })).toBeDisabled()
+ expect(screen.getByRole('dialog', { name: 'workflow.nodes.agent.roster.inlineSetup.name' })).toBeInTheDocument()
+ expect(screen.getByRole('region', { name: 'inline-orchestrate-panel' })).toBeInTheDocument()
+ expect(screen.queryByText('workflow.nodes.agent.roster.editInConsole')).not.toBeInTheDocument()
+ expect(screen.queryByText('workflow.nodes.agent.roster.makeCopy')).not.toBeInTheDocument()
+ expect(mockOrchestratePanelContentProps.at(-1)).toMatchObject({
+ agentId: undefined,
+ nodeId: 'agent-node',
+ open: true,
+ })
expect(screen.getByText('workflow.nodes.agent.task.label')).toBeInTheDocument()
expect(screen.getByText('workflow.nodes.agent.outputVars.text')).toBeInTheDocument()
expect(container.querySelector('[inert]')).toBeInTheDocument()
})
+ it('opens a pending inline agent modal and creates the inline agent before rendering details', () => {
+ const { container, rerender } = render(
+ <AgentV2Panel
+ id="agent-node"
+ data={createData({
+ agent_binding: {
+ binding_type: 'inline_agent',
+ },
+ })}
+ panelProps={panelProps}
+ />,
+ )
+
+ fireEvent.click(screen.getByRole('button', { name: /^workflow\.nodes\.agent\.roster\.openPanel/ }))
+
+ expect(mockStoreState.setOpenInlineAgentPanelNodeId).toHaveBeenCalledWith('agent-node')
+ expect(mockCreateInlineAgentBinding).toHaveBeenCalledWith('agent-node', expect.objectContaining({
+ onSuccess: expect.any(Function),
+ }))
+ mockStoreState.openInlineAgentPanelNodeId = 'agent-node'
+ rerender(
+ <AgentV2Panel
+ id="agent-node"
+ data={createData({
+ agent_binding: {
+ binding_type: 'inline_agent',
+ },
+ })}
+ panelProps={panelProps}
+ />,
+ )
+
+ expect(screen.getByRole('dialog', { name: 'workflow.nodes.agent.roster.inlineSetup.name' })).toBeInTheDocument()
+ expect(screen.getByRole('region', { name: 'inline-orchestrate-panel' })).toBeInTheDocument()
+ expect(container.querySelector('[aria-busy="true"]')).toBeInTheDocument()
+ })
+
it('renders inline agent detail from workflow composer state and opens the inline panel', () => {
mockStoreState.openInlineAgentPanelNodeId = 'agent-node'
const { container } = render(
@@ -361,22 +572,18 @@ describe('agent/panel', () => {
expect(mockUseAgentRosterDetail).toHaveBeenCalledWith(undefined)
expect(mockUseWorkflowInlineAgentDetail).toHaveBeenCalledWith('agent-node', 'inline-agent-1')
- expect(screen.queryByText('Workflow Agent 1')).not.toBeInTheDocument()
- const trigger = screen.getByRole('button', { name: /^workflow\.nodes\.agent\.roster\.openPanel/ })
+ expect(screen.getByRole('dialog', { name: 'Workflow Agent 1' })).toBeInTheDocument()
+ const trigger = screen.getByRole('button', { name: /^workflow\.nodes\.agent\.roster\.openPanel/, hidden: true })
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(panelRobotIcon).toHaveClass('size-5')
- expect(panelRobotIcon?.parentElement).toHaveClass('size-9', 'rounded-full', 'bg-background-default-burn')
+ const panel = screen.getByRole('dialog', { name: 'Workflow Agent 1' })
+ expect(container.querySelector('.i-custom-vender-agent-v2-configure')).toHaveClass('h-3.5', 'w-3')
+ expect(container.querySelector('.i-custom-vender-agent-v2-configure')?.parentElement).toHaveClass('size-8', '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(within(panel).getByText('workflow.nodes.agent.roster.inlineSetup.description')).toBeInTheDocument()
expect(screen.getByRole('region', { name: 'inline-orchestrate-panel' })).toBeInTheDocument()
- expect(mockOrchestrateDrawerPanelProps.at(-1)).toMatchObject({
+ expect(mockOrchestratePanelContentProps.at(-1)).toMatchObject({
agentId: 'inline-agent-1',
- isInline: true,
nodeId: 'agent-node',
open: true,
})
@@ -402,6 +609,7 @@ describe('agent/panel', () => {
fireEvent.click(screen.getByRole('button', { name: /^workflow\.nodes\.agent\.roster\.openPanel/ }))
expect(mockStoreState.setOpenInlineAgentPanelNodeId).toHaveBeenCalledWith('agent-node')
+ expect(mockWorkflowInlineAgentDetailRefetch).toHaveBeenCalled()
mockStoreState.openInlineAgentPanelNodeId = 'agent-node'
rerender(
@@ -418,19 +626,154 @@ describe('agent/panel', () => {
/>,
)
- const panel = screen.getByRole('dialog', { name: 'workflow.nodes.agent.roster.inlineSetup.name' })
+ const panel = screen.getByRole('dialog', { name: 'Workflow Agent 1' })
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).getByText('Workflow Agent 1')).toBeInTheDocument()
expect(within(panel).queryByText('workflow.nodes.agent.roster.inlineSetup.title')).not.toBeInTheDocument()
- expect(within(panel).queryByText('workflow.nodes.agent.roster.inlineSetup.description')).not.toBeInTheDocument()
+ expect(within(panel).getByText('workflow.nodes.agent.roster.inlineSetup.description')).toBeInTheDocument()
expect(within(panel).queryByRole('link', { name: 'workflow.nodes.agent.roster.editInConsole' })).not.toBeInTheDocument()
expect(within(panel).queryByRole('button', { name: 'workflow.nodes.agent.roster.makeCopy' })).not.toBeInTheDocument()
expect(screen.getByRole('region', { name: 'inline-orchestrate-panel' })).toBeInTheDocument()
})
+ it('keeps the inline roster trigger stable while opening refetches composer state', () => {
+ mockUseWorkflowInlineAgentDetail.mockReturnValue({
+ data: {
+ agent: {
+ id: 'inline-agent-1',
+ name: 'Workflow Agent 1',
+ description: '',
+ scope: 'workflow_only',
+ status: 'active',
+ },
+ },
+ isFetching: true,
+ refetch: mockWorkflowInlineAgentDetailRefetch,
+ })
+ const { rerender } = render(
+ <AgentV2Panel
+ id="agent-node"
+ data={createData({
+ agent_binding: {
+ binding_type: 'inline_agent',
+ agent_id: 'inline-agent-1',
+ current_snapshot_id: 'snapshot-1',
+ },
+ })}
+ panelProps={panelProps}
+ />,
+ )
+
+ fireEvent.click(screen.getByRole('button', { name: /^workflow\.nodes\.agent\.roster\.openPanel/ }))
+ expect(mockWorkflowInlineAgentDetailRefetch).toHaveBeenCalled()
+
+ mockStoreState.openInlineAgentPanelNodeId = 'agent-node'
+ rerender(
+ <AgentV2Panel
+ id="agent-node"
+ data={createData({
+ agent_binding: {
+ binding_type: 'inline_agent',
+ agent_id: 'inline-agent-1',
+ current_snapshot_id: 'snapshot-1',
+ },
+ })}
+ panelProps={panelProps}
+ />,
+ )
+
+ const trigger = screen.getByRole('button', { name: /^workflow\.nodes\.agent\.roster\.openPanel/, hidden: true })
+ expect(trigger).not.toHaveAttribute('aria-busy')
+ expect(within(trigger).getByText('workflow.nodes.agent.roster.inlineSetup.name')).toBeInTheDocument()
+ expect(within(trigger).getByText('workflow.nodes.agent.roster.inlineSetup.type')).toBeInTheDocument()
+ expect(mockOrchestratePanelContentProps.at(-1)).toMatchObject({
+ agentId: 'inline-agent-1',
+ inlineComposerState: expect.objectContaining({
+ agent: expect.objectContaining({
+ id: 'inline-agent-1',
+ }),
+ }),
+ nodeId: 'agent-node',
+ open: true,
+ })
+ })
+
+ it('opens save-to-roster action from the inline workspace menu and rebinds to the saved roster agent', () => {
+ mockStoreState.openInlineAgentPanelNodeId = 'agent-node'
+ 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}
+ />,
+ )
+
+ const panel = screen.getByRole('dialog', { name: 'Workflow Agent 1' })
+ expect(within(panel).queryByRole('button', { name: 'workflow.nodes.agent.roster.more' })).not.toBeInTheDocument()
+ fireEvent.click(within(panel).getByRole('button', { name: 'Inline workspace more' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Save inline agent to roster', hidden: true }))
+
+ expect(mockStoreState.setOpenInlineAgentPanelNodeId).toHaveBeenCalledWith(undefined)
+ expect(mockHandleNodeDataUpdateWithSyncDraft).toHaveBeenCalledWith(
+ {
+ id: 'agent-node',
+ data: expect.objectContaining({
+ agent_binding: {
+ binding_type: 'roster_agent',
+ agent_id: 'saved-roster-agent',
+ },
+ }),
+ },
+ expect.objectContaining({
+ sync: true,
+ notRefreshWhenSyncError: true,
+ }),
+ )
+ })
+
+ it('updates the inline binding snapshot from the inline workspace autosave response', () => {
+ mockStoreState.openInlineAgentPanelNodeId = 'agent-node'
+ 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: 'Autosave inline workspace' }))
+
+ expect(mockHandleNodeDataUpdateWithSyncDraft).toHaveBeenCalledWith(
+ {
+ id: 'agent-node',
+ data: expect.objectContaining({
+ agent_binding: {
+ binding_type: 'inline_agent',
+ agent_id: 'inline-agent-1',
+ current_snapshot_id: 'latest-snapshot-2',
+ },
+ }),
+ },
+ expect.objectContaining({
+ sync: true,
+ notRefreshWhenSyncError: true,
+ }),
+ )
+ expect(mockStoreState.setOpenInlineAgentPanelNodeId).not.toHaveBeenCalledWith(undefined)
+ })
+
it('does not show start from scratch for an existing inline agent binding', () => {
render(
<AgentV2Panel
@@ -453,7 +796,11 @@ describe('agent/panel', () => {
it('opens the inline panel while workflow composer state is still loading', () => {
mockStoreState.openInlineAgentPanelNodeId = 'agent-node'
- mockUseWorkflowInlineAgentDetail.mockReturnValue({ data: undefined })
+ mockUseWorkflowInlineAgentDetail.mockReturnValue({
+ data: undefined,
+ isFetching: true,
+ refetch: mockWorkflowInlineAgentDetailRefetch,
+ })
const { container } = render(
<AgentV2Panel
@@ -471,12 +818,13 @@ describe('agent/panel', () => {
expect(mockUseWorkflowInlineAgentDetail).toHaveBeenCalledWith('agent-node', 'inline-agent-1')
expect(container.querySelector('[aria-busy="true"]')).toBeInTheDocument()
- expect(screen.getByRole('dialog', { name: 'workflow.nodes.agent.roster.inlineSetup.name' })).toBeInTheDocument()
+ const panel = screen.getByRole('dialog', { name: 'workflow.nodes.agent.roster.inlineSetup.name' })
+ expect(panel).toBeInTheDocument()
+ expect(within(panel).queryByRole('button', { name: 'workflow.nodes.agent.roster.more' })).not.toBeInTheDocument()
expect(screen.getByRole('region', { name: 'inline-orchestrate-panel' })).toBeInTheDocument()
- expect(mockOrchestrateDrawerPanelProps.at(-1)).toMatchObject({
+ expect(mockOrchestratePanelContentProps.at(-1)).toMatchObject({
agentId: 'inline-agent-1',
inlineComposerState: undefined,
- isInline: true,
nodeId: 'agent-node',
open: true,
})
@@ -570,10 +918,30 @@ describe('agent/panel', () => {
fireEvent.click(screen.getByRole('button', { name: 'workflow.nodes.agent.roster.change' }))
fireEvent.click(screen.getByRole('button', { name: 'Start from Scratch' }))
+ expect(mockStoreState.setOpenInlineAgentPanelNodeId).toHaveBeenCalledWith('agent-node')
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_task: 'Keep this task',
+ agent_declared_outputs: [{
+ name: 'summary',
+ type: 'string',
+ }],
+ _openInlineAgentPanel: true,
+ }),
+ },
+ expect.objectContaining({
+ sync: true,
+ notRefreshWhenSyncError: true,
+ }),
+ )
expect(mockHandleNodeDataUpdateWithSyncDraft).toHaveBeenCalledWith(
{
id: 'agent-node',
@@ -642,6 +1010,7 @@ describe('agent/panel', () => {
expect(mockPromptEditorProps[0]?.workflowVariableBlock).toMatchObject({
show: true,
})
+ expect(mockPromptEditorProps[0]?.isSupportFileVar).toBe(true)
expect(mockPromptEditorProps[0]?.agentOutputBlock).toMatchObject({
show: true,
outputs: expect.arrayContaining([
diff --git a/web/app/components/workflow/nodes/agent-v2/agent-soul-config.ts b/web/app/components/workflow/nodes/agent-v2/agent-soul-config.ts
index be73fc9fa60..3db9cf28e15 100644
--- a/web/app/components/workflow/nodes/agent-v2/agent-soul-config.ts
+++ b/web/app/components/workflow/nodes/agent-v2/agent-soul-config.ts
@@ -1,4 +1,4 @@
-import type { AgentSoulConfig } from '@dify/contracts/api/console/apps/types.gen'
+import type { AgentSoulConfig, WorkflowAgentComposerResponse } from '@dify/contracts/api/console/apps/types.gen'
import type { DefaultModelResponse } from '@/app/components/header/account-setting/model-provider-page/declarations'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { debounce } from 'es-toolkit/compat'
@@ -54,6 +54,8 @@ export function useWorkflowInlineAgentConfigureSync({
nodeId,
baseConfig,
currentModel,
+ autoSaveEnabled = true,
+ onDraftSaved,
enabled,
}: {
nodeId: string
@@ -63,6 +65,8 @@ export function useWorkflowInlineAgentConfigureSync({
model: string
plugin_id?: string
}
+ autoSaveEnabled?: boolean
+ onDraftSaved?: (composerState: WorkflowAgentComposerResponse) => void
enabled: boolean
}) {
const queryClient = useQueryClient()
@@ -74,6 +78,7 @@ export function useWorkflowInlineAgentConfigureSync({
const baseConfigRef = useRef(baseConfig)
const currentModelRef = useRef(currentModel)
const enabledRef = useRef(enabled)
+ const onDraftSavedRef = useRef(onDraftSaved)
const lastAutosavedDraftKeyRef = useRef<string | undefined>(undefined)
const saveComposerMutation = useMutation(
consoleQuery.apps.byAppId.workflows.draft.nodes.byNodeId.agentComposer.put.mutationOptions(),
@@ -82,6 +87,7 @@ export function useWorkflowInlineAgentConfigureSync({
baseConfigRef.current = baseConfig
currentModelRef.current = currentModel
enabledRef.current = enabled
+ onDraftSavedRef.current = onDraftSaved
const getAgentSoulDraft = useCallback(() => formStateToAgentSoulConfig({
baseConfig: baseConfigRef.current,
@@ -89,7 +95,7 @@ export function useWorkflowInlineAgentConfigureSync({
currentModel: currentModelRef.current,
}), [store])
- const saveComposer = useSerialAsyncCallback(async (configSnapshot: AgentSoulConfig) => {
+ const saveComposer = useSerialAsyncCallback(async (configSnapshot: AgentSoulConfig): Promise<WorkflowAgentComposerResponse | undefined> => {
if (!configsMap?.flowId || configsMap.flowType !== FlowType.appFlow)
return
@@ -121,6 +127,8 @@ export function useWorkflowInlineAgentConfigureSync({
setOriginalDraft(agentSoulConfigToFormState(composerState.agent_soul))
setDraftSavedAt(Date.now())
lastAutosavedDraftKeyRef.current = savedDraftKey
+ onDraftSavedRef.current?.(composerState)
+ return composerState
})
const latestDraftSaveRef = useRef<() => void>(() => undefined)
@@ -137,7 +145,7 @@ export function useWorkflowInlineAgentConfigureSync({
return
debouncedSaveDraft.cancel?.()
- await saveComposer(getAgentSoulDraft())
+ return saveComposer(getAgentSoulDraft())
}, [debouncedSaveDraft, getAgentSoulDraft, saveComposer])
useEffect(() => {
@@ -147,6 +155,7 @@ export function useWorkflowInlineAgentConfigureSync({
if (
!enabledRef.current
+ || !autoSaveEnabled
|| !store.get(isAgentComposerDirtyAtom)
|| lastAutosavedDraftKeyRef.current === agentSoulDraftKey
) {
@@ -155,13 +164,14 @@ export function useWorkflowInlineAgentConfigureSync({
debouncedSaveDraft()
})
- }, [debouncedSaveDraft, getAgentSoulDraft, store])
+ }, [autoSaveEnabled, debouncedSaveDraft, getAgentSoulDraft, store])
useEffect(() => {
return () => {
- debouncedSaveDraft.flush?.()
+ if (autoSaveEnabled)
+ debouncedSaveDraft.flush?.()
}
- }, [debouncedSaveDraft])
+ }, [autoSaveEnabled, debouncedSaveDraft])
return {
draftSavedAt,
diff --git a/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-orchestrate-panel-content.spec.tsx b/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-orchestrate-panel-content.spec.tsx
new file mode 100644
index 00000000000..4905f88c1b6
--- /dev/null
+++ b/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-orchestrate-panel-content.spec.tsx
@@ -0,0 +1,193 @@
+import type { AgentSoulConfig, WorkflowAgentComposerResponse } from '@dify/contracts/api/console/apps/types.gen'
+import type { ReactNode } from 'react'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { WorkflowInlineAgentConfigureWorkspace } from '../agent-orchestrate-panel-content'
+
+const mocks = vi.hoisted(() => ({
+ checkoutBuildDraft: vi.fn(),
+ saveDraft: vi.fn(),
+}))
+
+vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({
+ useDefaultModel: () => ({
+ data: undefined,
+ }),
+ useTextGenerationCurrentProviderAndModelAndModelList: () => ({
+ textGenerationModelList: [],
+ }),
+}))
+
+vi.mock('@/features/agent-v2/agent-detail/configure/components/orchestrate', () => ({
+ AgentOrchestratePanel: (props: {
+ bottomBar?: ReactNode
+ headerAction?: ReactNode
+ }) => (
+ <div role="region" aria-label="orchestrate-panel">
+ {props.headerAction}
+ {props.bottomBar}
+ </div>
+ ),
+}))
+
+vi.mock('@/features/agent-v2/agent-detail/configure/components/preview/build-background', () => ({
+ AgentBuildPanelBackground: () => null,
+}))
+
+vi.mock('@/features/agent-v2/agent-detail/configure/components/preview/build-chat', () => ({
+ AgentBuildChat: (props: {
+ onSaveDraftBeforeRun?: () => Promise<void>
+ }) => (
+ <div role="region" aria-label="build-chat">
+ <button
+ type="button"
+ onClick={() => {
+ void props.onSaveDraftBeforeRun?.()
+ }}
+ >
+ start build
+ </button>
+ </div>
+ ),
+}))
+
+vi.mock('@/app/components/workflow/nodes/agent-v2/agent-soul-config', () => ({
+ useWorkflowInlineAgentConfigureSync: () => ({
+ draftSavedAt: undefined,
+ saveDraft: mocks.saveDraft,
+ }),
+}))
+
+vi.mock('@/service/client', () => ({
+ consoleQuery: {
+ agent: {
+ byAgentId: {
+ composer: {
+ get: {
+ queryOptions: vi.fn(),
+ },
+ },
+ buildDraft: {
+ get: {
+ queryOptions: () => ({ queryKey: ['build-draft'] }),
+ },
+ checkout: {
+ post: {
+ mutationOptions: () => ({ mutationFn: mocks.checkoutBuildDraft }),
+ },
+ },
+ },
+ },
+ },
+ },
+}))
+
+function createInlineComposerState(): WorkflowAgentComposerResponse {
+ return {
+ agent: {
+ id: 'agent-1',
+ icon: 'A',
+ icon_background: '#E0F2FE',
+ icon_type: 'emoji',
+ name: 'Inline Agent',
+ },
+ agent_soul: {
+ schema_version: 1,
+ prompt: {
+ system_prompt: 'Help with workflow tasks.',
+ },
+ } satisfies AgentSoulConfig,
+ binding: {
+ id: 'binding-1',
+ binding_type: 'inline_agent',
+ agent_id: 'agent-1',
+ current_snapshot_id: 'snapshot-1',
+ workflow_id: 'workflow-1',
+ node_id: 'node-1',
+ },
+ } as WorkflowAgentComposerResponse
+}
+
+describe('WorkflowInlineAgentConfigureWorkspace', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mocks.checkoutBuildDraft.mockResolvedValue({
+ agent_soul: {},
+ draft: {},
+ variant: 'agent_app',
+ })
+ mocks.saveDraft.mockResolvedValue(createInlineComposerState())
+ })
+
+ function renderWorkspace(props: {
+ onSaveInlineToRoster?: () => void
+ } = {}) {
+ const queryClient = new QueryClient()
+
+ render(
+ <QueryClientProvider client={queryClient}>
+ <WorkflowInlineAgentConfigureWorkspace
+ agentId="agent-1"
+ appId="app-1"
+ inlineComposerState={createInlineComposerState()}
+ nodeId="node-1"
+ onSaveInlineToRoster={props.onSaveInlineToRoster}
+ open
+ />
+ </QueryClientProvider>,
+ )
+ }
+
+ describe('Working Directory', () => {
+ it('should show save-to-roster in the configure header menu without rendering the old action bar', () => {
+ renderWorkspace({
+ onSaveInlineToRoster: vi.fn(),
+ })
+
+ expect(screen.getByRole('button', { name: 'common.operation.more' })).toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'common.operation.save' })).not.toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'common.operation.cancel' })).not.toBeInTheDocument()
+ })
+
+ it('should show the working directory panel when the header action is clicked', async () => {
+ renderWorkspace()
+
+ fireEvent.click(screen.getByRole('button', {
+ name: 'agentV2.agentDetail.configure.workingDirectory.open',
+ }))
+
+ expect(await screen.findByRole('dialog', {
+ name: 'agentV2.agentDetail.configure.workingDirectory.title',
+ })).toBeInTheDocument()
+ expect(screen.getByRole('region', {
+ name: 'agentV2.agentDetail.configure.workingDirectory.treeLabel',
+ })).toBeInTheDocument()
+ })
+ })
+
+ describe('Build Chat', () => {
+ it('should save the workflow agent draft and checkout a build draft before starting build chat', async () => {
+ renderWorkspace()
+
+ fireEvent.click(screen.getByRole('button', { name: 'start build' }))
+
+ await waitFor(() => expect(mocks.saveDraft).toHaveBeenCalled())
+ expect(mocks.checkoutBuildDraft).toHaveBeenCalledWith({
+ params: {
+ agent_id: 'agent-1',
+ },
+ body: {
+ force: false,
+ },
+ }, expect.any(Object))
+ const saveDraftCallOrder = mocks.saveDraft.mock.invocationCallOrder[0]
+ const checkoutBuildDraftCallOrder = mocks.checkoutBuildDraft.mock.invocationCallOrder[0]
+ expect(saveDraftCallOrder).toBeDefined()
+ expect(checkoutBuildDraftCallOrder).toBeDefined()
+ if (saveDraftCallOrder === undefined || checkoutBuildDraftCallOrder === undefined)
+ throw new Error('Expected save draft and checkout mutations to be called')
+
+ expect(saveDraftCallOrder).toBeLessThan(checkoutBuildDraftCallOrder)
+ })
+ })
+})
diff --git a/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-roster-field.spec.tsx b/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-roster-field.spec.tsx
new file mode 100644
index 00000000000..b05418bbd12
--- /dev/null
+++ b/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-roster-field.spec.tsx
@@ -0,0 +1,51 @@
+import { render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { useRef } from 'react'
+import { AgentRosterField } from '../agent-roster-field'
+
+vi.mock('@/app/components/workflow/block-selector/agent-selector', () => ({
+ AgentSelectorContent: () => null,
+}))
+
+function renderInlineRosterField() {
+ function Harness() {
+ const portalContainerRef = useRef<HTMLDivElement>(null)
+
+ return (
+ <div ref={portalContainerRef}>
+ <AgentRosterField
+ agent={{
+ id: 'inline-agent-1',
+ name: 'Inline Workspace',
+ role: 'Workflow-only agent',
+ }}
+ isInlineSetup
+ panelBody={<button type="button">Inline workspace action</button>}
+ portalContainerRef={portalContainerRef}
+ onChange={vi.fn()}
+ />
+ </div>
+ )
+ }
+
+ render(<Harness />)
+}
+
+describe('AgentRosterField', () => {
+ it('returns focus to the inline setup trigger when the dialog closes with Escape', async () => {
+ const user = userEvent.setup()
+ renderInlineRosterField()
+
+ const trigger = screen.getByRole('button', { name: /^workflow\.nodes\.agent\.roster\.openPanel/ })
+
+ await user.click(trigger)
+ expect(screen.getByRole('dialog', { name: 'Inline Workspace' })).toBeInTheDocument()
+
+ await user.keyboard('{Escape}')
+
+ await waitFor(() => {
+ expect(screen.queryByRole('dialog', { name: 'Inline Workspace' })).not.toBeInTheDocument()
+ })
+ expect(trigger).toHaveFocus()
+ })
+})
diff --git a/web/app/components/workflow/nodes/agent-v2/components/__tests__/save-inline-agent-to-roster-dialog.spec.tsx b/web/app/components/workflow/nodes/agent-v2/components/__tests__/save-inline-agent-to-roster-dialog.spec.tsx
new file mode 100644
index 00000000000..0d48cd93064
--- /dev/null
+++ b/web/app/components/workflow/nodes/agent-v2/components/__tests__/save-inline-agent-to-roster-dialog.spec.tsx
@@ -0,0 +1,213 @@
+import type { AgentComposerAgentResponse } from '@dify/contracts/api/console/apps/types.gen'
+import { render, screen, within } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { SaveInlineAgentToRosterDialog } from '../save-inline-agent-to-roster-dialog'
+
+const mutationMock = vi.hoisted(() => ({
+ isPending: false,
+ mutate: vi.fn(),
+}))
+
+const toastMock = vi.hoisted(() => ({
+ success: vi.fn(),
+}))
+
+vi.mock('@tanstack/react-query', () => ({
+ useMutation: () => ({
+ isPending: mutationMock.isPending,
+ mutate: mutationMock.mutate,
+ }),
+}))
+
+vi.mock('@langgenius/dify-ui/toast', () => ({
+ toast: toastMock,
+}))
+
+vi.mock('@/app/components/base/app-icon-picker', () => ({
+ __esModule: true,
+ default: ({
+ initialEmoji,
+ onSelect,
+ open,
+ }: {
+ initialEmoji?: { icon: string, background: string }
+ onSelect: (payload: { type: 'emoji', icon: string, background: string }) => void
+ open: boolean
+ }) => open
+ ? (
+ <div>
+ <span>{`${initialEmoji?.icon}:${initialEmoji?.background}`}</span>
+ <button
+ type="button"
+ onClick={() => onSelect({ type: 'emoji', icon: '🧠', background: '#E0F2FE' })}
+ >
+ Select brain icon
+ </button>
+ </div>
+ )
+ : null,
+}))
+
+vi.mock('@/service/client', () => ({
+ consoleQuery: {
+ apps: {
+ byAppId: {
+ workflows: {
+ draft: {
+ nodes: {
+ byNodeId: {
+ agentComposer: {
+ saveToRoster: {
+ post: {
+ mutationOptions: vi.fn(() => ({})),
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+}))
+
+const inlineAgent: AgentComposerAgentResponse = {
+ active_config_snapshot_id: 'snapshot-1',
+ description: 'Drafts tender clarifications.',
+ icon: '🤖',
+ icon_background: '#F5F3FF',
+ icon_type: 'emoji',
+ id: 'inline-agent-1',
+ name: 'Inline Tender Agent',
+ role: 'Tender Analyst',
+ scope: 'workflow_only',
+ status: 'active',
+}
+
+const renderDialog = (agent: AgentComposerAgentResponse = inlineAgent) => {
+ const onOpenChange = vi.fn()
+ const onSaved = vi.fn()
+
+ render(
+ <SaveInlineAgentToRosterDialog
+ appId="app-1"
+ formKey={1}
+ initialAgent={agent}
+ nodeId="node-1"
+ open
+ onOpenChange={onOpenChange}
+ onSaved={onSaved}
+ />,
+ )
+
+ return { onOpenChange, onSaved }
+}
+
+describe('SaveInlineAgentToRosterDialog', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mutationMock.isPending = false
+ })
+
+ it('initializes the roster name empty while keeping the other inline agent metadata', async () => {
+ const user = userEvent.setup()
+ renderDialog()
+
+ const dialog = screen.getByRole('dialog', { name: 'agentV2.roster.saveToRosterDialog.title' })
+ const nameInput = within(dialog).getByRole('textbox', { name: 'agentV2.roster.createForm.nameLabel' })
+ expect(nameInput).toHaveValue('')
+ expect(within(dialog).getByRole('textbox', { name: 'agentV2.roster.createForm.roleLabel' })).toHaveValue('Tender Analyst')
+ expect(within(dialog).getByPlaceholderText('agentV2.roster.createForm.descriptionPlaceholder')).toHaveValue('Drafts tender clarifications.')
+
+ await user.type(nameInput, 'Roster Tender Agent')
+ await user.click(within(dialog).getByRole('button', { name: 'common.operation.save' }))
+
+ expect(mutationMock.mutate).toHaveBeenCalledWith({
+ params: {
+ app_id: 'app-1',
+ node_id: 'node-1',
+ },
+ body: {
+ variant: 'workflow',
+ save_strategy: 'save_to_roster',
+ new_agent_name: 'Roster Tender Agent',
+ description: 'Drafts tender clarifications.',
+ role: 'Tender Analyst',
+ icon_type: 'emoji',
+ icon: '🤖',
+ icon_background: '#F5F3FF',
+ },
+ }, expect.objectContaining({
+ onSuccess: expect.any(Function),
+ }))
+ const mutationOptions = mutationMock.mutate.mock.calls[0]?.[1]
+ expect(mutationOptions).not.toHaveProperty('onError')
+ })
+
+ it('submits the visible default icon when the inline agent has no icon metadata', async () => {
+ const user = userEvent.setup()
+ renderDialog({
+ ...inlineAgent,
+ icon: null,
+ icon_background: null,
+ icon_type: null,
+ })
+
+ const dialog = screen.getByRole('dialog', { name: 'agentV2.roster.saveToRosterDialog.title' })
+ await user.type(within(dialog).getByRole('textbox', { name: 'agentV2.roster.createForm.nameLabel' }), 'Roster Tender Agent')
+ await user.click(within(dialog).getByRole('button', { name: 'common.operation.save' }))
+
+ expect(mutationMock.mutate).toHaveBeenCalledWith({
+ params: {
+ app_id: 'app-1',
+ node_id: 'node-1',
+ },
+ body: {
+ variant: 'workflow',
+ save_strategy: 'save_to_roster',
+ new_agent_name: 'Roster Tender Agent',
+ description: 'Drafts tender clarifications.',
+ role: 'Tender Analyst',
+ icon_type: 'emoji',
+ icon: '🧸',
+ icon_background: '#F5F3FF',
+ },
+ }, expect.objectContaining({
+ onSuccess: expect.any(Function),
+ }))
+ })
+
+ it('initializes the icon picker from the inline agent and submits changed icon fields', async () => {
+ const user = userEvent.setup()
+ renderDialog()
+
+ const dialog = screen.getByRole('dialog', { name: 'agentV2.roster.saveToRosterDialog.title' })
+ await user.click(within(dialog).getByRole('button', { name: 'agentV2.roster.saveToRosterForm.changeIcon' }))
+
+ expect(screen.getByText('🤖:#F5F3FF')).toBeInTheDocument()
+
+ await user.click(screen.getByRole('button', { hidden: true, name: 'Select brain icon' }))
+ await user.type(within(dialog).getByRole('textbox', { name: 'agentV2.roster.createForm.nameLabel' }), 'Roster Tender Agent')
+ await user.click(within(dialog).getByRole('button', { name: 'common.operation.save' }))
+
+ expect(mutationMock.mutate).toHaveBeenCalledWith({
+ params: {
+ app_id: 'app-1',
+ node_id: 'node-1',
+ },
+ body: {
+ variant: 'workflow',
+ save_strategy: 'save_to_roster',
+ new_agent_name: 'Roster Tender Agent',
+ description: 'Drafts tender clarifications.',
+ role: 'Tender Analyst',
+ icon_type: 'emoji',
+ icon: '🧠',
+ icon_background: '#E0F2FE',
+ },
+ }, expect.objectContaining({
+ onSuccess: expect.any(Function),
+ }))
+ })
+})
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.tsx
deleted file mode 100644
index 0b174d02280..00000000000
--- a/web/app/components/workflow/nodes/agent-v2/components/agent-orchestrate-drawer-panel.tsx
+++ /dev/null
@@ -1,123 +0,0 @@
-'use client'
-
-import type { AgentConfigSnapshotSummaryResponse, AgentSoulConfig } from '@dify/contracts/api/console/agent/types.gen'
-import type { WorkflowAgentComposerResponse } from '@dify/contracts/api/console/apps/types.gen'
-import { skipToken, useQuery } from '@tanstack/react-query'
-import { useAtom } from 'jotai'
-import Loading from '@/app/components/base/loading'
-import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
-import { useDefaultModel, useTextGenerationCurrentProviderAndModelAndModelList } from '@/app/components/header/account-setting/model-provider-page/hooks'
-import { AgentComposerProvider } from '@/features/agent-v2/agent-composer/provider'
-import { useHydrateAgentSoulConfigDraft } from '@/features/agent-v2/agent-composer/store'
-import { agentComposerModelAtom } from '@/features/agent-v2/agent-composer/store-modules/model'
-import { AgentOrchestratePanel } from '@/features/agent-v2/agent-detail/configure/components/orchestrate'
-import { consoleQuery } from '@/service/client'
-import { useWorkflowInlineAgentConfigureSync } from '../agent-soul-config'
-
-type AgentOrchestrateDrawerPanelProps = {
- agentId: string
- appId?: string
- inlineComposerState?: WorkflowAgentComposerResponse
- isInline: boolean
- nodeId: string
- open: boolean
-}
-
-export function AgentOrchestrateDrawerPanel(props: AgentOrchestrateDrawerPanelProps) {
- return (
- <AgentComposerProvider>
- <AgentOrchestrateDrawerPanelContent {...props} />
- </AgentComposerProvider>
- )
-}
-
-function AgentOrchestrateDrawerPanelContent({
- agentId,
- appId,
- inlineComposerState,
- isInline,
- nodeId,
- open,
-}: AgentOrchestrateDrawerPanelProps) {
- const rosterComposerQuery = useQuery(consoleQuery.agent.byAgentId.composer.get.queryOptions({
- input: open && !isInline
- ? {
- params: {
- agent_id: agentId,
- },
- }
- : skipToken,
- }))
- const composerState = isInline ? inlineComposerState : rosterComposerQuery.data
- const agentSoulConfig = composerState?.agent_soul
- const activeConfigSnapshot = ('active_config_snapshot' in (composerState ?? {}))
- ? composerState?.active_config_snapshot as AgentConfigSnapshotSummaryResponse | null | undefined
- : undefined
- const { currentModel, setConfigureModel, textGenerationModelList } = useAgentOrchestrateModelOptions()
- const { draftSavedAt, saveDraft } = useWorkflowInlineAgentConfigureSync({
- nodeId,
- baseConfig: agentSoulConfig,
- currentModel,
- enabled: open && isInline && !!agentSoulConfig,
- })
-
- useHydrateAgentSoulConfigDraft({
- agentId: isInline ? `${nodeId}:${agentId}` : agentId,
- activeVersionId: activeConfigSnapshot?.id,
- config: agentSoulConfig as AgentSoulConfig | undefined,
- })
-
- if (!agentSoulConfig) {
- return (
- <div className="flex h-full min-h-80 items-center justify-center bg-components-panel-bg">
- <Loading type="app" />
- </div>
- )
- }
-
- return (
- <AgentOrchestratePanel
- agentId={agentId}
- appId={isInline ? appId : undefined}
- nodeId={isInline ? nodeId : undefined}
- activeConfigSnapshot={activeConfigSnapshot}
- agentSoulConfig={agentSoulConfig as AgentSoulConfig}
- agentName={composerState?.agent?.name}
- currentModel={currentModel}
- textGenerationModelList={textGenerationModelList}
- draftSavedAt={draftSavedAt}
- readOnly={!isInline}
- showHeader={false}
- showPublishBar={false}
- className="h-full max-w-none min-w-0 flex-none rounded-none border-0"
- onSelectModel={setConfigureModel}
- onPublish={() => {
- void saveDraft()
- }}
- onOpenVersions={() => undefined}
- />
- )
-}
-
-function useAgentOrchestrateModelOptions() {
- const [model, setModel] = useAtom(agentComposerModelAtom)
- const {
- data: defaultTextGenerationModel,
- } = useDefaultModel(ModelTypeEnum.textGeneration)
- const defaultModel = defaultTextGenerationModel
- ? {
- provider: defaultTextGenerationModel.provider.provider,
- model: defaultTextGenerationModel.model,
- }
- : undefined
- const currentModel = model ?? defaultModel
- const {
- textGenerationModelList,
- } = useTextGenerationCurrentProviderAndModelAndModelList(currentModel)
-
- return {
- currentModel,
- setConfigureModel: setModel,
- textGenerationModelList,
- }
-}
diff --git a/web/app/components/workflow/nodes/agent-v2/components/agent-orchestrate-panel-content.tsx b/web/app/components/workflow/nodes/agent-v2/components/agent-orchestrate-panel-content.tsx
new file mode 100644
index 00000000000..43d1821b502
--- /dev/null
+++ b/web/app/components/workflow/nodes/agent-v2/components/agent-orchestrate-panel-content.tsx
@@ -0,0 +1,346 @@
+'use client'
+
+import type { AgentConfigSnapshotSummaryResponse, AgentSoulConfig } from '@dify/contracts/api/console/agent/types.gen'
+import type { AgentComposerBindingResponse, WorkflowAgentComposerResponse } from '@dify/contracts/api/console/apps/types.gen'
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from '@langgenius/dify-ui/dropdown-menu'
+import { skipToken, useQuery } from '@tanstack/react-query'
+import { useAtom } from 'jotai'
+import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import Loading from '@/app/components/base/loading'
+import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
+import { useDefaultModel, useTextGenerationCurrentProviderAndModelAndModelList } from '@/app/components/header/account-setting/model-provider-page/hooks'
+import { agentSoulConfigToFormState } from '@/features/agent-v2/agent-composer/conversions'
+import { AgentComposerProvider } from '@/features/agent-v2/agent-composer/provider'
+import { agentComposerModelAtom } from '@/features/agent-v2/agent-composer/store-modules/model'
+import { AgentOrchestratePanel } from '@/features/agent-v2/agent-detail/configure/components/orchestrate'
+import { AgentBuildPanelBackground } from '@/features/agent-v2/agent-detail/configure/components/preview/build-background'
+import { AgentBuildChat } from '@/features/agent-v2/agent-detail/configure/components/preview/build-chat'
+import { AgentPreviewHeader } from '@/features/agent-v2/agent-detail/configure/components/preview/header'
+import { useAgentWorkingDirectoryPanel } from '@/features/agent-v2/agent-detail/configure/components/preview/use-working-directory-panel'
+import { AgentConfigurePreviewSurface, AgentConfigureWorkspace } from '@/features/agent-v2/agent-detail/configure/components/workspace'
+import { useAgentPreviewSoulConfig } from '@/features/agent-v2/agent-detail/configure/hooks'
+import { usePrepareAgentBuildDraftBeforeRun } from '@/features/agent-v2/agent-detail/configure/use-agent-build-draft-run'
+import { consoleQuery } from '@/service/client'
+import { useWorkflowInlineAgentConfigureSync } from '../agent-soul-config'
+
+type WorkflowRosterAgentOrchestratePanelContentProps = {
+ agentId?: string
+ nodeId: string
+ open: boolean
+}
+
+type WorkflowInlineAgentConfigureWorkspaceProps = {
+ agentId?: string
+ appId?: string
+ inlineComposerState?: WorkflowAgentComposerResponse
+ nodeId: string
+ onClose?: () => void
+ onSaved?: (binding: AgentComposerBindingResponse) => void
+ onSaveInlineToRoster?: () => void
+ open: boolean
+}
+
+export function WorkflowRosterAgentOrchestratePanelContent(props: WorkflowRosterAgentOrchestratePanelContentProps) {
+ const {
+ agentId,
+ nodeId,
+ open,
+ } = props
+ const rosterComposerQuery = useQuery(consoleQuery.agent.byAgentId.composer.get.queryOptions({
+ input: open && agentId
+ ? {
+ params: {
+ agent_id: agentId,
+ },
+ }
+ : skipToken,
+ }))
+ const composerState = rosterComposerQuery.data
+ const agentSoulConfig = composerState?.agent_soul
+ const activeConfigSnapshot = ('active_config_snapshot' in (composerState ?? {}))
+ ? composerState?.active_config_snapshot as AgentConfigSnapshotSummaryResponse | null | undefined
+ : undefined
+
+ if (!agentId || !agentSoulConfig) {
+ return (
+ <div className="flex h-full min-h-80 items-center justify-center bg-components-panel-bg">
+ <Loading type="app" />
+ </div>
+ )
+ }
+
+ const initialAgentSoulConfig = agentSoulConfig as AgentSoulConfig
+ const composerSessionKey = `${agentId ?? nodeId}:${activeConfigSnapshot?.id ?? 'draft'}`
+
+ return (
+ <AgentComposerProvider
+ key={composerSessionKey}
+ initialDraft={agentSoulConfigToFormState(initialAgentSoulConfig)}
+ initialOriginalConfig={initialAgentSoulConfig}
+ >
+ <WorkflowRosterAgentOrchestratePanelContentInner
+ activeConfigSnapshot={activeConfigSnapshot}
+ agentId={agentId}
+ agentSoulConfig={initialAgentSoulConfig}
+ composerState={composerState}
+ />
+ </AgentComposerProvider>
+ )
+}
+
+function WorkflowRosterAgentOrchestratePanelContentInner({
+ activeConfigSnapshot,
+ agentId,
+ agentSoulConfig,
+ composerState,
+}: {
+ activeConfigSnapshot?: AgentConfigSnapshotSummaryResponse | null
+ agentId: string
+ agentSoulConfig: AgentSoulConfig
+ composerState?: {
+ agent?: {
+ name?: string | null
+ } | null
+ }
+}) {
+ const { currentModel, setConfigureModel, textGenerationModelList } = useAgentOrchestrateModelOptions()
+
+ return (
+ <AgentOrchestratePanel
+ agentId={agentId}
+ activeConfigSnapshot={activeConfigSnapshot}
+ agentSoulConfig={agentSoulConfig}
+ agentName={composerState?.agent?.name}
+ currentModel={currentModel}
+ textGenerationModelList={textGenerationModelList}
+ readOnly
+ showHeader={false}
+ showPublishBar={false}
+ className="h-full max-w-none min-w-0 flex-none rounded-none border-0"
+ onSelectModel={setConfigureModel}
+ onPublish={() => undefined}
+ onOpenVersions={() => undefined}
+ />
+ )
+}
+
+export function WorkflowInlineAgentConfigureWorkspace(props: WorkflowInlineAgentConfigureWorkspaceProps) {
+ const {
+ agentId,
+ inlineComposerState,
+ nodeId,
+ } = props
+ const composerState = inlineComposerState
+ const agentSoulConfig = composerState?.agent_soul as AgentSoulConfig | undefined
+ const activeConfigSnapshot = ('active_config_snapshot' in (composerState ?? {}))
+ ? composerState?.active_config_snapshot as AgentConfigSnapshotSummaryResponse | null | undefined
+ : undefined
+
+ if (!agentId || !agentSoulConfig) {
+ return (
+ <div className="flex h-full min-h-80 items-center justify-center bg-components-panel-bg">
+ <Loading type="app" />
+ </div>
+ )
+ }
+
+ const composerSessionKey = `${nodeId}:${agentId}:${activeConfigSnapshot?.id ?? 'draft'}`
+
+ return (
+ <AgentComposerProvider
+ key={composerSessionKey}
+ initialDraft={agentSoulConfigToFormState(agentSoulConfig)}
+ initialOriginalConfig={agentSoulConfig}
+ >
+ <WorkflowInlineAgentConfigureWorkspaceContent
+ {...props}
+ activeConfigSnapshot={activeConfigSnapshot}
+ agentId={agentId}
+ agentSoulConfig={agentSoulConfig}
+ />
+ </AgentComposerProvider>
+ )
+}
+
+function WorkflowInlineAgentConfigureWorkspaceContent({
+ activeConfigSnapshot,
+ agentId,
+ agentSoulConfig,
+ appId,
+ inlineComposerState,
+ nodeId,
+ onClose,
+ onSaved,
+ onSaveInlineToRoster,
+ open,
+}: Omit<WorkflowInlineAgentConfigureWorkspaceProps, 'agentId'> & {
+ activeConfigSnapshot?: AgentConfigSnapshotSummaryResponse | null
+ agentId: string
+ agentSoulConfig: AgentSoulConfig
+}) {
+ const { t } = useTranslation()
+ const [clearChatList, setClearChatList] = useState(false)
+ const [conversationId, setConversationId] = useState<string | null>(null)
+ const workingDirectoryPanel = useAgentWorkingDirectoryPanel()
+ const composerState = inlineComposerState
+ const { currentModel, setConfigureModel, textGenerationModelList } = useAgentOrchestrateModelOptions()
+ const { draftSavedAt, saveDraft } = useWorkflowInlineAgentConfigureSync({
+ nodeId,
+ baseConfig: agentSoulConfig,
+ currentModel,
+ onDraftSaved: (composerState) => {
+ const binding = composerState.binding
+ if (
+ binding?.binding_type !== 'inline_agent'
+ || !binding.agent_id
+ || !binding.current_snapshot_id
+ ) {
+ return
+ }
+
+ onSaved?.(binding)
+ },
+ enabled: open && !!agentSoulConfig,
+ })
+ const buildDraftRun = usePrepareAgentBuildDraftBeforeRun({
+ agentId,
+ isBuildDraftActive: false,
+ saveDraft,
+ })
+ const previewAgentSoulConfig = useAgentPreviewSoulConfig(agentSoulConfig as AgentSoulConfig | undefined)
+
+ return (
+ <AgentConfigureWorkspace
+ className="rounded-[inherit]"
+ leftPanel={(
+ <AgentOrchestratePanel
+ agentId={agentId}
+ appId={appId}
+ nodeId={nodeId}
+ activeConfigSnapshot={activeConfigSnapshot}
+ agentSoulConfig={agentSoulConfig}
+ agentName={composerState?.agent?.name}
+ currentModel={currentModel}
+ textGenerationModelList={textGenerationModelList}
+ draftSavedAt={draftSavedAt}
+ showPublishBar={false}
+ headerAction={onSaveInlineToRoster
+ ? <WorkflowInlineAgentConfigureMoreAction onSaveInlineToRoster={onSaveInlineToRoster} />
+ : undefined}
+ className="min-w-90"
+ onSelectModel={setConfigureModel}
+ onPublish={() => {
+ void saveDraft()
+ }}
+ onOpenVersions={() => undefined}
+ />
+ )}
+ rightPanel={(
+ <AgentConfigurePreviewSurface
+ background={<AgentBuildPanelBackground visible />}
+ header={(
+ <AgentPreviewHeader
+ mode="build"
+ previewEnabled={false}
+ isChatFeaturesOpen={false}
+ onModeChange={() => undefined}
+ onToggleChatFeatures={() => undefined}
+ onOpenWorkingDirectory={workingDirectoryPanel.openWorkingDirectory}
+ onRefresh={() => {
+ setConversationId(null)
+ setClearChatList(true)
+ }}
+ showChatFeaturesAction={false}
+ trailingAction={(
+ <button
+ type="button"
+ onClick={onClose}
+ className="flex size-8 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"
+ aria-label={t('operation.close', { ns: 'common' })}
+ >
+ <span aria-hidden className="i-ri-close-line size-4" />
+ </button>
+ )}
+ />
+ )}
+ chat={(
+ <AgentBuildChat
+ agentId={agentId}
+ agentIcon={composerState?.agent?.icon}
+ agentIconBackground={composerState?.agent?.icon_background}
+ agentIconType={composerState?.agent?.icon_type as Parameters<typeof AgentBuildChat>[0]['agentIconType']}
+ agentName={composerState?.agent?.name}
+ agentSoulConfig={previewAgentSoulConfig}
+ clearChatList={clearChatList}
+ conversationId={conversationId}
+ draftType="debug_build"
+ onClearChatListChange={setClearChatList}
+ onConversationIdChange={setConversationId}
+ onSaveDraftBeforeRun={buildDraftRun.prepareBuildDraftBeforeRun}
+ />
+ )}
+ />
+ )}
+ sidePanels={workingDirectoryPanel.panel}
+ />
+ )
+}
+
+function WorkflowInlineAgentConfigureMoreAction({
+ onSaveInlineToRoster,
+}: {
+ onSaveInlineToRoster: () => void
+}) {
+ const { t } = useTranslation('common')
+
+ return (
+ <DropdownMenu modal={false}>
+ <DropdownMenuTrigger
+ render={(
+ <button
+ type="button"
+ className="flex size-6 items-center justify-center rounded-md text-text-tertiary hover:bg-state-base-hover hover:text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"
+ aria-label={t('operation.more')}
+ >
+ <span aria-hidden className="i-ri-more-fill size-4" />
+ </button>
+ )}
+ />
+ <DropdownMenuContent placement="bottom-end" sideOffset={4} popupClassName="min-w-44 w-max">
+ <DropdownMenuItem className="gap-2 whitespace-nowrap" onClick={onSaveInlineToRoster}>
+ <span aria-hidden className="i-ri-inbox-archive-line size-4 shrink-0 text-text-tertiary" />
+ <span>{t('roster.saveToRoster', { ns: 'agentV2' })}</span>
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )
+}
+
+function useAgentOrchestrateModelOptions() {
+ const [model, setModel] = useAtom(agentComposerModelAtom)
+ const {
+ data: defaultTextGenerationModel,
+ } = useDefaultModel(ModelTypeEnum.textGeneration)
+ const defaultModel = defaultTextGenerationModel
+ ? {
+ provider: defaultTextGenerationModel.provider.provider,
+ model: defaultTextGenerationModel.model,
+ }
+ : undefined
+ const currentModel = model ?? defaultModel
+ const {
+ textGenerationModelList,
+ } = useTextGenerationCurrentProviderAndModelAndModelList(currentModel)
+
+ return {
+ currentModel,
+ setConfigureModel: setModel,
+ textGenerationModelList,
+ }
+}
diff --git a/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/__tests__/index.spec.tsx b/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/__tests__/index.spec.tsx
new file mode 100644
index 00000000000..2772d850f06
--- /dev/null
+++ b/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/__tests__/index.spec.tsx
@@ -0,0 +1,184 @@
+import type { DeclaredOutputConfig } from '@dify/contracts/api/console/apps/types.gen'
+import { render, screen, within } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { describe, expect, it, vi } from 'vitest'
+import { AgentOutputVariables } from '../index'
+
+const editorLabel = 'workflow.nodes.agent.outputVars.editorLabel'
+const nameLabel = 'workflow.nodes.agent.outputVars.nameLabel'
+const confirmLabel = 'workflow.nodes.agent.outputVars.confirm'
+
+async function expandOutputVars(user: ReturnType<typeof userEvent.setup>) {
+ await user.click(screen.getByRole('button', { name: 'workflow.nodes.common.outputVars' }))
+}
+
+function getAddButton(name: string) {
+ return screen.getByRole('button', { name: `common.operation.add ${name}` })
+}
+
+function getEditButton(name: string) {
+ return screen.getByRole('button', {
+ name: `workflow.nodes.agent.outputVars.edit:{"name":"${name}"}`,
+ })
+}
+
+async function confirmEditorName(user: ReturnType<typeof userEvent.setup>, name: string) {
+ const editor = screen.getByRole('form', { name: editorLabel })
+ const nameInput = within(editor).getByLabelText(nameLabel)
+
+ await user.clear(nameInput)
+ await user.type(nameInput, name)
+ await user.click(within(editor).getByRole('button', { name: confirmLabel }))
+}
+
+describe('AgentOutputVariables', () => {
+ it('should add an object child without opening the parent editor', async () => {
+ const user = userEvent.setup()
+ const onChange = vi.fn()
+ const outputs: DeclaredOutputConfig[] = [{
+ name: 'profile',
+ type: 'object',
+ required: true,
+ description: 'User profile',
+ }]
+
+ render(<AgentOutputVariables outputs={outputs} onChange={onChange} />)
+
+ await expandOutputVars(user)
+ await user.click(getAddButton('profile'))
+
+ expect(screen.getAllByRole('form', { name: editorLabel })).toHaveLength(1)
+ expect(screen.getByText('profile')).toBeInTheDocument()
+
+ await confirmEditorName(user, 'email')
+
+ expect(onChange).toHaveBeenCalledWith([{
+ name: 'profile',
+ type: 'object',
+ required: true,
+ description: 'User profile',
+ children: [{
+ name: 'email',
+ type: 'string',
+ required: false,
+ }],
+ }])
+ })
+
+ it('should append children to array object items', async () => {
+ const user = userEvent.setup()
+ const onChange = vi.fn()
+ const outputs: DeclaredOutputConfig[] = [{
+ name: 'addresses',
+ type: 'array',
+ required: false,
+ array_item: {
+ type: 'object',
+ },
+ }]
+
+ render(<AgentOutputVariables outputs={outputs} onChange={onChange} />)
+
+ await expandOutputVars(user)
+ await user.click(getAddButton('addresses'))
+ await confirmEditorName(user, 'city')
+
+ expect(onChange).toHaveBeenCalledWith([{
+ name: 'addresses',
+ type: 'array',
+ required: false,
+ array_item: {
+ type: 'object',
+ children: [{
+ name: 'city',
+ type: 'string',
+ required: false,
+ }],
+ },
+ }])
+ })
+
+ it('should add nested children under the selected object child', async () => {
+ const user = userEvent.setup()
+ const onChange = vi.fn()
+ const outputs: DeclaredOutputConfig[] = [{
+ name: 'profile',
+ type: 'object',
+ required: true,
+ children: [{
+ name: 'contact',
+ type: 'object',
+ required: true,
+ }],
+ }]
+
+ render(<AgentOutputVariables outputs={outputs} onChange={onChange} />)
+
+ await expandOutputVars(user)
+ await user.click(getAddButton('contact'))
+ await confirmEditorName(user, 'email')
+
+ expect(onChange).toHaveBeenCalledWith([{
+ name: 'profile',
+ type: 'object',
+ required: true,
+ children: [{
+ name: 'contact',
+ type: 'object',
+ required: true,
+ children: [{
+ name: 'email',
+ type: 'string',
+ required: false,
+ }],
+ }],
+ }])
+ })
+
+ it('should edit only the selected nested child', async () => {
+ const user = userEvent.setup()
+ const onChange = vi.fn()
+ const outputs: DeclaredOutputConfig[] = [{
+ name: 'profile',
+ type: 'object',
+ required: true,
+ children: [{
+ name: 'contact',
+ type: 'object',
+ required: true,
+ children: [{
+ name: 'email',
+ type: 'string',
+ required: true,
+ description: 'Primary email',
+ }],
+ }],
+ }]
+
+ render(<AgentOutputVariables outputs={outputs} onChange={onChange} />)
+
+ await expandOutputVars(user)
+ await user.click(getEditButton('email'))
+
+ expect(screen.getAllByRole('form', { name: editorLabel })).toHaveLength(1)
+
+ await confirmEditorName(user, 'work_email')
+
+ expect(onChange).toHaveBeenCalledWith([{
+ name: 'profile',
+ type: 'object',
+ required: true,
+ children: [{
+ name: 'contact',
+ type: 'object',
+ required: true,
+ children: [{
+ name: 'work_email',
+ type: 'string',
+ required: true,
+ description: 'Primary email',
+ }],
+ }],
+ }])
+ })
+})
diff --git a/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/__tests__/utils.spec.ts b/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/__tests__/utils.spec.ts
index 4648f90c238..50382fcd8f9 100644
--- a/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/__tests__/utils.spec.ts
+++ b/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/__tests__/utils.spec.ts
@@ -6,6 +6,7 @@ import {
} from '../utils'
const createDraft = (overrides: Partial<OutputDraft> = {}): OutputDraft => ({
+ children: [],
defaultValue: '',
description: '',
name: 'summary',
@@ -54,4 +55,49 @@ describe('agent output variables utils', () => {
type: 'array[file]',
}))).toBe('nodes.agent.outputVars.defaultValueFileUnsupported')
})
+
+ it('should preserve object children when building an output', () => {
+ expect(createOutputFromDraft(createDraft({
+ children: [{
+ name: 'email',
+ type: 'string',
+ required: true,
+ description: 'User email',
+ }],
+ name: 'profile',
+ type: 'object',
+ }))).toMatchObject({
+ name: 'profile',
+ type: 'object',
+ children: [{
+ name: 'email',
+ type: 'string',
+ required: true,
+ description: 'User email',
+ }],
+ })
+ })
+
+ it('should preserve array object item children when building an output', () => {
+ expect(createOutputFromDraft(createDraft({
+ children: [{
+ name: 'city',
+ type: 'string',
+ required: false,
+ }],
+ name: 'addresses',
+ type: 'array[object]',
+ }))).toMatchObject({
+ name: 'addresses',
+ type: 'array',
+ array_item: {
+ type: 'object',
+ children: [{
+ name: 'city',
+ type: 'string',
+ required: false,
+ }],
+ },
+ })
+ })
})
diff --git a/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/edit-card.tsx b/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/edit-card.tsx
index 3e66f868ad9..4db6f83d4df 100644
--- a/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/edit-card.tsx
+++ b/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/edit-card.tsx
@@ -1,5 +1,5 @@
import type { DeclaredOutputConfig } from '@dify/contracts/api/console/apps/types.gen'
-import type { EditingState, OutputDraft } from './utils'
+import type { EditableOutputConfig, EditingState, OutputDraft } from './utils'
import { Button } from '@langgenius/dify-ui/button'
import { CollapsiblePanel, CollapsibleRoot, CollapsibleTrigger } from '@langgenius/dify-ui/collapsible'
import { FieldControl, FieldError, FieldLabel, FieldRoot } from '@langgenius/dify-ui/field'
@@ -38,21 +38,25 @@ function ConfirmHotkeyHint() {
export function OutputEditCard({
existingOutputs,
+ editingIndex,
+ allowDefaultValue = true,
state,
onCancel,
onConfirm,
}: {
- existingOutputs: DeclaredOutputConfig[]
+ existingOutputs: EditableOutputConfig[]
+ editingIndex?: number
+ allowDefaultValue?: boolean
state: EditingState
onCancel: () => void
- onConfirm: (output: DeclaredOutputConfig, index?: number) => void
+ onConfirm: (output: DeclaredOutputConfig, state: EditingState) => void
}) {
const { t } = useTranslation()
const nameErrorId = useId()
const editorRef = useRef<HTMLDivElement>(null)
const [draft, setDraft] = useState(state.draft)
const trimmedName = draft.name.trim()
- const duplicateName = existingOutputs.some((output, index) => output.name === trimmedName && index !== state.index)
+ const duplicateName = existingOutputs.some((output, index) => output.name === trimmedName && index !== editingIndex)
const nameInvalid = !!trimmedName && !OUTPUT_NAME_PATTERN.test(trimmedName)
const hasNameError = duplicateName || nameInvalid
const defaultValueErrorKey = getDefaultValueErrorKey(draft)
@@ -63,7 +67,7 @@ export function OutputEditCard({
function handleConfirm() {
if (confirmDisabled)
return
- onConfirm(createOutputFromDraft(draft), state.index)
+ onConfirm(createOutputFromDraft(draft, { includeDefaultValue: allowDefaultValue }), state)
}
useHotkey(CONFIRM_HOTKEY, handleConfirm, { target: editorRef, ignoreInputs: false })
useHotkey('Escape', onCancel, { target: editorRef, ignoreInputs: false })
@@ -134,36 +138,38 @@ export function OutputEditCard({
/>
</FieldRoot>
</div>
- <CollapsibleRoot>
- <CollapsibleTrigger className="h-8 min-h-8 justify-start gap-x-0.5 rounded-none border-y border-divider-subtle pr-2 pl-2.5 system-xs-regular text-text-tertiary hover:not-data-disabled:bg-state-base-hover hover:not-data-disabled:text-text-tertiary focus-visible:bg-state-base-hover focus-visible:ring-inset data-panel-open:text-text-tertiary">
- <span
- aria-hidden="true"
- className="i-ri-arrow-down-double-line size-3 transition-transform duration-100 ease-out group-data-panel-open:rotate-180 motion-reduce:transition-none"
- />
- {t('nodes.agent.outputVars.showAdvancedOptions', { ns: 'workflow' })}
- </CollapsibleTrigger>
- <CollapsiblePanel className="border-t border-divider-subtle">
- <div className="px-3 py-2">
- <FieldRoot name="defaultValue" className="gap-1">
- <FieldLabel className="py-0 system-xs-medium text-text-secondary">
- {t('nodes.agent.outputVars.defaultValueLabel', { ns: 'workflow' })}
- </FieldLabel>
- <Textarea
- size="small"
- value={draft.defaultValue}
- placeholder={t('nodes.agent.outputVars.defaultValuePlaceholder', { ns: 'workflow' })}
- className="mt-1 min-h-6"
- onValueChange={defaultValue => updateDraft({ defaultValue })}
- />
- {defaultValueErrorKey && (
- <FieldError match className="py-0 system-xs-regular text-text-destructive">
- {t(defaultValueErrorKey, { ns: 'workflow' })}
- </FieldError>
- )}
- </FieldRoot>
- </div>
- </CollapsiblePanel>
- </CollapsibleRoot>
+ {allowDefaultValue && (
+ <CollapsibleRoot>
+ <CollapsibleTrigger className="h-8 min-h-8 justify-start gap-x-0.5 rounded-none border-y border-divider-subtle pr-2 pl-2.5 system-xs-regular text-text-tertiary hover:not-data-disabled:bg-state-base-hover hover:not-data-disabled:text-text-tertiary focus-visible:bg-state-base-hover focus-visible:ring-inset data-panel-open:text-text-tertiary">
+ <span
+ aria-hidden="true"
+ className="i-ri-arrow-down-double-line size-3 transition-transform duration-100 ease-out group-data-panel-open:rotate-180 motion-reduce:transition-none"
+ />
+ {t('nodes.agent.outputVars.showAdvancedOptions', { ns: 'workflow' })}
+ </CollapsibleTrigger>
+ <CollapsiblePanel className="border-t border-divider-subtle">
+ <div className="px-3 py-2">
+ <FieldRoot name="defaultValue" className="gap-1">
+ <FieldLabel className="py-0 system-xs-medium text-text-secondary">
+ {t('nodes.agent.outputVars.defaultValueLabel', { ns: 'workflow' })}
+ </FieldLabel>
+ <Textarea
+ size="small"
+ value={draft.defaultValue}
+ placeholder={t('nodes.agent.outputVars.defaultValuePlaceholder', { ns: 'workflow' })}
+ className="mt-1 min-h-6"
+ onValueChange={defaultValue => updateDraft({ defaultValue })}
+ />
+ {defaultValueErrorKey && (
+ <FieldError match className="py-0 system-xs-regular text-text-destructive">
+ {t(defaultValueErrorKey, { ns: 'workflow' })}
+ </FieldError>
+ )}
+ </FieldRoot>
+ </div>
+ </CollapsiblePanel>
+ </CollapsibleRoot>
+ )}
<div className="flex h-12 items-center justify-end gap-x-2 px-3">
<Button type="button" size="small" variant="secondary" onClick={onCancel}>
{t('operation.cancel', { ns: 'common' })}
diff --git a/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/index.tsx b/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/index.tsx
index 4303a18c1bc..e339fd3699b 100644
--- a/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/index.tsx
+++ b/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/index.tsx
@@ -1,5 +1,6 @@
import type { DeclaredOutputConfig } from '@dify/contracts/api/console/apps/types.gen'
-import type { AgentOutputVariablesProps, EditingState } from './utils'
+import type { ReactNode } from 'react'
+import type { AgentOutputVariablesProps, DeclaredOutputChildConfig, EditableOutputConfig, EditingState } from './utils'
import { Button } from '@langgenius/dify-ui/button'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
@@ -7,21 +8,30 @@ import Divider from '@/app/components/base/divider'
import OutputVars from '../../../_base/components/output-vars'
import { OutputEditCard } from './edit-card'
import {
+ canOutputHaveChildren,
createDraft,
+ deleteOutputChildAtPath,
+ getOutputChildren,
+ getOutputChildrenAtPath,
getOutputDescription,
getOutputDisplayType,
getOutputTypeOptionValue,
+ insertOutputChildAtPath,
isDefaultOutput,
+ toDeclaredOutputChild,
+ updateOutputChildAtPath,
} from './utils'
function OutputRow({
output,
editable,
+ onAddChild,
onDelete,
onEdit,
}: {
- output: DeclaredOutputConfig
+ output: EditableOutputConfig
editable: boolean
+ onAddChild?: () => void
onDelete: () => void
onEdit: () => void
}) {
@@ -43,6 +53,16 @@ function OutputRow({
</div>
{editable && (
<div className="pointer-events-none flex shrink-0 items-center gap-x-0.5 opacity-0 group-focus-within:pointer-events-auto group-focus-within:opacity-100 group-hover:pointer-events-auto group-hover:opacity-100">
+ {onAddChild && (
+ <button
+ type="button"
+ aria-label={`${t('operation.add', { ns: 'common' })} ${output.name}`}
+ className="flex size-6 items-center justify-center rounded-md text-text-tertiary hover:bg-state-base-hover-alt hover:text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"
+ onClick={onAddChild}
+ >
+ <span aria-hidden="true" className="i-ri-add-circle-line size-4" />
+ </button>
+ )}
<button
type="button"
aria-label={t('nodes.agent.outputVars.edit', { ns: 'workflow', name: output.name })}
@@ -70,6 +90,22 @@ function OutputRow({
</div>
)
}
+
+function ChildOutputFrame({ children, depth }: { children: ReactNode, depth: number }) {
+ return (
+ <div className="flex items-stretch">
+ {Array.from({ length: depth }, (_, index) => (
+ <div key={index} aria-hidden="true" className="flex w-5 shrink-0 justify-center">
+ <div className="w-px bg-divider-subtle" />
+ </div>
+ ))}
+ <div className="min-w-0 flex-1">
+ {children}
+ </div>
+ </div>
+ )
+}
+
export function AgentOutputVariables({
outputs,
onChange,
@@ -80,49 +116,151 @@ export function AgentOutputVariables({
setEditingState({ draft: createDraft() })
}
function handleEditOutput(index: number) {
- setEditingState({ index, draft: createDraft(outputs[index]) })
+ setEditingState({ outputIndex: index, draft: createDraft(outputs[index]) })
+ }
+ function handleNewChild(outputIndex: number, parentPath: number[]) {
+ setEditingState({ outputIndex, parentPath, draft: createDraft() })
+ }
+ function handleEditChild(outputIndex: number, childPath: number[], child: DeclaredOutputChildConfig) {
+ setEditingState({ outputIndex, childPath, draft: createDraft(child) })
}
function handleDeleteOutput(index: number) {
onChange(outputs.filter((_, outputIndex) => outputIndex !== index))
}
- function handleConfirm(output: DeclaredOutputConfig, index?: number) {
- if (typeof index === 'number') {
- onChange(outputs.map((item, outputIndex) => outputIndex === index ? output : item))
+ function handleDeleteChild(outputIndex: number, childPath: number[]) {
+ const parent = outputs[outputIndex]
+ if (!parent)
+ return
+
+ onChange(outputs.map((item, itemIndex) => (
+ itemIndex === outputIndex ? deleteOutputChildAtPath(item, childPath) : item
+ )))
+ }
+ function handleConfirm(output: DeclaredOutputConfig, state: EditingState) {
+ if (typeof state.outputIndex === 'number' && state.parentPath) {
+ const parent = outputs[state.outputIndex]
+ if (!parent)
+ return
+
+ const childOutput = toDeclaredOutputChild(output)
+ onChange(outputs.map((item, outputIndex) => (
+ outputIndex === state.outputIndex ? insertOutputChildAtPath(item, state.parentPath!, childOutput) : item
+ )))
+ }
+ else if (typeof state.outputIndex === 'number' && state.childPath) {
+ const childOutput = toDeclaredOutputChild(output)
+ onChange(outputs.map((item, outputIndex) => (
+ outputIndex === state.outputIndex ? updateOutputChildAtPath(item, state.childPath!, childOutput) : item
+ )))
+ }
+ else if (typeof state.outputIndex === 'number') {
+ onChange(outputs.map((item, outputIndex) => outputIndex === state.outputIndex ? output : item))
}
else {
onChange([...outputs, output])
}
setEditingState(null)
}
- return (
- <OutputVars>
- <div className="pb-2">
- <div className="flex flex-col">
- {outputs.map((output, index) => (
- editingState?.index === index
- ? (
+ function renderChildren(output: DeclaredOutputConfig, outputIndex: number, depth: number, children: DeclaredOutputChildConfig[], editable: boolean, parentPath: number[] = []) {
+ return (
+ <>
+ {children.map((child, childIndex) => {
+ const childPath = [...parentPath, childIndex]
+ const nestedChildren = getOutputChildren(child)
+ const isEditingChild = editingState?.outputIndex === outputIndex && pathsEqual(editingState.childPath, childPath)
+ return (
+ <div key={`${childPath.join('.')}-${child.name}-${getOutputTypeOptionValue(child)}`} className="flex flex-col">
+ {isEditingChild
+ ? (
+ <ChildOutputFrame depth={depth}>
+ <OutputEditCard
+ allowDefaultValue={false}
+ editingIndex={childIndex}
+ existingOutputs={getOutputChildrenAtPath(output, parentPath)}
+ state={editingState}
+ onCancel={() => setEditingState(null)}
+ onConfirm={handleConfirm}
+ />
+ </ChildOutputFrame>
+ )
+ : (
+ <ChildOutputFrame depth={depth}>
+ <OutputRow
+ output={child}
+ editable={editable}
+ onAddChild={editable && canOutputHaveChildren(child) ? () => handleNewChild(outputIndex, childPath) : undefined}
+ onDelete={() => handleDeleteChild(outputIndex, childPath)}
+ onEdit={() => handleEditChild(outputIndex, childPath, child)}
+ />
+ </ChildOutputFrame>
+ )}
+ {renderChildren(output, outputIndex, depth + 1, nestedChildren, editable, childPath)}
+ {editingState?.outputIndex === outputIndex && pathsEqual(editingState.parentPath, childPath) && (
+ <ChildOutputFrame depth={depth + 1}>
<OutputEditCard
- key={`${output.name}-editing`}
- existingOutputs={outputs}
+ allowDefaultValue={false}
+ existingOutputs={nestedChildren}
state={editingState}
onCancel={() => setEditingState(null)}
onConfirm={handleConfirm}
/>
- )
- : (
- <OutputRow
- key={`${output.name}-${getOutputTypeOptionValue(output)}`}
- output={output}
- editable={!isDefaultOutput(output)}
- onDelete={() => handleDeleteOutput(index)}
- onEdit={() => handleEditOutput(index)}
- />
- )
- ))}
+ </ChildOutputFrame>
+ )}
+ </div>
+ )
+ })}
+ </>
+ )
+ }
+ return (
+ <OutputVars>
+ <div className="pb-2">
+ <div className="flex flex-col">
+ {outputs.map((output, index) => {
+ const editable = !isDefaultOutput(output)
+ const children = getOutputChildren(output)
+ const isEditingOutput = editingState?.outputIndex === index && !editingState.childPath && !editingState.parentPath
+ return (
+ <div key={`${output.name}-${getOutputTypeOptionValue(output)}`} className="flex flex-col">
+ {isEditingOutput
+ ? (
+ <OutputEditCard
+ key={`${output.name}-editing`}
+ editingIndex={index}
+ existingOutputs={outputs}
+ state={editingState}
+ onCancel={() => setEditingState(null)}
+ onConfirm={handleConfirm}
+ />
+ )
+ : (
+ <OutputRow
+ output={output}
+ editable={editable}
+ onAddChild={editable && canOutputHaveChildren(output) ? () => handleNewChild(index, []) : undefined}
+ onDelete={() => handleDeleteOutput(index)}
+ onEdit={() => handleEditOutput(index)}
+ />
+ )}
+ {renderChildren(output, index, 1, children, editable)}
+ {editingState?.outputIndex === index && editingState.parentPath && !editingState.parentPath.length && (
+ <ChildOutputFrame depth={1}>
+ <OutputEditCard
+ allowDefaultValue={false}
+ existingOutputs={children}
+ state={editingState}
+ onCancel={() => setEditingState(null)}
+ onConfirm={handleConfirm}
+ />
+ </ChildOutputFrame>
+ )}
+ </div>
+ )
+ })}
<div className="py-1">
<Divider type="horizontal" className="h-px bg-divider-subtle" />
</div>
- {editingState && editingState.index == null
+ {editingState && editingState.outputIndex == null
? (
<OutputEditCard
existingOutputs={outputs}
@@ -149,3 +287,10 @@ export function AgentOutputVariables({
</OutputVars>
)
}
+
+function pathsEqual(left?: number[], right?: number[]) {
+ if (!left || !right || left.length !== right.length)
+ return false
+
+ return left.every((item, index) => item === right[index])
+}
diff --git a/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/utils.ts b/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/utils.ts
index 39e35c64a72..4d21da3e7c3 100644
--- a/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/utils.ts
+++ b/web/app/components/workflow/nodes/agent-v2/components/agent-output-variables/utils.ts
@@ -2,6 +2,10 @@ import type { DeclaredOutputConfig, DeclaredOutputType } from '@dify/contracts/a
import type { TFunction } from 'i18next'
import { defaultAgentV2DeclaredOutputs } from '../../output-variables'
+export type DeclaredOutputChildConfig = NonNullable<DeclaredOutputConfig['children']>[number]
+
+export type EditableOutputConfig = DeclaredOutputConfig | DeclaredOutputChildConfig
+
export type OutputTypeOptionValue
= DeclaredOutputType
| 'array[boolean]'
@@ -23,11 +27,14 @@ export type OutputDraft = {
name: string
required: boolean
type: OutputTypeOptionValue
+ children: DeclaredOutputChildConfig[]
}
export type EditingState = {
draft: OutputDraft
- index?: number
+ outputIndex?: number
+ childPath?: number[]
+ parentPath?: number[]
}
export type AgentOutputVariablesProps = {
@@ -51,7 +58,7 @@ export const OUTPUT_TYPE_OPTIONS: OutputTypeOption[] = [
{ value: 'array[file]', label: 'array[file]', type: 'array', arrayItemType: 'file' },
]
-export function getOutputTypeOptionValue(output: DeclaredOutputConfig): OutputTypeOptionValue {
+export function getOutputTypeOptionValue(output: EditableOutputConfig): OutputTypeOptionValue {
if (output.type !== 'array')
return output.type
@@ -62,7 +69,7 @@ export function getOutputTypeOption(value: OutputTypeOptionValue) {
return OUTPUT_TYPE_OPTIONS.find(option => option.value === value) || OUTPUT_TYPE_OPTIONS[0]!
}
-export function createDraft(output?: DeclaredOutputConfig): OutputDraft {
+export function createDraft(output?: EditableOutputConfig): OutputDraft {
if (!output) {
return {
defaultValue: '',
@@ -70,6 +77,7 @@ export function createDraft(output?: DeclaredOutputConfig): OutputDraft {
name: '',
required: false,
type: 'string',
+ children: [],
}
}
@@ -79,10 +87,14 @@ export function createDraft(output?: DeclaredOutputConfig): OutputDraft {
name: output.name,
required: output.required ?? true,
type: getOutputTypeOptionValue(output),
+ children: getOutputChildren(output),
}
}
-export function createOutputFromDraft(draft: OutputDraft): DeclaredOutputConfig {
+export function createOutputFromDraft(
+ draft: OutputDraft,
+ { includeDefaultValue = true }: { includeDefaultValue?: boolean } = {},
+): DeclaredOutputConfig {
const option = getOutputTypeOption(draft.type)
const output: DeclaredOutputConfig = {
name: draft.name.trim(),
@@ -99,6 +111,16 @@ export function createOutputFromDraft(draft: OutputDraft): DeclaredOutputConfig
}
}
+ if (draft.children.length && draft.type === 'object')
+ output.children = draft.children
+
+ if (draft.children.length && draft.type === 'array[object]') {
+ output.array_item = {
+ type: 'object',
+ children: draft.children,
+ }
+ }
+
if (option.type === 'file') {
output.file = {
extensions: [],
@@ -106,7 +128,7 @@ export function createOutputFromDraft(draft: OutputDraft): DeclaredOutputConfig
}
}
- if (draft.defaultValue.trim()) {
+ if (includeDefaultValue && draft.defaultValue.trim()) {
output.failure_strategy = {
on_failure: 'default_value',
default_value: coerceDefaultValue(draft.defaultValue, option),
@@ -116,6 +138,113 @@ export function createOutputFromDraft(draft: OutputDraft): DeclaredOutputConfig
return output
}
+export function toDeclaredOutputChild(output: DeclaredOutputConfig): DeclaredOutputChildConfig {
+ return {
+ name: output.name,
+ type: output.type,
+ required: output.required,
+ ...(output.description ? { description: output.description } : {}),
+ ...(output.file ? { file: output.file } : {}),
+ ...(output.children ? { children: output.children } : {}),
+ ...(output.array_item ? { array_item: output.array_item } : {}),
+ }
+}
+
+export function getOutputChildren(output: EditableOutputConfig): DeclaredOutputChildConfig[] {
+ if (getOutputTypeOptionValue(output) === 'array[object]')
+ return readOutputChildren(output.array_item?.children)
+
+ if (output.type === 'object')
+ return readOutputChildren(output.children)
+
+ return []
+}
+
+export function canOutputHaveChildren(output: EditableOutputConfig) {
+ const type = getOutputTypeOptionValue(output)
+ return type === 'object' || type === 'array[object]'
+}
+
+function updateOutputChildren(
+ output: DeclaredOutputConfig,
+ children: DeclaredOutputChildConfig[],
+): DeclaredOutputConfig {
+ if (getOutputTypeOptionValue(output) === 'array[object]') {
+ return {
+ ...output,
+ array_item: {
+ type: 'object',
+ ...output.array_item,
+ children: children.length ? children : undefined,
+ },
+ }
+ }
+
+ if (output.type === 'object') {
+ return {
+ ...output,
+ children: children.length ? children : undefined,
+ }
+ }
+
+ return output
+}
+
+export function getOutputChildrenAtPath(
+ output: DeclaredOutputConfig,
+ path: number[],
+): DeclaredOutputChildConfig[] {
+ const target = getOutputChildAtPath(output, path)
+ return target ? getOutputChildren(target) : getOutputChildren(output)
+}
+
+function getOutputChildAtPath(
+ output: DeclaredOutputConfig,
+ path: number[],
+): DeclaredOutputChildConfig | undefined {
+ let current: DeclaredOutputChildConfig | undefined
+ let children = getOutputChildren(output)
+ for (const index of path) {
+ current = children[index]
+ if (!current)
+ return undefined
+ children = getOutputChildren(current)
+ }
+
+ return current
+}
+
+export function insertOutputChildAtPath(
+ output: DeclaredOutputConfig,
+ parentPath: number[],
+ child: DeclaredOutputChildConfig,
+) {
+ return updateOutputChildrenAtPath(output, parentPath, children => [...children, child])
+}
+
+export function updateOutputChildAtPath(
+ output: DeclaredOutputConfig,
+ childPath: number[],
+ child: DeclaredOutputChildConfig,
+) {
+ const childIndex = childPath.at(-1)
+ if (childIndex == null)
+ return output
+
+ return updateOutputChildrenAtPath(output, childPath.slice(0, -1), children => children.map((item, index) => index === childIndex ? child : item))
+}
+
+export function deleteOutputChildAtPath(
+ output: DeclaredOutputConfig,
+ childPath: number[],
+) {
+ const childIndex = childPath.at(-1)
+ if (childIndex == null)
+ return output
+
+ return updateOutputChildrenAtPath(output, childPath.slice(0, -1), children => children.filter((_, index) => index !== childIndex))
+}
+
export function getDefaultValueErrorKey(draft: OutputDraft) {
const trimmed = draft.defaultValue.trim()
if (!trimmed)
@@ -157,7 +286,7 @@ export function isDefaultOutput(output: DeclaredOutputConfig) {
)
}
-export function getOutputDescription(output: DeclaredOutputConfig, t: TFunction) {
+export function getOutputDescription(output: EditableOutputConfig, t: TFunction) {
if (output.name === 'text')
return t('nodes.agent.outputVars.text', { ns: 'workflow' })
if (output.name === 'files')
@@ -167,11 +296,83 @@ export function getOutputDescription(output: DeclaredOutputConfig, t: TFunction)
return output.description || ''
}
-export function getOutputDisplayType(output: DeclaredOutputConfig) {
+export function getOutputDisplayType(output: EditableOutputConfig) {
return getOutputTypeOption(getOutputTypeOptionValue(output)).label
}
-function getOutputDefaultValue(output: DeclaredOutputConfig) {
+function readOutputChildren(children: EditableOutputConfig['children']) {
+ return (children ?? []) as DeclaredOutputChildConfig[]
+}
+
+function updateOutputChildrenAtPath(
+ output: DeclaredOutputConfig,
+ parentPath: number[],
+ updater: (children: DeclaredOutputChildConfig[]) => DeclaredOutputChildConfig[],
+): DeclaredOutputConfig {
+ if (!parentPath.length)
+ return updateOutputChildren(output, updater(getOutputChildren(output)))
+
+ const [childIndex, ...restPath] = parentPath
+ if (childIndex == null)
+ return output
+
+ const children = getOutputChildren(output)
+ const nextChildren = children.map((child, index) => (
+ index === childIndex ? updateChildChildrenAtPath(child, restPath, updater) : child
+ ))
+
+ return updateOutputChildren(output, nextChildren)
+}
+
+function updateChildChildrenAtPath(
+ child: DeclaredOutputChildConfig,
+ parentPath: number[],
+ updater: (children: DeclaredOutputChildConfig[]) => DeclaredOutputChildConfig[],
+): DeclaredOutputChildConfig {
+ if (!parentPath.length)
+ return updateChildChildren(child, updater(getOutputChildren(child)))
+
+ const [childIndex, ...restPath] = parentPath
+ if (childIndex == null)
+ return child
+
+ const children = getOutputChildren(child)
+ const nextChildren = children.map((nestedChild, index) => (
+ index === childIndex ? updateChildChildrenAtPath(nestedChild, restPath, updater) : nestedChild
+ ))
+
+ return updateChildChildren(child, nextChildren)
+}
+
+function updateChildChildren(
+ child: DeclaredOutputChildConfig,
+ children: DeclaredOutputChildConfig[],
+): DeclaredOutputChildConfig {
+ if (getOutputTypeOptionValue(child) === 'array[object]') {
+ return {
+ ...child,
+ array_item: {
+ type: 'object',
+ ...child.array_item,
+ children: children.length ? children : undefined,
+ },
+ }
+ }
+
+ if (child.type === 'object') {
+ return {
+ ...child,
+ children: children.length ? children : undefined,
+ }
+ }
+
+ return child
+}
+
+function getOutputDefaultValue(output: EditableOutputConfig) {
+ if (!('failure_strategy' in output))
+ return ''
+
const defaultValue = output.failure_strategy?.default_value
if (defaultValue == null)
return ''
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.tsx
index b95617ff4a3..fb669684bcc 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
@@ -1,8 +1,9 @@
-import type { ReactNode, RefObject } from 'react'
+import type { ReactElement, ReactNode, RefObject } from 'react'
import type { AgentRosterNodeData } from '@/app/components/workflow/block-selector/types'
import type { AppIconType } from '@/types/app'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
+import { Dialog, DialogContent, DialogDescription, DialogTitle, DialogTrigger } from '@langgenius/dify-ui/dialog'
import {
Drawer,
DrawerCloseButton,
@@ -12,6 +13,12 @@ import {
DrawerTitle,
DrawerViewport,
} from '@langgenius/dify-ui/drawer'
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from '@langgenius/dify-ui/dropdown-menu'
import { FieldLabel, FieldRoot } from '@langgenius/dify-ui/field'
import {
Popover,
@@ -76,7 +83,7 @@ function InlineSetupAvatar({
}) {
return (
<span className={cn('flex size-8 shrink-0 items-center justify-center rounded-full bg-background-default-burn', className)}>
- <span aria-hidden className="i-custom-vender-agent-v2-robot-3 size-5 text-text-tertiary" />
+ <span aria-hidden className="i-custom-vender-agent-v2-configure h-3.5 w-3 text-text-tertiary" />
</span>
)
}
@@ -91,23 +98,30 @@ function AgentRosterDrawer({
showAccessIcon = true,
showConsoleLink = true,
showDetailActions = true,
+ isCopyPending = false,
+ onMakeCopy,
+ onSaveInlineToRoster,
onClose,
}: {
agent: AgentRosterDisplayData
children?: ReactNode
isInlineSetup?: boolean
+ isCopyPending?: boolean
mode?: AgentRosterDrawerMode
open: boolean
portalContainerRef: RefObject<HTMLDivElement | null>
showAccessIcon?: boolean
showConsoleLink?: boolean
showDetailActions?: boolean
+ onMakeCopy?: () => void
+ onSaveInlineToRoster?: () => void
onClose: () => void
}) {
const { t } = useTranslation()
const isSetup = mode === 'setup'
const title = isInlineSetup ? t(`${i18nPrefix}.roster.inlineSetup.name`, { ns: 'workflow' }) : agent.name
const description = isSetup ? t(`${i18nPrefix}.roster.inlineSetup.description`, { ns: 'workflow' }) : agent.role
+ const showInlineActions = isInlineSetup && !!onSaveInlineToRoster
return (
<Drawer
@@ -160,16 +174,27 @@ function AgentRosterDrawer({
</div>
</div>
<div className="flex shrink-0 items-center gap-1 py-1">
- <button
- type="button"
- aria-label={t(`${i18nPrefix}.roster.more`, { ns: 'workflow' })}
- className="flex size-6 cursor-pointer items-center justify-center rounded-md text-text-tertiary hover:bg-state-base-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"
- >
- <span aria-hidden className="i-ri-more-fill size-4" />
- </button>
- <div className="flex h-3.5 items-start px-1">
- <div className="h-full w-px bg-divider-regular" />
- </div>
+ {showInlineActions && (
+ <>
+ <DropdownMenu modal={false}>
+ <DropdownMenuTrigger
+ aria-label={t(`${i18nPrefix}.roster.more`, { ns: 'workflow' })}
+ className="flex size-6 cursor-pointer items-center justify-center rounded-md text-text-tertiary hover:bg-state-base-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden data-popup-open:bg-state-base-hover"
+ >
+ <span aria-hidden className="i-ri-more-fill size-4" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent placement="bottom-end" sideOffset={4} popupClassName="min-w-44 w-max">
+ <DropdownMenuItem className="gap-2 whitespace-nowrap" onClick={onSaveInlineToRoster}>
+ <span aria-hidden className="i-ri-inbox-archive-line size-4 shrink-0 text-text-tertiary" />
+ <span>{t('roster.saveToRoster', { ns: 'agentV2' })}</span>
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ <div className="flex h-3.5 items-start px-1">
+ <div className="h-full w-px bg-divider-regular" />
+ </div>
+ </>
+ )}
<DrawerCloseButton
aria-label={t('operation.close', { ns: 'common' })}
className="size-6 rounded-md"
@@ -193,6 +218,8 @@ function AgentRosterDrawer({
variant="secondary"
size="medium"
className="min-w-0 flex-1 gap-1.5 px-3"
+ loading={isCopyPending}
+ onClick={onMakeCopy}
>
<span aria-hidden className="i-ri-file-copy-2-line size-4 shrink-0" />
<span className="truncate">
@@ -217,11 +244,47 @@ function AgentRosterDrawer({
)
}
+function AgentRosterInlineConfigureDialog({
+ agent,
+ children,
+ open,
+ trigger,
+ onOpenChange,
+}: {
+ agent: AgentRosterDisplayData
+ children?: ReactNode
+ open: boolean
+ trigger: ReactElement
+ onOpenChange: (open: boolean) => void
+}) {
+ const { t } = useTranslation()
+
+ return (
+ <Dialog
+ open={open}
+ onOpenChange={onOpenChange}
+ disablePointerDismissal
+ >
+ <DialogTrigger render={trigger} />
+ <DialogContent className="h-[min(760px,calc(100dvh-32px))] w-[min(1120px,calc(100vw-32px))] max-w-none overflow-hidden p-0">
+ <DialogTitle className="sr-only">
+ {agent.name}
+ </DialogTitle>
+ <DialogDescription className="sr-only">
+ {t(`${i18nPrefix}.roster.inlineSetup.description`, { ns: 'workflow' })}
+ </DialogDescription>
+ {children ?? <div className="h-full min-h-80 bg-components-panel-bg" />}
+ </DialogContent>
+ </Dialog>
+ )
+}
+
export function AgentRosterField({
agent,
agentId,
canOpenPanel = true,
isPanelOpen,
+ isPanelCopyPending = false,
isPending = false,
isLoading = false,
isInlineSetup = false,
@@ -230,13 +293,16 @@ export function AgentRosterField({
showPanelDetailActions = true,
portalContainerRef,
onChange,
+ onMakeCopy,
onPanelOpenChange,
+ onSaveInlineToRoster,
onStartFromScratch,
}: {
agent?: AgentRosterDisplayData
agentId?: string
canOpenPanel?: boolean
isPanelOpen?: boolean
+ isPanelCopyPending?: boolean
isLoading?: boolean
isInlineSetup?: boolean
isPending?: boolean
@@ -245,7 +311,9 @@ export function AgentRosterField({
showPanelDetailActions?: boolean
portalContainerRef: RefObject<HTMLDivElement | null>
onChange: (agent: AgentRosterNodeData) => void
+ onMakeCopy?: () => void
onPanelOpenChange?: (open: boolean) => void
+ onSaveInlineToRoster?: () => void
onStartFromScratch?: () => void
}) {
const { t } = useTranslation()
@@ -283,6 +351,20 @@ export function AgentRosterField({
</span>
</>
)
+ const renderPanelTrigger = (name: string, onClick?: () => void) => (
+ <button
+ type="button"
+ aria-label={t(`${i18nPrefix}.roster.openPanel`, { ns: 'workflow', name })}
+ aria-busy={isLoading || undefined}
+ className="flex h-13 w-full min-w-0 cursor-pointer items-center gap-2 rounded-[10px] border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg py-2 pr-4 pl-2 text-left shadow-xs shadow-shadow-shadow-3 hover:bg-components-panel-on-panel-item-bg-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"
+ onClick={onClick}
+ >
+ {isLoading ? loadingContent : agentContent}
+ <span className="flex shrink-0 items-center text-text-tertiary">
+ <span aria-hidden className="i-ri-arrow-right-line size-4" />
+ </span>
+ </button>
+ )
return (
<FieldRoot name="agent_binding" className="gap-1 px-4 py-2">
@@ -338,30 +420,36 @@ export function AgentRosterField({
canOpenPanel
? (
<>
- <button
- type="button"
- aria-label={t(`${i18nPrefix}.roster.openPanel`, { ns: 'workflow', name: isInlineSetup ? inlineSetupName : agent.name })}
- aria-busy={isLoading || undefined}
- className="flex h-13 w-full min-w-0 cursor-pointer items-center gap-2 rounded-[10px] border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg py-2 pr-4 pl-2 text-left shadow-xs shadow-shadow-shadow-3 hover:bg-components-panel-on-panel-item-bg-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"
- onClick={() => setPanelOpen(true)}
- >
- {isLoading ? loadingContent : agentContent}
- <span className="flex shrink-0 items-center text-text-tertiary">
- <span aria-hidden className="i-ri-arrow-right-line size-4" />
- </span>
- </button>
- <AgentRosterDrawer
- agent={agent}
- isInlineSetup={isInlineSetup}
- mode={panelMode}
- open={panelOpen}
- portalContainerRef={portalContainerRef}
- showAccessIcon={!isInlineSetup}
- showDetailActions={showPanelDetailActions}
- onClose={() => setPanelOpen(false)}
- >
- {panelBody}
- </AgentRosterDrawer>
+ {isInlineSetup
+ ? (
+ <AgentRosterInlineConfigureDialog
+ agent={agent}
+ open={panelOpen}
+ trigger={renderPanelTrigger(inlineSetupName)}
+ onOpenChange={setPanelOpen}
+ >
+ {panelBody}
+ </AgentRosterInlineConfigureDialog>
+ )
+ : (
+ <>
+ {renderPanelTrigger(agent.name, () => setPanelOpen(true))}
+ <AgentRosterDrawer
+ agent={agent}
+ mode={panelMode}
+ open={panelOpen}
+ portalContainerRef={portalContainerRef}
+ showAccessIcon
+ showDetailActions={showPanelDetailActions}
+ isCopyPending={isPanelCopyPending}
+ onMakeCopy={onMakeCopy}
+ onSaveInlineToRoster={onSaveInlineToRoster}
+ onClose={() => setPanelOpen(false)}
+ >
+ {panelBody}
+ </AgentRosterDrawer>
+ </>
+ )}
</>
)
: (
diff --git a/web/app/components/workflow/nodes/agent-v2/components/agent-task-field.tsx b/web/app/components/workflow/nodes/agent-v2/components/agent-task-field.tsx
index 7ae37e81dea..ef20a3c7c9e 100644
--- a/web/app/components/workflow/nodes/agent-v2/components/agent-task-field.tsx
+++ b/web/app/components/workflow/nodes/agent-v2/components/agent-task-field.tsx
@@ -103,7 +103,10 @@ export function AgentTaskField({
<FieldLabel className="min-w-0 py-1 system-sm-semibold-uppercase! text-text-secondary">
{t(`${i18nPrefix}.task.label`, { ns: 'workflow' })}
</FieldLabel>
- <Infotip aria-label={t(`${i18nPrefix}.task.tooltip`, { ns: 'workflow' })}>
+ <Infotip
+ aria-label={t(`${i18nPrefix}.task.tooltip`, { ns: 'workflow' })}
+ popupClassName="whitespace-pre-line"
+ >
{t(`${i18nPrefix}.task.tooltip`, { ns: 'workflow' })}
</Infotip>
</div>
@@ -132,6 +135,7 @@ export function AgentTaskField({
getVarType,
workflowNodesMap,
}}
+ isSupportFileVar
agentOutputBlock={{
show: true,
outputs,
diff --git a/web/app/components/workflow/nodes/agent-v2/components/save-inline-agent-to-roster-dialog.tsx b/web/app/components/workflow/nodes/agent-v2/components/save-inline-agent-to-roster-dialog.tsx
new file mode 100644
index 00000000000..783529fd6ed
--- /dev/null
+++ b/web/app/components/workflow/nodes/agent-v2/components/save-inline-agent-to-roster-dialog.tsx
@@ -0,0 +1,159 @@
+'use client'
+
+import type { AgentComposerAgentResponse, AgentComposerBindingResponse } from '@dify/contracts/api/console/apps/types.gen'
+import type { AgentFormValues, AgentIconSelection } from '@/features/agent-v2/roster/components/agent-form'
+import { Button } from '@langgenius/dify-ui/button'
+import { Dialog, DialogCloseButton, DialogContent, DialogDescription, DialogTitle } from '@langgenius/dify-ui/dialog'
+import { Form } from '@langgenius/dify-ui/form'
+import { toast } from '@langgenius/dify-ui/toast'
+import { useMutation } from '@tanstack/react-query'
+import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import AppIconPicker from '@/app/components/base/app-icon-picker'
+import { createAgentIconSelection, defaultAgentIcon } from '@/features/agent-v2/roster/components/agent-form'
+import { AgentFormFields } from '@/features/agent-v2/roster/components/agent-form-fields'
+import { consoleQuery } from '@/service/client'
+
+type SaveInlineAgentToRosterDialogProps = {
+ appId?: string
+ formKey: number
+ initialAgent?: AgentComposerAgentResponse | null
+ nodeId: string
+ open: boolean
+ onOpenChange: (open: boolean) => void
+ onSaved: (binding: AgentComposerBindingResponse) => void
+}
+
+export function SaveInlineAgentToRosterDialog({
+ appId,
+ formKey,
+ initialAgent,
+ nodeId,
+ open,
+ onOpenChange,
+ onSaved,
+}: SaveInlineAgentToRosterDialogProps) {
+ const { t } = useTranslation('agentV2')
+ const { t: tCommon } = useTranslation('common')
+ const [name, setName] = useState('')
+ const [description, setDescription] = useState(initialAgent?.description ?? '')
+ const [role, setRole] = useState(initialAgent?.role ?? '')
+ const [iconPickerOpen, setIconPickerOpen] = useState(false)
+ const [agentIcon, setAgentIcon] = useState<AgentIconSelection>(() => initialAgent
+ ? createAgentIconSelection(initialAgent)
+ : defaultAgentIcon)
+ const saveToRosterMutation = useMutation(
+ consoleQuery.apps.byAppId.workflows.draft.nodes.byNodeId.agentComposer.saveToRoster.post.mutationOptions(),
+ )
+
+ const handleOpenChange = (nextOpen: boolean) => {
+ if (nextOpen) {
+ setName('')
+ setDescription(initialAgent?.description ?? '')
+ setRole(initialAgent?.role ?? '')
+ setAgentIcon(initialAgent
+ ? createAgentIconSelection(initialAgent)
+ : defaultAgentIcon)
+ }
+ else {
+ setIconPickerOpen(false)
+ }
+ onOpenChange(nextOpen)
+ }
+
+ const handleSubmit = (formValues: AgentFormValues) => {
+ if (saveToRosterMutation.isPending)
+ return
+
+ if (!appId)
+ return
+
+ const trimmedName = formValues.name?.trim() ?? ''
+ const trimmedRole = formValues.role?.trim() ?? ''
+
+ saveToRosterMutation.mutate({
+ params: {
+ app_id: appId,
+ node_id: nodeId,
+ },
+ body: {
+ variant: 'workflow',
+ save_strategy: 'save_to_roster',
+ new_agent_name: trimmedName,
+ description: formValues.description?.trim() ?? '',
+ role: trimmedRole,
+ icon_type: agentIcon.type,
+ icon: agentIcon.type === 'image' ? agentIcon.fileId : agentIcon.icon,
+ icon_background: agentIcon.type === 'emoji' ? agentIcon.background : undefined,
+ },
+ }, {
+ onSuccess: (composerState) => {
+ const binding = composerState.binding
+ if (binding?.binding_type !== 'roster_agent' || !binding.agent_id)
+ return
+
+ toast.success(t('roster.saveToRosterSuccess'))
+ onSaved(binding)
+ 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.saveToRosterDialog.title')}
+ </DialogTitle>
+ <DialogDescription className="sr-only">
+ {t('roster.saveToRosterDialog.description')}
+ </DialogDescription>
+ </div>
+ <Form<AgentFormValues>
+ key={formKey}
+ className="min-h-0 flex-1"
+ onFormSubmit={handleSubmit}
+ >
+ <AgentFormFields
+ description={description}
+ icon={agentIcon}
+ iconAriaLabel={t('roster.saveToRosterForm.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={saveToRosterMutation.isPending}>
+ {tCommon('operation.cancel')}
+ </Button>
+ <Button
+ type="submit"
+ variant="primary"
+ className="min-w-18"
+ loading={saveToRosterMutation.isPending}
+ >
+ {tCommon('operation.save')}
+ </Button>
+ </div>
+ </Form>
+ </DialogContent>
+ </Dialog>
+ <AppIconPicker
+ open={iconPickerOpen}
+ initialEmoji={agentIcon.type === 'emoji'
+ ? { icon: agentIcon.icon, background: agentIcon.background }
+ : undefined}
+ onOpenChange={setIconPickerOpen}
+ onSelect={(icon) => {
+ setAgentIcon(icon)
+ }}
+ />
+ </>
+ )
+}
diff --git a/web/app/components/workflow/nodes/agent-v2/hooks.ts b/web/app/components/workflow/nodes/agent-v2/hooks.ts
index 7df158bda9f..6976969f350 100644
--- a/web/app/components/workflow/nodes/agent-v2/hooks.ts
+++ b/web/app/components/workflow/nodes/agent-v2/hooks.ts
@@ -1,6 +1,6 @@
import type { AgentInlineBinding } from '../../block-selector/types'
import { toast } from '@langgenius/dify-ui/toast'
-import { skipToken, useMutation, useQuery } from '@tanstack/react-query'
+import { skipToken, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useCallback } from 'react'
import { useTranslation } from 'react-i18next'
import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
@@ -51,22 +51,23 @@ export function useCreateInlineAgentBinding() {
const { t } = useTranslation('agentV2')
const configsMap = useHooksStore(state => state.configsMap)
const { data: defaultModel } = useDefaultModel(ModelTypeEnum.textGeneration)
+ const queryClient = useQueryClient()
const {
isPending,
- mutate,
+ mutateAsync,
} = useMutation(
consoleQuery.apps.byAppId.workflows.draft.nodes.byNodeId.agentComposer.put.mutationOptions(),
)
- const createInlineAgentBinding = useCallback((nodeId: string, options?: CreateInlineAgentBindingOptions) => {
+ const createInlineAgentBinding = useCallback(async (nodeId: string, options?: CreateInlineAgentBindingOptions) => {
if (!configsMap?.flowId || configsMap.flowType !== FlowType.appFlow) {
toast.error(t('roster.nodeSelector.createInlineFailed'))
options?.onError?.()
return
}
- mutate(
- {
+ try {
+ const composerState = await mutateAsync({
params: {
app_id: configsMap.flowId,
node_id: nodeId,
@@ -82,33 +83,40 @@ export function useCreateInlineAgentBinding() {
},
agent_soul: getDefaultAgentSoul(defaultModel),
},
- },
- {
- onSuccess: (composerState) => {
- const binding = composerState.binding
+ })
+ const binding = composerState.binding
- if (
- binding?.binding_type !== 'inline_agent'
- || !binding.agent_id
- || !binding.current_snapshot_id
- ) {
- toast.error(t('roster.nodeSelector.createInlineFailed'))
- options?.onError?.()
- return
- }
+ if (
+ binding?.binding_type !== 'inline_agent'
+ || !binding.agent_id
+ || !binding.current_snapshot_id
+ ) {
+ toast.error(t('roster.nodeSelector.createInlineFailed'))
+ options?.onError?.()
+ return
+ }
- options?.onSuccess?.({
- binding_type: 'inline_agent',
- agent_id: binding.agent_id,
- current_snapshot_id: binding.current_snapshot_id,
- })
- },
- onError: () => {
- options?.onError?.()
- },
- },
- )
- }, [configsMap?.flowId, configsMap?.flowType, defaultModel, mutate, t])
+ queryClient.setQueryData(
+ consoleQuery.apps.byAppId.workflows.draft.nodes.byNodeId.agentComposer.get.queryKey({
+ input: {
+ params: {
+ app_id: configsMap.flowId,
+ node_id: nodeId,
+ },
+ },
+ }),
+ composerState,
+ )
+ options?.onSuccess?.({
+ binding_type: 'inline_agent',
+ agent_id: binding.agent_id,
+ current_snapshot_id: binding.current_snapshot_id,
+ })
+ }
+ catch {
+ options?.onError?.()
+ }
+ }, [configsMap?.flowId, configsMap?.flowType, defaultModel, mutateAsync, queryClient, t])
return {
createInlineAgentBinding,
diff --git a/web/app/components/workflow/nodes/agent-v2/node.tsx b/web/app/components/workflow/nodes/agent-v2/node.tsx
index 33dcd303832..1a750b84de4 100644
--- a/web/app/components/workflow/nodes/agent-v2/node.tsx
+++ b/web/app/components/workflow/nodes/agent-v2/node.tsx
@@ -24,7 +24,7 @@ function AgentNodeAvatar({
if (isInlineAgent) {
return (
<span className="flex size-8 shrink-0 items-center justify-center rounded-full bg-background-default-burn text-text-tertiary">
- <span aria-hidden className="i-custom-vender-agent-v2-robot-3 size-5" />
+ <span aria-hidden className="i-custom-vender-agent-v2-configure h-3.5 w-3" />
</span>
)
}
diff --git a/web/app/components/workflow/nodes/agent-v2/panel.tsx b/web/app/components/workflow/nodes/agent-v2/panel.tsx
index c80c021407d..a3c922de7ce 100644
--- a/web/app/components/workflow/nodes/agent-v2/panel.tsx
+++ b/web/app/components/workflow/nodes/agent-v2/panel.tsx
@@ -1,6 +1,8 @@
+import type { AgentComposerBindingResponse } from '@dify/contracts/api/console/apps/types.gen'
import type { AgentRosterNodeData } from '../../block-selector/types'
import type { NodePanelProps } from '../../types'
import type { AgentV2NodeType } from './types'
+import { useMutation } from '@tanstack/react-query'
import { produce } from 'immer'
import { useCallback, useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
@@ -10,12 +12,14 @@ import {
} from '@/app/components/base/prompt-editor/plugins/agent-output-block/utils'
import { useNodeDataUpdate } from '@/app/components/workflow/hooks'
import { useStore } from '@/app/components/workflow/store'
+import { consoleQuery } from '@/service/client'
import useNodeCrud from '../_base/hooks/use-node-crud'
import { AgentAdvancedSettings } from './components/agent-advanced-settings'
-import { AgentOrchestrateDrawerPanel } from './components/agent-orchestrate-drawer-panel'
+import { WorkflowInlineAgentConfigureWorkspace, WorkflowRosterAgentOrchestratePanelContent } from './components/agent-orchestrate-panel-content'
import { AgentOutputVariables } from './components/agent-output-variables'
import { AgentRosterField } from './components/agent-roster-field'
import { AgentTaskField } from './components/agent-task-field'
+import { SaveInlineAgentToRosterDialog } from './components/save-inline-agent-to-roster-dialog'
import { useAgentRosterDetail, useCreateInlineAgentBinding, useWorkflowInlineAgentDetail } from './hooks'
import { getAgentV2DeclaredOutputs } from './output-variables'
import { hasValidInlineAgentBinding } from './types'
@@ -30,6 +34,8 @@ export function AgentV2Panel({
const promptOutputNamesRef = useRef(extractAgentOutputNames(inputs.agent_task || ''))
const [isRosterAgentPanelOpen, setIsRosterAgentPanelOpen] = useState(false)
const [isInlineAgentPanelOpenedFromTrigger, setIsInlineAgentPanelOpenedFromTrigger] = useState(false)
+ const [isSaveToRosterDialogOpen, setIsSaveToRosterDialogOpen] = useState(false)
+ const [saveToRosterSessionKey, setSaveToRosterSessionKey] = useState(0)
const { handleNodeDataUpdate, handleNodeDataUpdateWithSyncDraft } = useNodeDataUpdate()
const openInlineAgentPanelNodeId = useStore(state => state.openInlineAgentPanelNodeId)
const setOpenInlineAgentPanelNodeId = useStore(state => state.setOpenInlineAgentPanelNodeId)
@@ -40,18 +46,26 @@ export function AgentV2Panel({
const inlineAgentId = inputs.agent_binding?.binding_type === 'inline_agent' ? inputs.agent_binding.agent_id : undefined
const isInlineAgentReady = hasValidInlineAgentBinding(inputs)
const isInlineAgentPending = inputs.agent_binding?.binding_type === 'inline_agent' && !isInlineAgentReady
- const isInlineAgentPanelOpen = isInlineAgentReady && openInlineAgentPanelNodeId === id
+ const isInlineAgentPanelOpen = (isInlineAgentReady || isInlineAgentPending) && openInlineAgentPanelNodeId === id
const rosterAgentQuery = useAgentRosterDetail(rosterAgentId)
const inlineAgentQuery = useWorkflowInlineAgentDetail(id, inlineAgentId)
const { createInlineAgentBinding, isCreatingInlineAgent } = useCreateInlineAgentBinding()
const inlineAgent = inlineAgentQuery.data?.agent
- const isAgentPanelOpen = isInlineAgentReady ? isInlineAgentPanelOpen : isRosterAgentPanelOpen
- const isInlineAgentLoading = isInlineAgentReady && !inlineAgent
+ const {
+ isPending: isCopyingFromRoster,
+ mutate: copyFromRoster,
+ } = useMutation(
+ consoleQuery.apps.byAppId.workflows.draft.nodes.byNodeId.agentComposer.copyFromRoster.post.mutationOptions(),
+ )
+ const isAgentPanelOpen = isInlineAgentReady || isInlineAgentPending ? isInlineAgentPanelOpen : isRosterAgentPanelOpen
+ const isInlineAgentLoading = isInlineAgentPending || (isInlineAgentReady && !inlineAgent)
const isAgentBindingPending = isInlineAgentPending || isCreatingInlineAgent
const canStartFromScratch = inputs.agent_binding?.binding_type !== 'inline_agent'
- const displayedAgent = rosterAgentQuery.data ?? (inlineAgentId && isInlineAgentReady
+ const canSaveInlineToRoster = isInlineAgentReady && !!inlineAgent
+ const inlineComposerStateForPanel = inlineAgentQuery.data
+ const displayedAgent = rosterAgentQuery.data ?? (isInlineAgentPending || isInlineAgentReady
? {
- id: inlineAgentId,
+ id: inlineAgentId ?? id,
name: inlineAgent?.name || t('nodes.agent.roster.inlineSetup.name', { ns: 'workflow' }),
description: inlineAgent?.description,
role: t('nodes.agent.roster.inlineSetup.type', { ns: 'workflow' }),
@@ -113,16 +127,40 @@ export function AgentV2Panel({
)
}, [handleNodeDataUpdateWithSyncDraft, id, inputs, setOpenInlineAgentPanelNodeId])
- const handleStartFromScratch = useCallback(() => {
- createInlineAgentBinding(id, {
- onSuccess: (binding) => {
+ const handleMakeRosterCopy = useCallback(() => {
+ if (!appId || !rosterAgentId || isCopyingFromRoster)
+ return
+
+ copyFromRoster({
+ params: {
+ app_id: appId,
+ node_id: id,
+ },
+ body: {
+ source_agent_id: rosterAgentId,
+ },
+ }, {
+ onSuccess: (composerState) => {
+ const binding = composerState.binding
+ if (
+ binding?.binding_type !== 'inline_agent'
+ || !binding.agent_id
+ || !binding.current_snapshot_id
+ ) {
+ return
+ }
+
setIsRosterAgentPanelOpen(false)
- setIsInlineAgentPanelOpenedFromTrigger(false)
+ setIsInlineAgentPanelOpenedFromTrigger(true)
setOpenInlineAgentPanelNodeId(id)
const newInputs = produce(inputsRef.current, (draft) => {
delete (draft as AgentV2NodeType & { agent_roster?: unknown }).agent_roster
- draft.agent_binding = binding
+ draft.agent_binding = {
+ binding_type: 'inline_agent',
+ agent_id: binding.agent_id,
+ current_snapshot_id: binding.current_snapshot_id,
+ }
draft._openInlineAgentPanel = true
})
inputsRef.current = newInputs
@@ -138,19 +176,144 @@ export function AgentV2Panel({
)
},
})
- }, [createInlineAgentBinding, handleNodeDataUpdateWithSyncDraft, id, setOpenInlineAgentPanelNodeId])
+ }, [appId, copyFromRoster, handleNodeDataUpdateWithSyncDraft, id, isCopyingFromRoster, rosterAgentId, setOpenInlineAgentPanelNodeId])
+
+ const handleSaveInlineToRosterOpen = useCallback(() => {
+ setSaveToRosterSessionKey(key => key + 1)
+ setIsSaveToRosterDialogOpen(true)
+ }, [])
+
+ const handleInlineSavedToRoster = useCallback((binding: AgentComposerBindingResponse) => {
+ if (binding.binding_type !== 'roster_agent' || !binding.agent_id)
+ return
+
+ setOpenInlineAgentPanelNodeId(undefined)
+ setIsInlineAgentPanelOpenedFromTrigger(false)
+ setIsRosterAgentPanelOpen(true)
+
+ const newInputs = produce(inputsRef.current, (draft) => {
+ delete (draft as AgentV2NodeType & { agent_roster?: unknown }).agent_roster
+ delete draft._openInlineAgentPanel
+ draft.agent_binding = {
+ binding_type: 'roster_agent',
+ agent_id: binding.agent_id!,
+ }
+ })
+ inputsRef.current = newInputs
+ handleNodeDataUpdateWithSyncDraft(
+ {
+ id,
+ data: newInputs,
+ },
+ {
+ sync: true,
+ notRefreshWhenSyncError: true,
+ },
+ )
+ }, [handleNodeDataUpdateWithSyncDraft, id, setOpenInlineAgentPanelNodeId])
+
+ const handleInlineAgentBindingCreated = useCallback((binding: {
+ agent_id: string
+ binding_type: 'inline_agent'
+ current_snapshot_id: string
+ }) => {
+ 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,
+ },
+ )
+ }, [handleNodeDataUpdateWithSyncDraft, id])
+
+ const handleInlineAgentSaved = useCallback((binding: AgentComposerBindingResponse) => {
+ if (
+ binding.binding_type !== 'inline_agent'
+ || !binding.agent_id
+ || !binding.current_snapshot_id
+ ) {
+ return
+ }
+
+ const newInputs = produce(inputsRef.current, (draft) => {
+ delete (draft as AgentV2NodeType & { agent_roster?: unknown }).agent_roster
+ delete draft._openInlineAgentPanel
+ draft.agent_binding = {
+ binding_type: 'inline_agent',
+ agent_id: binding.agent_id,
+ current_snapshot_id: binding.current_snapshot_id,
+ }
+ })
+ inputsRef.current = newInputs
+ handleNodeDataUpdateWithSyncDraft(
+ {
+ id,
+ data: newInputs,
+ },
+ {
+ sync: true,
+ notRefreshWhenSyncError: true,
+ },
+ )
+ }, [handleNodeDataUpdateWithSyncDraft, id])
+
+ const handleStartFromScratch = useCallback(() => {
+ setIsRosterAgentPanelOpen(false)
+ setIsInlineAgentPanelOpenedFromTrigger(false)
+ setOpenInlineAgentPanelNodeId(id)
+
+ const pendingInputs = produce(inputsRef.current, (draft) => {
+ delete (draft as AgentV2NodeType & { agent_roster?: unknown }).agent_roster
+ draft.agent_binding = {
+ binding_type: 'inline_agent',
+ }
+ draft._openInlineAgentPanel = true
+ })
+ inputsRef.current = pendingInputs
+ handleNodeDataUpdateWithSyncDraft(
+ {
+ id,
+ data: pendingInputs,
+ },
+ {
+ sync: true,
+ notRefreshWhenSyncError: true,
+ },
+ )
+
+ createInlineAgentBinding(id, {
+ onSuccess: handleInlineAgentBindingCreated,
+ })
+ }, [createInlineAgentBinding, handleInlineAgentBindingCreated, handleNodeDataUpdateWithSyncDraft, id, setOpenInlineAgentPanelNodeId])
const handleAgentPanelOpenChange = useCallback((open: boolean) => {
- if (isInlineAgentReady) {
+ if (isInlineAgentReady || isInlineAgentPending) {
if (open)
setIsInlineAgentPanelOpenedFromTrigger(true)
setOpenInlineAgentPanelNodeId(open ? id : undefined)
+ if (open && isInlineAgentReady)
+ void inlineAgentQuery.refetch()
+
+ if (open && isInlineAgentPending && !isCreatingInlineAgent) {
+ createInlineAgentBinding(id, {
+ onSuccess: handleInlineAgentBindingCreated,
+ })
+ }
return
}
setIsRosterAgentPanelOpen(open)
- }, [id, isInlineAgentReady, setOpenInlineAgentPanelNodeId])
+ }, [createInlineAgentBinding, handleInlineAgentBindingCreated, id, inlineAgentQuery, isCreatingInlineAgent, isInlineAgentPending, isInlineAgentReady, setOpenInlineAgentPanelNodeId])
const handleDeclaredOutputsChange = useCallback((outputs: ReturnType<typeof getAgentV2DeclaredOutputs>, agentTask?: string) => {
const previousOutputs = getAgentV2DeclaredOutputs(inputsRef.current)
@@ -196,31 +359,56 @@ export function AgentV2Panel({
<div className="border-b border-divider-subtle">
<AgentRosterField
agent={displayedAgent}
- agentId={rosterAgentId ?? inlineAgentId ?? undefined}
- canOpenPanel={!isInlineAgentPending}
- isInlineSetup={isInlineAgentReady}
+ agentId={rosterAgentId ?? inlineAgentId ?? (isInlineAgentPending ? id : undefined)}
+ canOpenPanel
+ isInlineSetup={isInlineAgentReady || isInlineAgentPending}
isLoading={isInlineAgentLoading}
+ isPanelCopyPending={isCopyingFromRoster}
isPanelOpen={isAgentPanelOpen}
isPending={isAgentBindingPending}
panelBody={isAgentPanelOpen && displayedAgent
? (
- <AgentOrchestrateDrawerPanel
- agentId={displayedAgent.id}
- appId={appId}
- inlineComposerState={inlineAgentQuery.data}
- isInline={isInlineAgentReady}
- nodeId={id}
- open={isAgentPanelOpen}
- />
+ isInlineAgentReady || isInlineAgentPending
+ ? (
+ <WorkflowInlineAgentConfigureWorkspace
+ agentId={inlineAgentId ?? undefined}
+ appId={appId}
+ inlineComposerState={inlineComposerStateForPanel}
+ nodeId={id}
+ onClose={() => handleAgentPanelOpenChange(false)}
+ onSaved={handleInlineAgentSaved}
+ onSaveInlineToRoster={canSaveInlineToRoster ? handleSaveInlineToRosterOpen : undefined}
+ open={isAgentPanelOpen}
+ />
+ )
+ : (
+ <WorkflowRosterAgentOrchestratePanelContent
+ agentId={rosterAgentId}
+ nodeId={id}
+ open={isAgentPanelOpen}
+ />
+ )
)
: undefined}
- panelMode={isInlineAgentReady && !isInlineAgentPanelOpenedFromTrigger ? 'setup' : 'detail'}
+ panelMode={isInlineAgentPending || (isInlineAgentReady && !isInlineAgentPanelOpenedFromTrigger) ? 'setup' : 'detail'}
portalContainerRef={drawerPortalContainerRef}
- showPanelDetailActions={!isInlineAgentReady}
+ showPanelDetailActions={!isInlineAgentReady && !isInlineAgentPending}
onChange={handleRosterChange}
+ onMakeCopy={rosterAgentId ? handleMakeRosterCopy : undefined}
onPanelOpenChange={handleAgentPanelOpenChange}
+ onSaveInlineToRoster={canSaveInlineToRoster ? handleSaveInlineToRosterOpen : undefined}
onStartFromScratch={canStartFromScratch ? handleStartFromScratch : undefined}
/>
+ <SaveInlineAgentToRosterDialog
+ key={saveToRosterSessionKey}
+ appId={appId}
+ formKey={saveToRosterSessionKey}
+ initialAgent={inlineAgent}
+ nodeId={id}
+ open={isSaveToRosterDialogOpen}
+ onOpenChange={setIsSaveToRosterDialogOpen}
+ onSaved={handleInlineSavedToRoster}
+ />
</div>
<div
aria-disabled={isInlineAgentPending}
diff --git a/web/app/components/workflow/operator/__tests__/add-block.spec.tsx b/web/app/components/workflow/operator/__tests__/add-block.spec.tsx
index df06db1d948..f4d92a0790b 100644
--- a/web/app/components/workflow/operator/__tests__/add-block.spec.tsx
+++ b/web/app/components/workflow/operator/__tests__/add-block.spec.tsx
@@ -27,17 +27,12 @@ type BlockSelectorMockProps = {
const {
mockHandlePaneContextmenuCancel,
mockWorkflowStoreSetState,
- mockSetOpenInlineAgentPanelNodeId,
mockGenerateNewNode,
mockGetNodeCustomTypeByNodeDataType,
mockGetNodesWithSameDefaultDataType,
- mockCreateInlineAgentBinding,
- mockHandleSyncWorkflowDraft,
- mockSaveStateToHistory,
} = vi.hoisted(() => ({
mockHandlePaneContextmenuCancel: vi.fn(),
mockWorkflowStoreSetState: vi.fn(),
- mockSetOpenInlineAgentPanelNodeId: vi.fn(),
mockGenerateNewNode: vi.fn(({ type, data }: { type: string, data: Record<string, unknown> }) => ({
newNode: {
id: 'generated-node',
@@ -66,9 +61,6 @@ const {
return nodes.filter(node => node.data.type === dataType)
}),
- mockCreateInlineAgentBinding: vi.fn(),
- mockHandleSyncWorkflowDraft: vi.fn(),
- mockSaveStateToHistory: vi.fn(),
}))
let latestBlockSelectorProps: BlockSelectorMockProps | null = null
@@ -120,44 +112,11 @@ vi.mock('../../hooks-store', () => ({
}))
vi.mock('../../store', () => ({
- useStore: (selector: (state: { mousePosition: { pageX: number, pageY: number, elementX: number, elementY: number } }) => unknown) =>
- selector({
- mousePosition: {
- pageX: 120,
- pageY: 240,
- elementX: 12,
- elementY: 24,
- },
- }),
useWorkflowStore: () => ({
- getState: () => ({
- setOpenInlineAgentPanelNodeId: mockSetOpenInlineAgentPanelNodeId,
- }),
setState: mockWorkflowStoreSetState,
}),
}))
-vi.mock('../../hooks/use-nodes-sync-draft', () => ({
- useNodesSyncDraft: () => ({
- handleSyncWorkflowDraft: mockHandleSyncWorkflowDraft,
- }),
-}))
-
-vi.mock('../../hooks/use-workflow-history', () => ({
- WorkflowHistoryEvent: {
- NodeAdd: 'NodeAdd',
- },
- useWorkflowHistory: () => ({
- saveStateToHistory: mockSaveStateToHistory,
- }),
-}))
-
-vi.mock('../../nodes/agent-v2/hooks', () => ({
- useCreateInlineAgentBinding: () => ({
- createInlineAgentBinding: mockCreateInlineAgentBinding,
- }),
-}))
-
vi.mock('../../utils', () => ({
generateNewNode: mockGenerateNewNode,
getNodeCustomTypeByNodeDataType: mockGetNodeCustomTypeByNodeDataType,
@@ -178,17 +137,6 @@ describe('AddBlock', () => {
mockNodesReadOnly = false
mockIsChatMode = false
mockFlowType = FlowType.appFlow
- mockCreateInlineAgentBinding.mockImplementation((_nodeId: string, options?: { onSuccess?: (binding: {
- binding_type: 'inline_agent'
- agent_id: string
- current_snapshot_id: string
- }) => void }) => {
- options?.onSuccess?.({
- binding_type: 'inline_agent',
- agent_id: 'inline-agent-1',
- current_snapshot_id: 'snapshot-1',
- })
- })
})
// Rendering and selector configuration.
@@ -358,7 +306,7 @@ describe('AddBlock', () => {
})
})
- it('should commit start-from-scratch Agent v2 immediately and create the inline binding', async () => {
+ it('should keep start-from-scratch Agent v2 as a candidate node before placement', async () => {
mockNodesMetaDataMap[BlockEnum.AgentV2] = {
defaultValue: {
title: 'Agent',
@@ -383,14 +331,22 @@ describe('AddBlock', () => {
})
expect(mockWorkflowStoreSetState).toHaveBeenCalledWith({
- candidateNode: undefined,
+ candidateNode: expect.objectContaining({
+ id: 'generated-node',
+ type: 'agent-v2-custom',
+ data: {
+ title: 'Agent',
+ desc: '',
+ agent_binding: {
+ binding_type: 'inline_agent',
+ },
+ agent_node_kind: 'dify_agent',
+ type: BlockEnum.Agent,
+ version: '2',
+ _isCandidate: true,
+ },
+ }),
})
- expect(mockCreateInlineAgentBinding).toHaveBeenCalledWith('generated-node', expect.objectContaining({
- onSuccess: expect.any(Function),
- }))
- expect(mockSetOpenInlineAgentPanelNodeId).toHaveBeenCalledWith('generated-node')
- expect(mockHandleSyncWorkflowDraft).toHaveBeenCalledWith(true, true)
- expect(mockSaveStateToHistory).toHaveBeenCalledWith('NodeAdd', { nodeId: 'generated-node' })
})
})
})
diff --git a/web/app/components/workflow/operator/add-block.tsx b/web/app/components/workflow/operator/add-block.tsx
index 364c55ee93e..5a0d2998b4b 100644
--- a/web/app/components/workflow/operator/add-block.tsx
+++ b/web/app/components/workflow/operator/add-block.tsx
@@ -1,10 +1,10 @@
import type { OffsetOptions } from '@floating-ui/react'
import type {
+ Node,
OnSelectBlock,
} from '@/app/components/workflow/types'
import { cn } from '@langgenius/dify-ui/cn'
import { RiAddCircleFill } from '@remixicon/react'
-import { produce } from 'immer'
import {
memo,
useCallback,
@@ -12,7 +12,6 @@ import {
} from 'react'
import { useTranslation } from 'react-i18next'
import {
- useReactFlow,
useStoreApi,
} from 'reactflow'
import BlockSelector from '@/app/components/workflow/block-selector'
@@ -28,12 +27,7 @@ import {
usePanelInteractions,
} from '../hooks'
import { useHooksStore } from '../hooks-store'
-import { useCollaborativeWorkflow } from '../hooks/use-collaborative-workflow'
-import { useNodesSyncDraft } from '../hooks/use-nodes-sync-draft'
-import { useWorkflowHistory, WorkflowHistoryEvent } from '../hooks/use-workflow-history'
-import { useCreateInlineAgentBinding } from '../nodes/agent-v2/hooks'
-import { isAgentV2NodeData, needsInlineAgentBindingCreation } from '../nodes/agent-v2/types'
-import { useStore, useWorkflowStore } from '../store'
+import { useWorkflowStore } from '../store'
import {
generateNewNode,
getNodeCustomTypeByNodeDataType,
@@ -57,16 +51,10 @@ const AddBlock = ({
}: AddBlockProps) => {
const { t } = useTranslation()
const store = useStoreApi()
- const reactflow = useReactFlow()
const workflowStore = useWorkflowStore()
- const mousePosition = useStore(s => s.mousePosition)
- const collaborativeWorkflow = useCollaborativeWorkflow()
const isChatMode = useIsChatMode()
const { nodesReadOnly } = useNodesReadOnly()
const { handlePaneContextmenuCancel } = usePanelInteractions()
- const { handleSyncWorkflowDraft } = useNodesSyncDraft()
- const { saveStateToHistory } = useWorkflowHistory()
- const { createInlineAgentBinding } = useCreateInlineAgentBinding()
const [open, setOpen] = useState(false)
const { availableNextBlocks } = useAvailableBlocks(BlockEnum.Start, false)
const { nodesMap: nodesMetaDataMap } = useNodesMetaData()
@@ -91,7 +79,7 @@ const AddBlock = ({
const { newNode } = generateNewNode({
type: getNodeCustomTypeByNodeDataType(type),
data: {
- ...(defaultValue as any),
+ ...(defaultValue as Node['data']),
title: nodesWithSameType.length > 0 ? `${defaultValue.title} ${nodesWithSameType.length + 1}` : defaultValue.title,
...pluginDefaultValue,
_isCandidate: true,
@@ -101,56 +89,10 @@ const AddBlock = ({
y: 0,
},
})
- if (isAgentV2NodeData(newNode.data) && needsInlineAgentBindingCreation(newNode.data)) {
- const { nodes, setNodes } = collaborativeWorkflow.getState()
- const { screenToFlowPosition } = reactflow
- const position = screenToFlowPosition({
- x: mousePosition.pageX,
- y: mousePosition.pageY,
- })
- const nodeToInsert = {
- ...newNode,
- data: {
- ...newNode.data,
- _isCandidate: false,
- _isTempNode: true,
- selected: true,
- },
- position,
- }
- setNodes(produce(nodes, (draft) => {
- draft.forEach((node) => {
- node.data.selected = false
- })
- draft.push(nodeToInsert)
- }))
- workflowStore.setState({
- candidateNode: undefined,
- })
- saveStateToHistory(WorkflowHistoryEvent.NodeAdd, { nodeId: newNode.id })
- createInlineAgentBinding(newNode.id, {
- onSuccess: (binding) => {
- const { nodes, setNodes } = collaborativeWorkflow.getState()
- setNodes(produce(nodes, (draft) => {
- const node = draft.find(node => node.id === newNode.id)
- if (node) {
- if (isAgentV2NodeData(node.data) && needsInlineAgentBindingCreation(node.data))
- node.data.agent_binding = binding
- node.data._openInlineAgentPanel = true
- delete node.data._isTempNode
- }
- }))
- workflowStore.getState().setOpenInlineAgentPanelNodeId(newNode.id)
- handleSyncWorkflowDraft(true, true)
- },
- })
- setOpen(false)
- return
- }
workflowStore.setState({
candidateNode: newNode,
})
- }, [collaborativeWorkflow, createInlineAgentBinding, handleSyncWorkflowDraft, mousePosition.pageX, mousePosition.pageY, reactflow, saveStateToHistory, store, workflowStore, nodesMetaDataMap])
+ }, [store, workflowStore, nodesMetaDataMap])
const renderTriggerElement = useCallback((open: boolean) => {
return (
diff --git a/web/app/components/main-nav/components/nav-link.css b/web/app/styles/glass-surface.css
similarity index 98%
rename from web/app/components/main-nav/components/nav-link.css
rename to web/app/styles/glass-surface.css
index 20839c746ea..7ac33aa3799 100644
--- a/web/app/components/main-nav/components/nav-link.css
+++ b/web/app/styles/glass-surface.css
@@ -1,4 +1,4 @@
-@utility main-nav-active-glass {
+@utility dify-blue-glass-surface {
@apply overflow-hidden system-md-semibold text-saas-dify-blue-inverted backdrop-blur-[5px];
background-image: linear-gradient(
diff --git a/web/app/styles/tailwind-core.css b/web/app/styles/tailwind-core.css
index 7707eca879c..57ae587bfe3 100644
--- a/web/app/styles/tailwind-core.css
+++ b/web/app/styles/tailwind-core.css
@@ -28,7 +28,7 @@
@import '../components/base/action-button/index.css';
@import '../components/base/badge/index.css';
@import '../components/base/premium-badge/index.css';
-@import '../components/main-nav/components/nav-link.css';
+@import './glass-surface.css';
/* ---------- JS plugins ------------------------------------------------ */
@plugin './plugins/icons.ts';
diff --git a/web/features/agent-v2/agent-composer/__tests__/knowledge-validation.spec.ts b/web/features/agent-v2/agent-composer/__tests__/knowledge-validation.spec.ts
new file mode 100644
index 00000000000..1665c1c89cb
--- /dev/null
+++ b/web/features/agent-v2/agent-composer/__tests__/knowledge-validation.spec.ts
@@ -0,0 +1,101 @@
+import { describe, expect, it } from 'vitest'
+import { LogicalOperator, MetadataFilteringModeEnum } from '@/app/components/workflow/nodes/knowledge-retrieval/types'
+import { RETRIEVE_TYPE } from '@/types/app'
+import { validateKnowledgeRetrievals } from '../knowledge-validation'
+
+describe('validateKnowledgeRetrievals', () => {
+ it('should accept a valid generated-query knowledge retrieval', () => {
+ const result = validateKnowledgeRetrievals([
+ {
+ id: 'retrieval-1',
+ name: 'Docs Search',
+ datasetRefs: [{ id: 'dataset-1', name: 'Docs' }],
+ queryMode: 'agent',
+ retrievalMode: RETRIEVE_TYPE.multiWay,
+ },
+ ])
+
+ expect(result).toMatchObject({
+ isValid: true,
+ byId: {},
+ firstIssue: undefined,
+ })
+ })
+
+ it('should reject blank and duplicate names', () => {
+ const result = validateKnowledgeRetrievals([
+ {
+ id: 'retrieval-1',
+ name: ' ',
+ datasetRefs: [{ id: 'dataset-1', name: 'Docs' }],
+ },
+ {
+ id: 'retrieval-2',
+ name: 'Docs Search',
+ datasetRefs: [{ id: 'dataset-2', name: 'FAQ' }],
+ },
+ {
+ id: 'retrieval-3',
+ name: ' docs search ',
+ datasetRefs: [{ id: 'dataset-3', name: 'Guide' }],
+ },
+ ])
+
+ expect(result.isValid).toBe(false)
+ expect(result.byId['retrieval-1']).toMatchObject({ name: 'name_required' })
+ expect(result.byId['retrieval-2']).toMatchObject({ name: 'name_duplicate' })
+ expect(result.byId['retrieval-3']).toMatchObject({ name: 'name_duplicate' })
+ })
+
+ it('should reject missing datasets, blank custom queries, and missing single-retrieval model', () => {
+ const result = validateKnowledgeRetrievals([
+ {
+ id: 'retrieval-1',
+ name: 'Product Docs',
+ queryMode: 'custom',
+ customQuery: ' ',
+ retrievalMode: RETRIEVE_TYPE.oneWay,
+ singleRetrievalConfig: {
+ model: {
+ provider: '',
+ name: '',
+ mode: 'chat',
+ completion_params: {},
+ },
+ },
+ },
+ ])
+
+ expect(result.isValid).toBe(false)
+ expect(result.byId['retrieval-1']).toMatchObject({
+ datasets: 'datasets_required',
+ query: 'custom_query_required',
+ retrieval: 'single_model_required',
+ })
+ })
+
+ it('should reject invalid metadata filtering requirements', () => {
+ const result = validateKnowledgeRetrievals([
+ {
+ id: 'retrieval-1',
+ name: 'Auto Metadata',
+ datasetRefs: [{ id: 'dataset-1', name: 'Docs' }],
+ metadataFilterMode: MetadataFilteringModeEnum.automatic,
+ },
+ {
+ id: 'retrieval-2',
+ name: 'Manual Metadata',
+ datasetRefs: [{ id: 'dataset-2', name: 'FAQ' }],
+ metadataFilterMode: MetadataFilteringModeEnum.manual,
+ metadataFilteringConditions: {
+ logical_operator: LogicalOperator.and,
+ conditions: [],
+ },
+ },
+ ])
+
+ expect(result.isValid).toBe(false)
+ expect(result.byId['retrieval-1']).toMatchObject({ metadata: 'metadata_model_required' })
+ expect(result.byId['retrieval-2']).toMatchObject({ metadata: 'metadata_conditions_required' })
+ })
+})
diff --git a/web/features/agent-v2/agent-composer/__tests__/provider.spec.tsx b/web/features/agent-v2/agent-composer/__tests__/provider.spec.tsx
new file mode 100644
index 00000000000..327396b6061
--- /dev/null
+++ b/web/features/agent-v2/agent-composer/__tests__/provider.spec.tsx
@@ -0,0 +1,98 @@
+import type { AgentSoulConfig } from '@dify/contracts/api/console/agent/types.gen'
+import { render, screen } from '@testing-library/react'
+import { useAtomValue } from 'jotai'
+import { describe, expect, it } from 'vitest'
+import { defaultAgentSoulConfigFormState } from '../form-state'
+import { AgentComposerProvider } from '../provider'
+import {
+ agentComposerDraftAtom,
+ agentComposerOriginalConfigAtom,
+ agentComposerOriginalDraftAtom,
+ agentComposerPublishedDraftAtom,
+ hasAgentComposerUnpublishedChangesAtom,
+ isAgentComposerDirtyAtom,
+} from '../store'
+
+function StoreSnapshot() {
+ const draft = useAtomValue(agentComposerDraftAtom)
+ const originalDraft = useAtomValue(agentComposerOriginalDraftAtom)
+ const publishedDraft = useAtomValue(agentComposerPublishedDraftAtom)
+ const originalConfig = useAtomValue(agentComposerOriginalConfigAtom)
+ const isDirty = useAtomValue(isAgentComposerDirtyAtom)
+ const hasUnpublishedChanges = useAtomValue(hasAgentComposerUnpublishedChangesAtom)
+
+ return (
+ <dl>
+ <dt>draft</dt>
+ <dd data-testid="draft-prompt">{draft.prompt}</dd>
+ <dt>original draft</dt>
+ <dd data-testid="original-draft-prompt">{originalDraft?.prompt}</dd>
+ <dt>published draft</dt>
+ <dd data-testid="published-draft-prompt">{publishedDraft?.prompt}</dd>
+ <dt>original config</dt>
+ <dd data-testid="original-config-prompt">{originalConfig?.prompt?.system_prompt}</dd>
+ <dt>dirty</dt>
+ <dd data-testid="dirty">{String(isDirty)}</dd>
+ <dt>unpublished</dt>
+ <dd data-testid="unpublished">{String(hasUnpublishedChanges)}</dd>
+ </dl>
+ )
+}
+
+describe('AgentComposerProvider', () => {
+ it('initializes draft baselines when creating the scoped store', () => {
+ const initialDraft = {
+ ...defaultAgentSoulConfigFormState,
+ prompt: 'Be precise.',
+ }
+ const initialOriginalConfig = {
+ prompt: {
+ system_prompt: 'Be precise.',
+ },
+ } satisfies AgentSoulConfig
+
+ render(
+ <AgentComposerProvider
+ initialDraft={initialDraft}
+ initialOriginalConfig={initialOriginalConfig}
+ >
+ <StoreSnapshot />
+ </AgentComposerProvider>,
+ )
+
+ expect(screen.getByTestId('draft-prompt')).toHaveTextContent('Be precise.')
+ expect(screen.getByTestId('original-draft-prompt')).toHaveTextContent('Be precise.')
+ expect(screen.getByTestId('published-draft-prompt')).toHaveTextContent('Be precise.')
+ expect(screen.getByTestId('original-config-prompt')).toHaveTextContent('Be precise.')
+ expect(screen.getByTestId('dirty')).toHaveTextContent('false')
+ expect(screen.getByTestId('unpublished')).toHaveTextContent('false')
+ })
+
+ it('creates a new scoped store when the composer session key changes', () => {
+ const firstDraft = {
+ ...defaultAgentSoulConfigFormState,
+ prompt: 'Agent one draft',
+ }
+ const secondDraft = {
+ ...defaultAgentSoulConfigFormState,
+ prompt: 'Agent two draft',
+ }
+ const { rerender } = render(
+ <AgentComposerProvider key="agent-1:draft" initialDraft={firstDraft}>
+ <StoreSnapshot />
+ </AgentComposerProvider>,
+ )
+
+ expect(screen.getByTestId('draft-prompt')).toHaveTextContent('Agent one draft')
+
+ rerender(
+ <AgentComposerProvider key="agent-2:draft" initialDraft={secondDraft}>
+ <StoreSnapshot />
+ </AgentComposerProvider>,
+ )
+
+ expect(screen.getByTestId('draft-prompt')).toHaveTextContent('Agent two draft')
+ expect(screen.getByTestId('original-draft-prompt')).toHaveTextContent('Agent two draft')
+ expect(screen.getByTestId('published-draft-prompt')).toHaveTextContent('Agent two draft')
+ })
+})
diff --git a/web/features/agent-v2/agent-composer/__tests__/store.spec.ts b/web/features/agent-v2/agent-composer/__tests__/store.spec.ts
index a48369d876a..17acef94a85 100644
--- a/web/features/agent-v2/agent-composer/__tests__/store.spec.ts
+++ b/web/features/agent-v2/agent-composer/__tests__/store.spec.ts
@@ -1,11 +1,12 @@
import type { AgentSoulConfig } from '@dify/contracts/api/console/agent/types.gen'
+import type { AgentSoulConfigWithFiles } from '../conversions'
import { describe, expect, it } from 'vitest'
import { agentSoulConfigToFormState, formStateToAgentSoulConfig } from '../conversions'
import { defaultAgentSoulConfigFormState } from '../form-state'
describe('agent composer store conversions', () => {
- it('should hydrate editable form state from an AgentSoulConfig and preserve it in publish payload', () => {
- const baseConfig: AgentSoulConfig = {
+ it('should hydrate editable form state from an AgentSoulConfig and preserve it in the config snapshot', () => {
+ const baseConfig: AgentSoulConfigWithFiles = {
app_features: {
opening_statement: 'Hello',
suggested_questions: ['What changed?'],
@@ -27,20 +28,50 @@ describe('agent composer store conversions', () => {
],
},
knowledge: {
- datasets: [
+ sets: [
{
- id: 'dataset-1',
+ id: 'support',
name: 'Product Docs',
description: 'Docs corpus',
+ datasets: [
+ {
+ id: 'dataset-1',
+ name: 'Product Docs',
+ description: 'Docs corpus',
+ },
+ ],
+ query: {
+ mode: 'user_query',
+ value: 'release notes',
+ },
+ retrieval: {
+ mode: 'multiple',
+ top_k: 8,
+ score_threshold: 0.72,
+ reranking_enable: false,
+ },
+ },
+ ],
+ },
+ files: {
+ skills: [
+ {
+ id: 'tender-analyzer',
+ name: 'Tender Analyzer',
+ description: 'Parses RFPs.',
+ path: 'tender-analyzer',
+ skill_md_key: 'tender-analyzer/SKILL.md',
+ full_archive_key: 'tender-analyzer/.DIFY-SKILL-FULL.zip',
+ },
+ ],
+ files: [
+ {
+ id: 'files/sample.pdf',
+ file_id: 'drive-file-1',
+ name: 'sample.pdf',
+ drive_key: 'files/sample.pdf',
},
],
- query_config: {
- query: 'release notes',
- score_threshold: 0.72,
- score_threshold_enabled: true,
- top_k: 8,
- },
- query_mode: 'user_query',
},
model: {
model: 'gpt-4.1',
@@ -100,7 +131,7 @@ describe('agent composer store conversions', () => {
},
knowledgeRetrievals: [
expect.objectContaining({
- id: 'dataset-1',
+ id: 'support',
name: 'Product Docs',
queryMode: 'custom',
customQuery: 'release notes',
@@ -119,6 +150,20 @@ describe('agent composer store conversions', () => {
value: 'credential-1',
}),
],
+ skills: [
+ expect.objectContaining({
+ name: 'Tender Analyzer',
+ skillMdKey: 'tender-analyzer/SKILL.md',
+ archiveKey: 'tender-analyzer/.DIFY-SKILL-FULL.zip',
+ }),
+ ],
+ files: [
+ expect.objectContaining({
+ name: 'sample.pdf',
+ fileId: 'drive-file-1',
+ driveKey: 'files/sample.pdf',
+ }),
+ ],
})
expect(formState.tools).toEqual(expect.arrayContaining([
expect.objectContaining({
@@ -142,6 +187,26 @@ describe('agent composer store conversions', () => {
})
expect(publishConfig).not.toHaveProperty('skills_files')
+ expect(publishConfig.files).toEqual({
+ skills: [
+ {
+ id: 'tender-analyzer',
+ name: 'Tender Analyzer',
+ description: 'Parses RFPs.',
+ path: 'tender-analyzer',
+ skill_md_key: 'tender-analyzer/SKILL.md',
+ full_archive_key: 'tender-analyzer/.DIFY-SKILL-FULL.zip',
+ },
+ ],
+ files: [
+ {
+ id: 'files/sample.pdf',
+ file_id: 'drive-file-1',
+ name: 'sample.pdf',
+ drive_key: 'files/sample.pdf',
+ },
+ ],
+ })
expect(publishConfig.tools?.dify_tools).toEqual([
expect.objectContaining({
provider: 'DuckDuckGo',
@@ -166,20 +231,30 @@ describe('agent composer store conversions', () => {
}),
])
expect(publishConfig.knowledge).toMatchObject({
- datasets: [
+ sets: [
{
- id: 'dataset-1',
+ id: 'support',
name: 'Product Docs',
description: 'Docs corpus',
+ datasets: [
+ {
+ id: 'dataset-1',
+ name: 'Product Docs',
+ description: 'Docs corpus',
+ },
+ ],
+ query: {
+ mode: 'user_query',
+ value: 'release notes',
+ },
+ retrieval: {
+ mode: 'multiple',
+ top_k: 8,
+ score_threshold: 0.72,
+ reranking_enable: false,
+ },
},
],
- query_config: {
- query: 'release notes',
- score_threshold: 0.72,
- score_threshold_enabled: true,
- top_k: 8,
- },
- query_mode: 'user_query',
})
expect(publishConfig.env).toMatchObject({
variables: [
@@ -285,21 +360,232 @@ describe('agent composer store conversions', () => {
})
})
- it('should not hydrate a knowledge retrieval row when the config has no datasets', () => {
+ it('should not hydrate a knowledge retrieval row when the config has no sets', () => {
const formState = agentSoulConfigToFormState({
knowledge: {
- datasets: [],
- query_config: {
- top_k: 4,
- },
- query_mode: 'generated_query',
+ sets: [],
},
})
expect(formState.knowledgeRetrievals).toEqual([])
})
- it('should omit incomplete environment variables from the publish payload', () => {
+ it('should keep explicitly cleared selected datasets instead of falling back to dataset refs', () => {
+ const publishConfig = formStateToAgentSoulConfig({
+ formState: {
+ ...defaultAgentSoulConfigFormState,
+ knowledgeRetrievals: [
+ {
+ id: 'retrieval-1',
+ name: 'Docs Search',
+ selectedDatasets: [],
+ datasetRefs: [
+ {
+ id: 'dataset-stale',
+ name: 'Stale Docs',
+ description: 'Should stay cleared',
+ },
+ ],
+ },
+ ],
+ },
+ })
+
+ expect(publishConfig.knowledge).toMatchObject({
+ sets: [
+ {
+ id: 'retrieval-1',
+ datasets: [],
+ },
+ ],
+ })
+ })
+
+ it('should round-trip single retrieval model config', () => {
+ const baseConfig: AgentSoulConfig = {
+ knowledge: {
+ sets: [
+ {
+ id: 'retrieval-1',
+ name: 'Docs Search',
+ datasets: [{ id: 'dataset-1', name: 'Docs' }],
+ query: { mode: 'generated_query' },
+ retrieval: {
+ mode: 'single',
+ model: {
+ provider: 'langgenius/openai/openai',
+ name: 'gpt-4.1',
+ mode: 'chat',
+ completion_params: { temperature: 0.1 },
+ },
+ },
+ },
+ ],
+ },
+ }
+
+ const formState = agentSoulConfigToFormState(baseConfig)
+ const publishConfig = formStateToAgentSoulConfig({ baseConfig, formState })
+
+ expect(formState.knowledgeRetrievals).toEqual([
+ expect.objectContaining({
+ id: 'retrieval-1',
+ retrievalMode: 'single',
+ singleRetrievalConfig: {
+ model: {
+ provider: 'langgenius/openai/openai',
+ name: 'gpt-4.1',
+ mode: 'chat',
+ completion_params: { temperature: 0.1 },
+ },
+ },
+ }),
+ ])
+ expect(publishConfig.knowledge).toMatchObject({
+ sets: [
+ {
+ id: 'retrieval-1',
+ retrieval: {
+ mode: 'single',
+ model: {
+ provider: 'langgenius/openai/openai',
+ name: 'gpt-4.1',
+ mode: 'chat',
+ completion_params: { temperature: 0.1 },
+ },
+ },
+ },
+ ],
+ })
+ })
+
+ it('should round-trip automatic metadata filtering model config', () => {
+ const baseConfig: AgentSoulConfig = {
+ knowledge: {
+ sets: [
+ {
+ id: 'retrieval-1',
+ name: 'Docs Search',
+ datasets: [{ id: 'dataset-1', name: 'Docs' }],
+ query: { mode: 'generated_query' },
+ retrieval: { mode: 'multiple', top_k: 4 },
+ metadata_filtering: {
+ mode: 'automatic',
+ model_config: {
+ provider: 'langgenius/openai/openai',
+ name: 'gpt-4.1-mini',
+ mode: 'chat',
+ completion_params: { temperature: 0.2 },
+ },
+ },
+ },
+ ],
+ },
+ }
+
+ const formState = agentSoulConfigToFormState(baseConfig)
+ const publishConfig = formStateToAgentSoulConfig({ baseConfig, formState })
+
+ expect(formState.knowledgeRetrievals).toEqual([
+ expect.objectContaining({
+ id: 'retrieval-1',
+ metadataFilterMode: 'automatic',
+ metadataModelConfig: {
+ provider: 'langgenius/openai/openai',
+ name: 'gpt-4.1-mini',
+ mode: 'chat',
+ completion_params: { temperature: 0.2 },
+ },
+ }),
+ ])
+ expect(publishConfig.knowledge).toMatchObject({
+ sets: [
+ {
+ id: 'retrieval-1',
+ metadata_filtering: {
+ mode: 'automatic',
+ model_config: {
+ provider: 'langgenius/openai/openai',
+ name: 'gpt-4.1-mini',
+ mode: 'chat',
+ completion_params: { temperature: 0.2 },
+ },
+ },
+ },
+ ],
+ })
+ })
+
+ it('should round-trip manual metadata filtering conditions', () => {
+ const baseConfig: AgentSoulConfig = {
+ knowledge: {
+ sets: [
+ {
+ id: 'retrieval-1',
+ name: 'Docs Search',
+ datasets: [{ id: 'dataset-1', name: 'Docs' }],
+ query: { mode: 'generated_query' },
+ retrieval: { mode: 'multiple', top_k: 4 },
+ metadata_filtering: {
+ mode: 'manual',
+ conditions: {
+ logical_operator: 'and',
+ conditions: [
+ {
+ name: 'language',
+ comparison_operator: 'is',
+ value: 'en',
+ },
+ ],
+ },
+ },
+ },
+ ],
+ },
+ }
+
+ const formState = agentSoulConfigToFormState(baseConfig)
+ const publishConfig = formStateToAgentSoulConfig({ baseConfig, formState })
+
+ expect(formState.knowledgeRetrievals).toEqual([
+ expect.objectContaining({
+ id: 'retrieval-1',
+ metadataFilterMode: 'manual',
+ metadataFilteringConditions: {
+ logical_operator: 'and',
+ conditions: [
+ {
+ name: 'language',
+ comparison_operator: 'is',
+ value: 'en',
+ },
+ ],
+ },
+ }),
+ ])
+ expect(publishConfig.knowledge).toMatchObject({
+ sets: [
+ {
+ id: 'retrieval-1',
+ metadata_filtering: {
+ mode: 'manual',
+ conditions: {
+ logical_operator: 'and',
+ conditions: [
+ {
+ name: 'language',
+ comparison_operator: 'is',
+ value: 'en',
+ },
+ ],
+ },
+ },
+ },
+ ],
+ })
+ })
+
+ it('should omit incomplete environment variables from the config snapshot', () => {
const publishConfig = formStateToAgentSoulConfig({
formState: {
...defaultAgentSoulConfigFormState,
diff --git a/web/features/agent-v2/agent-composer/conversions.ts b/web/features/agent-v2/agent-composer/conversions.ts
index e9d0fe9fecd..6aa2339730b 100644
--- a/web/features/agent-v2/agent-composer/conversions.ts
+++ b/web/features/agent-v2/agent-composer/conversions.ts
@@ -1,88 +1,174 @@
-import type { AgentSoulConfig } from '@dify/contracts/api/console/agent/types.gen'
+import type {
+ AgentKnowledgeMetadataConditions,
+ AgentKnowledgeModelConfig,
+ AgentKnowledgeRetrievalConfig,
+ AgentKnowledgeSetConfig,
+ AgentSoulConfig,
+} from '@dify/contracts/api/console/agent/types.gen'
import type {
AgentCliTool,
+ AgentFileNode,
AgentKnowledgeRetrievalItem,
AgentProviderTool,
+ AgentSkill,
AgentSoulConfigFormState,
AgentTool,
EnvVariable,
} from './form-state'
import type { DefaultModel } from '@/app/components/header/account-setting/model-provider-page/declarations'
+import type {
+ MetadataFilteringConditions,
+ MultipleRetrievalConfig,
+ SingleRetrievalConfig,
+} from '@/app/components/workflow/nodes/knowledge-retrieval/types'
+import type { ModelConfig } from '@/app/components/workflow/types'
+import { MetadataFilteringModeEnum } from '@/app/components/workflow/nodes/knowledge-retrieval/types'
+import { DATASET_DEFAULT } from '@/config'
+import { RETRIEVE_TYPE } from '@/types/app'
import { checkKey } from '@/utils/var'
import { defaultAgentSoulConfigFormState } from './form-state'
+import { getKnowledgeRetrievalSetName } from './knowledge-validation'
+
+type AgentSoulFileRefConfig = {
+ id?: string | null
+ file_id?: string | null
+ name?: string | null
+ type?: string | null
+ drive_key?: string | null
+}
+
+type AgentSoulSkillRefConfig = {
+ id?: string | null
+ name?: string | null
+ description?: string | null
+ path?: string | null
+ skill_md_key?: string | null
+ full_archive_key?: string | null
+}
+
+type AgentSoulFilesConfig = {
+ skills?: AgentSoulSkillRefConfig[]
+ files?: AgentSoulFileRefConfig[]
+}
+
+export type AgentSoulConfigWithFiles = AgentSoulConfig & {
+ files?: AgentSoulFilesConfig
+}
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 AgentSoulEnvVariableConfig = NonNullable<NonNullable<AgentSoulConfig['env']>['variables']>[number]
-const getKnowledgeRetrievalName = (item: AgentKnowledgeRetrievalItem) => item.name ?? item.nameKey ?? item.id
-
-const toKnowledgeDatasets = (knowledgeRetrievals: AgentKnowledgeRetrievalItem[]) => knowledgeRetrievals.flatMap((item) => {
- if (item.selectedDatasets?.length) {
+const toKnowledgeDatasetRefs = (item: AgentKnowledgeRetrievalItem) => {
+ if (item.selectedDatasets !== undefined) {
return item.selectedDatasets.map(dataset => ({
description: dataset.description,
id: dataset.id,
name: dataset.name,
}))
}
- if (item.datasetRefs?.length)
- return item.datasetRefs
- return [{
- id: item.id,
- name: getKnowledgeRetrievalName(item),
- }]
-})
+ return item.datasetRefs ?? []
+}
-const toKnowledgeRetrievalFormState = (config?: AgentSoulConfig): AgentKnowledgeRetrievalItem[] => {
- const knowledge = config?.knowledge
- const datasets = knowledge?.datasets ?? []
+const toRetrievalConfig = (item: AgentKnowledgeRetrievalItem): AgentKnowledgeRetrievalConfig => {
+ if (item.retrievalMode === RETRIEVE_TYPE.oneWay) {
+ return {
+ mode: 'single',
+ model: item.singleRetrievalConfig?.model,
+ }
+ }
- if (datasets.length === 0)
- return []
+ const config = item.multipleRetrievalConfig
+ return {
+ mode: 'multiple',
+ top_k: config?.top_k ?? DATASET_DEFAULT.top_k,
+ score_threshold: config?.score_threshold ?? undefined,
+ reranking_mode: config?.reranking_mode,
+ reranking_enable: config?.reranking_enable ?? false,
+ reranking_model: config?.reranking_model,
+ weights: config?.weights,
+ }
+}
- return [{
- id: datasets[0]?.id ?? 'knowledge-retrieval',
- name: datasets[0]?.name ?? 'Knowledge Retrieval',
- queryMode: knowledge?.query_mode === 'user_query' ? 'custom' : 'agent',
- customQuery: knowledge?.query_config?.query ?? undefined,
- datasetRefs: datasets,
- multipleRetrievalConfig: {
- top_k: knowledge?.query_config?.top_k ?? 4,
- score_threshold: knowledge?.query_config?.score_threshold ?? null,
- reranking_enable: false,
- },
- }]
+const toModelFormState = (model?: AgentKnowledgeModelConfig | null): ModelConfig | undefined => {
+ if (!model)
+ return undefined
+
+ return {
+ provider: model.provider,
+ name: model.name,
+ mode: model.mode,
+ completion_params: model.completion_params ?? {},
+ }
}
-const toKnowledgeConfig = (
- baseKnowledge: AgentSoulConfig['knowledge'],
- knowledgeRetrievals: AgentKnowledgeRetrievalItem[],
-): AgentSoulConfig['knowledge'] => {
- const primaryRetrieval = knowledgeRetrievals.find(retrieval =>
- retrieval.queryMode === 'custom'
- || retrieval.customQuery
- || retrieval.multipleRetrievalConfig
- || retrieval.selectedDatasets?.length,
- ) ?? knowledgeRetrievals[0]
- const multipleRetrievalConfig = primaryRetrieval?.multipleRetrievalConfig
- const scoreThreshold = multipleRetrievalConfig?.score_threshold
+const toMultipleRetrievalFormState = (config?: AgentKnowledgeRetrievalConfig): MultipleRetrievalConfig => ({
+ top_k: config?.top_k ?? DATASET_DEFAULT.top_k,
+ score_threshold: config?.score_threshold ?? null,
+ reranking_model: config?.reranking_model ?? undefined,
+ reranking_mode: config?.reranking_mode as MultipleRetrievalConfig['reranking_mode'],
+ weights: config?.weights as MultipleRetrievalConfig['weights'],
+ reranking_enable: config?.reranking_enable ?? false,
+})
+
+const toSingleRetrievalFormState = (config?: AgentKnowledgeRetrievalConfig): SingleRetrievalConfig | undefined => (
+ config?.model
+ ? {
+ model: toModelFormState(config.model)!,
+ }
+ : undefined
+)
+
+const toMetadataFilteringConfig = (item: AgentKnowledgeRetrievalItem): AgentKnowledgeSetConfig['metadata_filtering'] => {
+ const mode = item.metadataFilterMode ?? MetadataFilteringModeEnum.disabled
return {
- ...baseKnowledge,
- datasets: toKnowledgeDatasets(knowledgeRetrievals),
- query_mode: primaryRetrieval?.queryMode === 'custom' ? 'user_query' : 'generated_query',
- query_config: {
- ...baseKnowledge?.query_config,
- query: primaryRetrieval?.queryMode === 'custom' ? primaryRetrieval.customQuery : null,
- score_threshold: scoreThreshold,
- score_threshold_enabled: scoreThreshold !== undefined && scoreThreshold !== null,
- top_k: multipleRetrievalConfig?.top_k ?? baseKnowledge?.query_config?.top_k,
- },
+ mode,
+ model_config: mode === MetadataFilteringModeEnum.automatic ? item.metadataModelConfig : undefined,
+ conditions: mode === MetadataFilteringModeEnum.manual
+ ? item.metadataFilteringConditions as AgentKnowledgeMetadataConditions | undefined
+ : undefined,
}
}
+const toKnowledgeSets = (knowledgeRetrievals: AgentKnowledgeRetrievalItem[]): AgentKnowledgeSetConfig[] => knowledgeRetrievals.map(item => ({
+ id: item.id,
+ name: getKnowledgeRetrievalSetName(item),
+ description: item.description,
+ datasets: toKnowledgeDatasetRefs(item),
+ query: {
+ mode: item.queryMode === 'custom' ? ('user_query' as const) : ('generated_query' as const),
+ value: item.queryMode === 'custom' ? (item.customQuery?.trim() || undefined) : undefined,
+ },
+ retrieval: toRetrievalConfig(item),
+ metadata_filtering: toMetadataFilteringConfig(item),
+}))
+
+const toKnowledgeRetrievalFormState = (config?: AgentSoulConfig): AgentKnowledgeRetrievalItem[] => {
+ return (config?.knowledge?.sets ?? []).map(knowledgeSet => ({
+ id: knowledgeSet.id,
+ name: knowledgeSet.name,
+ description: knowledgeSet.description ?? undefined,
+ queryMode: knowledgeSet.query.mode === 'user_query' ? 'custom' : 'agent',
+ customQuery: knowledgeSet.query.value ?? undefined,
+ datasetRefs: knowledgeSet.datasets,
+ retrievalMode: knowledgeSet.retrieval.mode === 'single' ? RETRIEVE_TYPE.oneWay : RETRIEVE_TYPE.multiWay,
+ multipleRetrievalConfig: toMultipleRetrievalFormState(knowledgeSet.retrieval),
+ singleRetrievalConfig: toSingleRetrievalFormState(knowledgeSet.retrieval),
+ metadataFilterMode: (knowledgeSet.metadata_filtering?.mode ?? MetadataFilteringModeEnum.disabled) as MetadataFilteringModeEnum,
+ metadataFilteringConditions: knowledgeSet.metadata_filtering?.conditions as MetadataFilteringConditions | undefined,
+ metadataModelConfig: toModelFormState(knowledgeSet.metadata_filtering?.model_config),
+ }))
+}
+
+const toKnowledgeConfig = (
+ knowledgeRetrievals: AgentKnowledgeRetrievalItem[],
+): AgentSoulConfig['knowledge'] => ({
+ sets: toKnowledgeSets(knowledgeRetrievals),
+})
+
const isToolRuntimeParameterValue = (value: unknown): value is AgentSoulToolRuntimeParameterValue => {
if (value === null || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean')
return true
@@ -338,6 +424,79 @@ const toEnvConfig = (variables: EnvVariable[]): AgentSoulConfig['env'] => ({
})),
})
+const toSkillConfigs = (skills: AgentSkill[]): AgentSoulSkillRefConfig[] => skills.map(skill => ({
+ id: skill.path ?? skill.id,
+ name: skill.name,
+ description: skill.description,
+ path: skill.path,
+ skill_md_key: skill.skillMdKey,
+ full_archive_key: skill.archiveKey,
+}))
+
+const toFileConfigs = (files: AgentFileNode[]): AgentSoulFileRefConfig[] => files.flatMap((file) => {
+ if (file.children?.length)
+ return toFileConfigs(file.children)
+
+ return [{
+ id: file.id,
+ file_id: file.fileId,
+ name: file.name,
+ drive_key: file.driveKey,
+ }]
+})
+
+const toFilesConfig = (formState: AgentSoulConfigFormState): AgentSoulFilesConfig => ({
+ skills: toSkillConfigs(formState.skills),
+ files: toFileConfigs(formState.files),
+})
+
+const getAgentFileName = (file: AgentSoulFileRefConfig) => {
+ if (file.name)
+ return file.name
+
+ const driveKey = file.drive_key ?? file.id ?? file.file_id ?? ''
+ return driveKey.split('/').pop() || driveKey
+}
+
+const toSkillFormState = (config?: AgentSoulConfig): AgentSkill[] => {
+ const filesConfig = (config as AgentSoulConfigWithFiles | undefined)?.files
+
+ return (filesConfig?.skills ?? []).flatMap((skill) => {
+ const id = skill.skill_md_key ?? skill.path ?? skill.id
+ const name = skill.name ?? skill.path ?? id
+ if (!id || !name)
+ return []
+
+ return [{
+ id,
+ name,
+ description: skill.description ?? undefined,
+ path: skill.path ?? undefined,
+ skillMdKey: skill.skill_md_key ?? undefined,
+ archiveKey: skill.full_archive_key ?? undefined,
+ }]
+ })
+}
+
+const toFileFormState = (config?: AgentSoulConfig): AgentFileNode[] => {
+ const filesConfig = (config as AgentSoulConfigWithFiles | undefined)?.files
+
+ return (filesConfig?.files ?? []).flatMap((file) => {
+ const id = file.drive_key ?? file.file_id ?? file.id
+ const name = getAgentFileName(file)
+ if (!id || !name)
+ return []
+
+ return [{
+ id,
+ name,
+ icon: 'file' as const,
+ fileId: file.file_id ?? undefined,
+ driveKey: file.drive_key ?? undefined,
+ }]
+ })
+}
+
const toDraftModel = (config?: AgentSoulConfig): DefaultModel | undefined => {
const modelProvider = config?.model?.model_provider
const model = config?.model?.model
@@ -375,7 +534,7 @@ export const formStateToAgentSoulConfig = ({
baseConfig?: AgentSoulConfig
formState: AgentSoulConfigFormState
currentModel?: DefaultModel
-}): AgentSoulConfig => {
+}): AgentSoulConfigWithFiles => {
return {
...baseConfig,
prompt: {
@@ -396,8 +555,9 @@ export const formStateToAgentSoulConfig = ({
cli_tools: toCliToolConfigs(formState.tools),
},
app_features: formState.appFeatures ?? baseConfig?.app_features,
- knowledge: toKnowledgeConfig(baseConfig?.knowledge, formState.knowledgeRetrievals),
+ knowledge: toKnowledgeConfig(formState.knowledgeRetrievals),
env: toEnvConfig(formState.envVariables),
+ files: toFilesConfig(formState),
}
}
@@ -412,6 +572,8 @@ 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.ts
index 80429d8be84..42598a0d214 100644
--- a/web/features/agent-v2/agent-composer/form-state.ts
+++ b/web/features/agent-v2/agent-composer/form-state.ts
@@ -6,6 +6,7 @@ import type {
MetadataFilteringConditions,
MetadataFilteringModeEnum,
MultipleRetrievalConfig,
+ SingleRetrievalConfig,
} from '@/app/components/workflow/nodes/knowledge-retrieval/types'
import type { ModelConfig } from '@/app/components/workflow/types'
import type { DataSet } from '@/models/datasets'
@@ -35,6 +36,7 @@ export type AgentFileNode = {
id: string
name: string
icon: FileTreeIconType
+ fileId?: string
driveKey?: string
children?: AgentFileNode[]
}
@@ -42,6 +44,7 @@ export type AgentFileNode = {
export type AgentKnowledgeRetrievalItem = {
id: string
name?: string
+ description?: string
nameKey?: I18nKeysWithPrefix<'agentV2', 'agentDetail.configure.knowledgeRetrieval.'>
queryMode?: 'agent' | 'custom'
customQuery?: string
@@ -49,6 +52,7 @@ export type AgentKnowledgeRetrievalItem = {
selectedDatasets?: DataSet[]
retrievalMode?: RETRIEVE_TYPE
multipleRetrievalConfig?: MultipleRetrievalConfig
+ singleRetrievalConfig?: SingleRetrievalConfig
metadataFilterMode?: MetadataFilteringModeEnum
metadataFilteringConditions?: MetadataFilteringConditions
metadataModelConfig?: ModelConfig
@@ -96,6 +100,8 @@ export type AgentSoulConfigFormState = {
prompt: string
model?: DefaultModel
appFeatures?: AgentSoulAppFeaturesConfig
+ skills: AgentSkill[]
+ files: AgentFileNode[]
tools: AgentTool[]
knowledgeRetrievals: AgentKnowledgeRetrievalItem[]
envVariables: EnvVariable[]
@@ -104,6 +110,8 @@ export type AgentSoulConfigFormState = {
export const defaultAgentSoulConfigFormState: AgentSoulConfigFormState = {
prompt: '',
+ skills: [],
+ files: [],
tools: [],
knowledgeRetrievals: [],
envVariables: [],
diff --git a/web/features/agent-v2/agent-composer/knowledge-validation.ts b/web/features/agent-v2/agent-composer/knowledge-validation.ts
new file mode 100644
index 00000000000..3d2c89c4318
--- /dev/null
+++ b/web/features/agent-v2/agent-composer/knowledge-validation.ts
@@ -0,0 +1,175 @@
+import type { AgentKnowledgeRetrievalItem } from './form-state'
+import { useTranslation } from 'react-i18next'
+import { MetadataFilteringModeEnum } from '@/app/components/workflow/nodes/knowledge-retrieval/types'
+import { RETRIEVE_TYPE } from '@/types/app'
+
+export type KnowledgeValidationIssueCode
+ = | 'name_required'
+ | 'name_duplicate'
+ | 'datasets_required'
+ | 'custom_query_required'
+ | 'single_model_required'
+ | 'metadata_model_required'
+ | 'metadata_conditions_required'
+
+type KnowledgeValidationField = 'name' | 'datasets' | 'query' | 'retrieval' | 'metadata'
+
+type KnowledgeValidationIssue = {
+ itemId: string
+ code: KnowledgeValidationIssueCode
+ field: KnowledgeValidationField
+}
+
+export type KnowledgeValidationResult = {
+ byId: Record<string, Partial<Record<KnowledgeValidationField, KnowledgeValidationIssueCode>>>
+ firstIssue?: KnowledgeValidationIssue
+ isValid: boolean
+}
+
+const getKnowledgeRetrievalConcreteName = (item: AgentKnowledgeRetrievalItem) => item.name?.trim() ?? ''
+
+export const getKnowledgeRetrievalSetName = (item: AgentKnowledgeRetrievalItem) =>
+ getKnowledgeRetrievalConcreteName(item) || item.id
+
+export const useKnowledgeValidationMessage = () => {
+ const { t } = useTranslation('agentV2')
+ const { t: tCommon } = useTranslation('common')
+ const { t: tAppDebug } = useTranslation('appDebug')
+ const { t: tWorkflow } = useTranslation('workflow')
+
+ return (issueCode?: KnowledgeValidationIssueCode) => {
+ switch (issueCode) {
+ case 'name_required':
+ return tCommon('errorMsg.fieldRequired', {
+ field: t('agentDetail.configure.knowledgeRetrieval.dialog.nameLabel'),
+ })
+ case 'name_duplicate':
+ return tAppDebug('varKeyError.keyAlreadyExists', {
+ key: t('agentDetail.configure.knowledgeRetrieval.dialog.nameLabel'),
+ })
+ case 'datasets_required':
+ return tCommon('errorMsg.fieldRequired', {
+ field: t('agentDetail.configure.knowledgeRetrieval.dialog.knowledge.label'),
+ })
+ case 'custom_query_required':
+ return tCommon('errorMsg.fieldRequired', {
+ field: t('agentDetail.configure.knowledgeRetrieval.dialog.query.customInputLabel'),
+ })
+ case 'single_model_required':
+ case 'metadata_model_required':
+ return tCommon('errorMsg.fieldRequired', {
+ field: tCommon('modelProvider.systemReasoningModel.key'),
+ })
+ case 'metadata_conditions_required':
+ return tCommon('errorMsg.fieldRequired', {
+ field: tWorkflow('nodes.knowledgeRetrieval.metadata.panel.conditions'),
+ })
+ default:
+ return undefined
+ }
+ }
+}
+
+const getKnowledgeDatasetCount = (item: AgentKnowledgeRetrievalItem) =>
+ item.selectedDatasets?.length ?? item.datasetRefs?.length ?? 0
+
+const getNormalizedKnowledgeName = (item: AgentKnowledgeRetrievalItem) => getKnowledgeRetrievalConcreteName(item).toLowerCase()
+
+export const validateKnowledgeRetrievals = (
+ retrievals: AgentKnowledgeRetrievalItem[],
+): KnowledgeValidationResult => {
+ const byId: KnowledgeValidationResult['byId'] = {}
+ const issues: KnowledgeValidationIssue[] = []
+ const nameCounts = new Map<string, number>()
+
+ retrievals.forEach((item) => {
+ const normalizedName = getNormalizedKnowledgeName(item)
+ if (!normalizedName)
+ return
+
+ nameCounts.set(normalizedName, (nameCounts.get(normalizedName) ?? 0) + 1)
+ })
+
+ const pushIssue = (issue: KnowledgeValidationIssue) => {
+ byId[issue.itemId] ??= {}
+ const itemIssues = byId[issue.itemId]
+ if (itemIssues)
+ itemIssues[issue.field] ??= issue.code
+ issues.push(issue)
+ }
+
+ retrievals.forEach((item) => {
+ const setName = getKnowledgeRetrievalConcreteName(item)
+ const normalizedName = setName.toLowerCase()
+
+ if (!setName) {
+ pushIssue({
+ itemId: item.id,
+ code: 'name_required',
+ field: 'name',
+ })
+ }
+ else if ((nameCounts.get(normalizedName) ?? 0) > 1) {
+ pushIssue({
+ itemId: item.id,
+ code: 'name_duplicate',
+ field: 'name',
+ })
+ }
+
+ if (!getKnowledgeDatasetCount(item)) {
+ pushIssue({
+ itemId: item.id,
+ code: 'datasets_required',
+ field: 'datasets',
+ })
+ }
+
+ if (item.queryMode === 'custom' && !item.customQuery?.trim()) {
+ pushIssue({
+ itemId: item.id,
+ code: 'custom_query_required',
+ field: 'query',
+ })
+ }
+
+ if (
+ item.retrievalMode === RETRIEVE_TYPE.oneWay
+ && (!item.singleRetrievalConfig?.model?.provider || !item.singleRetrievalConfig.model.name)
+ ) {
+ pushIssue({
+ itemId: item.id,
+ code: 'single_model_required',
+ field: 'retrieval',
+ })
+ }
+
+ if (
+ item.metadataFilterMode === MetadataFilteringModeEnum.automatic
+ && (!item.metadataModelConfig?.provider || !item.metadataModelConfig.name)
+ ) {
+ pushIssue({
+ itemId: item.id,
+ code: 'metadata_model_required',
+ field: 'metadata',
+ })
+ }
+
+ if (
+ item.metadataFilterMode === MetadataFilteringModeEnum.manual
+ && !item.metadataFilteringConditions?.conditions.length
+ ) {
+ pushIssue({
+ itemId: item.id,
+ code: 'metadata_conditions_required',
+ field: 'metadata',
+ })
+ }
+ })
+
+ return {
+ byId,
+ firstIssue: issues[0],
+ isValid: issues.length === 0,
+ }
+}
diff --git a/web/features/agent-v2/agent-composer/provider.tsx b/web/features/agent-v2/agent-composer/provider.tsx
index 189d828b45e..e5c5fdec5f7 100644
--- a/web/features/agent-v2/agent-composer/provider.tsx
+++ b/web/features/agent-v2/agent-composer/provider.tsx
@@ -1,18 +1,34 @@
'use client'
+import type { AgentSoulConfig } from '@dify/contracts/api/console/agent/types.gen'
import type { ReactNode } from 'react'
import type { AgentSoulConfigFormState } from './form-state'
import { createStore, Provider as JotaiProvider } from 'jotai'
import { useRef } from 'react'
-import { agentComposerDraftAtom, agentComposerOriginalDraftAtom } from './store'
+import {
+ agentComposerDraftAtom,
+ agentComposerOriginalConfigAtom,
+ agentComposerOriginalDraftAtom,
+ agentComposerPublishedDraftAtom,
+} from './store'
-function createAgentComposerStore(initialDraft?: AgentSoulConfigFormState) {
+function createAgentComposerStore({
+ initialDraft,
+ initialOriginalConfig,
+}: {
+ initialDraft?: AgentSoulConfigFormState
+ initialOriginalConfig?: AgentSoulConfig
+}) {
const store = createStore()
+ if (initialOriginalConfig)
+ store.set(agentComposerOriginalConfigAtom, initialOriginalConfig)
if (initialDraft)
store.set(agentComposerDraftAtom, initialDraft)
if (initialDraft)
store.set(agentComposerOriginalDraftAtom, initialDraft)
+ if (initialDraft)
+ store.set(agentComposerPublishedDraftAtom, initialDraft)
return store
}
@@ -20,13 +36,19 @@ function createAgentComposerStore(initialDraft?: AgentSoulConfigFormState) {
export function AgentComposerProvider({
children,
initialDraft,
+ initialOriginalConfig,
}: {
children: ReactNode
initialDraft?: AgentSoulConfigFormState
+ initialOriginalConfig?: AgentSoulConfig
}) {
const storeRef = useRef<ReturnType<typeof createAgentComposerStore> | null>(null)
- if (!storeRef.current)
- storeRef.current = createAgentComposerStore(initialDraft)
+ if (!storeRef.current) {
+ storeRef.current = createAgentComposerStore({
+ initialDraft,
+ initialOriginalConfig,
+ })
+ }
const store = storeRef.current
return (
diff --git a/web/features/agent-v2/agent-composer/reference-labels.ts b/web/features/agent-v2/agent-composer/reference-labels.ts
index 25eaa9c7063..0616129fd7c 100644
--- a/web/features/agent-v2/agent-composer/reference-labels.ts
+++ b/web/features/agent-v2/agent-composer/reference-labels.ts
@@ -1,4 +1,4 @@
-import type { AgentKnowledgeRetrievalItem, AgentTool } from './form-state'
+import type { AgentFileNode, AgentKnowledgeRetrievalItem, AgentSkill, AgentTool } from './form-state'
const getKnowledgeRetrievalName = (item: AgentKnowledgeRetrievalItem) => item.name ?? item.nameKey ?? item.id
@@ -73,3 +73,37 @@ export const syncCliToolReferenceLabels = ({
currentItems: toReferenceLabelItems(currentTools.filter(tool => tool.kind === 'cli'), tool => tool.name),
nextItems: toReferenceLabelItems(nextTools.filter(tool => tool.kind === 'cli'), tool => tool.name),
})
+
+export const syncSkillReferenceLabels = ({
+ prompt,
+ currentSkills,
+ nextSkills,
+}: {
+ prompt: string
+ currentSkills: AgentSkill[]
+ nextSkills: AgentSkill[]
+}) => syncReferenceLabels({
+ prompt,
+ kind: 'skill',
+ currentItems: toReferenceLabelItems(currentSkills, skill => skill.name),
+ nextItems: toReferenceLabelItems(nextSkills, skill => skill.name),
+})
+
+const flattenFileNodes = (files: AgentFileNode[]): AgentFileNode[] => files.flatMap(file => (
+ file.children?.length ? flattenFileNodes(file.children) : [file]
+))
+
+export const syncFileReferenceLabels = ({
+ prompt,
+ currentFiles,
+ nextFiles,
+}: {
+ prompt: string
+ currentFiles: AgentFileNode[]
+ nextFiles: AgentFileNode[]
+}) => syncReferenceLabels({
+ prompt,
+ kind: 'file',
+ currentItems: toReferenceLabelItems(flattenFileNodes(currentFiles), file => file.name),
+ nextItems: toReferenceLabelItems(flattenFileNodes(nextFiles), file => file.name),
+})
diff --git a/web/features/agent-v2/agent-composer/store-modules/files.ts b/web/features/agent-v2/agent-composer/store-modules/files.ts
new file mode 100644
index 00000000000..e686116a8ff
--- /dev/null
+++ b/web/features/agent-v2/agent-composer/store-modules/files.ts
@@ -0,0 +1,24 @@
+import type { AgentFileNode } from '../form-state'
+import type { DraftFieldUpdate } from './utils'
+import { atom } from 'jotai'
+import { syncFileReferenceLabels } from '../reference-labels'
+import { agentComposerDraftAtom } from '../store'
+import { resolveDraftFieldUpdate } from './utils'
+
+export const agentComposerFilesAtom = atom<AgentFileNode[], [DraftFieldUpdate<AgentFileNode[]>], void>(
+ get => get(agentComposerDraftAtom).files,
+ (get, set, filesUpdate: DraftFieldUpdate<AgentFileNode[]>) => {
+ const draft = get(agentComposerDraftAtom)
+ const files = resolveDraftFieldUpdate(draft.files, filesUpdate)
+
+ set(agentComposerDraftAtom, {
+ ...draft,
+ prompt: syncFileReferenceLabels({
+ prompt: draft.prompt,
+ currentFiles: draft.files,
+ nextFiles: files,
+ }),
+ files,
+ })
+ },
+)
diff --git a/web/features/agent-v2/agent-composer/store-modules/skills.ts b/web/features/agent-v2/agent-composer/store-modules/skills.ts
new file mode 100644
index 00000000000..2fa8bd47740
--- /dev/null
+++ b/web/features/agent-v2/agent-composer/store-modules/skills.ts
@@ -0,0 +1,24 @@
+import type { AgentSkill } from '../form-state'
+import type { DraftFieldUpdate } from './utils'
+import { atom } from 'jotai'
+import { syncSkillReferenceLabels } from '../reference-labels'
+import { agentComposerDraftAtom } from '../store'
+import { resolveDraftFieldUpdate } from './utils'
+
+export const agentComposerSkillsAtom = atom<AgentSkill[], [DraftFieldUpdate<AgentSkill[]>], void>(
+ get => get(agentComposerDraftAtom).skills,
+ (get, set, skillsUpdate: DraftFieldUpdate<AgentSkill[]>) => {
+ const draft = get(agentComposerDraftAtom)
+ const skills = resolveDraftFieldUpdate(draft.skills, skillsUpdate)
+
+ set(agentComposerDraftAtom, {
+ ...draft,
+ prompt: syncSkillReferenceLabels({
+ prompt: draft.prompt,
+ currentSkills: draft.skills,
+ nextSkills: skills,
+ }),
+ skills,
+ })
+ },
+)
diff --git a/web/features/agent-v2/agent-composer/store.ts b/web/features/agent-v2/agent-composer/store.ts
index 446529ba556..66389542e3a 100644
--- a/web/features/agent-v2/agent-composer/store.ts
+++ b/web/features/agent-v2/agent-composer/store.ts
@@ -1,10 +1,7 @@
import type { AgentSoulConfig } from '@dify/contracts/api/console/agent/types.gen'
import type { AgentSoulConfigFormState } from './form-state'
-import type { DefaultModel } from '@/app/components/header/account-setting/model-provider-page/declarations'
import isEqual from 'fast-deep-equal'
-import { atom, useAtomValue, useSetAtom } from 'jotai'
-import { useEffect, useMemo, useRef } from 'react'
-import { agentSoulConfigToFormState, formStateToAgentSoulConfig } from './conversions'
+import { atom } from 'jotai'
import { defaultAgentSoulConfigFormState } from './form-state'
export const agentComposerOriginalConfigAtom = atom<AgentSoulConfig | undefined>(undefined)
@@ -19,114 +16,9 @@ export const isAgentComposerDirtyAtom = atom((get) => {
return !isEqual(draft, originalDraft ?? defaultAgentSoulConfigFormState)
})
-const hasAgentComposerUnpublishedChangesAtom = atom((get) => {
+export const hasAgentComposerUnpublishedChangesAtom = atom((get) => {
const publishedDraft = get(agentComposerPublishedDraftAtom)
const draft = get(agentComposerDraftAtom)
return !isEqual(draft, publishedDraft ?? defaultAgentSoulConfigFormState)
})
-
-function useHydrate({
- defaultDraft = defaultAgentSoulConfigFormState,
- instanceKey,
- draft,
- originalConfig,
- waitForDraft,
-}: {
- defaultDraft?: AgentSoulConfigFormState
- instanceKey: string
- draft?: AgentSoulConfigFormState
- originalConfig?: AgentSoulConfig
- waitForDraft?: boolean
-}) {
- const setOriginalDraft = useSetAtom(agentComposerOriginalDraftAtom)
- const setPublishedDraft = useSetAtom(agentComposerPublishedDraftAtom)
- const setOriginalConfig = useSetAtom(agentComposerOriginalConfigAtom)
- const setDraft = useSetAtom(agentComposerDraftAtom)
- const resetKeyRef = useRef<string | undefined>(undefined)
- const hydratedKeyRef = useRef<string | undefined>(undefined)
-
- useEffect(() => {
- if (resetKeyRef.current !== instanceKey) {
- resetKeyRef.current = instanceKey
- hydratedKeyRef.current = undefined
- setOriginalConfig(undefined)
- setOriginalDraft(defaultDraft)
- setPublishedDraft(defaultDraft)
- setDraft(defaultDraft)
- }
-
- if (waitForDraft && !draft)
- return
-
- if (hydratedKeyRef.current === instanceKey)
- return
-
- hydratedKeyRef.current = instanceKey
- setOriginalConfig(originalConfig)
- setOriginalDraft(draft ?? defaultDraft)
- setPublishedDraft(draft ?? defaultDraft)
- setDraft(draft ?? defaultDraft)
- }, [defaultDraft, draft, instanceKey, originalConfig, setDraft, setOriginalConfig, setOriginalDraft, setPublishedDraft, waitForDraft])
-}
-
-export function useHydrateAgentSoulConfigDraft({
- agentId,
- activeVersionId,
- baseDraft = defaultAgentSoulConfigFormState,
- config,
-}: {
- agentId: string
- activeVersionId?: string | null
- baseDraft?: AgentSoulConfigFormState
- config?: AgentSoulConfig
-}) {
- const routeKey = `${agentId}:${activeVersionId ?? 'draft'}`
- useHydrate({
- defaultDraft: baseDraft,
- instanceKey: routeKey,
- draft: agentSoulConfigToFormState(config, baseDraft),
- originalConfig: config,
- waitForDraft: !!activeVersionId && !config,
- })
-}
-
-export function useHasAgentComposerUnpublishedChanges() {
- return useAtomValue(hasAgentComposerUnpublishedChangesAtom)
-}
-
-export function useAgentComposerConfigSnapshot({
- baseConfig,
- currentModel,
-}: {
- baseConfig?: AgentSoulConfig
- currentModel?: DefaultModel
-}) {
- const draft = useAtomValue(agentComposerDraftAtom)
-
- return useMemo(() => formStateToAgentSoulConfig({
- baseConfig,
- formState: draft,
- currentModel,
- }), [baseConfig, currentModel, draft])
-}
-
-export function useConfigPublishPayload({
- agentId,
- baseConfig,
- currentModel,
-}: {
- agentId: string
- baseConfig?: AgentSoulConfig
- currentModel?: DefaultModel
-}) {
- const configSnapshot = useAgentComposerConfigSnapshot({
- baseConfig,
- currentModel,
- })
-
- return useMemo(() => ({
- agent_id: agentId,
- config_snapshot: configSnapshot,
- }), [agentId, configSnapshot])
-}
diff --git a/web/features/agent-v2/agent-detail/access/components/__tests__/access-surface-card.spec.tsx b/web/features/agent-v2/agent-detail/access/components/__tests__/access-surface-card.spec.tsx
new file mode 100644
index 00000000000..d7b95a5aa84
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/access/components/__tests__/access-surface-card.spec.tsx
@@ -0,0 +1,68 @@
+import { render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { AccessSurfaceCard } from '../access-surface-card'
+
+const mockCopy = vi.fn()
+let mockCopied = false
+
+vi.mock('foxact/use-clipboard', () => ({
+ useClipboard: () => ({
+ copied: mockCopied,
+ copy: mockCopy,
+ }),
+}))
+
+vi.mock('@langgenius/dify-ui/toast', () => ({
+ toast: {
+ error: vi.fn(),
+ },
+}))
+
+describe('AccessSurfaceCard', () => {
+ beforeEach(() => {
+ mockCopied = false
+ vi.clearAllMocks()
+ })
+
+ describe('Copy feedback', () => {
+ it('should copy the endpoint and render copied state from the clipboard hook', async () => {
+ const user = userEvent.setup()
+ const { rerender } = render(
+ <AccessSurfaceCard
+ title="Web app"
+ icon="i-ri-window-line"
+ iconClassName="bg-state-accent-solid"
+ endpointLabel="Access URL"
+ endpoint="https://chat.example.test/agent/token"
+ enabled
+ onEnabledChange={vi.fn()}
+ copyLabel="Copy access URL"
+ >
+ <button type="button">Action</button>
+ </AccessSurfaceCard>,
+ )
+
+ await user.click(screen.getByRole('button', { name: 'Copy access URL' }))
+
+ expect(mockCopy).toHaveBeenCalledWith('https://chat.example.test/agent/token')
+
+ mockCopied = true
+ rerender(
+ <AccessSurfaceCard
+ title="Web app"
+ icon="i-ri-window-line"
+ iconClassName="bg-state-accent-solid"
+ endpointLabel="Access URL"
+ endpoint="https://chat.example.test/agent/token"
+ enabled
+ onEnabledChange={vi.fn()}
+ copyLabel="Copy access URL"
+ >
+ <button type="button">Action</button>
+ </AccessSurfaceCard>,
+ )
+
+ expect(screen.getByRole('button', { name: 'common.operation.copied' })).toBeInTheDocument()
+ })
+ })
+})
diff --git a/web/features/agent-v2/agent-detail/access/components/__tests__/access-surface-cards.spec.tsx b/web/features/agent-v2/agent-detail/access/components/__tests__/access-surface-cards.spec.tsx
new file mode 100644
index 00000000000..5926dad56ca
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/access/components/__tests__/access-surface-cards.spec.tsx
@@ -0,0 +1,462 @@
+import type { AgentAppDetailWithSite } from '@dify/contracts/api/console/agent/types.gen'
+import type React from 'react'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { render, screen, waitFor, within } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { ServiceApiAccessCard } from '../service-api-access-card'
+import { WebAppAccessCard } from '../web-app-access-card'
+
+const mocks = vi.hoisted(() => ({
+ apiAccessQueryFn: vi.fn(),
+ apiKeysQueryFn: vi.fn(),
+ siteEnableMutation: vi.fn(),
+ siteMutation: vi.fn(),
+ siteAccessTokenResetMutation: vi.fn(),
+ apiEnableMutation: vi.fn(),
+ createApiKeyMutation: vi.fn(),
+ deleteApiKeyMutation: vi.fn(),
+}))
+
+vi.mock('@/context/i18n', () => ({
+ useDocLink: () => (path: string) => `https://docs.example.test${path}`,
+}))
+
+vi.mock('@langgenius/dify-ui/toast', () => ({
+ toast: {
+ error: vi.fn(),
+ success: vi.fn(),
+ },
+}))
+
+vi.mock('@/hooks/use-timestamp', () => ({
+ default: () => ({
+ formatTime: (value: number) => `formatted-${value}`,
+ }),
+}))
+
+vi.mock('@/app/components/base/chat/embedded-chatbot/theme/theme-context', () => ({
+ useThemeContext: () => ({
+ buildTheme: vi.fn(),
+ theme: {
+ primaryColor: '#1C64F2',
+ },
+ }),
+}))
+
+vi.mock('@/context/app-context', () => ({
+ useAppContext: () => ({
+ langGeniusVersionInfo: {
+ current_env: 'PRODUCTION',
+ },
+ }),
+}))
+
+vi.mock('@/service/client', () => ({
+ consoleQuery: {
+ apps: {
+ byAppId: {
+ siteEnable: {
+ post: {
+ mutationOptions: (options = {}) => ({
+ mutationFn: mocks.siteEnableMutation,
+ ...options,
+ }),
+ },
+ },
+ site: {
+ post: {
+ mutationOptions: (options = {}) => ({
+ mutationFn: mocks.siteMutation,
+ ...options,
+ }),
+ },
+ accessTokenReset: {
+ post: {
+ mutationOptions: (options = {}) => ({
+ mutationFn: mocks.siteAccessTokenResetMutation,
+ ...options,
+ }),
+ },
+ },
+ },
+ },
+ },
+ agent: {
+ byAgentId: {
+ get: {
+ queryKey: ({ input }: { input: { params: { agent_id: string } } }) => ['agent-detail', input.params.agent_id],
+ },
+ apiAccess: {
+ get: {
+ queryKey: ({ input }: { input: { params: { agent_id: string } } }) => ['agent-api-access', input.params.agent_id],
+ queryOptions: ({ input }: { input: { params: { agent_id: string } } }) => ({
+ queryKey: ['agent-api-access', input.params.agent_id],
+ queryFn: () => mocks.apiAccessQueryFn(input),
+ }),
+ },
+ },
+ apiEnable: {
+ post: {
+ mutationOptions: (options = {}) => ({
+ mutationFn: mocks.apiEnableMutation,
+ ...options,
+ }),
+ },
+ },
+ apiKeys: {
+ get: {
+ queryOptions: ({ input }: { input: { params: { agent_id: string } } }) => ({
+ queryKey: ['agent-api-keys', input.params.agent_id],
+ queryFn: () => mocks.apiKeysQueryFn(input),
+ }),
+ },
+ post: {
+ mutationOptions: (options = {}) => ({
+ mutationFn: mocks.createApiKeyMutation,
+ ...options,
+ }),
+ },
+ byApiKeyId: {
+ delete: {
+ mutationOptions: (options = {}) => ({
+ mutationFn: mocks.deleteApiKeyMutation,
+ ...options,
+ }),
+ },
+ },
+ },
+ },
+ },
+ },
+}))
+
+function createAgent(overrides: Partial<AgentAppDetailWithSite> = {}): AgentAppDetailWithSite {
+ return {
+ enable_api: true,
+ enable_site: true,
+ icon_url: null,
+ id: 'agent-1',
+ mode: 'agent',
+ name: 'Support Agent',
+ app_id: 'app-1',
+ api_base_url: 'https://api.example.test/v1',
+ access_mode: 'sso_verified',
+ site: {
+ access_token: 'site-token',
+ app_base_url: 'https://chat.example.test',
+ chat_color_theme_inverted: false,
+ default_language: 'en-US',
+ icon_url: null,
+ show_workflow_steps: false,
+ title: 'Support Agent',
+ use_icon_as_answer_icon: false,
+ } as NonNullable<AgentAppDetailWithSite['site']> & {
+ access_token: string
+ app_base_url: string
+ },
+ ...overrides,
+ }
+}
+
+function renderWithQueryClient(ui: React.ReactElement) {
+ const queryClient = createTestQueryClient()
+
+ render(
+ <QueryClientProvider client={queryClient}>
+ {ui}
+ </QueryClientProvider>,
+ )
+
+ return queryClient
+}
+
+function createTestQueryClient() {
+ return new QueryClient({
+ defaultOptions: {
+ queries: {
+ retry: false,
+ },
+ mutations: {
+ retry: false,
+ },
+ },
+ })
+}
+
+describe('Agent access surface cards', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ describe('Web app access', () => {
+ it('should render the backend web app URL and toggle site status through the backing app id', async () => {
+ const user = userEvent.setup()
+ mocks.siteEnableMutation.mockResolvedValueOnce({ enable_site: false })
+
+ renderWithQueryClient(
+ <WebAppAccessCard agent={createAgent()} agentId="agent-1" isLoading={false} />,
+ )
+
+ expect(screen.getByText('https://chat.example.test/agent/site-token')).toBeInTheDocument()
+ expect(screen.getByRole('link', { name: 'agentV2.agentDetail.access.webApp.actions.launch' })).toHaveAttribute('href', 'https://chat.example.test/agent/site-token')
+ expect(screen.getByText('agentV2.agentDetail.access.webApp.ssoEnabled')).toBeInTheDocument()
+
+ await user.click(screen.getByRole('switch', { name: 'agentV2.agentDetail.access.toggleSurface:{"name":"agentV2.agentDetail.access.webApp.title"}' }))
+
+ await waitFor(() => {
+ expect(mocks.siteEnableMutation.mock.calls[0]?.[0]).toEqual({
+ params: {
+ app_id: 'app-1',
+ },
+ body: {
+ enable_site: false,
+ },
+ })
+ })
+ })
+
+ it('should open the customize dialog with the backing app id and API base URL', async () => {
+ const user = userEvent.setup()
+
+ renderWithQueryClient(
+ <WebAppAccessCard agent={createAgent()} agentId="agent-1" isLoading={false} />,
+ )
+
+ await user.click(screen.getByRole('button', { name: 'agentV2.agentDetail.access.webApp.actions.customize' }))
+
+ const dialog = await screen.findByRole('dialog', { name: 'appOverview.overview.appInfo.customize.title' })
+ expect(dialog).toHaveTextContent(/NEXT_PUBLIC_APP_ID=\s*'app-1'/)
+ expect(dialog).toHaveTextContent(/NEXT_PUBLIC_API_URL=\s*'https:\/\/api\.example\.test\/v1'/)
+ expect(within(dialog).getByRole('button', { name: /appOverview\.overview\.appInfo\.customize\.way1\.step1Operation/ })).toHaveAttribute('href', 'https://github.com/langgenius/webapp-conversation')
+ })
+
+ it('should open the embedded dialog with the Agent web app route', async () => {
+ const user = userEvent.setup()
+
+ renderWithQueryClient(
+ <WebAppAccessCard agent={createAgent()} agentId="agent-1" isLoading={false} />,
+ )
+
+ await user.click(screen.getByRole('button', { name: 'agentV2.agentDetail.access.webApp.actions.embedded' }))
+
+ const dialog = await screen.findByRole('dialog', { name: 'appOverview.overview.appInfo.embedded.title' })
+ await waitFor(() => {
+ expect(dialog).toHaveTextContent('https://chat.example.test/agent/site-token')
+ })
+
+ await user.click(within(dialog).getByRole('button', { name: 'appOverview.overview.appInfo.embedded.scripts' }))
+
+ await waitFor(() => {
+ expect(dialog).toHaveTextContent('routeSegment: \'agent\'')
+ })
+ })
+
+ it('should save settings through the backing app id and update the agent detail cache', async () => {
+ const user = userEvent.setup()
+ const agent = createAgent()
+ mocks.siteMutation.mockResolvedValueOnce({
+ app_id: 'app-1',
+ code: 'new-site-token',
+ copyright: '',
+ custom_disclaimer: '',
+ customize_domain: null,
+ customize_token_strategy: 'allow',
+ default_language: 'en-US',
+ description: 'Updated web description.',
+ icon: '🤖',
+ icon_background: '#FFEAD5',
+ privacy_policy: '',
+ prompt_public: false,
+ show_workflow_steps: false,
+ title: 'Support Portal',
+ use_icon_as_answer_icon: true,
+ })
+
+ const queryClient = renderWithQueryClient(
+ <WebAppAccessCard agent={agent} agentId="agent-1" isLoading={false} />,
+ )
+ queryClient.setQueryData(['agent-detail', 'agent-1'], agent)
+ const invalidateSpy = vi.spyOn(queryClient, 'invalidateQueries')
+
+ await user.click(screen.getByRole('button', { name: 'agentV2.agentDetail.access.webApp.actions.settings' }))
+ const dialog = await screen.findByRole('dialog', { name: 'appOverview.overview.appInfo.settings.title' })
+
+ await user.clear(within(dialog).getByPlaceholderText('app.appNamePlaceholder'))
+ await user.type(within(dialog).getByPlaceholderText('app.appNamePlaceholder'), 'Support Portal')
+ await user.clear(within(dialog).getByRole('textbox', { name: 'appOverview.overview.appInfo.settings.webDesc' }))
+ await user.type(within(dialog).getByRole('textbox', { name: 'appOverview.overview.appInfo.settings.webDesc' }), 'Updated web description.')
+ await user.clear(within(dialog).getByPlaceholderText('E.g #A020F0'))
+ await user.type(within(dialog).getByPlaceholderText('E.g #A020F0'), '#123456')
+ await user.click(within(dialog).getByRole('button', { name: 'common.operation.save' }))
+
+ await waitFor(() => {
+ expect(mocks.siteMutation.mock.calls[0]?.[0]).toEqual({
+ params: {
+ app_id: 'app-1',
+ },
+ body: expect.objectContaining({
+ title: 'Support Portal',
+ description: 'Updated web description.',
+ chat_color_theme: '#123456',
+ }),
+ })
+ })
+ expect(mocks.siteMutation.mock.calls[0]?.[0].body).not.toHaveProperty('enable_sso')
+ expect(queryClient.getQueryData<AgentAppDetailWithSite>(['agent-detail', 'agent-1'])).toMatchObject({
+ site: {
+ access_token: 'new-site-token',
+ chat_color_theme: '#123456',
+ description: 'Updated web description.',
+ title: 'Support Portal',
+ },
+ })
+ expect(invalidateSpy).toHaveBeenCalledWith({ queryKey: ['agent-detail', 'agent-1'] })
+ })
+
+ it('should keep embedded disabled until the backing app id and web app token are available', () => {
+ renderWithQueryClient(
+ <WebAppAccessCard
+ agent={createAgent({
+ app_id: null,
+ site: {
+ ...createAgent().site!,
+ access_token: null,
+ code: null,
+ },
+ })}
+ agentId="agent-1"
+ isLoading={false}
+ />,
+ )
+
+ expect(screen.getByRole('button', { name: 'agentV2.agentDetail.access.webApp.actions.embedded' })).toBeDisabled()
+ })
+
+ it('should keep settings disabled until the backing app id and site data are available', () => {
+ const agentWithoutApp = createAgent({
+ app_id: null,
+ })
+ const agentWithoutSite = createAgent({
+ site: null,
+ })
+ const queryClient = createTestQueryClient()
+ const { rerender } = render(
+ <QueryClientProvider client={queryClient}>
+ <WebAppAccessCard agent={agentWithoutApp} agentId="agent-1" isLoading={false} />
+ </QueryClientProvider>,
+ )
+
+ expect(screen.getByRole('button', { name: 'agentV2.agentDetail.access.webApp.actions.settings' })).toBeDisabled()
+
+ rerender(
+ <QueryClientProvider client={queryClient}>
+ <WebAppAccessCard agent={agentWithoutSite} agentId="agent-1" isLoading={false} />
+ </QueryClientProvider>,
+ )
+
+ expect(screen.getByRole('button', { name: 'agentV2.agentDetail.access.webApp.actions.settings' })).toBeDisabled()
+ })
+
+ it('should keep customize disabled until the generated contract provides the required fields', () => {
+ renderWithQueryClient(
+ <WebAppAccessCard agent={createAgent({ api_base_url: null })} agentId="agent-1" isLoading={false} />,
+ )
+
+ expect(screen.getByRole('button', { name: 'agentV2.agentDetail.access.webApp.actions.customize' })).toBeDisabled()
+ })
+ })
+
+ describe('Service API access', () => {
+ it('should render service API data and toggle Agent API status through the generated Agent endpoint', async () => {
+ const user = userEvent.setup()
+ mocks.apiAccessQueryFn.mockResolvedValueOnce({
+ api_key_count: 2,
+ enabled: true,
+ service_api_base_url: 'https://api.example.test/v1',
+ })
+ mocks.apiEnableMutation.mockResolvedValueOnce({
+ api_key_count: 2,
+ enabled: false,
+ service_api_base_url: 'https://api.example.test/v1',
+ })
+
+ renderWithQueryClient(<ServiceApiAccessCard agentId="agent-1" />)
+
+ expect(await screen.findByText('https://api.example.test/v1')).toBeInTheDocument()
+ expect(screen.getByText('2')).toBeInTheDocument()
+
+ await user.click(screen.getByRole('switch', { name: 'agentV2.agentDetail.access.toggleSurface:{"name":"agentV2.agentDetail.access.serviceApi.title"}' }))
+
+ await waitFor(() => {
+ expect(mocks.apiEnableMutation.mock.calls[0]?.[0]).toEqual({
+ params: {
+ agent_id: 'agent-1',
+ },
+ body: {
+ enable_api: false,
+ },
+ })
+ })
+ })
+
+ it('should manage API keys with the Agent API key endpoints', async () => {
+ const user = userEvent.setup()
+ mocks.apiAccessQueryFn.mockResolvedValue({
+ api_key_count: 1,
+ enabled: true,
+ service_api_base_url: 'https://api.example.test/v1',
+ })
+ mocks.apiKeysQueryFn.mockResolvedValue({
+ data: [
+ {
+ created_at: 1781660000,
+ id: 'key-1',
+ last_used_at: null,
+ token: 'app-existing-secret-key-token',
+ type: 'app',
+ },
+ ],
+ })
+ mocks.createApiKeyMutation.mockResolvedValueOnce({
+ created_at: 1781660100,
+ id: 'key-2',
+ last_used_at: null,
+ token: 'app-new-secret-key-token',
+ type: 'app',
+ })
+ mocks.deleteApiKeyMutation.mockResolvedValueOnce(undefined)
+
+ renderWithQueryClient(<ServiceApiAccessCard agentId="agent-1" />)
+
+ await user.click(await screen.findByRole('button', { name: /agentV2\.agentDetail\.access\.serviceApi\.actions\.apiKey/ }))
+
+ const dialog = await screen.findByRole('dialog', { name: 'appApi.apiKeyModal.apiSecretKey' })
+ expect(await within(dialog).findByText('app...ing-secret-key-token')).toBeInTheDocument()
+
+ await user.click(within(dialog).getByRole('button', { name: 'appApi.apiKeyModal.createNewSecretKey' }))
+
+ await waitFor(() => {
+ expect(mocks.createApiKeyMutation.mock.calls[0]?.[0]).toEqual({
+ params: {
+ agent_id: 'agent-1',
+ },
+ })
+ })
+ expect(await screen.findByText('appApi.apiKeyModal.generateTips')).toBeInTheDocument()
+ expect(screen.getByText('app-new-secret-key-token')).toBeInTheDocument()
+ await user.click(screen.getByRole('button', { name: 'appApi.actionMsg.ok' }))
+
+ await user.click(within(dialog).getByRole('button', { name: 'common.operation.delete' }))
+ await user.click(await screen.findByRole('button', { name: 'common.operation.confirm' }))
+
+ await waitFor(() => {
+ expect(mocks.deleteApiKeyMutation.mock.calls[0]?.[0]).toEqual({
+ params: {
+ agent_id: 'agent-1',
+ api_key_id: 'key-1',
+ },
+ })
+ })
+ })
+ })
+})
diff --git a/web/features/agent-v2/agent-detail/access/components/__tests__/workflow-references-table.spec.tsx b/web/features/agent-v2/agent-detail/access/components/__tests__/workflow-references-table.spec.tsx
index a201666c869..e8f012397fb 100644
--- a/web/features/agent-v2/agent-detail/access/components/__tests__/workflow-references-table.spec.tsx
+++ b/web/features/agent-v2/agent-detail/access/components/__tests__/workflow-references-table.spec.tsx
@@ -97,8 +97,10 @@ describe('WorkflowReferencesTable', () => {
expect(screen.getByText('v3')).toBeInTheDocument()
expect(screen.getByText('agentV2.agentDetail.access.workflow.nodeCount:{"count":2}')).toBeInTheDocument()
expect(screen.getByText('formatted-1781660000')).toBeInTheDocument()
- expect(screen.getByRole('link', { name: 'agentV2.agentDetail.access.workflow.openInStudioFor:{"name":"Support Workflow"}' }))
- .toHaveAttribute('href', '/app/workflow-app-id/workflow')
+ const studioLink = screen.getByRole('link', { name: 'agentV2.agentDetail.access.workflow.openInStudioFor:{"name":"Support Workflow"}' })
+ expect(studioLink).toHaveAttribute('href', '/app/workflow-app-id/workflow')
+ expect(studioLink).toHaveAttribute('target', '_blank')
+ expect(studioLink).toHaveAttribute('rel', 'noopener noreferrer')
})
it('should render an empty state when the agent has no workflow references', async () => {
diff --git a/web/features/agent-v2/agent-detail/access/components/access-surface-card.tsx b/web/features/agent-v2/agent-detail/access/components/access-surface-card.tsx
new file mode 100644
index 00000000000..146a0812077
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/access/components/access-surface-card.tsx
@@ -0,0 +1,124 @@
+'use client'
+
+import type { ReactNode } from 'react'
+import { Button } from '@langgenius/dify-ui/button'
+import { cn } from '@langgenius/dify-ui/cn'
+import { StatusDot } from '@langgenius/dify-ui/status-dot'
+import { Switch } from '@langgenius/dify-ui/switch'
+import { toast } from '@langgenius/dify-ui/toast'
+import { useClipboard } from 'foxact/use-clipboard'
+import { useTranslation } from 'react-i18next'
+
+export type AccessSurfaceCardProps = {
+ title: string
+ icon: string
+ iconClassName: string
+ endpointLabel: string
+ endpoint: string
+ enabled: boolean
+ onEnabledChange: (enabled: boolean) => void
+ copyLabel: string
+ children: ReactNode
+ badge?: ReactNode
+ endpointActions?: ReactNode
+ disabled?: boolean
+ busy?: boolean
+}
+
+export const accessSurfaceActionClassName = 'inline-flex h-8 items-center justify-center gap-1.5 whitespace-nowrap rounded-lg border-[0.5px] border-components-button-secondary-border bg-components-button-secondary-bg px-3 text-[13px] leading-4 font-medium text-components-button-secondary-text shadow-xs outline-hidden backdrop-blur-[5px] hover:border-components-button-secondary-border-hover hover:bg-components-button-secondary-bg-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid'
+
+export function AccessSurfaceCard({
+ title,
+ icon,
+ iconClassName,
+ endpointLabel,
+ endpoint,
+ enabled,
+ onEnabledChange,
+ copyLabel,
+ children,
+ badge,
+ endpointActions,
+ disabled = false,
+ busy = false,
+}: AccessSurfaceCardProps) {
+ const { t } = useTranslation('agentV2')
+ const { t: tCommon } = useTranslation('common')
+ const { copied, copy } = useClipboard({
+ timeout: 2000,
+ onCopyError: () => {
+ toast.error(t('agentDetail.access.copyFailed'))
+ },
+ })
+ const canCopyEndpoint = Boolean(endpoint)
+ const switchDisabled = disabled || busy
+
+ const handleCopyEndpoint = () => {
+ if (!canCopyEndpoint)
+ return
+
+ void copy(endpoint)
+ }
+
+ return (
+ <article className="rounded-xl border border-components-panel-border bg-components-panel-bg shadow-xs">
+ <div className="px-4 pt-4 pb-4">
+ <div className="flex min-w-0 items-center gap-3">
+ <div className="flex min-w-0 flex-1 items-center gap-2">
+ <span className={cn('flex size-6 shrink-0 items-center justify-center rounded-lg', iconClassName)}>
+ <span aria-hidden className={cn(icon, 'size-4')} />
+ </span>
+ <h3 className="truncate system-md-semibold text-text-secondary">
+ {title}
+ </h3>
+ {badge}
+ </div>
+
+ <div className="flex shrink-0 items-center gap-3">
+ <span className={cn(
+ 'inline-flex items-center gap-1 system-xs-semibold-uppercase',
+ enabled ? 'text-util-colors-green-green-700' : 'text-text-tertiary',
+ )}
+ >
+ <StatusDot status={enabled ? 'success' : 'disabled'} size="small" />
+ {t(enabled ? 'agentDetail.access.status.inService' : 'agentDetail.access.status.outOfService')}
+ </span>
+ <Switch
+ size="md"
+ checked={enabled}
+ disabled={switchDisabled}
+ aria-label={t('agentDetail.access.toggleSurface', { name: title })}
+ onCheckedChange={onEnabledChange}
+ />
+ </div>
+ </div>
+
+ <div className="mt-3">
+ <div className="system-xs-medium text-text-tertiary">
+ {endpointLabel}
+ </div>
+ <div className="mt-1 flex h-8 min-w-0 items-center rounded-lg bg-components-input-bg-normal px-2">
+ <span className="min-w-0 flex-1 truncate system-sm-regular text-text-secondary" translate="no">
+ {endpoint || t('agentDetail.access.workflow.notAvailable')}
+ </span>
+ <Button
+ variant="ghost"
+ size="small"
+ className="size-6 shrink-0 px-0 text-text-tertiary hover:text-text-secondary"
+ aria-label={copied ? tCommon('operation.copied') : copyLabel}
+ disabled={!canCopyEndpoint}
+ onClick={handleCopyEndpoint}
+ >
+ <span aria-hidden className={cn(copied ? 'i-ri-check-line' : 'i-ri-file-copy-line', 'size-4')} />
+ </Button>
+ {endpointActions}
+ </div>
+ </div>
+ </div>
+
+ <div className="flex min-h-16 flex-wrap items-center gap-2 border-t border-divider-subtle px-4 py-4">
+ {children}
+ </div>
+ </article>
+ )
+}
diff --git a/web/features/agent-v2/agent-detail/access/components/agent-api-key-modal.tsx b/web/features/agent-v2/agent-detail/access/components/agent-api-key-modal.tsx
new file mode 100644
index 00000000000..a4c57ec8945
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/access/components/agent-api-key-modal.tsx
@@ -0,0 +1,283 @@
+'use client'
+
+import type { ApiKeyItem } from '@dify/contracts/api/console/agent/types.gen'
+import {
+ AlertDialog,
+ AlertDialogActions,
+ AlertDialogCancelButton,
+ AlertDialogConfirmButton,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogTitle,
+} from '@langgenius/dify-ui/alert-dialog'
+import { Button } from '@langgenius/dify-ui/button'
+import { Dialog, DialogCloseButton, DialogContent, DialogDescription, DialogTitle } from '@langgenius/dify-ui/dialog'
+import { toast } from '@langgenius/dify-ui/toast'
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
+import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import CopyFeedback from '@/app/components/base/copy-feedback'
+import useTimestamp from '@/hooks/use-timestamp'
+import { consoleQuery } from '@/service/client'
+
+export function AgentApiKeyModal({
+ agentId,
+ open,
+ onOpenChange,
+}: {
+ agentId: string
+ open: boolean
+ onOpenChange: (open: boolean) => void
+}) {
+ const { t } = useTranslation('appApi')
+ const { t: tCommon } = useTranslation('common')
+ const { formatTime } = useTimestamp()
+ const queryClient = useQueryClient()
+ const [newKey, setNewKey] = useState<ApiKeyItem | null>(null)
+ const [apiKeyToDelete, setApiKeyToDelete] = useState<ApiKeyItem | null>(null)
+ const apiKeysQueryOptions = consoleQuery.agent.byAgentId.apiKeys.get.queryOptions({
+ input: {
+ params: {
+ agent_id: agentId,
+ },
+ },
+ })
+ const apiKeysQuery = useQuery({
+ ...apiKeysQueryOptions,
+ enabled: open,
+ })
+ const createApiKeyMutation = useMutation(consoleQuery.agent.byAgentId.apiKeys.post.mutationOptions({
+ onSuccess: (createdKey) => {
+ setNewKey(createdKey)
+ queryClient.invalidateQueries({ queryKey: apiKeysQueryOptions.queryKey })
+ queryClient.invalidateQueries({
+ queryKey: consoleQuery.agent.byAgentId.apiAccess.get.queryKey({
+ input: {
+ params: {
+ agent_id: agentId,
+ },
+ },
+ }),
+ })
+ toast.success(tCommon('actionMsg.modifiedSuccessfully'))
+ },
+ onError: () => {
+ toast.error(tCommon('actionMsg.modifiedUnsuccessfully'))
+ },
+ }))
+ const deleteApiKeyMutation = useMutation(consoleQuery.agent.byAgentId.apiKeys.byApiKeyId.delete.mutationOptions({
+ onSuccess: () => {
+ setApiKeyToDelete(null)
+ queryClient.invalidateQueries({ queryKey: apiKeysQueryOptions.queryKey })
+ queryClient.invalidateQueries({
+ queryKey: consoleQuery.agent.byAgentId.apiAccess.get.queryKey({
+ input: {
+ params: {
+ agent_id: agentId,
+ },
+ },
+ }),
+ })
+ toast.success(tCommon('actionMsg.modifiedSuccessfully'))
+ },
+ onError: () => {
+ toast.error(tCommon('actionMsg.modifiedUnsuccessfully'))
+ },
+ }))
+ const apiKeys = apiKeysQuery.data?.data ?? []
+ const isCreating = createApiKeyMutation.isPending
+ const isDeleting = deleteApiKeyMutation.isPending
+
+ function handleCreateApiKey() {
+ createApiKeyMutation.mutate({
+ params: {
+ agent_id: agentId,
+ },
+ })
+ }
+
+ function handleDeleteApiKey() {
+ if (!apiKeyToDelete)
+ return
+
+ deleteApiKeyMutation.mutate({
+ params: {
+ agent_id: agentId,
+ api_key_id: apiKeyToDelete.id,
+ },
+ })
+ }
+
+ function handleOpenChange(nextOpen: boolean) {
+ if (!nextOpen) {
+ setNewKey(null)
+ setApiKeyToDelete(null)
+ }
+
+ onOpenChange(nextOpen)
+ }
+
+ return (
+ <>
+ <Dialog open={open} onOpenChange={handleOpenChange}>
+ <DialogContent className="flex w-full max-w-[800px]! flex-col overflow-hidden px-8">
+ <DialogCloseButton />
+ <DialogTitle className="title-2xl-semi-bold text-text-primary">
+ {t('apiKeyModal.apiSecretKey')}
+ </DialogTitle>
+ <DialogDescription className="mt-1 system-sm-regular text-text-tertiary">
+ {t('apiKeyModal.apiSecretKeyTips')}
+ </DialogDescription>
+
+ <div className="mt-4 min-h-20 overflow-hidden">
+ <div className="flex h-9 shrink-0 items-center border-b border-divider-regular text-xs font-semibold text-text-tertiary">
+ <div className="w-64 shrink-0 px-3">{t('apiKeyModal.secretKey')}</div>
+ <div className="w-[200px] shrink-0 px-3">{t('apiKeyModal.created')}</div>
+ <div className="w-[200px] shrink-0 px-3">{t('apiKeyModal.lastUsed')}</div>
+ <div className="grow px-3" />
+ </div>
+ <div className="max-h-[280px] overflow-auto">
+ {apiKeysQuery.isPending && (
+ <div role="status" className="flex h-20 items-center justify-center system-sm-regular text-text-tertiary">
+ {t('loading')}
+ </div>
+ )}
+ {apiKeysQuery.isError && (
+ <div className="flex h-20 items-center justify-center gap-2 system-sm-regular text-text-tertiary">
+ <span>{tCommon('api.actionFailed')}</span>
+ <Button
+ variant="secondary"
+ size="small"
+ onClick={() => {
+ void apiKeysQuery.refetch()
+ }}
+ >
+ {tCommon('operation.retry')}
+ </Button>
+ </div>
+ )}
+ {apiKeysQuery.isSuccess && apiKeys.length === 0 && (
+ <div className="flex h-20 items-center justify-center system-sm-regular text-text-tertiary">
+ {tCommon('noData')}
+ </div>
+ )}
+ {apiKeysQuery.isSuccess && apiKeys.map(apiKey => (
+ <div className="flex h-9 items-center border-b border-divider-regular text-sm font-normal text-text-secondary last:border-b-0" key={apiKey.id}>
+ <div className="w-64 shrink-0 truncate px-3 font-mono" translate="no">
+ {maskApiKey(apiKey.token)}
+ </div>
+ <div className="w-[200px] shrink-0 truncate px-3">
+ {apiKey.created_at ? formatTime(apiKey.created_at, t('dateTimeFormat', { ns: 'appLog' })) : t('never')}
+ </div>
+ <div className="w-[200px] shrink-0 truncate px-3">
+ {apiKey.last_used_at ? formatTime(apiKey.last_used_at, t('dateTimeFormat', { ns: 'appLog' })) : t('never')}
+ </div>
+ <div className="flex grow gap-2 px-3">
+ <CopyFeedback content={apiKey.token} />
+ <Button
+ variant="ghost"
+ size="small"
+ className="size-6 px-0 text-text-tertiary hover:text-text-secondary"
+ aria-label={tCommon('operation.delete')}
+ disabled={isDeleting}
+ onClick={() => setApiKeyToDelete(apiKey)}
+ >
+ <span aria-hidden className="i-ri-delete-bin-line size-4" />
+ </Button>
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+
+ <div className="mt-4 flex justify-start">
+ <Button onClick={handleCreateApiKey} loading={isCreating}>
+ <span aria-hidden className="mr-1 i-heroicons-plus-20-solid size-4" />
+ {t('apiKeyModal.createNewSecretKey')}
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+
+ <AgentApiKeyGenerateModal
+ apiKey={newKey}
+ onClose={() => setNewKey(null)}
+ />
+
+ <AlertDialog
+ open={Boolean(apiKeyToDelete)}
+ onOpenChange={(nextOpen) => {
+ if (!nextOpen)
+ setApiKeyToDelete(null)
+ }}
+ >
+ <AlertDialogContent>
+ <div className="flex flex-col gap-2 px-6 pt-6 pb-4">
+ <AlertDialogTitle className="w-full truncate title-2xl-semi-bold text-text-primary">
+ {t('actionMsg.deleteConfirmTitle')}
+ </AlertDialogTitle>
+ <AlertDialogDescription className="w-full system-md-regular wrap-break-word whitespace-pre-wrap text-text-tertiary">
+ {t('actionMsg.deleteConfirmTips')}
+ </AlertDialogDescription>
+ </div>
+ <AlertDialogActions>
+ <AlertDialogCancelButton>
+ {tCommon('operation.cancel')}
+ </AlertDialogCancelButton>
+ <AlertDialogConfirmButton loading={isDeleting} onClick={handleDeleteApiKey}>
+ {tCommon('operation.confirm')}
+ </AlertDialogConfirmButton>
+ </AlertDialogActions>
+ </AlertDialogContent>
+ </AlertDialog>
+ </>
+ )
+}
+
+function AgentApiKeyGenerateModal({
+ apiKey,
+ onClose,
+}: {
+ apiKey: ApiKeyItem | null
+ onClose: () => void
+}) {
+ const { t } = useTranslation('appApi')
+
+ return (
+ <Dialog
+ open={Boolean(apiKey)}
+ onOpenChange={(nextOpen) => {
+ if (!nextOpen)
+ onClose()
+ }}
+ >
+ <DialogContent className="w-full max-w-[480px]! overflow-hidden px-8">
+ <DialogCloseButton />
+ <DialogTitle className="title-2xl-semi-bold text-text-primary">
+ {t('apiKeyModal.apiSecretKey')}
+ </DialogTitle>
+ <DialogDescription className="mt-1 text-[13px] leading-5 font-normal text-text-tertiary">
+ {t('apiKeyModal.generateTips')}
+ </DialogDescription>
+ <div className="my-4 flex h-9 min-w-0 items-center rounded-lg bg-components-input-bg-normal px-2">
+ <span className="min-w-0 flex-1 truncate font-mono system-sm-medium text-text-secondary" translate="no">
+ {apiKey?.token}
+ </span>
+ {apiKey && <CopyFeedback content={apiKey.token} />}
+ </div>
+ <div className="my-4 flex justify-end">
+ <Button className="w-16 shrink-0" onClick={onClose}>
+ {t('actionMsg.ok')}
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ )
+}
+
+function maskApiKey(token: string) {
+ if (token.length <= 24)
+ return token
+
+ return `${token.slice(0, 3)}...${token.slice(-20)}`
+}
diff --git a/web/features/agent-v2/agent-detail/access/components/service-api-access-card.tsx b/web/features/agent-v2/agent-detail/access/components/service-api-access-card.tsx
new file mode 100644
index 00000000000..28d3b72cd13
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/access/components/service-api-access-card.tsx
@@ -0,0 +1,123 @@
+'use client'
+
+import type { AgentAppDetailWithSite } from '@dify/contracts/api/console/agent/types.gen'
+import { Button } from '@langgenius/dify-ui/button'
+import { toast } from '@langgenius/dify-ui/toast'
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
+import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { useDocLink } from '@/context/i18n'
+import { consoleQuery } from '@/service/client'
+import { accessSurfaceActionClassName, AccessSurfaceCard } from './access-surface-card'
+import { AgentApiKeyModal } from './agent-api-key-modal'
+
+export function ServiceApiAccessCard({
+ agentId,
+}: {
+ agentId: string
+}) {
+ const { t } = useTranslation('agentV2')
+ const { t: tCommon } = useTranslation('common')
+ const docLink = useDocLink()
+ const queryClient = useQueryClient()
+ const [apiKeyModalOpen, setApiKeyModalOpen] = useState(false)
+ const apiAccessQueryOptions = consoleQuery.agent.byAgentId.apiAccess.get.queryOptions({
+ input: {
+ params: {
+ agent_id: agentId,
+ },
+ },
+ })
+ const apiAccessQuery = useQuery(apiAccessQueryOptions)
+ const apiAccess = apiAccessQuery.data
+ const toggleServiceApiMutation = useMutation(consoleQuery.agent.byAgentId.apiEnable.post.mutationOptions({
+ onSuccess: (updatedApiAccess, variables) => {
+ queryClient.setQueryData(apiAccessQueryOptions.queryKey, updatedApiAccess)
+ queryClient.setQueryData<AgentAppDetailWithSite | undefined>(
+ consoleQuery.agent.byAgentId.get.queryKey({ input: { params: { agent_id: agentId } } }),
+ agentDetail => agentDetail
+ ? {
+ ...agentDetail,
+ enable_api: variables.body.enable_api,
+ }
+ : agentDetail,
+ )
+ toast.success(tCommon('actionMsg.modifiedSuccessfully'))
+ },
+ onError: () => {
+ toast.error(tCommon('actionMsg.modifiedUnsuccessfully'))
+ },
+ }))
+ const isBusy = apiAccessQuery.isPending || toggleServiceApiMutation.isPending
+
+ function handleEnabledChange(enabled: boolean) {
+ toggleServiceApiMutation.mutate({
+ params: {
+ agent_id: agentId,
+ },
+ body: {
+ enable_api: enabled,
+ },
+ })
+ }
+
+ return (
+ <>
+ <AccessSurfaceCard
+ title={t('agentDetail.access.serviceApi.title')}
+ icon="i-ri-node-tree"
+ iconClassName="bg-state-accent-solid text-text-primary-on-surface"
+ endpointLabel={t('agentDetail.access.serviceApi.endpoint')}
+ endpoint={apiAccess?.service_api_base_url ?? ''}
+ enabled={Boolean(apiAccess?.enabled)}
+ onEnabledChange={handleEnabledChange}
+ copyLabel={t('agentDetail.access.copyServiceEndpoint')}
+ disabled={apiAccessQuery.isPending || apiAccessQuery.isError}
+ busy={toggleServiceApiMutation.isPending}
+ >
+ <Button
+ variant="secondary"
+ size="medium"
+ className="gap-1.5 px-3"
+ disabled={isBusy || apiAccessQuery.isError}
+ onClick={() => setApiKeyModalOpen(true)}
+ >
+ <span aria-hidden className="i-ri-key-2-line size-4" />
+ {t('agentDetail.access.serviceApi.actions.apiKey')}
+ <span className="rounded-md bg-components-badge-bg-gray-soft px-1.5 code-xs-regular text-text-tertiary">
+ {apiAccess?.api_key_count ?? 0}
+ </span>
+ </Button>
+ <a
+ href={docLink('/use-dify/publish/developing-with-apis')}
+ target="_blank"
+ rel="noreferrer"
+ aria-label={t('agentDetail.access.serviceApi.actions.apiReference')}
+ className={accessSurfaceActionClassName}
+ >
+ <span aria-hidden className="i-ri-book-open-line size-4" />
+ {t('agentDetail.access.serviceApi.actions.apiReference')}
+ </a>
+ {apiAccessQuery.isError && (
+ <Button
+ variant="secondary"
+ size="medium"
+ className="gap-1.5 px-3"
+ onClick={() => {
+ void apiAccessQuery.refetch()
+ }}
+ >
+ <span aria-hidden className="i-ri-refresh-line size-4" />
+ {tCommon('operation.retry')}
+ </Button>
+ )}
+ </AccessSurfaceCard>
+
+ <AgentApiKeyModal
+ agentId={agentId}
+ open={apiKeyModalOpen}
+ onOpenChange={setApiKeyModalOpen}
+ />
+ </>
+ )
+}
diff --git a/web/features/agent-v2/agent-detail/access/components/web-app-access-card.tsx b/web/features/agent-v2/agent-detail/access/components/web-app-access-card.tsx
new file mode 100644
index 00000000000..60b4b2d6241
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/access/components/web-app-access-card.tsx
@@ -0,0 +1,335 @@
+'use client'
+
+import type { AgentAppDetailWithSite } from '@dify/contracts/api/console/agent/types.gen'
+import type { AppSiteUpdatePayload } from '@dify/contracts/api/console/apps/types.gen'
+import type { ConfigParams, SettingsAppInfo } from '@/app/components/app/overview/settings'
+import { Button } from '@langgenius/dify-ui/button'
+import { toast } from '@langgenius/dify-ui/toast'
+import { useMutation, useQueryClient } from '@tanstack/react-query'
+import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import CustomizeModal from '@/app/components/app/overview/customize'
+import EmbeddedModal from '@/app/components/app/overview/embedded'
+import SettingsModal from '@/app/components/app/overview/settings'
+import ShareQRCode from '@/app/components/base/qrcode'
+import { AccessMode } from '@/models/access-control'
+import { consoleQuery } from '@/service/client'
+import { AppModeEnum } from '@/types/app'
+import { accessSurfaceActionClassName, AccessSurfaceCard } from './access-surface-card'
+
+export function WebAppAccessCard({
+ agent,
+ agentId,
+ isLoading,
+}: {
+ agent?: AgentAppDetailWithSite
+ agentId: string
+ isLoading: boolean
+}) {
+ const { t } = useTranslation('agentV2')
+ const { t: tCommon } = useTranslation('common')
+ const queryClient = useQueryClient()
+ const appId = agent?.app_id
+ const apiBaseUrl = agent?.api_base_url
+ const site = agent?.site
+ const accessToken = site?.access_token ?? site?.code
+ const appBaseUrl = site?.app_base_url || (typeof window === 'undefined' ? '' : window.location.origin)
+ const webAppUrl = getAgentWebAppUrl(agent)
+ const isEnabled = Boolean(agent?.enable_site)
+ const canManageWebApp = Boolean(appId)
+ const embeddedConfig = appId && accessToken
+ ? {
+ accessToken,
+ appBaseUrl,
+ siteInfo: {
+ title: site?.title ?? agent?.name ?? '',
+ chat_color_theme: site?.chat_color_theme ?? undefined,
+ chat_color_theme_inverted: site?.chat_color_theme_inverted ?? undefined,
+ },
+ }
+ : null
+ const settingsAppInfo = agent ? createSettingsAppInfo(agent) : null
+ const customizeConfig = appId && apiBaseUrl
+ ? {
+ apiBaseUrl,
+ appId,
+ }
+ : null
+ const showSsoBadge = agent?.access_mode === AccessMode.EXTERNAL_MEMBERS
+ const [showCustomizeModal, setShowCustomizeModal] = useState(false)
+ const [showEmbeddedModal, setShowEmbeddedModal] = useState(false)
+ const [showSettingsModal, setShowSettingsModal] = useState(false)
+ const agentDetailQueryKey = consoleQuery.agent.byAgentId.get.queryKey({ input: { params: { agent_id: agentId } } })
+ const toggleSiteMutation = useMutation(consoleQuery.apps.byAppId.siteEnable.post.mutationOptions({
+ onSuccess: (_updatedApp, variables) => {
+ queryClient.setQueryData<AgentAppDetailWithSite | undefined>(
+ agentDetailQueryKey,
+ agentDetail => agentDetail
+ ? {
+ ...agentDetail,
+ enable_site: variables.body.enable_site,
+ }
+ : agentDetail,
+ )
+ toast.success(tCommon('actionMsg.modifiedSuccessfully'))
+ },
+ onError: () => {
+ toast.error(tCommon('actionMsg.modifiedUnsuccessfully'))
+ },
+ }))
+ const resetAccessTokenMutation = useMutation(consoleQuery.apps.byAppId.site.accessTokenReset.post.mutationOptions({
+ onSuccess: (site) => {
+ queryClient.setQueryData<AgentAppDetailWithSite | undefined>(
+ agentDetailQueryKey,
+ (agentDetail) => {
+ if (!agentDetail || !agentDetail.site)
+ return agentDetail
+
+ return {
+ ...agentDetail,
+ site: {
+ ...agentDetail.site,
+ ...site,
+ access_token: site.code,
+ },
+ }
+ },
+ )
+ toast.success(tCommon('actionMsg.generatedSuccessfully'))
+ },
+ onError: () => {
+ toast.error(tCommon('actionMsg.generatedUnsuccessfully'))
+ },
+ }))
+ const updateSiteMutation = useMutation(consoleQuery.apps.byAppId.site.post.mutationOptions())
+ const isBusy = toggleSiteMutation.isPending || resetAccessTokenMutation.isPending || updateSiteMutation.isPending
+
+ function handleEnabledChange(enabled: boolean) {
+ if (!appId)
+ return
+
+ toggleSiteMutation.mutate({
+ params: {
+ app_id: appId,
+ },
+ body: {
+ enable_site: enabled,
+ },
+ })
+ }
+
+ function handleRefreshUrl() {
+ if (!appId)
+ return
+
+ resetAccessTokenMutation.mutate({
+ params: {
+ app_id: appId,
+ },
+ })
+ }
+
+ async function handleSaveSettings(params: ConfigParams) {
+ if (!appId)
+ return
+
+ const { enable_sso: _enableSso, ...body } = params
+ const sitePayload = body satisfies AppSiteUpdatePayload
+
+ try {
+ const updatedSite = await updateSiteMutation.mutateAsync({
+ params: {
+ app_id: appId,
+ },
+ body: sitePayload,
+ })
+
+ queryClient.setQueryData<AgentAppDetailWithSite | undefined>(
+ agentDetailQueryKey,
+ agentDetail => agentDetail
+ ? {
+ ...agentDetail,
+ site: {
+ ...agentDetail.site,
+ ...updatedSite,
+ ...sitePayload,
+ access_token: updatedSite.code ?? agentDetail.site?.access_token ?? agentDetail.site?.code ?? null,
+ code: updatedSite.code ?? agentDetail.site?.code ?? agentDetail.site?.access_token ?? null,
+ app_base_url: agentDetail.site?.app_base_url ?? site?.app_base_url ?? null,
+ icon_url: agentDetail.site?.icon_url ?? null,
+ },
+ }
+ : agentDetail,
+ )
+ await queryClient.invalidateQueries({ queryKey: agentDetailQueryKey })
+ toast.success(tCommon('actionMsg.modifiedSuccessfully'))
+ }
+ catch {
+ toast.error(tCommon('actionMsg.modifiedUnsuccessfully'))
+ }
+ }
+
+ return (
+ <AccessSurfaceCard
+ title={t('agentDetail.access.webApp.title')}
+ icon="i-ri-window-line"
+ iconClassName="bg-state-accent-solid text-text-primary-on-surface"
+ endpointLabel={t('agentDetail.access.webApp.accessUrl')}
+ endpoint={webAppUrl}
+ enabled={isEnabled}
+ onEnabledChange={handleEnabledChange}
+ copyLabel={t('agentDetail.access.copyAccessUrl')}
+ badge={showSsoBadge ? <SsoBadge /> : undefined}
+ endpointActions={webAppUrl
+ ? (
+ <>
+ <span className="mx-1.5 h-3.5 w-px shrink-0 bg-divider-regular" />
+ <ShareQRCode content={webAppUrl} />
+ <Button
+ variant="ghost"
+ size="small"
+ className="size-6 shrink-0 px-0 text-text-tertiary hover:text-text-secondary"
+ aria-label={t('agentDetail.access.webApp.refreshUrl')}
+ disabled={!canManageWebApp || isBusy}
+ onClick={handleRefreshUrl}
+ >
+ <span aria-hidden className="i-ri-refresh-line size-4" />
+ </Button>
+ </>
+ )
+ : undefined}
+ disabled={isLoading || !canManageWebApp}
+ busy={isBusy}
+ >
+ {webAppUrl && isEnabled
+ ? (
+ <a
+ href={webAppUrl}
+ target="_blank"
+ rel="noreferrer"
+ aria-label={t('agentDetail.access.webApp.actions.launch')}
+ className={accessSurfaceActionClassName}
+ >
+ <span aria-hidden className="i-ri-external-link-line size-4" />
+ {t('agentDetail.access.webApp.actions.launch')}
+ </a>
+ )
+ : (
+ <Button variant="secondary" size="medium" className="gap-1.5 px-3" disabled>
+ <span aria-hidden className="i-ri-external-link-line size-4" />
+ {t('agentDetail.access.webApp.actions.launch')}
+ </Button>
+ )}
+ <Button
+ variant="secondary"
+ size="medium"
+ className="gap-1.5 px-3"
+ disabled={!embeddedConfig}
+ onClick={() => setShowEmbeddedModal(true)}
+ >
+ <span aria-hidden className="i-ri-window-line size-4" />
+ {t('agentDetail.access.webApp.actions.embedded')}
+ </Button>
+ <Button
+ variant="secondary"
+ size="medium"
+ className="gap-1.5 px-3"
+ disabled={!customizeConfig}
+ onClick={() => setShowCustomizeModal(true)}
+ >
+ <span aria-hidden className="i-ri-paint-brush-line size-4" />
+ {t('agentDetail.access.webApp.actions.customize')}
+ </Button>
+ <Button
+ variant="secondary"
+ size="medium"
+ className="gap-1.5 px-3"
+ disabled={!settingsAppInfo || updateSiteMutation.isPending}
+ onClick={() => setShowSettingsModal(true)}
+ >
+ <span aria-hidden className="i-ri-equalizer-2-line size-4" />
+ {t('agentDetail.access.webApp.actions.settings')}
+ </Button>
+ {settingsAppInfo && (
+ <SettingsModal
+ isChat
+ appInfo={settingsAppInfo}
+ isShow={showSettingsModal}
+ onClose={() => setShowSettingsModal(false)}
+ onSave={handleSaveSettings}
+ />
+ )}
+ {customizeConfig && (
+ <CustomizeModal
+ isShow={showCustomizeModal}
+ onClose={() => setShowCustomizeModal(false)}
+ appId={customizeConfig.appId}
+ api_base_url={customizeConfig.apiBaseUrl}
+ sourceCodeRepository="webapp-conversation"
+ />
+ )}
+ {embeddedConfig && (
+ <EmbeddedModal
+ isShow={showEmbeddedModal}
+ onClose={() => setShowEmbeddedModal(false)}
+ appBaseUrl={embeddedConfig.appBaseUrl}
+ accessToken={embeddedConfig.accessToken}
+ siteInfo={embeddedConfig.siteInfo}
+ webAppRoute="agent"
+ />
+ )}
+ </AccessSurfaceCard>
+ )
+}
+
+function createSettingsAppInfo(agent: AgentAppDetailWithSite): SettingsAppInfo | null {
+ const site = agent.site
+ const appId = agent.app_id
+ if (!site || !appId)
+ return null
+
+ return {
+ id: appId,
+ mode: AppModeEnum.CHAT,
+ site: {
+ title: site.title ?? agent.name,
+ description: site.description ?? agent.description ?? '',
+ default_language: (site.default_language ?? 'en-US') as SettingsAppInfo['site']['default_language'],
+ chat_color_theme: site.chat_color_theme ?? '',
+ chat_color_theme_inverted: site.chat_color_theme_inverted ?? false,
+ copyright: site.copyright ?? '',
+ privacy_policy: site.privacy_policy ?? '',
+ custom_disclaimer: site.custom_disclaimer ?? '',
+ input_placeholder: site.input_placeholder ?? '',
+ icon_type: site.icon_type === 'image' || site.icon_type === 'emoji' || site.icon_type === 'link'
+ ? site.icon_type
+ : 'emoji',
+ icon: site.icon ?? agent.icon ?? '',
+ icon_background: site.icon_background ?? agent.icon_background ?? null,
+ icon_url: site.icon_url ?? null,
+ show_workflow_steps: site.show_workflow_steps ?? false,
+ use_icon_as_answer_icon: site.use_icon_as_answer_icon ?? false,
+ },
+ }
+}
+
+function getAgentWebAppUrl(agent?: AgentAppDetailWithSite) {
+ const site = agent?.site
+ const token = site?.access_token ?? site?.code
+ if (!token)
+ return ''
+
+ const baseUrl = site?.app_base_url || (typeof window === 'undefined' ? '' : window.location.origin)
+ return `${baseUrl.replace(/\/$/, '')}/agent/${token}`
+}
+
+function SsoBadge() {
+ const { t } = useTranslation('agentV2')
+
+ return (
+ <span className="inline-flex h-4.5 shrink-0 items-center gap-1 rounded-sm border border-divider-deep px-1.5 system-2xs-semibold-uppercase text-text-tertiary">
+ <span aria-hidden className="i-ri-shield-check-line size-3" />
+ {t('agentDetail.access.webApp.ssoEnabled')}
+ </span>
+ )
+}
diff --git a/web/features/agent-v2/agent-detail/access/components/workflow-references-table.tsx b/web/features/agent-v2/agent-detail/access/components/workflow-references-table.tsx
index 0113fd5e45b..7dffef6ebee 100644
--- a/web/features/agent-v2/agent-detail/access/components/workflow-references-table.tsx
+++ b/web/features/agent-v2/agent-detail/access/components/workflow-references-table.tsx
@@ -145,6 +145,8 @@ function WorkflowAccessRow({
<td className="px-3">
<Link
href={getWorkflowReferenceHref(reference)}
+ target="_blank"
+ rel="noopener noreferrer"
aria-label={t('agentDetail.access.workflow.openInStudioFor', { name: reference.app_name })}
className="inline-flex items-center gap-0.5 rounded-sm text-text-secondary hover:text-text-accent hover:underline focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"
>
diff --git a/web/features/agent-v2/agent-detail/access/page.tsx b/web/features/agent-v2/agent-detail/access/page.tsx
index a22373e7bfe..7e1d653fb70 100644
--- a/web/features/agent-v2/agent-detail/access/page.tsx
+++ b/web/features/agent-v2/agent-detail/access/page.tsx
@@ -1,57 +1,18 @@
'use client'
-import type { AgentAppDetailWithSite } from '@dify/contracts/api/console/agent/types.gen'
-import type { ReactNode } from 'react'
-import { Button } from '@langgenius/dify-ui/button'
-import { cn } from '@langgenius/dify-ui/cn'
import { ScrollArea } from '@langgenius/dify-ui/scroll-area'
-import { StatusDot } from '@langgenius/dify-ui/status-dot'
-import { Switch } from '@langgenius/dify-ui/switch'
-import { toast } from '@langgenius/dify-ui/toast'
import { useQuery } from '@tanstack/react-query'
-import { useClipboard } from 'foxact/use-clipboard'
-import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useDocLink } from '@/context/i18n'
import { consoleQuery } from '@/service/client'
+import { ServiceApiAccessCard } from './components/service-api-access-card'
+import { WebAppAccessCard } from './components/web-app-access-card'
import { WorkflowReferencesTable } from './components/workflow-references-table'
type AgentAccessPageProps = {
agentId: string
}
-const serviceApiEndpoint = 'https://api.dify.ai/v1'
-
-type AgentWebAppSite = NonNullable<AgentAppDetailWithSite['site']> & {
- access_token?: string | null
- app_base_url?: string | null
- code?: string | null
-}
-
-type AccessSurfaceCardProps = {
- title: string
- icon: string
- iconClassName: string
- endpointLabel: string
- endpoint: string
- enabled: boolean
- onEnabledChange: (enabled: boolean) => void
- copyLabel: string
- children: ReactNode
- badge?: ReactNode
- onUnavailableAction: () => void
-}
-
-const getAgentWebAppUrl = (agent?: AgentAppDetailWithSite) => {
- const site = agent?.site as AgentWebAppSite | null | undefined
- const token = site?.access_token ?? site?.code
- if (!token)
- return ''
-
- const baseUrl = site?.app_base_url || (typeof window === 'undefined' ? '' : window.location.origin)
- return `${baseUrl.replace(/\/$/, '')}/agent/${token}`
-}
-
export function AgentAccessPage({
agentId,
}: AgentAccessPageProps) {
@@ -64,12 +25,6 @@ export function AgentAccessPage({
},
},
}))
- const [isWebAppEnabled, setIsWebAppEnabled] = useState(true)
- const [isServiceApiEnabled, setIsServiceApiEnabled] = useState(true)
- const webAppUrl = getAgentWebAppUrl(agentQuery.data)
- const handleUnavailableAction = () => {
- toast.info(t('agentDetail.access.actionUnavailable'))
- }
return (
<section
@@ -104,71 +59,8 @@ export function AgentAccessPage({
>
<div className="w-full min-w-0 space-y-6">
<div className="grid w-full grid-cols-1 gap-3 xl:grid-cols-2">
- <AccessSurfaceCard
- title={t('agentDetail.access.webApp.title')}
- icon="i-ri-window-line"
- iconClassName="bg-state-accent-solid text-text-primary-on-surface"
- endpointLabel={t('agentDetail.access.webApp.accessUrl')}
- endpoint={webAppUrl}
- enabled={isWebAppEnabled}
- onEnabledChange={setIsWebAppEnabled}
- copyLabel={t('agentDetail.access.copyAccessUrl')}
- badge={<SsoBadge />}
- onUnavailableAction={handleUnavailableAction}
- >
- <Button
- variant="secondary"
- size="medium"
- nativeButton={false}
- className="gap-1.5 px-3"
- render={<a href={webAppUrl} target="_blank" rel="noreferrer" aria-label={t('agentDetail.access.webApp.actions.launch')} />}
- >
- <span aria-hidden className="i-ri-external-link-line size-4" />
- {t('agentDetail.access.webApp.actions.launch')}
- </Button>
- <Button variant="secondary" size="medium" className="gap-1.5 px-3" onClick={handleUnavailableAction}>
- <span aria-hidden className="i-ri-window-line size-4" />
- {t('agentDetail.access.webApp.actions.embedded')}
- </Button>
- <Button variant="secondary" size="medium" className="gap-1.5 px-3" onClick={handleUnavailableAction}>
- <span aria-hidden className="i-ri-paint-brush-line size-4" />
- {t('agentDetail.access.webApp.actions.customize')}
- </Button>
- <Button variant="secondary" size="medium" className="gap-1.5 px-3" onClick={handleUnavailableAction}>
- <span aria-hidden className="i-ri-equalizer-line size-4" />
- {t('agentDetail.access.webApp.actions.settings')}
- </Button>
- </AccessSurfaceCard>
-
- <AccessSurfaceCard
- title={t('agentDetail.access.serviceApi.title')}
- icon="i-ri-node-tree"
- iconClassName="bg-state-accent-solid text-text-primary-on-surface"
- endpointLabel={t('agentDetail.access.serviceApi.endpoint')}
- endpoint={serviceApiEndpoint}
- enabled={isServiceApiEnabled}
- onEnabledChange={setIsServiceApiEnabled}
- copyLabel={t('agentDetail.access.copyServiceEndpoint')}
- onUnavailableAction={handleUnavailableAction}
- >
- <Button variant="secondary" size="medium" className="gap-1.5 px-3" onClick={handleUnavailableAction}>
- <span aria-hidden className="i-ri-key-2-line size-4" />
- {t('agentDetail.access.serviceApi.actions.apiKey')}
- <span className="rounded-md bg-components-badge-bg-gray-soft px-1.5 code-xs-regular text-text-tertiary">
- 21
- </span>
- </Button>
- <Button
- variant="secondary"
- size="medium"
- nativeButton={false}
- className="gap-1.5 px-3"
- render={<a href={docLink('/use-dify/publish/developing-with-apis')} target="_blank" rel="noreferrer" aria-label={t('agentDetail.access.serviceApi.actions.apiReference')} />}
- >
- <span aria-hidden className="i-ri-book-open-line size-4" />
- {t('agentDetail.access.serviceApi.actions.apiReference')}
- </Button>
- </AccessSurfaceCard>
+ <WebAppAccessCard agent={agentQuery.data} agentId={agentId} isLoading={agentQuery.isPending} />
+ <ServiceApiAccessCard agentId={agentId} />
</div>
<section aria-labelledby="agent-workflow-access-title">
@@ -188,121 +80,3 @@ export function AgentAccessPage({
</section>
)
}
-
-function AccessSurfaceCard({
- title,
- icon,
- iconClassName,
- endpointLabel,
- endpoint,
- enabled,
- onEnabledChange,
- copyLabel,
- children,
- badge,
- onUnavailableAction,
-}: AccessSurfaceCardProps) {
- const { t } = useTranslation('agentV2')
- const { copy } = useClipboard({
- onCopyError: () => {
- toast.error(t('agentDetail.access.copyFailed'))
- },
- })
-
- const handleCopyEndpoint = () => {
- void copy(endpoint)
- }
-
- return (
- <article className="overflow-hidden rounded-xl border border-components-panel-border bg-components-panel-bg shadow-xs">
- <div className="px-4 pt-4 pb-4">
- <div className="flex min-w-0 items-center gap-3">
- <div className="flex min-w-0 flex-1 items-center gap-2">
- <span className={cn('flex size-6 shrink-0 items-center justify-center rounded-lg', iconClassName)}>
- <span aria-hidden className={cn(icon, 'size-4')} />
- </span>
- <h3 className="truncate system-md-semibold text-text-secondary">
- {title}
- </h3>
- {badge}
- </div>
-
- <div className="flex shrink-0 items-center gap-3">
- <span className={cn(
- 'inline-flex items-center gap-1 system-xs-semibold-uppercase',
- enabled ? 'text-util-colors-green-green-700' : 'text-text-tertiary',
- )}
- >
- <StatusDot status={enabled ? 'success' : 'disabled'} size="small" />
- {t(enabled ? 'agentDetail.access.status.inService' : 'agentDetail.access.status.outOfService')}
- </span>
- <Switch
- size="md"
- checked={enabled}
- aria-label={t('agentDetail.access.toggleSurface', { name: title })}
- onCheckedChange={onEnabledChange}
- />
- </div>
- </div>
-
- <div className="mt-3">
- <div className="system-xs-medium text-text-tertiary">
- {endpointLabel}
- </div>
- <div className="mt-1 flex h-8 min-w-0 items-center rounded-lg bg-components-input-bg-normal px-2">
- <span className="min-w-0 flex-1 truncate system-sm-regular text-text-secondary" translate="no">
- {endpoint}
- </span>
- <Button
- variant="ghost"
- size="small"
- className="size-6 shrink-0 px-0 text-text-tertiary hover:text-text-secondary"
- aria-label={copyLabel}
- onClick={handleCopyEndpoint}
- >
- <span aria-hidden className="i-ri-file-copy-line size-4" />
- </Button>
- {badge !== undefined && badge !== null && (
- <>
- <span className="mx-1.5 h-3.5 w-px shrink-0 bg-divider-regular" />
- <Button
- variant="ghost"
- size="small"
- className="size-6 shrink-0 px-0 text-text-tertiary hover:text-text-secondary"
- aria-label={t('agentDetail.access.webApp.showQrCode')}
- onClick={onUnavailableAction}
- >
- <span aria-hidden className="i-ri-qr-code-line size-4" />
- </Button>
- <Button
- variant="ghost"
- size="small"
- className="size-6 shrink-0 px-0 text-text-tertiary hover:text-text-secondary"
- aria-label={t('agentDetail.access.webApp.refreshUrl')}
- onClick={onUnavailableAction}
- >
- <span aria-hidden className="i-ri-refresh-line size-4" />
- </Button>
- </>
- )}
- </div>
- </div>
- </div>
-
- <div className="flex min-h-16 flex-wrap items-center gap-2 border-t border-divider-subtle px-4 py-4">
- {children}
- </div>
- </article>
- )
-}
-
-function SsoBadge() {
- const { t } = useTranslation('agentV2')
-
- return (
- <span className="inline-flex h-4.5 shrink-0 items-center gap-1 rounded-sm border border-divider-deep px-1.5 system-2xs-semibold-uppercase text-text-tertiary">
- <span aria-hidden className="i-ri-shield-check-line size-3" />
- {t('agentDetail.access.webApp.ssoEnabled')}
- </span>
- )
-}
diff --git a/web/features/agent-v2/agent-detail/configure/__tests__/page.spec.tsx b/web/features/agent-v2/agent-detail/configure/__tests__/page.spec.tsx
index e40ddfadd0d..09b9be74b9a 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,32 +1,53 @@
+import type { ReactNode } from 'react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
-import { render, screen } from '@testing-library/react'
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { AgentConfigurePage } from '../page'
const mocks = vi.hoisted(() => ({
+ applyBuildDraft: vi.fn(),
+ checkoutBuildDraft: vi.fn(),
+ discardBuildDraft: vi.fn(),
+ refreshDebugConversation: vi.fn(),
queryState: {
agent: {
data: {
+ debug_conversation_id: 'debug-conversation-old',
icon: 'agent',
icon_background: '#E0F2FE',
icon_type: 'emoji',
name: 'Research Agent',
},
isFetching: false,
+ isError: false,
isPending: false,
isSuccess: true,
},
composer: {
data: undefined as unknown,
isFetching: true,
+ isError: false,
isPending: true,
isSuccess: false,
+ refetch: vi.fn(),
},
version: {
data: undefined as unknown,
isFetching: false,
+ isError: false,
isPending: false,
isSuccess: false,
},
+ buildDraft: {
+ data: undefined as unknown,
+ dataUpdatedAt: 0,
+ error: null as unknown,
+ isFetching: false,
+ isError: false,
+ isPending: false,
+ isSuccess: false,
+ refetch: vi.fn(),
+ },
},
}))
@@ -44,10 +65,13 @@ vi.mock('@tanstack/react-query', async (importOriginal) => {
return mocks.queryState.composer
if (queryKey === 'version')
return mocks.queryState.version
+ if (queryKey === 'build-draft')
+ return mocks.queryState.buildDraft
return {
data: undefined,
isFetching: false,
+ isError: false,
isPending: false,
isSuccess: false,
}
@@ -63,6 +87,21 @@ vi.mock('@/service/client', () => ({
queryOptions: () => ({ queryKey: ['agent'] }),
queryKey: () => ['agent'],
},
+ debugConversation: {
+ refresh: {
+ post: {
+ mutationOptions: (options?: { onSuccess?: (data: { debug_conversation_id: string }) => void }) => ({
+ mutationFn: mocks.refreshDebugConversation,
+ ...options,
+ }),
+ },
+ },
+ },
+ publish: {
+ post: {
+ mutationOptions: () => ({ mutationFn: vi.fn() }),
+ },
+ },
composer: {
get: {
queryOptions: () => ({ queryKey: ['composer'] }),
@@ -72,6 +111,24 @@ vi.mock('@/service/client', () => ({
mutationOptions: () => ({ mutationFn: vi.fn() }),
},
},
+ buildDraft: {
+ get: {
+ queryOptions: () => ({ queryKey: ['build-draft'] }),
+ },
+ checkout: {
+ post: {
+ mutationOptions: () => ({ mutationFn: mocks.checkoutBuildDraft }),
+ },
+ },
+ apply: {
+ post: {
+ mutationOptions: () => ({ mutationFn: mocks.applyBuildDraft }),
+ },
+ },
+ delete: {
+ mutationOptions: () => ({ mutationFn: mocks.discardBuildDraft }),
+ },
+ },
versions: {
byVersionId: {
get: {
@@ -87,6 +144,23 @@ vi.mock('@/service/client', () => ({
},
}))
+vi.mock('../build-draft-query', () => ({
+ agentConfigureConsoleQuery: {
+ agent: {
+ byAgentId: {
+ buildDraft: {
+ get: {
+ queryOptions: () => ({
+ queryFn: vi.fn(),
+ queryKey: ['build-draft'],
+ }),
+ },
+ },
+ },
+ },
+ },
+}))
+
vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({
useDefaultModel: () => ({ data: undefined }),
useTextGenerationCurrentProviderAndModelAndModelList: () => ({
@@ -94,12 +168,87 @@ vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', ()
}),
}))
-vi.mock('../components/orchestrate', () => ({
- AgentOrchestratePanel: () => <div role="region" aria-label="orchestrate-panel" />,
+vi.mock('../components/orchestrate', async () => {
+ const { useAtomValue } = await import('jotai')
+ const { agentComposerPromptAtom } = await import('@/features/agent-v2/agent-composer/store-modules/prompt')
+
+ return {
+ AgentOrchestratePanel: (props: {
+ bottomAction?: ReactNode
+ isBuildDraftActive?: boolean
+ onOpenVersions?: () => void
+ readOnly?: boolean
+ showPublishBar?: boolean
+ }) => {
+ const prompt = useAtomValue(agentComposerPromptAtom)
+
+ return (
+ <div role="region" aria-label="orchestrate-panel">
+ <span>{`buildDraft:${props.isBuildDraftActive ? 'yes' : 'no'}`}</span>
+ <span>{`readonly:${props.readOnly ? 'yes' : 'no'}`}</span>
+ <span>{`publish:${props.showPublishBar ? 'yes' : 'no'}`}</span>
+ <span>{`prompt:${prompt}`}</span>
+ <button type="button" onClick={props.onOpenVersions}>open versions</button>
+ {props.bottomAction}
+ </div>
+ )
+ },
+ }
+})
+
+vi.mock('../components/orchestrate/build-draft-bar', () => ({
+ AgentBuildDraftBar: (props: {
+ changesCount: number
+ onApply: () => void
+ onDiscard: () => void
+ }) => (
+ <div role="region" aria-label="build-draft-bar">
+ <span>{`changes:${props.changesCount}`}</span>
+ <button type="button" onClick={props.onApply}>apply build draft</button>
+ <button type="button" onClick={props.onDiscard}>discard build draft</button>
+ </div>
+ ),
+}))
+
+vi.mock('../components/preview/build-chat', () => ({
+ AgentBuildChat: (props: {
+ conversationId?: string | null
+ onConversationComplete?: () => void
+ onConversationIdChange?: (conversationId: string) => void
+ onSaveDraftBeforeRun?: () => Promise<void>
+ }) => (
+ <div role="region" aria-label="build-chat">
+ <span>{`build:${props.conversationId ?? 'none'}`}</span>
+ <button type="button" onClick={() => props.onConversationIdChange?.('build-conversation-new')}>
+ save build conversation
+ </button>
+ <button
+ type="button"
+ onClick={() => {
+ void props.onSaveDraftBeforeRun?.()
+ }}
+ >
+ send build message
+ </button>
+ <button type="button" onClick={() => props.onConversationComplete?.()}>
+ complete build conversation
+ </button>
+ </div>
+ ),
}))
-vi.mock('../components/preview/chat', () => ({
- AgentPreviewChat: () => <div role="region" aria-label="preview-chat" />,
+vi.mock('../components/preview/preview-chat', () => ({
+ AgentPreviewChat: (props: {
+ conversationId?: string | null
+ onConversationIdChange?: (conversationId: string) => void
+ }) => (
+ <div role="region" aria-label="preview-chat">
+ <span>{`preview:${props.conversationId ?? 'none'}`}</span>
+ <button type="button" onClick={() => props.onConversationIdChange?.('preview-conversation-new')}>
+ save preview conversation
+ </button>
+ </div>
+ ),
}))
vi.mock('../components/preview/chat-features-panel', () => ({
@@ -107,7 +256,29 @@ vi.mock('../components/preview/chat-features-panel', () => ({
}))
vi.mock('../components/preview/header', () => ({
- AgentPreviewHeader: () => <div role="banner" />,
+ AgentPreviewHeader: (props: {
+ mode: 'build' | 'preview'
+ previewEnabled: boolean
+ onModeChange: (mode: 'build' | 'preview') => void
+ onOpenWorkingDirectory: () => void
+ onRefresh: () => void
+ }) => (
+ <div>
+ <div>{props.mode}</div>
+ <button type="button" disabled={!props.previewEnabled} onClick={() => props.onModeChange('preview')}>
+ preview mode
+ </button>
+ <button type="button" onClick={() => props.onModeChange('build')}>
+ build mode
+ </button>
+ <button type="button" onClick={props.onOpenWorkingDirectory}>
+ open working directory
+ </button>
+ <button type="button" onClick={props.onRefresh}>
+ restart preview
+ </button>
+ </div>
+ ),
}))
vi.mock('../components/preview/versions-panel', () => ({
@@ -119,33 +290,62 @@ vi.mock('../components/preview/versions-panel', () => ({
describe('AgentConfigurePage', () => {
beforeEach(() => {
vi.clearAllMocks()
+ mocks.refreshDebugConversation.mockResolvedValue({
+ debug_conversation_id: 'debug-conversation-new',
+ })
+ mocks.applyBuildDraft.mockResolvedValue({ result: 'success', draft: {} })
+ mocks.checkoutBuildDraft.mockResolvedValue({
+ variant: 'agent_app',
+ draft: {},
+ agent_soul: {},
+ })
+ mocks.discardBuildDraft.mockResolvedValue({ result: 'success' })
mocks.queryState.agent = {
data: {
icon: 'agent',
icon_background: '#E0F2FE',
icon_type: 'emoji',
name: 'Research Agent',
+ debug_conversation_id: 'debug-conversation-old',
},
isFetching: false,
+ isError: false,
isPending: false,
isSuccess: true,
}
mocks.queryState.composer = {
data: undefined as unknown,
isFetching: true,
+ isError: false,
isPending: true,
isSuccess: false,
+ refetch: vi.fn(),
}
mocks.queryState.version = {
data: undefined as unknown,
isFetching: false,
+ isError: false,
+ isPending: false,
+ isSuccess: false,
+ }
+ mocks.queryState.buildDraft = {
+ data: undefined as unknown,
+ dataUpdatedAt: 0,
+ error: null,
+ isFetching: false,
+ isError: false,
isPending: false,
isSuccess: false,
+ refetch: vi.fn(),
}
})
+ afterEach(() => {
+ vi.useRealTimers()
+ })
+
describe('Loading state', () => {
- it('should show loading instead of the configure panels while composer data is pending', () => {
+ it('should show the page loading indicator instead of skeleton panels while composer data is pending', () => {
const queryClient = new QueryClient()
render(
@@ -154,8 +354,614 @@ describe('AgentConfigurePage', () => {
</QueryClientProvider>,
)
+ const configureSection = screen.getByRole('region', { name: 'agentV2.agentDetail.sections.configure' })
+ expect(configureSection).toHaveAttribute('aria-busy', 'true')
+ expect(configureSection).toHaveClass('bg-background-body')
expect(screen.getByRole('status', { name: 'appApi.loading' })).toBeInTheDocument()
expect(screen.queryByRole('region', { name: 'orchestrate-panel' })).not.toBeInTheDocument()
})
})
+
+ describe('Right panel mode', () => {
+ it('should keep preview disabled and stay in build mode', async () => {
+ const user = userEvent.setup()
+ const queryClient = new QueryClient()
+ mocks.queryState.composer = {
+ data: {},
+ isFetching: false,
+ isError: false,
+ isPending: false,
+ isSuccess: true,
+ refetch: vi.fn(),
+ }
+
+ render(
+ <QueryClientProvider client={queryClient}>
+ <AgentConfigurePage agentId="agent-1" />
+ </QueryClientProvider>,
+ )
+
+ expect(screen.getByRole('region', { name: 'build-chat' })).toHaveTextContent('build:debug-conversation-old')
+ expect(screen.queryByRole('region', { name: 'preview-chat' })).not.toBeInTheDocument()
+
+ await user.click(screen.getByRole('button', { name: 'save build conversation' }))
+
+ expect(screen.getByRole('region', { name: 'build-chat' })).toHaveTextContent('build:build-conversation-new')
+ expect(mocks.refreshDebugConversation).not.toHaveBeenCalled()
+
+ await user.click(screen.getByRole('button', { name: 'restart preview' }))
+
+ expect(mocks.refreshDebugConversation).toHaveBeenCalledWith({
+ params: {
+ agent_id: 'agent-1',
+ },
+ body: {
+ debug_conversation_id: 'build-conversation-new',
+ },
+ }, expect.any(Object))
+
+ expect(screen.getByRole('region', { name: 'build-chat' })).toHaveTextContent('build:none')
+
+ const previewButton = screen.getByRole('button', { name: 'preview mode' })
+ expect(previewButton).toBeDisabled()
+
+ await user.click(previewButton)
+
+ expect(screen.getByRole('region', { name: 'build-chat' })).toHaveTextContent('build:none')
+ expect(screen.queryByRole('region', { name: 'preview-chat' })).not.toBeInTheDocument()
+ })
+
+ it('should keep preview disabled', async () => {
+ const user = userEvent.setup()
+ const queryClient = new QueryClient()
+ mocks.queryState.composer = {
+ data: {},
+ isFetching: false,
+ isError: false,
+ isPending: false,
+ isSuccess: true,
+ refetch: vi.fn(),
+ }
+
+ render(
+ <QueryClientProvider client={queryClient}>
+ <AgentConfigurePage agentId="agent-1" />
+ </QueryClientProvider>,
+ )
+
+ const previewButton = screen.getByRole('button', { name: 'preview mode' })
+ expect(previewButton).toBeDisabled()
+
+ await user.click(previewButton)
+
+ expect(screen.getByRole('region', { name: 'build-chat' })).toHaveTextContent('build:debug-conversation-old')
+ expect(screen.queryByRole('region', { name: 'preview-chat', hidden: true })).not.toBeInTheDocument()
+ })
+
+ it('should stay in normal draft mode when build draft returns 404 even if a debug conversation exists', () => {
+ const queryClient = new QueryClient()
+ mocks.queryState.composer = {
+ data: {
+ agent_soul: {
+ prompt: {
+ system_prompt: 'draft prompt',
+ },
+ },
+ },
+ isFetching: false,
+ isError: false,
+ isPending: false,
+ isSuccess: true,
+ refetch: vi.fn(),
+ }
+ mocks.queryState.buildDraft = {
+ data: undefined as unknown,
+ dataUpdatedAt: 0,
+ error: new Response(null, { status: 404 }),
+ isFetching: false,
+ isError: true,
+ isPending: false,
+ isSuccess: false,
+ refetch: vi.fn(),
+ }
+
+ render(
+ <QueryClientProvider client={queryClient}>
+ <AgentConfigurePage agentId="agent-1" />
+ </QueryClientProvider>,
+ )
+
+ expect(screen.getByRole('region', { name: 'orchestrate-panel' })).toHaveTextContent('readonly:no')
+ expect(screen.getByRole('region', { name: 'orchestrate-panel' })).toHaveTextContent('buildDraft:no')
+ expect(screen.getByRole('region', { name: 'orchestrate-panel' })).toHaveTextContent('publish:yes')
+ expect(screen.queryByRole('region', { name: 'build-draft-bar' })).not.toBeInTheDocument()
+ })
+
+ it('should enter build draft mode when build draft data exists', () => {
+ const queryClient = new QueryClient()
+ mocks.queryState.composer = {
+ data: {
+ agent_soul: {
+ prompt: {
+ system_prompt: 'draft prompt',
+ },
+ },
+ },
+ isFetching: false,
+ isError: false,
+ isPending: false,
+ isSuccess: true,
+ refetch: vi.fn(),
+ }
+ mocks.queryState.buildDraft = {
+ data: {
+ agent_soul: {
+ prompt: {
+ system_prompt: 'build prompt',
+ },
+ },
+ draft: {},
+ variant: 'agent_app',
+ },
+ dataUpdatedAt: 1,
+ error: null,
+ isFetching: false,
+ isError: false,
+ isPending: false,
+ isSuccess: true,
+ refetch: vi.fn(),
+ }
+
+ render(
+ <QueryClientProvider client={queryClient}>
+ <AgentConfigurePage agentId="agent-1" />
+ </QueryClientProvider>,
+ )
+
+ expect(screen.getByRole('region', { name: 'orchestrate-panel' })).toHaveTextContent('readonly:yes')
+ expect(screen.getByRole('region', { name: 'orchestrate-panel' })).toHaveTextContent('buildDraft:yes')
+ expect(screen.getByRole('region', { name: 'orchestrate-panel' })).toHaveTextContent('publish:no')
+ expect(screen.getByRole('region', { name: 'build-draft-bar' })).toBeInTheDocument()
+ })
+
+ it('should show the build draft bar after a new build conversation refresh completes', async () => {
+ vi.useFakeTimers()
+ const queryClient = new QueryClient()
+ const refetchBuildDraft = vi.fn().mockResolvedValue({})
+ mocks.queryState.composer = {
+ data: {
+ agent_soul: {
+ prompt: {
+ system_prompt: 'draft prompt',
+ },
+ },
+ },
+ isFetching: false,
+ isError: false,
+ isPending: false,
+ isSuccess: true,
+ refetch: vi.fn(),
+ }
+ mocks.queryState.buildDraft = {
+ data: {
+ agent_soul: {
+ prompt: {
+ system_prompt: 'build prompt',
+ },
+ },
+ draft: {},
+ variant: 'agent_app',
+ },
+ dataUpdatedAt: 1,
+ error: null,
+ isFetching: false,
+ isError: false,
+ isPending: false,
+ isSuccess: true,
+ refetch: refetchBuildDraft,
+ }
+
+ render(
+ <QueryClientProvider client={queryClient}>
+ <AgentConfigurePage agentId="agent-1" />
+ </QueryClientProvider>,
+ )
+
+ expect(screen.getByRole('region', { name: 'build-draft-bar' })).toBeInTheDocument()
+
+ fireEvent.click(screen.getByRole('button', { name: 'send build message' }))
+
+ expect(screen.queryByRole('region', { name: 'build-draft-bar' })).not.toBeInTheDocument()
+
+ fireEvent.click(screen.getByRole('button', { name: 'complete build conversation' }))
+
+ expect(refetchBuildDraft).not.toHaveBeenCalled()
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1000)
+ })
+
+ expect(refetchBuildDraft).toHaveBeenCalled()
+ expect(screen.getByRole('region', { name: 'build-draft-bar' })).toBeInTheDocument()
+ })
+
+ it('should discard the build draft when restarting build mode with a build draft', async () => {
+ const user = userEvent.setup()
+ const queryClient = new QueryClient()
+ mocks.queryState.composer = {
+ data: {},
+ isFetching: false,
+ isError: false,
+ isPending: false,
+ isSuccess: true,
+ refetch: vi.fn(),
+ }
+ mocks.queryState.buildDraft = {
+ data: {
+ agent_soul: {},
+ draft: {},
+ variant: 'agent_app',
+ },
+ dataUpdatedAt: 1,
+ error: null,
+ isFetching: false,
+ isError: false,
+ isPending: false,
+ isSuccess: true,
+ refetch: vi.fn(),
+ }
+
+ render(
+ <QueryClientProvider client={queryClient}>
+ <AgentConfigurePage agentId="agent-1" />
+ </QueryClientProvider>,
+ )
+
+ await user.click(screen.getByRole('button', { name: 'restart preview' }))
+
+ await waitFor(() => expect(mocks.discardBuildDraft).toHaveBeenCalledWith(
+ {
+ params: {
+ agent_id: 'agent-1',
+ },
+ },
+ expect.any(Object),
+ ))
+ expect(mocks.refreshDebugConversation).toHaveBeenCalledWith({
+ params: {
+ agent_id: 'agent-1',
+ },
+ body: {
+ debug_conversation_id: 'debug-conversation-old',
+ },
+ }, expect.any(Object))
+ expect(screen.getByRole('region', { name: 'build-chat' })).toHaveTextContent('build:none')
+ })
+
+ it('should switch soul source to view version when selecting a version from build draft mode', async () => {
+ const user = userEvent.setup()
+ const queryClient = new QueryClient()
+ mocks.queryState.composer = {
+ data: {
+ agent_soul: {
+ prompt: {
+ system_prompt: 'draft prompt',
+ },
+ },
+ },
+ isFetching: false,
+ isError: false,
+ isPending: false,
+ isSuccess: true,
+ refetch: vi.fn(),
+ }
+ mocks.queryState.buildDraft = {
+ data: {
+ agent_soul: {
+ prompt: {
+ system_prompt: 'build prompt',
+ },
+ },
+ draft: {},
+ variant: 'agent_app',
+ },
+ dataUpdatedAt: 1,
+ error: null,
+ isFetching: false,
+ isError: false,
+ isPending: false,
+ isSuccess: true,
+ refetch: vi.fn(),
+ }
+
+ render(
+ <QueryClientProvider client={queryClient}>
+ <AgentConfigurePage agentId="agent-1" />
+ </QueryClientProvider>,
+ )
+
+ expect(screen.getByRole('region', { name: 'build-draft-bar' })).toBeInTheDocument()
+
+ await user.click(screen.getByRole('button', { name: 'open versions' }))
+ await user.click(screen.getByRole('button', { name: 'select version' }))
+
+ expect(screen.getByRole('region', { name: 'orchestrate-panel' })).toHaveTextContent('readonly:yes')
+ expect(screen.getByRole('region', { name: 'orchestrate-panel' })).toHaveTextContent('publish:yes')
+ expect(screen.queryByRole('region', { name: 'build-draft-bar' })).not.toBeInTheDocument()
+ })
+
+ it('should apply the build draft and rebase the composer store from the refetched normal draft', async () => {
+ const user = userEvent.setup()
+ const queryClient = new QueryClient()
+ const refetchComposer = vi.fn(async () => {
+ mocks.queryState.composer = {
+ ...mocks.queryState.composer,
+ data: {
+ agent_soul: {
+ prompt: {
+ system_prompt: 'applied prompt',
+ },
+ },
+ },
+ }
+
+ return {}
+ })
+ mocks.queryState.composer = {
+ data: {
+ agent_soul: {
+ prompt: {
+ system_prompt: 'old draft prompt',
+ },
+ },
+ },
+ isFetching: false,
+ isError: false,
+ isPending: false,
+ isSuccess: true,
+ refetch: refetchComposer,
+ }
+ mocks.queryState.buildDraft = {
+ data: {
+ agent_soul: {
+ prompt: {
+ system_prompt: 'build prompt',
+ },
+ },
+ draft: {},
+ variant: 'agent_app',
+ },
+ dataUpdatedAt: 1,
+ error: null,
+ isFetching: false,
+ isError: false,
+ isPending: false,
+ isSuccess: true,
+ refetch: vi.fn(),
+ }
+
+ render(
+ <QueryClientProvider client={queryClient}>
+ <AgentConfigurePage agentId="agent-1" />
+ </QueryClientProvider>,
+ )
+
+ await user.click(screen.getByRole('button', { name: 'apply build draft' }))
+
+ await waitFor(() => expect(mocks.applyBuildDraft).toHaveBeenCalledWith(
+ {
+ params: {
+ agent_id: 'agent-1',
+ },
+ },
+ expect.any(Object),
+ ))
+ expect(mocks.refreshDebugConversation).toHaveBeenCalledWith({
+ params: {
+ agent_id: 'agent-1',
+ },
+ body: {
+ debug_conversation_id: 'debug-conversation-old',
+ },
+ }, expect.any(Object))
+ expect(refetchComposer).toHaveBeenCalled()
+ expect(screen.getByRole('region', { name: 'build-chat' })).toHaveTextContent('build:none')
+ await waitFor(() => {
+ expect(screen.getByRole('region', { name: 'orchestrate-panel' })).toHaveTextContent('prompt:applied prompt')
+ })
+ })
+
+ it('should keep exiting build draft when debug conversation refresh fails after applying build draft', async () => {
+ const user = userEvent.setup()
+ const queryClient = new QueryClient()
+ const refetchComposer = vi.fn(async () => {
+ mocks.queryState.composer = {
+ ...mocks.queryState.composer,
+ data: {
+ agent_soul: {
+ prompt: {
+ system_prompt: 'applied prompt',
+ },
+ },
+ },
+ }
+
+ return {}
+ })
+ mocks.refreshDebugConversation.mockRejectedValueOnce(new Error('refresh failed'))
+ mocks.queryState.composer = {
+ data: {
+ agent_soul: {
+ prompt: {
+ system_prompt: 'old draft prompt',
+ },
+ },
+ },
+ isFetching: false,
+ isError: false,
+ isPending: false,
+ isSuccess: true,
+ refetch: refetchComposer,
+ }
+ mocks.queryState.buildDraft = {
+ data: {
+ agent_soul: {
+ prompt: {
+ system_prompt: 'build prompt',
+ },
+ },
+ draft: {},
+ variant: 'agent_app',
+ },
+ dataUpdatedAt: 1,
+ error: null,
+ isFetching: false,
+ isError: false,
+ isPending: false,
+ isSuccess: true,
+ refetch: vi.fn(),
+ }
+
+ render(
+ <QueryClientProvider client={queryClient}>
+ <AgentConfigurePage agentId="agent-1" />
+ </QueryClientProvider>,
+ )
+
+ await user.click(screen.getByRole('button', { name: 'apply build draft' }))
+
+ await waitFor(() => expect(mocks.applyBuildDraft).toHaveBeenCalledWith(
+ {
+ params: {
+ agent_id: 'agent-1',
+ },
+ },
+ expect.any(Object),
+ ))
+ expect(mocks.refreshDebugConversation).toHaveBeenCalledWith({
+ params: {
+ agent_id: 'agent-1',
+ },
+ body: {
+ debug_conversation_id: 'debug-conversation-old',
+ },
+ }, expect.any(Object))
+ expect(refetchComposer).toHaveBeenCalled()
+ expect(screen.getByRole('region', { name: 'build-chat' })).toHaveTextContent('build:none')
+ await waitFor(() => {
+ expect(screen.getByRole('region', { name: 'orchestrate-panel' })).toHaveTextContent('buildDraft:no')
+ expect(screen.getByRole('region', { name: 'orchestrate-panel' })).toHaveTextContent('prompt:applied prompt')
+ })
+ })
+
+ it('should discard the build draft and start a new build session', async () => {
+ const user = userEvent.setup()
+ const queryClient = new QueryClient()
+ mocks.queryState.composer = {
+ data: {},
+ isFetching: false,
+ isError: false,
+ isPending: false,
+ isSuccess: true,
+ refetch: vi.fn(),
+ }
+ mocks.queryState.buildDraft = {
+ data: {
+ agent_soul: {},
+ draft: {},
+ variant: 'agent_app',
+ },
+ dataUpdatedAt: 1,
+ error: null,
+ isFetching: false,
+ isError: false,
+ isPending: false,
+ isSuccess: true,
+ refetch: vi.fn(),
+ }
+
+ render(
+ <QueryClientProvider client={queryClient}>
+ <AgentConfigurePage agentId="agent-1" />
+ </QueryClientProvider>,
+ )
+
+ await user.click(screen.getByRole('button', { name: 'discard build draft' }))
+
+ await waitFor(() => expect(mocks.discardBuildDraft).toHaveBeenCalledWith(
+ {
+ params: {
+ agent_id: 'agent-1',
+ },
+ },
+ expect.any(Object),
+ ))
+ expect(mocks.refreshDebugConversation).toHaveBeenCalledWith({
+ params: {
+ agent_id: 'agent-1',
+ },
+ body: {
+ debug_conversation_id: 'debug-conversation-old',
+ },
+ }, expect.any(Object))
+ expect(screen.getByRole('region', { name: 'build-chat' })).toHaveTextContent('build:none')
+ })
+
+ it('should keep exiting build draft when debug conversation refresh fails after discarding build draft', async () => {
+ const user = userEvent.setup()
+ const queryClient = new QueryClient()
+ mocks.refreshDebugConversation.mockRejectedValueOnce(new Error('refresh failed'))
+ mocks.queryState.composer = {
+ data: {},
+ isFetching: false,
+ isError: false,
+ isPending: false,
+ isSuccess: true,
+ refetch: vi.fn(),
+ }
+ mocks.queryState.buildDraft = {
+ data: {
+ agent_soul: {},
+ draft: {},
+ variant: 'agent_app',
+ },
+ dataUpdatedAt: 1,
+ error: null,
+ isFetching: false,
+ isError: false,
+ isPending: false,
+ isSuccess: true,
+ refetch: vi.fn(),
+ }
+
+ render(
+ <QueryClientProvider client={queryClient}>
+ <AgentConfigurePage agentId="agent-1" />
+ </QueryClientProvider>,
+ )
+
+ await user.click(screen.getByRole('button', { name: 'discard build draft' }))
+
+ await waitFor(() => expect(mocks.discardBuildDraft).toHaveBeenCalledWith(
+ {
+ params: {
+ agent_id: 'agent-1',
+ },
+ },
+ expect.any(Object),
+ ))
+ expect(mocks.refreshDebugConversation).toHaveBeenCalledWith({
+ params: {
+ agent_id: 'agent-1',
+ },
+ body: {
+ debug_conversation_id: 'debug-conversation-old',
+ },
+ }, expect.any(Object))
+ expect(screen.getByRole('region', { name: 'build-chat' })).toHaveTextContent('build:none')
+ await waitFor(() => {
+ expect(screen.getByRole('region', { name: 'orchestrate-panel' })).toHaveTextContent('buildDraft:no')
+ })
+ })
+ })
})
diff --git a/web/features/agent-v2/agent-detail/configure/__tests__/use-agent-configure-sync.spec.tsx b/web/features/agent-v2/agent-detail/configure/__tests__/use-agent-configure-sync.spec.tsx
index 69f8ff0735a..70d0b4fc352 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
@@ -3,9 +3,15 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { act, renderHook } from '@testing-library/react'
import { createStore, Provider as JotaiProvider } from 'jotai'
import { defaultAgentSoulConfigFormState } from '@/features/agent-v2/agent-composer/form-state'
-import { agentComposerDraftAtom } from '@/features/agent-v2/agent-composer/store'
+import { agentComposerDraftAtom, agentComposerPublishedDraftAtom } from '@/features/agent-v2/agent-composer/store'
+import { agentComposerFilesAtom } from '@/features/agent-v2/agent-composer/store-modules/files'
+import { agentComposerPromptAtom } from '@/features/agent-v2/agent-composer/store-modules/prompt'
import { useAgentConfigureSync } from '../use-agent-configure-sync'
+const toastMock = vi.hoisted(() => ({
+ success: vi.fn(),
+}))
+
const composerPutMutationFn = vi.hoisted(() => vi.fn(async (variables: {
body: {
agent_soul: Record<string, unknown>
@@ -34,6 +40,38 @@ const composerPutMutationOptions = vi.hoisted(() => vi.fn((options?: {
},
})))
+type PublishAgentVariables = {
+ params: { agent_id: string }
+ body: Record<string, never>
+}
+
+type PublishAgentResponse = {
+ active_config_snapshot: Record<string, unknown> | null
+ active_config_snapshot_id: string
+ result: string
+}
+
+const publishAgentMutationFn = vi.hoisted(() => vi.fn(async (_variables: PublishAgentVariables): Promise<PublishAgentResponse> => ({
+ active_config_snapshot: {
+ id: 'snapshot-1',
+ },
+ active_config_snapshot_id: 'snapshot-1',
+ result: 'success',
+})))
+
+const publishAgentMutationOptions = vi.hoisted(() => vi.fn((options?: {
+ onSuccess?: (
+ data: PublishAgentResponse,
+ variables: PublishAgentVariables,
+ ) => void
+}) => ({
+ mutationFn: async (variables: PublishAgentVariables) => {
+ const data = await publishAgentMutationFn(variables)
+ options?.onSuccess?.(data, variables)
+ return data
+ },
+})))
+
function createDeferredPromise<T>() {
let resolve!: (value: T) => void
const promise = new Promise<T>((promiseResolve) => {
@@ -43,6 +81,10 @@ function createDeferredPromise<T>() {
return { promise, resolve }
}
+vi.mock('@langgenius/dify-ui/toast', () => ({
+ toast: toastMock,
+}))
+
vi.mock('@/service/client', () => ({
consoleQuery: {
agent: {
@@ -64,6 +106,11 @@ vi.mock('@/service/client', () => ({
mutationOptions: composerPutMutationOptions,
},
},
+ publish: {
+ post: {
+ mutationOptions: publishAgentMutationOptions,
+ },
+ },
versions: {
get: {
key: () => ['agent-versions'],
@@ -74,7 +121,13 @@ vi.mock('@/service/client', () => ({
},
}))
-function renderUseAgentConfigureSync() {
+function renderUseAgentConfigureSync({
+ baseConfig,
+ currentModel,
+}: {
+ baseConfig?: Parameters<typeof useAgentConfigureSync>[0]['baseConfig']
+ currentModel?: Parameters<typeof useAgentConfigureSync>[0]['currentModel']
+} = {}) {
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false },
@@ -93,6 +146,8 @@ function renderUseAgentConfigureSync() {
return {
...renderHook(() => useAgentConfigureSync({
agentId: 'agent-1',
+ baseConfig,
+ currentModel,
enabled: true,
}), { wrapper }),
queryClient,
@@ -113,6 +168,10 @@ describe('useAgentConfigureSync', () => {
it('should automatically save configure page changes to draft', async () => {
vi.setSystemTime(1710000100000)
const { queryClient, result, store } = renderUseAgentConfigureSync()
+ queryClient.setQueryData(['agent-detail', 'agent-1'], {
+ active_config_is_published: true,
+ name: 'Agent',
+ })
expect(result.current.draftSavedAt).toBeUndefined()
@@ -123,6 +182,12 @@ describe('useAgentConfigureSync', () => {
})
})
+ expect(queryClient.getQueryData(['agent-detail', 'agent-1'])).toEqual({
+ active_config_is_published: false,
+ name: 'Agent',
+ })
+ expect(composerPutMutationFn).not.toHaveBeenCalled()
+
await act(async () => {
await vi.advanceTimersByTimeAsync(5000)
})
@@ -142,9 +207,120 @@ describe('useAgentConfigureSync', () => {
}),
}))
expect(queryClient.getQueryData(['agent-composer', 'agent-1'])).toBeUndefined()
+ expect(queryClient.getQueryData(['agent-detail', 'agent-1'])).toEqual({
+ active_config_is_published: false,
+ name: 'Agent',
+ })
expect(result.current.draftSavedAt).toBe(1710000105000)
})
+ it('should include Agent Soul files when autosaving file changes', async () => {
+ const { store } = renderUseAgentConfigureSync()
+
+ act(() => {
+ store.set(agentComposerDraftAtom, {
+ ...defaultAgentSoulConfigFormState,
+ files: [
+ {
+ id: 'files/uploaded.md',
+ name: 'uploaded.md',
+ icon: 'markdown',
+ fileId: 'drive-file-1',
+ driveKey: 'files/uploaded.md',
+ },
+ ],
+ })
+ })
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(5000)
+ })
+
+ expect(composerPutMutationFn).toHaveBeenCalledWith(expect.objectContaining({
+ body: expect.objectContaining({
+ agent_soul: expect.objectContaining({
+ files: {
+ skills: [],
+ files: [
+ {
+ id: 'files/uploaded.md',
+ file_id: 'drive-file-1',
+ name: 'uploaded.md',
+ drive_key: 'files/uploaded.md',
+ },
+ ],
+ },
+ }),
+ }),
+ }))
+ })
+
+ it('should preserve uploaded files when prompt is updated immediately after upload', async () => {
+ const { store } = renderUseAgentConfigureSync()
+
+ act(() => {
+ store.set(agentComposerFilesAtom, [
+ {
+ id: 'files/uploaded.md',
+ name: 'uploaded.md',
+ icon: 'markdown',
+ fileId: 'drive-file-1',
+ driveKey: 'files/uploaded.md',
+ },
+ ])
+ store.set(agentComposerPromptAtom, 'Use [§file:files%2Fuploaded.md:uploaded.md§]')
+ })
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(5000)
+ })
+
+ expect(composerPutMutationFn).toHaveBeenCalledWith(expect.objectContaining({
+ body: expect.objectContaining({
+ agent_soul: expect.objectContaining({
+ prompt: expect.objectContaining({
+ system_prompt: 'Use [§file:files%2Fuploaded.md:uploaded.md§]',
+ }),
+ files: {
+ skills: [],
+ files: [
+ {
+ id: 'files/uploaded.md',
+ file_id: 'drive-file-1',
+ name: 'uploaded.md',
+ drive_key: 'files/uploaded.md',
+ },
+ ],
+ },
+ }),
+ }),
+ }))
+ })
+
+ it('should skip autosave when knowledge retrieval validation fails', async () => {
+ const { result, store } = renderUseAgentConfigureSync()
+
+ act(() => {
+ store.set(agentComposerDraftAtom, {
+ ...defaultAgentSoulConfigFormState,
+ knowledgeRetrievals: [
+ {
+ id: 'retrieval-1',
+ name: 'Docs Search',
+ datasetRefs: [],
+ },
+ ],
+ })
+ })
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(5000)
+ })
+
+ expect(composerPutMutationFn).not.toHaveBeenCalled()
+ expect(result.current.draftSavedAt).toBeUndefined()
+ })
+
it('should save the latest draft immediately when requested', async () => {
vi.setSystemTime(1710000200000)
const { result, store } = renderUseAgentConfigureSync()
@@ -178,22 +354,42 @@ describe('useAgentConfigureSync', () => {
expect(result.current.draftSavedAt).toBe(1710000200000)
})
+ it('should reject manual save when knowledge retrieval validation fails', async () => {
+ const { result, store } = renderUseAgentConfigureSync()
+
+ act(() => {
+ store.set(agentComposerDraftAtom, {
+ ...defaultAgentSoulConfigFormState,
+ knowledgeRetrievals: [
+ {
+ id: 'retrieval-1',
+ name: 'Docs Search',
+ datasetRefs: [],
+ },
+ ],
+ })
+ })
+
+ await expect(result.current.saveDraft()).rejects.toThrow('Agent knowledge retrieval configuration is invalid.')
+ expect(composerPutMutationFn).not.toHaveBeenCalled()
+ })
+
it('should publish only when publishDraft is called explicitly', async () => {
- const { queryClient, result } = renderUseAgentConfigureSync()
+ const { queryClient, result, store } = renderUseAgentConfigureSync()
+ const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')
queryClient.setQueryData(['agent-detail', 'agent-1'], {
active_config_is_published: false,
name: 'Agent',
})
+ act(() => {
+ store.set(agentComposerDraftAtom, {
+ ...defaultAgentSoulConfigFormState,
+ prompt: 'Published prompt',
+ })
+ })
await act(async () => {
- await result.current.publishDraft({
- agent_id: 'agent-1',
- config_snapshot: {
- prompt: {
- system_prompt: 'Published prompt',
- },
- },
- })
+ await result.current.publishDraft()
})
expect(composerPutMutationFn).toHaveBeenCalledWith(expect.objectContaining({
@@ -202,43 +398,138 @@ describe('useAgentConfigureSync', () => {
},
body: expect.objectContaining({
variant: 'agent_app',
- save_strategy: 'save_as_new_version',
- agent_soul: {
- prompt: {
+ save_strategy: 'save_to_current_version',
+ agent_soul: expect.objectContaining({
+ prompt: expect.objectContaining({
system_prompt: 'Published prompt',
- },
- },
+ }),
+ }),
}),
}))
- expect(queryClient.getQueryData(['agent-composer', 'agent-1'])).toEqual({
- agent_soul: {
- prompt: {
- system_prompt: 'Published prompt',
- },
+ expect(publishAgentMutationFn).toHaveBeenCalledWith({
+ params: {
+ agent_id: 'agent-1',
},
+ body: {},
+ })
+ expect(invalidateQueries).toHaveBeenCalledWith({
+ queryKey: ['agent-composer', 'agent-1'],
})
expect(queryClient.getQueryData(['agent-detail', 'agent-1'])).toEqual({
active_config_is_published: true,
name: 'Agent',
})
+ expect(toastMock.success).toHaveBeenCalledWith('common.api.actionSuccess')
})
- 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',
+ it('should keep default model fallback from creating unpublished changes after publish', async () => {
+ const { result, store } = renderUseAgentConfigureSync({
+ currentModel: {
+ provider: 'langgenius/openai/openai',
+ model: 'gpt-4o-mini',
+ },
+ })
+ act(() => {
+ store.set(agentComposerDraftAtom, {
+ ...defaultAgentSoulConfigFormState,
+ prompt: 'Published prompt',
+ })
+ })
+
+ await act(async () => {
+ await result.current.publishDraft()
+ })
+
+ expect(publishAgentMutationFn).toHaveBeenCalledTimes(1)
+ const publishedDraft = store.get(agentComposerPublishedDraftAtom)
+ expect(store.get(agentComposerDraftAtom).model).toBeUndefined()
+ expect(publishedDraft?.model).toBeUndefined()
+ expect(publishedDraft).toEqual(store.get(agentComposerDraftAtom))
+ })
+
+ it('should keep base config fallback fields from creating unpublished changes after publish', async () => {
+ const { result, store } = renderUseAgentConfigureSync({
+ baseConfig: {
+ app_features: {
+ file_upload: {
+ enabled: true,
+ },
},
},
- }
+ })
+ act(() => {
+ store.set(agentComposerDraftAtom, {
+ ...defaultAgentSoulConfigFormState,
+ prompt: 'Published prompt',
+ })
+ })
+
+ await act(async () => {
+ await result.current.publishDraft()
+ })
+
+ expect(publishAgentMutationFn).toHaveBeenCalledTimes(1)
+ const publishedDraft = store.get(agentComposerPublishedDraftAtom)
+ expect(store.get(agentComposerDraftAtom).appFeatures).toBeUndefined()
+ expect(publishedDraft?.appFeatures).toBeUndefined()
+ expect(publishedDraft).toEqual(store.get(agentComposerDraftAtom))
+ })
+
+ it('should publish the current draft snapshot instead of a stale caller payload', async () => {
+ const { result, store } = renderUseAgentConfigureSync()
+
+ act(() => {
+ store.set(agentComposerDraftAtom, {
+ ...defaultAgentSoulConfigFormState,
+ prompt: 'Current draft prompt',
+ })
+ })
+
+ await act(async () => {
+ await result.current.publishDraft()
+ })
+
+ expect(composerPutMutationFn).toHaveBeenCalledWith(expect.objectContaining({
+ body: expect.objectContaining({
+ save_strategy: 'save_to_current_version',
+ agent_soul: expect.objectContaining({
+ prompt: expect.objectContaining({
+ system_prompt: 'Current draft prompt',
+ }),
+ }),
+ }),
+ }))
+ expect(publishAgentMutationFn).toHaveBeenCalledTimes(1)
+ })
+
+ it('should reject publish when knowledge retrieval validation fails', async () => {
+ const { result, store } = renderUseAgentConfigureSync()
+ act(() => {
+ store.set(agentComposerDraftAtom, {
+ ...defaultAgentSoulConfigFormState,
+ knowledgeRetrievals: [
+ {
+ id: 'retrieval-1',
+ name: 'Docs Search',
+ datasetRefs: [],
+ },
+ ],
+ })
+ })
+
+ await expect(result.current.publishDraft()).rejects.toThrow('Agent knowledge retrieval configuration is invalid.')
+ expect(composerPutMutationFn).not.toHaveBeenCalled()
+ expect(publishAgentMutationFn).not.toHaveBeenCalled()
+ })
+
+ it('should expose publishing status from the publish mutation while publish is pending', async () => {
+ const publishDeferred = createDeferredPromise<PublishAgentResponse>()
+ publishAgentMutationFn.mockReturnValueOnce(publishDeferred.promise)
+ const { result } = renderUseAgentConfigureSync()
let publishPromise!: Promise<void>
act(() => {
- publishPromise = result.current.publishDraft(publishPayload)
+ publishPromise = result.current.publishDraft()
})
await act(async () => {
@@ -250,7 +541,9 @@ describe('useAgentConfigureSync', () => {
await act(async () => {
publishDeferred.resolve({
- agent_soul: publishPayload.config_snapshot,
+ active_config_snapshot: {},
+ active_config_snapshot_id: 'snapshot-1',
+ result: 'success',
})
await publishPromise
await vi.advanceTimersByTimeAsync(0)
diff --git a/web/features/agent-v2/agent-detail/configure/build-draft-query.ts b/web/features/agent-v2/agent-detail/configure/build-draft-query.ts
new file mode 100644
index 00000000000..c1799c61e83
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/configure/build-draft-query.ts
@@ -0,0 +1,38 @@
+'use client'
+
+import type { ContractRouterClient } from '@orpc/contract'
+import type { JsonifiedClient } from '@orpc/openapi-client'
+import { createORPCClient } from '@orpc/client'
+import { OpenAPILink } from '@orpc/openapi-client/fetch'
+import { createTanstackQueryUtils } from '@orpc/tanstack-query'
+import { API_PREFIX } from '@/config'
+import { consoleRouterContract } from '@/contract/router'
+// eslint-disable-next-line no-restricted-imports
+import { request } from '@/service/base'
+import { getBaseURL } from '@/service/client'
+
+type AgentConfigureConsoleClientContext = {
+ silent?: boolean
+}
+
+const agentConfigureConsoleLink = new OpenAPILink<AgentConfigureConsoleClientContext>(consoleRouterContract, {
+ url: getBaseURL(API_PREFIX),
+ fetch: (input, init, options) => {
+ return request(
+ input.url,
+ init,
+ {
+ fetchCompat: true,
+ request: input,
+ silent: options.context.silent,
+ },
+ )
+ },
+})
+
+const agentConfigureConsoleClient: JsonifiedClient<ContractRouterClient<typeof consoleRouterContract, AgentConfigureConsoleClientContext>>
+ = createORPCClient(agentConfigureConsoleLink)
+
+export const agentConfigureConsoleQuery = createTanstackQueryUtils(agentConfigureConsoleClient, {
+ path: ['console'],
+})
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.tsx
index bc10dec2ac7..9a5a9d73a75 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
@@ -3,6 +3,7 @@ import type { PromptEditorProps } from '@/app/components/base/prompt-editor'
import type { AgentTool } from '@/features/agent-v2/agent-composer/form-state'
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import { createStore, Provider as JotaiProvider } from 'jotai'
+import { API_PREFIX } from '@/config'
import { defaultAgentSoulConfigFormState } from '@/features/agent-v2/agent-composer/form-state'
import { agentComposerDraftAtom } from '@/features/agent-v2/agent-composer/store'
import { agentComposerKnowledgeRetrievalsAtom } from '@/features/agent-v2/agent-composer/store-modules/knowledge'
@@ -20,7 +21,8 @@ const mockBuiltInTools = vi.hoisted(() => [
name: 'DuckDuckGo',
author: 'Dify',
description: { en_US: 'DuckDuckGo tools' },
- icon: '/duckduckgo.svg',
+ icon: 'duckduckgo.svg',
+ icon_dark: 'duckduckgo-dark.svg',
label: { en_US: 'DuckDuckGo' },
type: 'builtin',
team_credentials: {},
@@ -78,6 +80,13 @@ vi.mock('foxact/use-clipboard', () => ({
vi.mock('@/context/i18n', () => ({
useGetLanguage: () => 'en_US',
+ useDocLink: () => 'https://docs.example.com',
+}))
+
+vi.mock('@/context/app-context', () => ({
+ useSelector: (selector: (value: { currentWorkspace: { id: string } }) => string) => selector({
+ currentWorkspace: { id: 'workspace-123' },
+ }),
}))
vi.mock('@/service/use-tools', () => ({
@@ -221,7 +230,12 @@ describe('AgentPromptEditor', () => {
})
it('should render selected tool reference icons from configured tools', () => {
- renderAgentPromptEditor('Run tools')
+ renderAgentPromptEditor('Run tools', {
+ tools: [{
+ ...duckDuckGoProviderTool,
+ iconClassName: 'i-custom-public-other-default-tool-icon',
+ }],
+ })
const promptEditorProps = mockPromptEditor.mock.calls.at(-1)?.[0] as PromptEditorProps
const renderIcon = promptEditorProps.rosterReferenceBlock?.renderIcon
@@ -237,7 +251,11 @@ describe('AgentPromptEditor', () => {
</>,
)
- expect(container.querySelector('.i-simple-icons-duckduckgo')).toBeInTheDocument()
+ const providerIcon = Array.from(container.querySelectorAll<HTMLElement>('[style]'))
+ .find(element => element.style.backgroundImage)
+ expect(providerIcon).toHaveStyle({
+ backgroundImage: `url(${API_PREFIX}/workspaces/current/plugin/icon?tenant_id=workspace-123&filename=duckduckgo.svg)`,
+ })
rerender(
<>
@@ -249,7 +267,7 @@ describe('AgentPromptEditor', () => {
</>,
)
- expect(container.querySelector('.i-ri-terminal-box-line')).toBeInTheDocument()
+ expect(container.querySelector('.i-ri-terminal-box-line')).not.toBeInTheDocument()
})
})
@@ -295,7 +313,7 @@ describe('AgentPromptEditor', () => {
expect(screen.queryByRole('button', { name: /agentDetail\.configure\.prompt\.mention\.label/i })).not.toBeInTheDocument()
})
- it('should insert references after prompt add actions create skills, files, CLI tools, or knowledge retrievals', () => {
+ it('should insert references after prompt add actions create skills, files, or knowledge retrievals', () => {
const onSelect = vi.fn()
const categories = [
{ key: 'skills' as const, label: 'Skills', icon: 'i-ri-box-3-line' },
@@ -373,15 +391,20 @@ describe('AgentPromptEditor', () => {
onSelect={onSelect}
/>,
)
- fireEvent.click(screen.getByRole('button', { name: /agentDetail\.configure\.tools\.cliDialog\.title/i }))
- expect(onSelect).toHaveBeenCalledWith('[§cli_tool:cli-1:Lark CLI§]')
+ expect(screen.queryByRole('button', { name: /agentDetail\.configure\.tools\.cliDialog\.title/i })).not.toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: /agentDetail\.configure\.tools\.toolTabs\.cli/i })).not.toBeInTheDocument()
})
it('should append available provider tool references and add missing tools to the configuration', () => {
const { store, rerenderWithValue } = renderAgentPromptEditor('Research/', { tools: [] })
+ const expectedProviderIcon = `${API_PREFIX}/workspaces/current/plugin/icon?tenant_id=workspace-123&filename=duckduckgo.svg`
fireEvent.keyDown(screen.getByRole('textbox'), { key: '/' })
fireEvent.click(screen.getByRole('button', { name: /agentDetail\.configure\.tools\.label/i }))
+ const providerButton = screen.getByRole('button', { name: /DuckDuckGo.*agentDetail\.configure\.tools\.toolTabs\.plugins/i })
+ const providerIcon = Array.from(providerButton.querySelectorAll<HTMLElement>('[style]'))
+ .find(element => element.style.backgroundImage)
+ expect(providerIcon).toHaveStyle({ backgroundImage: `url(${expectedProviderIcon})` })
fireEvent.click(screen.getByRole('button', { name: 'DuckDuckGo' }))
fireEvent.click(screen.getByRole('button', { name: /DuckDuckGo Search/i }))
@@ -389,6 +412,7 @@ describe('AgentPromptEditor', () => {
expect(store.get(agentComposerDraftAtom).tools).toEqual([
expect.objectContaining({
id: 'duckduckgo',
+ icon: expectedProviderIcon,
actions: [
expect.objectContaining({
name: 'DuckDuckGo Search',
diff --git a/web/features/agent-v2/agent-detail/configure/components/composer-session.tsx b/web/features/agent-v2/agent-detail/configure/components/composer-session.tsx
new file mode 100644
index 00000000000..e6ec0d94c1c
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/configure/components/composer-session.tsx
@@ -0,0 +1,431 @@
+'use client'
+
+import type { AgentAppDetailWithSite, AgentIconType } from '@dify/contracts/api/console/agent/types.gen'
+import type { Dispatch, SetStateAction } from 'react'
+import type { useAgentConfigureData } from '../hooks'
+import type { AgentConfigureConversationIds, AgentConfigureRightPanelMode } from './preview/right-panel-chat'
+import { useMutation, useQueryClient } from '@tanstack/react-query'
+import { useCallback, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { agentSoulConfigToFormState } from '@/features/agent-v2/agent-composer/conversions'
+import { AgentComposerProvider } from '@/features/agent-v2/agent-composer/provider'
+import { consoleQuery } from '@/service/client'
+import { useAgentConfigureModelOptions } from '../hooks'
+import { useAgentConfigureBuildDraftActions, useAgentConfigureBuildDraftData } from '../use-agent-configure-build-draft'
+import { useAgentConfigureSync } from '../use-agent-configure-sync'
+import { AgentOrchestratePanel } from './orchestrate'
+import { AgentBuildDraftBar } from './orchestrate/build-draft-bar'
+import { AgentConfigurePageLoading } from './page-loading'
+import { AgentBuildPanelBackground } from './preview/build-background'
+import { AgentChatFeaturesPanel } from './preview/chat-features-panel'
+import { AgentPreviewHeader } from './preview/header'
+import { AgentConfigureRightPanelChat } from './preview/right-panel-chat'
+import { useAgentWorkingDirectoryPanel } from './preview/use-working-directory-panel'
+import { AgentPreviewVersionsPanel } from './preview/versions-panel'
+import { AgentConfigurePreviewSurface, AgentConfigureWorkspace } from './workspace'
+
+type DebugConversationRefreshInput = {
+ params: {
+ agent_id: string
+ }
+ body: {
+ debug_conversation_id: string
+ }
+}
+
+export function AgentConfigureComposerScope({
+ agentId,
+ composerRebaseRevision,
+ configureData,
+ onComposerRebase,
+ onSelectVersion,
+}: {
+ agentId: string
+ composerRebaseRevision: number
+ configureData: ReturnType<typeof useAgentConfigureData>
+ onComposerRebase: () => void
+ onSelectVersion: (versionId: string | null) => void
+}) {
+ const { t } = useTranslation('agentV2')
+ const {
+ composerQuery,
+ selectedVersionId,
+ activeVersionId,
+ agentSoulConfig,
+ } = configureData
+ const isViewingVersion = !!selectedVersionId
+ const buildDraft = useAgentConfigureBuildDraftData({
+ agentId,
+ activeVersionId,
+ composerAgentSoulConfig: composerQuery.data?.agent_soul,
+ isViewingVersion,
+ normalAgentSoulConfig: agentSoulConfig,
+ })
+
+ if (buildDraft.isPending) {
+ return (
+ <AgentConfigurePageLoading label={t('agentDetail.sections.configure')} />
+ )
+ }
+
+ const composerSessionKey = buildDraft.isActive
+ ? `${agentId}:${buildDraft.activeVersionId ?? 'build-draft'}`
+ : `${agentId}:${buildDraft.activeVersionId ?? 'draft'}:${composerRebaseRevision}`
+
+ return (
+ <AgentConfigurePageComposerSession
+ agentId={agentId}
+ buildDraft={buildDraft}
+ composerSessionKey={composerSessionKey}
+ configureData={configureData}
+ isViewingVersion={isViewingVersion}
+ onComposerRebase={onComposerRebase}
+ onSelectVersion={onSelectVersion}
+ />
+ )
+}
+
+function AgentConfigurePageComposerSession({
+ agentId,
+ buildDraft,
+ composerSessionKey,
+ configureData,
+ isViewingVersion,
+ onComposerRebase,
+ onSelectVersion,
+}: {
+ agentId: string
+ buildDraft: ReturnType<typeof useAgentConfigureBuildDraftData>
+ composerSessionKey: string
+ configureData: ReturnType<typeof useAgentConfigureData>
+ isViewingVersion: boolean
+ onComposerRebase: () => void
+ onSelectVersion: (versionId: string | null) => void
+}) {
+ const {
+ agentQuery,
+ } = configureData
+ const queryClient = useQueryClient()
+ const [showChatFeatures, setShowChatFeatures] = useState(false)
+ const [showPreviewVersions, setShowPreviewVersions] = useState(false)
+ const workingDirectoryPanel = useAgentWorkingDirectoryPanel()
+ const [clearPreviewChat, setClearPreviewChat] = useState(false)
+ const [rightPanelMode, setRightPanelMode] = useState<AgentConfigureRightPanelMode>('build')
+ const [hideBuildDraftBarUntilRefresh, setHideBuildDraftBarUntilRefresh] = useState(false)
+ const [conversationIds, setConversationIds] = useState<AgentConfigureConversationIds>({
+ build: agentQuery.data?.debug_conversation_id ?? null,
+ preview: null,
+ })
+ const agentIconType = agentQuery.data?.icon_type as AgentIconType | null | undefined
+ const refreshDebugConversationMutation = useMutation(consoleQuery.agent.byAgentId.debugConversation.refresh.post.mutationOptions({
+ onSuccess: ({ debug_conversation_id }) => {
+ queryClient.setQueryData<AgentAppDetailWithSite | undefined>(
+ consoleQuery.agent.byAgentId.get.queryKey({ input: { params: { agent_id: agentId } } }),
+ (agentDetail) => {
+ if (!agentDetail)
+ return agentDetail
+
+ return {
+ ...agentDetail,
+ debug_conversation_id,
+ }
+ },
+ )
+ },
+ }))
+ const {
+ mutate: refreshDebugConversationRequest,
+ mutateAsync: refreshDebugConversationRequestAsync,
+ isPending: isRefreshingDebugConversation,
+ } = refreshDebugConversationMutation
+ const refreshDebugConversationInput = useCallback((conversationId: string): DebugConversationRefreshInput => ({
+ params: {
+ agent_id: agentId,
+ },
+ body: {
+ debug_conversation_id: conversationId,
+ },
+ }), [agentId])
+ const refreshDebugConversation = useCallback((conversationId: string) => {
+ const input = refreshDebugConversationInput(conversationId)
+
+ refreshDebugConversationRequest(
+ input as unknown as Parameters<typeof refreshDebugConversationRequest>[0],
+ )
+ }, [refreshDebugConversationInput, refreshDebugConversationRequest])
+ const refreshDebugConversationAsync = useCallback((conversationId: string) => {
+ const input = refreshDebugConversationInput(conversationId)
+
+ return refreshDebugConversationRequestAsync(
+ input as unknown as Parameters<typeof refreshDebugConversationRequestAsync>[0],
+ )
+ }, [refreshDebugConversationInput, refreshDebugConversationRequestAsync])
+ const resetBuildChatSession = useCallback(async () => {
+ try {
+ await refreshDebugConversationAsync(conversationIds.build ?? '')
+ }
+ finally {
+ setConversationIds(current => ({
+ ...current,
+ build: null,
+ }))
+ setClearPreviewChat(true)
+ }
+ }, [conversationIds.build, refreshDebugConversationAsync])
+
+ return (
+ <AgentComposerProvider
+ key={composerSessionKey}
+ initialDraft={agentSoulConfigToFormState(buildDraft.agentSoulConfig)}
+ initialOriginalConfig={buildDraft.agentSoulConfig}
+ >
+ <AgentConfigurePageComposerContent
+ agentId={agentId}
+ agentIconType={agentIconType}
+ buildDraft={buildDraft}
+ clearPreviewChat={clearPreviewChat}
+ configureData={configureData}
+ conversationIds={conversationIds}
+ hideBuildDraftBarUntilRefresh={hideBuildDraftBarUntilRefresh}
+ isRefreshingDebugConversation={isRefreshingDebugConversation}
+ isViewingVersion={isViewingVersion}
+ resetBuildChatSession={resetBuildChatSession}
+ rightPanelMode={rightPanelMode}
+ setClearPreviewChat={setClearPreviewChat}
+ setConversationIds={setConversationIds}
+ setHideBuildDraftBarUntilRefresh={setHideBuildDraftBarUntilRefresh}
+ setRightPanelMode={setRightPanelMode}
+ setShowChatFeatures={setShowChatFeatures}
+ setShowPreviewVersions={setShowPreviewVersions}
+ showChatFeatures={showChatFeatures}
+ showPreviewVersions={showPreviewVersions}
+ workingDirectoryPanel={workingDirectoryPanel}
+ onComposerRebase={onComposerRebase}
+ onRefreshDebugConversation={refreshDebugConversation}
+ onSelectVersion={onSelectVersion}
+ />
+ </AgentComposerProvider>
+ )
+}
+
+function AgentConfigurePageComposerContent({
+ agentId,
+ agentIconType,
+ buildDraft,
+ clearPreviewChat,
+ configureData,
+ conversationIds,
+ hideBuildDraftBarUntilRefresh,
+ isRefreshingDebugConversation,
+ isViewingVersion,
+ resetBuildChatSession,
+ rightPanelMode,
+ setClearPreviewChat,
+ setConversationIds,
+ setHideBuildDraftBarUntilRefresh,
+ setRightPanelMode,
+ setShowChatFeatures,
+ setShowPreviewVersions,
+ showChatFeatures,
+ showPreviewVersions,
+ workingDirectoryPanel,
+ onComposerRebase,
+ onRefreshDebugConversation,
+ onSelectVersion,
+}: {
+ agentId: string
+ agentIconType: AgentIconType | null | undefined
+ buildDraft: ReturnType<typeof useAgentConfigureBuildDraftData>
+ clearPreviewChat: boolean
+ configureData: ReturnType<typeof useAgentConfigureData>
+ conversationIds: AgentConfigureConversationIds
+ hideBuildDraftBarUntilRefresh: boolean
+ isRefreshingDebugConversation: boolean
+ isViewingVersion: boolean
+ resetBuildChatSession: () => Promise<void>
+ rightPanelMode: AgentConfigureRightPanelMode
+ setClearPreviewChat: Dispatch<SetStateAction<boolean>>
+ setConversationIds: Dispatch<SetStateAction<AgentConfigureConversationIds>>
+ setHideBuildDraftBarUntilRefresh: Dispatch<SetStateAction<boolean>>
+ setRightPanelMode: Dispatch<SetStateAction<AgentConfigureRightPanelMode>>
+ setShowChatFeatures: Dispatch<SetStateAction<boolean>>
+ setShowPreviewVersions: Dispatch<SetStateAction<boolean>>
+ showChatFeatures: boolean
+ showPreviewVersions: boolean
+ workingDirectoryPanel: ReturnType<typeof useAgentWorkingDirectoryPanel>
+ onComposerRebase: () => void
+ onRefreshDebugConversation: (conversationId: string) => void
+ onSelectVersion: (versionId: string | null) => void
+}) {
+ const {
+ agentQuery,
+ composerQuery,
+ versionQuery,
+ selectedVersionId,
+ activeVersionId,
+ activeConfigSnapshot,
+ agentSoulConfig,
+ } = configureData
+ const rightPanelChatMode: AgentConfigureRightPanelMode = rightPanelMode === 'preview' ? 'build' : rightPanelMode
+ const showBuildDraftBar = buildDraft.isActive && !hideBuildDraftBarUntilRefresh
+ const {
+ currentModel,
+ setConfigureModel,
+ textGenerationModelList,
+ } = useAgentConfigureModelOptions()
+ const {
+ draftSavedAt,
+ isPublishing,
+ publishDraft,
+ saveDraft,
+ } = useAgentConfigureSync({
+ agentId,
+ baseConfig: agentSoulConfig,
+ currentModel,
+ enabled: composerQuery.isSuccess && !selectedVersionId && !buildDraft.isActive,
+ })
+ const buildDraftActions = useAgentConfigureBuildDraftActions({
+ agentId,
+ isActive: buildDraft.isActive,
+ refetchBuildDraft: buildDraft.refetch,
+ refetchComposer: composerQuery.refetch,
+ resetBuildChatSession,
+ saveDraft,
+ onComposerRebased: onComposerRebase,
+ setSoulSourceOverride: buildDraft.setSoulSourceOverride,
+ })
+ const selectVersion = useCallback((versionId: string | null) => {
+ buildDraft.setSoulSourceOverride(versionId ? 'view-version' : null)
+ onSelectVersion(versionId)
+ }, [buildDraft, onSelectVersion])
+ const restartCurrentChat = () => {
+ if (rightPanelChatMode === 'build' && buildDraft.isActive) {
+ void buildDraftActions.discardBuildDraft()
+ return
+ }
+
+ if (rightPanelChatMode === 'build')
+ onRefreshDebugConversation(conversationIds.build ?? '')
+
+ setConversationIds(current => ({
+ ...current,
+ [rightPanelChatMode]: null,
+ }))
+ setClearPreviewChat(true)
+ }
+
+ return (
+ <AgentConfigureWorkspace
+ aria-busy={agentQuery.isFetching}
+ leftPanel={(
+ <AgentOrchestratePanel
+ agentId={agentId}
+ activeConfigIsPublished={agentQuery.data?.active_config_is_published}
+ activeConfigSnapshot={activeConfigSnapshot}
+ agentSoulConfig={buildDraft.agentSoulConfig}
+ agentName={agentQuery.data?.name}
+ currentModel={currentModel}
+ textGenerationModelList={textGenerationModelList}
+ draftSavedAt={draftSavedAt}
+ isPublishing={isPublishing}
+ readOnly={isViewingVersion || buildDraft.isActive}
+ selectedVersionSnapshot={isViewingVersion ? activeConfigSnapshot : undefined}
+ isBuildDraftActive={buildDraft.isActive}
+ showPublishBar={!buildDraft.isActive}
+ bottomAction={showBuildDraftBar
+ ? (
+ <AgentBuildDraftBar
+ changesCount={buildDraft.changesCount}
+ isApplying={buildDraftActions.isApplyingBuildDraft}
+ isDiscarding={buildDraftActions.isDiscardingBuildDraft}
+ onApply={() => {
+ void buildDraftActions.applyBuildDraft()
+ }}
+ onDiscard={() => {
+ void buildDraftActions.discardBuildDraft()
+ }}
+ />
+ )
+ : undefined}
+ onSelectModel={setConfigureModel}
+ onPublish={publishDraft}
+ onOpenVersions={() => {
+ workingDirectoryPanel.closeWorkingDirectory()
+ setShowPreviewVersions(true)
+ }}
+ onExitVersions={() => selectVersion(null)}
+ />
+ )}
+ rightPanel={(
+ <AgentConfigurePreviewSurface
+ background={<AgentBuildPanelBackground visible={rightPanelChatMode === 'build'} />}
+ header={(
+ <AgentPreviewHeader
+ mode={rightPanelChatMode}
+ previewEnabled={false}
+ isChatFeaturesOpen={showChatFeatures}
+ onModeChange={setRightPanelMode}
+ onToggleChatFeatures={() => setShowChatFeatures(open => !open)}
+ onOpenWorkingDirectory={() => {
+ setShowPreviewVersions(false)
+ workingDirectoryPanel.openWorkingDirectory()
+ }}
+ onRefresh={restartCurrentChat}
+ refreshDisabled={isRefreshingDebugConversation || buildDraftActions.isDiscardingBuildDraft}
+ />
+ )}
+ chat={(
+ <AgentConfigureRightPanelChat
+ agentId={agentId}
+ agentIcon={agentQuery.data?.icon}
+ agentIconBackground={agentQuery.data?.icon_background}
+ agentIconType={agentIconType}
+ agentName={agentQuery.data?.name}
+ agentSoulConfig={buildDraft.agentSoulConfig}
+ clearChatList={clearPreviewChat}
+ conversationIds={conversationIds}
+ draftType={rightPanelChatMode === 'build' ? 'debug_build' : undefined}
+ mode={rightPanelChatMode}
+ onClearChatListChange={setClearPreviewChat}
+ onConversationComplete={(mode) => {
+ if (mode === 'build')
+ buildDraftActions.refreshBuildDraftAfterBuildChat(() => setHideBuildDraftBarUntilRefresh(false))
+ }}
+ onConversationIdChange={(mode, conversationId) => {
+ setConversationIds(current => ({
+ ...current,
+ [mode]: conversationId,
+ }))
+ }}
+ onSaveDraftBeforeRun={rightPanelChatMode === 'build'
+ ? async () => {
+ setHideBuildDraftBarUntilRefresh(true)
+ await buildDraftActions.prepareBuildDraftBeforeRun()
+ }
+ : saveDraft}
+ />
+ )}
+ />
+ )}
+ sidePanels={(
+ <>
+ {showPreviewVersions && (
+ <AgentPreviewVersionsPanel
+ agentId={agentId}
+ activeVersionId={activeVersionId}
+ onSelectVersion={selectVersion}
+ onClose={() => setShowPreviewVersions(false)}
+ />
+ )}
+ {workingDirectoryPanel.panel}
+ <AgentChatFeaturesPanel
+ show={showChatFeatures}
+ appFeatures={agentSoulConfig?.app_features}
+ disabled={versionQuery.isPending}
+ onClose={() => setShowChatFeatures(false)}
+ />
+ </>
+ )}
+ />
+ )
+}
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/__tests__/header.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/__tests__/header.spec.tsx
new file mode 100644
index 00000000000..56460278d34
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/__tests__/header.spec.tsx
@@ -0,0 +1,29 @@
+import { render, screen } from '@testing-library/react'
+import { AgentOrchestrateHeader } from '../header'
+
+describe('AgentOrchestrateHeader', () => {
+ it('should render configure title without build mode copy by default', () => {
+ render(<AgentOrchestrateHeader headingId="configure-heading" />)
+
+ expect(screen.getByRole('heading', { name: 'agentV2.agentDetail.configure.title' })).toBeInTheDocument()
+ expect(screen.queryByText('agentV2.agentDetail.configure.buildDraft.modeBadge')).not.toBeInTheDocument()
+ })
+
+ it('should render build mode copy when build draft is active', () => {
+ render(<AgentOrchestrateHeader headingId="configure-heading" isBuildDraftActive />)
+
+ expect(screen.getByText('agentV2.agentDetail.configure.buildDraft.modeBadge')).toBeInTheDocument()
+ expect(screen.getByText('agentV2.agentDetail.configure.buildDraft.modeDescription')).toBeInTheDocument()
+ })
+
+ it('should render trailing action on the configure title row', () => {
+ render(
+ <AgentOrchestrateHeader
+ headingId="configure-heading"
+ trailingAction={<button type="button">More actions</button>}
+ />,
+ )
+
+ expect(screen.getByRole('button', { name: 'More actions' })).toBeInTheDocument()
+ })
+})
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/__tests__/publish-bar.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/__tests__/publish-bar.spec.tsx
index 6beb7cc649c..495ac86caef 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
@@ -248,6 +248,33 @@ describe('AgentConfigurePublishBar', () => {
)
})
+ it('should block publish when knowledge retrieval validation fails', () => {
+ const { onPublish } = renderPublishBar({
+ setupStore: (store) => {
+ store.set(agentComposerDraftAtom, {
+ ...defaultAgentSoulConfigFormState,
+ knowledgeRetrievals: [
+ {
+ id: 'retrieval-1',
+ name: 'Docs Search',
+ datasetRefs: [],
+ },
+ ],
+ })
+ },
+ })
+
+ expect(screen.getByRole('button', { name: /agentV2\.agentDetail\.configure\.publishBar\.publishUpdate/ })).toBeDisabled()
+ expect(screen.getByText('common.errorMsg.fieldRequired:{"field":"agentV2.agentDetail.configure.knowledgeRetrieval.dialog.knowledge.label"}')).toBeInTheDocument()
+ expect(hotkeyRegistrations.get('Mod+Shift+P')?.options).toEqual(
+ expect.objectContaining({ enabled: false, ignoreInputs: false }),
+ )
+
+ fireEvent.click(screen.getByRole('button', { name: /agentV2\.agentDetail\.configure\.publishBar\.publishUpdate/ }))
+
+ expect(onPublish).not.toHaveBeenCalled()
+ })
+
it('should restore the selected version from view-only mode', async () => {
const selectedVersionSnapshot = {
...activeConfigSnapshot,
@@ -306,6 +333,33 @@ describe('AgentConfigurePublishBar', () => {
expect(onPublish).not.toHaveBeenCalled()
})
+ it('should keep published state when the published detail updates before the active snapshot is refreshed', () => {
+ renderPublishBar({
+ activeConfigIsPublished: true,
+ activeConfigSnapshot: null,
+ })
+
+ expect(screen.getByText('agentV2.agentDetail.configure.publishBar.upToDate')).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.publishBar.published' })).toBeDisabled()
+ expect(hotkeyRegistrations.get('Mod+Shift+P')?.options).toEqual(
+ expect.objectContaining({ enabled: false, ignoreInputs: false }),
+ )
+ })
+
+ it('should keep published state from active config status even when local draft differs', () => {
+ renderPublishBar({
+ activeConfigIsPublished: true,
+ activeConfigSnapshot: null,
+ prompt: 'Updated system prompt',
+ })
+
+ expect(screen.getByText('agentV2.agentDetail.configure.publishBar.upToDate')).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.publishBar.published' })).toBeDisabled()
+ expect(hotkeyRegistrations.get('Mod+Shift+P')?.options).toEqual(
+ expect.objectContaining({ enabled: false, ignoreInputs: false }),
+ )
+ })
+
it('should initialize unpublished state when active config is not published', async () => {
const { onPublish } = renderPublishBar({
activeConfigIsPublished: false,
@@ -322,9 +376,7 @@ describe('AgentConfigurePublishBar', () => {
fireEvent.click(screen.getByRole('button', { name: /agentV2\.agentDetail\.configure\.publishBar\.publishUpdate/ }))
await waitFor(() => {
- expect(onPublish).toHaveBeenCalledWith(expect.objectContaining({
- agent_id: 'agent-1',
- }))
+ expect(onPublish).toHaveBeenCalledTimes(1)
})
expect(screen.queryByRole('region', {
name: /agentV2\.agentDetail\.configure\.publishImpact\.title/,
@@ -342,14 +394,7 @@ describe('AgentConfigurePublishBar', () => {
fireEvent.click(screen.getByRole('button', { name: /agentV2\.agentDetail\.configure\.publishBar\.publishUpdate/ }))
await waitFor(() => {
- expect(onPublish).toHaveBeenCalledWith(expect.objectContaining({
- agent_id: 'agent-1',
- config_snapshot: expect.objectContaining({
- prompt: expect.objectContaining({
- system_prompt: 'Updated system prompt',
- }),
- }),
- }))
+ expect(onPublish).toHaveBeenCalledTimes(1)
})
})
@@ -460,9 +505,7 @@ describe('AgentConfigurePublishBar', () => {
})).toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: /agentV2\.agentDetail\.configure\.publishBar\.publishUpdate/ }))
- expect(onPublish).toHaveBeenCalledWith(expect.objectContaining({
- agent_id: 'agent-1',
- }))
+ expect(onPublish).toHaveBeenCalledTimes(1)
expect(screen.getByRole('region', {
name: /agentV2\.agentDetail\.configure\.publishImpact\.title/,
})).toBeInTheDocument()
@@ -526,9 +569,7 @@ describe('AgentConfigurePublishBar', () => {
await hotkeyRegistrations.get('Mod+Shift+P')?.callback({ preventDefault: vi.fn() })
})
- expect(onPublish).toHaveBeenCalledWith(expect.objectContaining({
- agent_id: 'agent-1',
- }))
+ expect(onPublish).toHaveBeenCalledTimes(1)
})
it('should publish directly from the publish shortcut when no workflows reference the agent', async () => {
@@ -545,8 +586,6 @@ describe('AgentConfigurePublishBar', () => {
expect(screen.queryByRole('region', {
name: /agentV2\.agentDetail\.configure\.publishImpact\.title/,
})).not.toBeInTheDocument()
- expect(onPublish).toHaveBeenCalledWith(expect.objectContaining({
- agent_id: 'agent-1',
- }))
+ expect(onPublish).toHaveBeenCalledTimes(1)
})
})
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.tsx
index 7a5578fbff1..57c1ec9d543 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
@@ -109,8 +109,6 @@ function AgentContentModerationSettingsContent() {
labelId="agent-configure-content-moderation-label"
headingLevel="h4"
panelId={panelId}
- tip={t('feature.moderation.description', { ns: 'appDebug' })}
- tipAriaLabel={t('feature.moderation.description', { ns: 'appDebug' })}
rootClassName="gap-1 border-t border-divider-subtle py-3"
headerClassName="mb-0 gap-1 px-3"
panelContentClassName="px-3 pt-1"
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/advanced/env.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/advanced/env.tsx
index cd8044c3030..e989cd9e365 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/advanced/env.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/advanced/env.tsx
@@ -13,6 +13,7 @@ import { useTranslation } from 'react-i18next'
import { agentComposerEnvVariablesAtom } from '@/features/agent-v2/agent-composer/store-modules/env'
import { checkKeys } from '@/utils/var'
import { ConfigureSection } from '../common/section'
+import { AgentConfigureTipContent } from '../common/tip-content'
import { useAgentOrchestrateReadOnly } from '../read-only-context'
import { getEnvImportPlatform, parseEnvVariables } from './env-utils'
@@ -480,7 +481,7 @@ export function AgentEnvEditor() {
labelId="agent-configure-env-editor-label"
headingLevel="h4"
panelId={envEditorTableId}
- tip={envEditorTip}
+ tip={<AgentConfigureTipContent type="env" />}
tipAriaLabel={envEditorTip}
rootClassName="gap-1 pt-3"
headerClassName="mb-0 gap-1 px-3"
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/bottom-actions.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/bottom-actions.tsx
new file mode 100644
index 00000000000..cd61ce1b2f1
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/bottom-actions.tsx
@@ -0,0 +1,23 @@
+import type { ReactNode } from 'react'
+
+export function AgentOrchestrateBottomActions({
+ 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
+ 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>
+ )
+}
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/build-draft-bar.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/build-draft-bar.tsx
new file mode 100644
index 00000000000..ca91a3959e5
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/build-draft-bar.tsx
@@ -0,0 +1,60 @@
+'use client'
+
+import { Button } from '@langgenius/dify-ui/button'
+import { useTranslation } from 'react-i18next'
+
+type AgentBuildDraftBarProps = {
+ changesCount: number
+ isApplying?: boolean
+ isDiscarding?: boolean
+ onApply: () => void
+ onDiscard: () => void
+}
+
+export function AgentBuildDraftBar({
+ changesCount,
+ isApplying = false,
+ isDiscarding = false,
+ onApply,
+ onDiscard,
+}: AgentBuildDraftBarProps) {
+ const { t } = useTranslation('agentV2')
+ const { t: tCustom } = useTranslation('custom')
+ const isPending = isApplying || isDiscarding
+ const metaLabel = changesCount > 0
+ ? t('agentDetail.configure.buildDraft.changes', { count: changesCount })
+ : t('agentDetail.configure.buildDraft.noChanges')
+
+ return (
+ <div className="pointer-events-auto flex max-w-full min-w-0 items-center gap-2 overflow-hidden rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur py-2 pr-2 pl-4 shadow-lg shadow-shadow-shadow-5 backdrop-blur-[5px]">
+ <div className="flex min-w-0 flex-1 flex-col justify-center gap-0.5 pr-2">
+ <p className="min-w-0 truncate system-sm-semibold text-text-primary">
+ {t('agentDetail.configure.buildDraft.title')}
+ </p>
+ <p className="min-w-0 truncate system-xs-regular text-text-tertiary">
+ {metaLabel}
+ </p>
+ </div>
+ <Button
+ type="button"
+ variant="primary"
+ loading={isApplying}
+ disabled={isPending}
+ className="h-8 rounded-lg px-3"
+ onClick={onApply}
+ >
+ {tCustom('apply')}
+ </Button>
+ <Button
+ type="button"
+ variant="secondary"
+ loading={isDiscarding}
+ disabled={isPending}
+ className="h-8 rounded-lg px-3"
+ onClick={onDiscard}
+ >
+ {t('agentDetail.configure.buildDraft.discard')}
+ </Button>
+ </div>
+ )
+}
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/common/tip-content.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/common/tip-content.tsx
new file mode 100644
index 00000000000..7edbcbe6a27
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/common/tip-content.tsx
@@ -0,0 +1,76 @@
+'use client'
+
+import type { ReactNode } from 'react'
+import { Trans, useTranslation } from 'react-i18next'
+import { useDocLink } from '@/context/i18n'
+
+type AgentConfigureTipContentProps = {
+ type: 'prompt' | 'skills' | 'files' | 'tools' | 'env'
+}
+
+function DocsLink({
+ children,
+ href,
+}: {
+ children?: ReactNode
+ href: string
+}) {
+ return (
+ <a
+ href={href}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-text-accent hover:underline"
+ >
+ {children}
+ </a>
+ )
+}
+
+export function AgentConfigureTipContent({ type }: AgentConfigureTipContentProps) {
+ const { t } = useTranslation('agentV2')
+ const docLink = useDocLink()
+
+ if (type === 'env') {
+ return (
+ <span className="whitespace-pre-line">
+ <Trans
+ i18nKey="agentDetail.configure.advancedSettings.envEditor.richTip"
+ ns="agentV2"
+ components={{
+ docLink: <DocsLink href={docLink('/use-dify/build/agent')} />,
+ }}
+ />
+ </span>
+ )
+ }
+
+ if (type === 'skills') {
+ return (
+ <Trans
+ i18nKey="agentDetail.configure.skills.richTip"
+ ns="agentV2"
+ components={{
+ docLink: <DocsLink href={docLink()} />,
+ }}
+ />
+ )
+ }
+
+ if (type === 'tools') {
+ return (
+ <span className="whitespace-pre-line">
+ <Trans
+ i18nKey="agentDetail.configure.tools.richTip"
+ ns="agentV2"
+ components={{
+ pluginDocLink: <DocsLink href={docLink('/develop-plugin/getting-started/getting-started-dify-plugin')} />,
+ buildDocLink: <DocsLink href={docLink('/use-dify/build/agent')} />,
+ }}
+ />
+ </span>
+ )
+ }
+
+ return <>{t(`agentDetail.configure.${type}.tip`)}</>
+}
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.ts
index d94a0632471..b9443c6b59d 100644
--- 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.ts
@@ -1,11 +1,9 @@
'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 { useAtomValue } from 'jotai'
import { createContext, use, useMemo } from 'react'
-import { consoleQuery } from '@/service/client'
-import { getDriveFileIconType } from './files/file-icon'
+import { agentComposerFilesAtom } from '@/features/agent-v2/agent-composer/store-modules/files'
+import { agentComposerSkillsAtom } from '@/features/agent-v2/agent-composer/store-modules/skills'
export type AgentDriveApiContext = {
agentId: string
@@ -21,41 +19,6 @@ 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)
@@ -66,35 +29,10 @@ export const useAgentDriveApiContext = () => {
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])
+ const skills = useAtomValue(agentComposerSkillsAtom)
return {
apiContext,
- query,
skills,
}
}
@@ -105,42 +43,14 @@ export const useAgentDriveFiles = ({
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 draftFiles = useAtomValue(agentComposerFilesAtom)
const files = useMemo(
- () => (query.data?.items ?? []).map((item: AgentDriveItemResponse) => toAgentFileNodeFromDriveItem(item)),
- [query.data?.items],
+ () => draftFiles.filter(file => !prefix || file.driveKey?.startsWith(prefix)),
+ [draftFiles, prefix],
)
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.tsx
index b8728fe9572..02c263be6da 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
@@ -1,9 +1,12 @@
import type { AgentSoulConfigFormState } from '@/features/agent-v2/agent-composer/form-state'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'
+import { useAtomValue } from 'jotai'
import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { formStateToAgentSoulConfig } from '@/features/agent-v2/agent-composer/conversions'
import { defaultAgentSoulConfigFormState } from '@/features/agent-v2/agent-composer/form-state'
import { AgentComposerProvider } from '@/features/agent-v2/agent-composer/provider'
+import { agentComposerDraftAtom } from '@/features/agent-v2/agent-composer/store'
import { AgentDriveApiContextProvider } from '../../drive-context'
import { AgentOrchestrateReadOnlyContext } from '../../read-only-context'
import { AgentFiles } from '../index'
@@ -101,10 +104,38 @@ vi.mock('@/service/client', () => ({
const agentFilesDraft = {
...defaultAgentSoulConfigFormState,
+ files: [
+ {
+ id: 'files/agent-roster-skill-detail-dialog-preview-image.png',
+ name: 'agent-roster-skill-detail-dialog-preview-image.png',
+ icon: 'image',
+ driveKey: 'files/agent-roster-skill-detail-dialog-preview-image.png',
+ },
+ {
+ id: 'files/brief.md',
+ name: 'brief.md',
+ icon: 'markdown',
+ driveKey: 'files/brief.md',
+ },
+ ],
} satisfies AgentSoulConfigFormState
const agentSkillFilesDraft = {
...defaultAgentSoulConfigFormState,
+ files: [
+ {
+ id: 'files/run.py',
+ name: 'run.py',
+ icon: 'code',
+ driveKey: 'files/run.py',
+ },
+ {
+ id: 'files/SKILL.md',
+ name: 'SKILL.md',
+ icon: 'markdown',
+ driveKey: 'files/SKILL.md',
+ },
+ ],
} satisfies AgentSoulConfigFormState
function renderAgentFiles(initialDraft: AgentSoulConfigFormState = agentFilesDraft) {
@@ -169,6 +200,17 @@ function renderWorkflowAgentFiles(initialDraft: AgentSoulConfigFormState = agent
)
}
+function ConfigSnapshotProbe() {
+ const draft = useAtomValue(agentComposerDraftAtom)
+ const configSnapshot = formStateToAgentSoulConfig({ formState: draft })
+
+ return (
+ <pre data-testid="config-snapshot-probe">
+ {JSON.stringify(configSnapshot)}
+ </pre>
+ )
+}
+
describe('AgentFiles', () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -264,35 +306,18 @@ describe('AgentFiles', () => {
})
})
- it('should list Agent App drive files under the files prefix', () => {
+ it('should list Agent Soul files under the files prefix', () => {
renderAgentFiles()
- expect(mocks.agentDriveFilesQueryOptions).toHaveBeenCalledWith({
- input: {
- params: {
- agent_id: 'agent-1',
- },
- query: {
- prefix: 'files/',
- },
- },
- })
+ expect(screen.getByRole('button', { name: 'brief.md' })).toBeInTheDocument()
+ expect(mocks.agentDriveFilesQueryOptions).not.toHaveBeenCalled()
})
- it('should list workflow-node drive files under the files prefix', () => {
+ it('should list workflow-node Agent Soul files under the files prefix', () => {
renderWorkflowAgentFiles()
- expect(mocks.workflowAgentDriveFilesQueryOptions).toHaveBeenCalledWith({
- input: {
- params: {
- app_id: 'app-1',
- },
- query: {
- node_id: 'node-1',
- prefix: 'files/',
- },
- },
- })
+ expect(screen.getByRole('button', { name: 'brief.md' })).toBeInTheDocument()
+ expect(mocks.workflowAgentDriveFilesQueryOptions).not.toHaveBeenCalled()
})
it('should keep the file preview trigger focus ring inside the row bounds', () => {
@@ -547,10 +572,25 @@ describe('AgentFiles', () => {
}),
mutationKey: ['commit-agent-file'],
})
- renderAgentFiles({
- ...defaultAgentSoulConfigFormState,
+ const queryClient = new QueryClient({
+ defaultOptions: {
+ queries: {
+ retry: false,
+ },
+ },
})
+ render(
+ <QueryClientProvider client={queryClient}>
+ <AgentDriveApiContextProvider value={{ agentId: 'agent-1' }}>
+ <AgentComposerProvider initialDraft={defaultAgentSoulConfigFormState}>
+ <AgentFiles />
+ <ConfigSnapshotProbe />
+ </AgentComposerProvider>
+ </AgentDriveApiContextProvider>
+ </QueryClientProvider>,
+ )
+
fireEvent.click(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.files.add' }))
const input = document.querySelector('input[type="file"]')
expect(input).toBeInstanceOf(HTMLInputElement)
@@ -576,6 +616,52 @@ describe('AgentFiles', () => {
)
})
expect(await screen.findByRole('button', { name: 'uploaded.md' })).toBeInTheDocument()
+ await waitFor(() => {
+ const serializedConfig = JSON.parse(screen.getByTestId('config-snapshot-probe').textContent ?? '{}')
+ expect(serializedConfig.files.files).toEqual([
+ {
+ id: 'drive-file-1',
+ file_id: 'drive-file-1',
+ name: 'uploaded.md',
+ drive_key: 'files/uploaded.md',
+ },
+ ])
+ })
+ })
+
+ it('should upload a dropped file before committing it to the Agent App drive', async () => {
+ renderAgentFiles({
+ ...defaultAgentSoulConfigFormState,
+ })
+
+ fireEvent.click(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.files.add' }))
+
+ const uploadArea = screen.getByRole('group', { name: 'agentV2.agentDetail.configure.files.upload.title' })
+ const file = new File(['# Uploaded'], 'uploaded.md', { type: 'text/markdown' })
+ fireEvent.dragEnter(uploadArea, {
+ dataTransfer: {
+ files: [file],
+ types: ['Files'],
+ },
+ })
+ fireEvent.drop(uploadArea, {
+ dataTransfer: {
+ files: [file],
+ types: ['Files'],
+ },
+ })
+ fireEvent.click(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.files.upload.action' }))
+
+ await waitFor(() => {
+ expect(mocks.uploadFileMutationFn).toHaveBeenCalledWith(
+ {
+ body: {
+ file,
+ },
+ },
+ expect.anything(),
+ )
+ })
})
it('should commit an uploaded file through workflow-node drive endpoints and refresh the list', async () => {
@@ -750,13 +836,10 @@ describe('AgentFiles', () => {
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()
+ it('should render the empty state when Agent Soul has no files', () => {
+ renderAgentFiles({
+ ...defaultAgentSoulConfigFormState,
+ })
expect(screen.getByText('agentV2.agentDetail.configure.files.empty.title')).toBeInTheDocument()
})
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/index.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/index.tsx
index da8ff756469..d8b5663c3bb 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
@@ -12,14 +12,17 @@ import {
FileTreeGuide,
} from '@langgenius/dify-ui/file-tree'
import { useMutation, useQuery } from '@tanstack/react-query'
+import { useAtomValue, useSetAtom } from 'jotai'
import { useCallback, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
+import { agentComposerFilesAtom } from '@/features/agent-v2/agent-composer/store-modules/files'
import { consoleQuery } from '@/service/client'
import { useRegisterAgentOrchestrateAddAction } from '../add-actions-context'
import { ConfigureSectionAddButton } from '../common/add-button'
import { ConfigureSectionEmpty } from '../common/empty'
import { ConfigureSection } from '../common/section'
-import { FILES_DRIVE_PREFIX, useAgentDriveApiContext, useAgentDriveFiles } from '../drive-context'
+import { AgentConfigureTipContent } from '../common/tip-content'
+import { FILES_DRIVE_PREFIX, useAgentDriveApiContext } from '../drive-context'
import { useAgentOrchestrateReadOnly } from '../read-only-context'
import { AgentSkillDetailDialog } from '../skills/detail-dialog'
import { AgentFileTree } from './tree'
@@ -38,6 +41,16 @@ const findAgentFileNode = (files: AgentFileNode[], fileId: string): AgentFileNod
}
}
+const removeAgentFileNode = (files: AgentFileNode[], fileId: string): AgentFileNode[] => files.flatMap((file) => {
+ if (file.id === fileId)
+ return []
+
+ if (file.children)
+ return [{ ...file, children: removeAgentFileNode(file.children, fileId) }]
+
+ return [file]
+})
+
function AgentFileItem({
children,
depth,
@@ -193,7 +206,9 @@ export function AgentFiles() {
const [isUploadOpen, setIsUploadOpen] = useState(false)
const promptAddCallbackRef = useRef<AgentOrchestrateAddActionOptions['onAdded']>(undefined)
const apiContext = useAgentDriveApiContext()
- const { query: driveFilesQuery, files } = useAgentDriveFiles({ prefix: FILES_DRIVE_PREFIX })
+ const draftFiles = useAtomValue(agentComposerFilesAtom)
+ const setFiles = useSetAtom(agentComposerFilesAtom)
+ const files = draftFiles.filter(file => file.driveKey?.startsWith(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 removeFile = useCallback((fileId: string) => {
@@ -204,7 +219,7 @@ export function AgentFiles() {
return
const onSuccess = () => {
- void driveFilesQuery.refetch()
+ setFiles(files => removeAgentFileNode(files, fileId))
}
if (apiContext.workflow) {
deleteWorkflowAgentFile({
@@ -227,17 +242,20 @@ export function AgentFiles() {
key: driveKey,
},
}, { onSuccess })
- }, [apiContext, deleteAgentFile, deleteWorkflowAgentFile, driveFilesQuery, files])
+ }, [apiContext, deleteAgentFile, deleteWorkflowAgentFile, files, setFiles])
const handleOpenUpload = useCallback((options?: AgentOrchestrateAddActionOptions) => {
promptAddCallbackRef.current = options?.onAdded
setIsUploadOpen(true)
}, [])
useRegisterAgentOrchestrateAddAction('files', handleOpenUpload)
const handleUploaded = useCallback((file: AgentFileNode) => {
- void driveFilesQuery.refetch()
+ setFiles(files => [
+ ...removeAgentFileNode(files, file.id),
+ file,
+ ])
promptAddCallbackRef.current?.(file)
promptAddCallbackRef.current = undefined
- }, [driveFilesQuery])
+ }, [setFiles])
const handleUploadOpenChange = useCallback((open: boolean) => {
if (!open)
promptAddCallbackRef.current = undefined
@@ -249,7 +267,7 @@ export function AgentFiles() {
<ConfigureSection
label={t('agentDetail.configure.files.label')}
labelId="agent-configure-files-label"
- tip={filesTip}
+ tip={<AgentConfigureTipContent type="files" />}
tipAriaLabel={filesTip}
rootClassName="border-b border-divider-subtle pt-4"
panelContentClassName="pb-4"
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/upload-dialog.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/files/upload-dialog.tsx
index 3abb5fdabba..cb91d28a633 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,6 +1,7 @@
'use client'
import type { FileResponse } from '@dify/contracts/api/console/files/types.gen'
+import type { ChangeEvent, DragEvent } from 'react'
import type { AgentDriveApiContext } from '../drive-context'
import type { AgentFileNode } from '@/features/agent-v2/agent-composer/form-state'
import { Button } from '@langgenius/dify-ui/button'
@@ -30,10 +31,15 @@ function toAgentFileNode(committedFile: AgentDriveFileCommit['file']): AgentFile
id: committedFile.file_id,
name: committedFile.name,
icon: getFileIconType(committedFile.name, committedFile.mime_type),
+ fileId: committedFile.file_id,
driveKey: committedFile.drive_key,
}
}
+function hasDraggedFiles(event: DragEvent<HTMLDivElement>) {
+ return Array.from(event.dataTransfer.types).includes('Files')
+}
+
function AgentFileUploader({
file,
onChange,
@@ -43,6 +49,7 @@ function AgentFileUploader({
}) {
const { t } = useTranslation('agentV2')
const fileInputRef = useRef<HTMLInputElement>(null)
+ const dragDepthRef = useRef(0)
const [dragging, setDragging] = useState(false)
const setUploadFiles = (files: File[]) => {
@@ -55,22 +62,63 @@ function AgentFileUploader({
onChange(uploadFile)
}
- const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
+ const handleFileChange = (event: ChangeEvent<HTMLInputElement>) => {
const files = Array.from(event.target.files ?? [])
event.target.value = ''
setUploadFiles(files)
}
- const handleDrop = (event: React.DragEvent<HTMLDivElement>) => {
+ const handleDragEnter = (event: DragEvent<HTMLDivElement>) => {
+ if (!hasDraggedFiles(event))
+ return
+
+ event.preventDefault()
+ event.stopPropagation()
+ dragDepthRef.current += 1
+ setDragging(true)
+ }
+
+ const handleDragOver = (event: DragEvent<HTMLDivElement>) => {
+ if (!hasDraggedFiles(event))
+ return
+
+ event.preventDefault()
+ event.dataTransfer.dropEffect = 'copy'
+ }
+
+ const handleDragLeave = (event: DragEvent<HTMLDivElement>) => {
+ if (!hasDraggedFiles(event))
+ return
+
+ event.preventDefault()
+ event.stopPropagation()
+ dragDepthRef.current = Math.max(0, dragDepthRef.current - 1)
+ if (dragDepthRef.current === 0)
+ setDragging(false)
+ }
+
+ const handleDrop = (event: DragEvent<HTMLDivElement>) => {
+ if (!hasDraggedFiles(event))
+ return
+
event.preventDefault()
event.stopPropagation()
+ dragDepthRef.current = 0
setDragging(false)
setUploadFiles(Array.from(event.dataTransfer.files))
}
return (
- <div className="mt-6">
+ <div
+ className="mt-6"
+ role="group"
+ aria-label={t('agentDetail.configure.files.upload.title')}
+ onDragEnter={handleDragEnter}
+ onDragOver={handleDragOver}
+ onDragLeave={handleDragLeave}
+ onDrop={handleDrop}
+ >
<input
ref={fileInputRef}
className="hidden"
@@ -83,13 +131,6 @@ function AgentFileUploader({
'relative flex h-16 items-center rounded-[10px] border border-dashed border-components-dropzone-border bg-components-dropzone-bg text-sm font-normal',
dragging && 'border-components-dropzone-border-accent bg-components-dropzone-bg-accent',
)}
- onDragEnter={(event) => {
- event.preventDefault()
- setDragging(true)
- }}
- onDragOver={event => event.preventDefault()}
- onDragLeave={() => setDragging(false)}
- onDrop={handleDrop}
>
<div className="flex w-full items-center justify-center space-x-2">
<span aria-hidden className="i-ri-upload-cloud-2-line size-6 text-text-tertiary" />
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/header.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/header.tsx
index 36d11483928..269a453028e 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/header.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/header.tsx
@@ -1,23 +1,45 @@
'use client'
+import type { ReactNode } from 'react'
import { useTranslation } from 'react-i18next'
type AgentOrchestrateHeaderProps = {
headingId: string
+ trailingAction?: ReactNode
+ isBuildDraftActive?: boolean
}
export function AgentOrchestrateHeader({
headingId,
+ trailingAction,
+ isBuildDraftActive = false,
}: AgentOrchestrateHeaderProps) {
const { t } = useTranslation('agentV2')
return (
- <div className="flex shrink-0 items-center gap-1 px-4 py-2">
- <div className="flex min-w-0 flex-1 flex-col justify-center">
- <h2 id={headingId} className="truncate title-xl-semi-bold text-text-primary">
- {t('agentDetail.configure.orchestrate')}
- </h2>
+ <div className="shrink-0 px-4 py-3">
+ <div className="flex h-6 min-w-0 items-center justify-between gap-2">
+ <div className="flex min-w-0 items-center gap-2">
+ <h2 id={headingId} className="truncate title-xl-semi-bold text-text-primary">
+ {t('agentDetail.configure.title')}
+ </h2>
+ {isBuildDraftActive && (
+ <span className="flex min-w-[18px] shrink-0 items-center justify-center rounded-[5px] border border-text-accent-secondary bg-components-badge-bg-dimm px-1.25 py-0.75 system-2xs-medium-uppercase text-text-accent-secondary">
+ {t('agentDetail.configure.buildDraft.modeBadge')}
+ </span>
+ )}
+ </div>
+ {trailingAction != null && (
+ <div className="shrink-0">
+ {trailingAction}
+ </div>
+ )}
</div>
+ {isBuildDraftActive && (
+ <p className="mt-1 w-full system-xs-regular text-text-tertiary">
+ {t('agentDetail.configure.buildDraft.modeDescription')}
+ </p>
+ )}
</div>
)
}
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/index.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/index.tsx
index cddbec00d68..f79f475dba8 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
@@ -1,7 +1,7 @@
'use client'
import type { AgentConfigSnapshotDetailResponse, AgentConfigSnapshotSummaryResponse } from '@dify/contracts/api/console/agent/types.gen'
-import type { AgentConfigurePublishPayload } from './publish-bar'
+import type { ReactNode } from 'react'
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'
@@ -9,6 +9,7 @@ import { useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import { AgentOrchestrateAddActionsProvider } from './add-actions'
import { AgentAdvancedSettings } from './advanced'
+import { AgentOrchestrateBottomActions } from './bottom-actions'
import { AgentDriveApiContextProvider } from './drive-context'
import { AgentFiles } from './files'
import { AgentOrchestrateHeader } from './header'
@@ -35,10 +36,13 @@ type AgentOrchestratePanelProps = {
className?: string
readOnly?: boolean
selectedVersionSnapshot?: AgentConfigSnapshotSummaryResponse | null
+ isBuildDraftActive?: boolean
showHeader?: boolean
showPublishBar?: boolean
+ headerAction?: ReactNode
+ bottomAction?: ReactNode
onSelectModel: (model: DefaultModel) => void
- onPublish: (payload: AgentConfigurePublishPayload) => void | Promise<void>
+ onPublish: () => void | Promise<void>
onExitVersions?: () => void
onOpenVersions: () => void
}
@@ -49,7 +53,7 @@ export function AgentOrchestratePanel({
nodeId,
activeConfigIsPublished,
activeConfigSnapshot,
- agentSoulConfig,
+ agentSoulConfig: _agentSoulConfig,
agentName,
currentModel,
textGenerationModelList,
@@ -58,8 +62,11 @@ export function AgentOrchestratePanel({
className,
readOnly = false,
selectedVersionSnapshot,
+ isBuildDraftActive = false,
showHeader = true,
showPublishBar = true,
+ headerAction,
+ bottomAction,
onSelectModel,
onPublish,
onExitVersions,
@@ -67,7 +74,24 @@ export function AgentOrchestratePanel({
}: AgentOrchestratePanelProps) {
const { t } = useTranslation('agentV2')
const orchestrateHeadingId = 'agent-configure-orchestrate-heading'
- const orchestrateLabel = t('agentDetail.configure.orchestrate')
+ const orchestrateLabel = t('agentDetail.configure.title')
+ const orchestrateBottomAction = bottomAction ?? (showPublishBar
+ ? (
+ <AgentConfigurePublishBar
+ agentId={agentId}
+ activeConfigIsPublished={activeConfigIsPublished}
+ activeConfigSnapshot={activeConfigSnapshot}
+ agentName={agentName}
+ draftSavedAt={draftSavedAt}
+ isPublishing={isPublishing}
+ selectedVersionSnapshot={selectedVersionSnapshot}
+ onPublish={onPublish}
+ onExitVersions={onExitVersions}
+ onOpenVersions={onOpenVersions}
+ />
+ )
+ : null)
+ const hasBottomAction = !!orchestrateBottomAction
const driveApiContext = useMemo(() => appId && nodeId
? {
agentId,
@@ -80,7 +104,7 @@ export function AgentOrchestratePanel({
return (
<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} />}
+ {showHeader && <AgentOrchestrateHeader headingId={orchestrateHeadingId} trailingAction={headerAction} isBuildDraftActive={isBuildDraftActive} />}
<AgentOrchestrateReadOnlyContext value={readOnly}>
<div
@@ -93,8 +117,8 @@ export function AgentOrchestratePanel({
labelledBy={showHeader ? orchestrateHeadingId : undefined}
slotClassNames={{
viewport: 'overscroll-contain',
- content: cn('min-h-full px-4 py-3', showPublishBar && 'pb-20'),
- scrollbar: showPublishBar ? 'z-20' : undefined,
+ content: cn('min-h-full px-4 py-3', hasBottomAction && 'pb-20'),
+ scrollbar: hasBottomAction ? 'z-20' : undefined,
}}
>
<AgentDriveApiContextProvider value={driveApiContext}>
@@ -116,22 +140,13 @@ export function AgentOrchestratePanel({
</div>
</AgentOrchestrateReadOnlyContext>
- {showPublishBar && (
- <AgentConfigurePublishBar
- agentId={agentId}
- activeConfigIsPublished={activeConfigIsPublished}
- activeConfigSnapshot={activeConfigSnapshot}
- agentSoulConfig={agentSoulConfig}
- agentName={agentName}
- currentModel={currentModel}
- draftSavedAt={draftSavedAt}
- isPublishing={isPublishing}
- selectedVersionSnapshot={selectedVersionSnapshot}
- onPublish={onPublish}
- onExitVersions={onExitVersions}
- onOpenVersions={onOpenVersions}
- />
- )}
+ {orchestrateBottomAction
+ ? (
+ <AgentOrchestrateBottomActions>
+ {orchestrateBottomAction}
+ </AgentOrchestrateBottomActions>
+ )
+ : null}
</div>
)
}
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/__tests__/index.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/__tests__/index.spec.tsx
index 8f3e683002e..f2434667119 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
@@ -1,11 +1,13 @@
import type { AgentSoulConfigFormState } from '@/features/agent-v2/agent-composer/form-state'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
-import { render, screen, within } from '@testing-library/react'
+import { fireEvent, render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { useAtomValue } from 'jotai'
import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { formStateToAgentSoulConfig } from '@/features/agent-v2/agent-composer/conversions'
import { defaultAgentSoulConfigFormState } from '@/features/agent-v2/agent-composer/form-state'
import { AgentComposerProvider } from '@/features/agent-v2/agent-composer/provider'
-import { useConfigPublishPayload } from '@/features/agent-v2/agent-composer/store'
+import { agentComposerDraftAtom } from '@/features/agent-v2/agent-composer/store'
import { AgentOrchestrateReadOnlyContext } from '../../read-only-context'
import { AgentKnowledgeRetrieval } from '../index'
@@ -14,17 +16,18 @@ const agentKnowledgeDraft = {
knowledgeRetrievals: [
{
id: 'retrieval-1',
- nameKey: 'agentDetail.configure.knowledgeRetrieval.retrievalOne',
+ name: 'agentV2.agentDetail.configure.knowledgeRetrieval.retrievalOne',
},
],
} satisfies AgentSoulConfigFormState
-function PublishPayloadPreview() {
- const payload = useConfigPublishPayload({ agentId: 'agent-1' })
+function ConfigSnapshotPreview() {
+ const draft = useAtomValue(agentComposerDraftAtom)
+ const configSnapshot = formStateToAgentSoulConfig({ formState: draft })
return (
- <output aria-label="publish payload">
- {JSON.stringify(payload.config_snapshot.knowledge)}
+ <output aria-label="config snapshot">
+ {JSON.stringify(configSnapshot.knowledge)}
</output>
)
}
@@ -32,11 +35,11 @@ function PublishPayloadPreview() {
function renderKnowledgeRetrieval({
initialDraft = agentKnowledgeDraft,
readOnly = false,
- showPublishPayload = false,
+ showConfigSnapshot = false,
}: {
initialDraft?: AgentSoulConfigFormState
readOnly?: boolean
- showPublishPayload?: boolean
+ showConfigSnapshot?: boolean
} = {}) {
const queryClient = new QueryClient()
@@ -46,7 +49,7 @@ function renderKnowledgeRetrieval({
<AgentOrchestrateReadOnlyContext value={readOnly}>
<AgentKnowledgeRetrieval />
</AgentOrchestrateReadOnlyContext>
- {showPublishPayload && <PublishPayloadPreview />}
+ {showConfigSnapshot && <ConfigSnapshotPreview />}
</AgentComposerProvider>
</QueryClientProvider>,
)
@@ -159,9 +162,68 @@ describe('AgentKnowledgeRetrieval', () => {
expect(within(dialog).queryByText('agentV2.agentDetail.configure.knowledgeRetrieval.dialog.query.agentDescription')).not.toBeInTheDocument()
})
- it('should save newly added retrieval data into the publish config', async () => {
+ it('should show inline validation for missing datasets and blank custom queries', async () => {
const user = userEvent.setup()
- renderKnowledgeRetrieval({ showPublishPayload: true })
+ renderKnowledgeRetrieval()
+
+ await user.click(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.knowledgeRetrieval.add' }))
+ const dialog = screen.getByRole('dialog', {
+ name: 'agentV2.agentDetail.configure.knowledgeRetrieval.dialog.title',
+ })
+
+ expect(within(dialog).getByText('common.errorMsg.fieldRequired:{"field":"agentV2.agentDetail.configure.knowledgeRetrieval.dialog.knowledge.label"}')).toBeInTheDocument()
+
+ await user.click(within(dialog).getByRole('radio', {
+ name: 'agentV2.agentDetail.configure.knowledgeRetrieval.dialog.query.custom',
+ }))
+
+ expect(within(dialog).getByText('common.errorMsg.fieldRequired:{"field":"agentV2.agentDetail.configure.knowledgeRetrieval.dialog.query.customInputLabel"}')).toBeInTheDocument()
+ })
+
+ it('should show duplicate-name validation in the dialog', async () => {
+ const user = userEvent.setup()
+ renderKnowledgeRetrieval({
+ initialDraft: {
+ ...defaultAgentSoulConfigFormState,
+ knowledgeRetrievals: [
+ {
+ id: 'retrieval-1',
+ name: 'Docs Search',
+ datasetRefs: [{ id: 'dataset-1', name: 'Docs' }],
+ },
+ {
+ id: 'retrieval-2',
+ name: 'FAQ Search',
+ datasetRefs: [{ id: 'dataset-2', name: 'FAQ' }],
+ },
+ ],
+ },
+ })
+
+ await user.click(screen.getByRole('button', {
+ name: 'agentV2.agentDetail.configure.knowledgeRetrieval.edit:{"name":"FAQ Search"}',
+ }))
+
+ const dialog = screen.getByRole('dialog', {
+ name: 'agentV2.agentDetail.configure.knowledgeRetrieval.dialog.title',
+ })
+
+ await user.click(within(dialog).getByRole('button', {
+ name: 'FAQ Search',
+ }))
+ const nameInput = within(dialog).getByRole('textbox', {
+ name: 'agentV2.agentDetail.configure.knowledgeRetrieval.dialog.nameLabel',
+ })
+ await user.clear(nameInput)
+ await user.type(nameInput, 'Docs Search')
+ fireEvent.blur(nameInput)
+
+ expect(within(dialog).getByText('appDebug.varKeyError.keyAlreadyExists:{"key":"agentV2.agentDetail.configure.knowledgeRetrieval.dialog.nameLabel"}')).toBeInTheDocument()
+ })
+
+ it('should save newly added retrieval data into the config snapshot', async () => {
+ const user = userEvent.setup()
+ renderKnowledgeRetrieval({ showConfigSnapshot: true })
await user.click(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.knowledgeRetrieval.add' }))
const dialog = screen.getByRole('dialog', {
@@ -179,23 +241,29 @@ describe('AgentKnowledgeRetrieval', () => {
name: 'agentV2.agentDetail.configure.knowledgeRetrieval.dialog.query.customInputLabel',
}), 'new release notes')
- const knowledgeConfig = JSON.parse(screen.getByLabelText('publish payload').textContent ?? '{}')
- expect(knowledgeConfig.datasets).toEqual(expect.arrayContaining([
- {
+ const knowledgeConfig = JSON.parse(screen.getByLabelText('config snapshot').textContent ?? '{}')
+ expect(knowledgeConfig.sets).toEqual(expect.arrayContaining([
+ expect.objectContaining({
id: 'retrieval-1',
- name: 'agentDetail.configure.knowledgeRetrieval.retrievalOne',
- },
+ name: 'agentV2.agentDetail.configure.knowledgeRetrieval.retrievalOne',
+ datasets: [],
+ query: {
+ mode: 'generated_query',
+ },
+ }),
expect.objectContaining({
name: 'agentV2.agentDetail.configure.knowledgeRetrieval.retrievalTwo',
+ datasets: [],
+ query: {
+ mode: 'user_query',
+ value: 'new release notes',
+ },
+ retrieval: expect.objectContaining({
+ mode: 'multiple',
+ top_k: 4,
+ }),
}),
]))
- expect(knowledgeConfig).toMatchObject({
- query_config: {
- query: 'new release notes',
- top_k: 4,
- },
- query_mode: 'user_query',
- })
})
it('should open the knowledge retrieval dialog from the edit button', async () => {
@@ -251,9 +319,9 @@ describe('AgentKnowledgeRetrieval', () => {
expect(within(dialog).queryByText('appDebug.datasetConfig.knowledgeTip')).not.toBeInTheDocument()
})
- it('should save edited retrieval data into the publish config', async () => {
+ it('should save edited retrieval data into the config snapshot', async () => {
const user = userEvent.setup()
- renderKnowledgeRetrieval({ showPublishPayload: true })
+ renderKnowledgeRetrieval({ showConfigSnapshot: true })
await user.click(screen.getByRole('button', {
name: 'agentV2.agentDetail.configure.knowledgeRetrieval.edit:{"name":"agentV2.agentDetail.configure.knowledgeRetrieval.retrievalOne"}',
@@ -277,19 +345,23 @@ describe('AgentKnowledgeRetrieval', () => {
name: 'agentV2.agentDetail.configure.knowledgeRetrieval.dialog.query.customInputLabel',
}), 'release notes')
- const knowledgeConfig = JSON.parse(screen.getByLabelText('publish payload').textContent ?? '{}')
+ const knowledgeConfig = JSON.parse(screen.getByLabelText('config snapshot').textContent ?? '{}')
expect(knowledgeConfig).toMatchObject({
- datasets: [
+ sets: [
{
id: 'retrieval-1',
name: 'Release Search',
+ datasets: [],
+ query: {
+ mode: 'user_query',
+ value: 'release notes',
+ },
+ retrieval: {
+ mode: 'multiple',
+ top_k: 4,
+ },
},
],
- query_config: {
- query: 'release notes',
- top_k: 4,
- },
- query_mode: 'user_query',
})
})
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/dialog.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/dialog.tsx
index 200313ca813..0b8529617fe 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/dialog.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/dialog.tsx
@@ -1,11 +1,12 @@
'use client'
import type { AgentKnowledgeDatasetConfig } from '@dify/contracts/api/console/agent/types.gen'
-import type { ReactNode } from 'react'
+import type { ReactNode, SetStateAction } from 'react'
import type {
MetadataFilteringCondition,
MetadataFilteringModeEnum,
MultipleRetrievalConfig,
+ SingleRetrievalConfig,
} from '@/app/components/workflow/nodes/knowledge-retrieval/types'
import type { ModelConfig } from '@/app/components/workflow/types'
import type { AgentKnowledgeRetrievalItem } from '@/features/agent-v2/agent-composer/form-state'
@@ -17,6 +18,7 @@ import { RadioRoot } from '@langgenius/dify-ui/radio'
import { RadioGroup } from '@langgenius/dify-ui/radio-group'
import { Textarea } from '@langgenius/dify-ui/textarea'
import { intersectionBy } from 'es-toolkit/compat'
+import { useAtomValue } from 'jotai'
import { useEffect, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { IndexingType } from '@/app/components/datasets/create/step-two/hooks/use-indexing-config'
@@ -33,10 +35,32 @@ import {
} from '@/app/components/workflow/nodes/knowledge-retrieval/types'
import { DATASET_DEFAULT } from '@/config'
import { useDocLink } from '@/context/i18n'
+import { useKnowledgeValidationMessage, validateKnowledgeRetrievals } from '@/features/agent-v2/agent-composer/knowledge-validation'
+import { agentComposerKnowledgeRetrievalsAtom } from '@/features/agent-v2/agent-composer/store-modules/knowledge'
import { ChunkingMode, DatasetPermission, DataSourceType } from '@/models/datasets'
import { AppModeEnum, RETRIEVE_METHOD, RETRIEVE_TYPE } from '@/types/app'
type KnowledgeRetrievalQueryMode = 'agent' | 'custom'
+type MetadataFilteringConditions = {
+ logical_operator: LogicalOperator
+ conditions: MetadataFilteringCondition[]
+}
+
+type KnowledgeRetrievalDialogState = {
+ customQuery: string
+ hydratedKey: string | null
+ isEditingName: boolean
+ metadataFilterMode: MetadataFilteringModeEnum
+ metadataFilteringConditions: MetadataFilteringConditions
+ metadataModelConfig?: ModelConfig
+ multipleRetrievalConfig: MultipleRetrievalConfig
+ name: string
+ queryMode: KnowledgeRetrievalQueryMode
+ rerankModelOpen: boolean
+ retrievalMode: typeof RETRIEVE_TYPE[keyof typeof RETRIEVE_TYPE]
+ selectedDatasets: DataSet[]
+ singleRetrievalConfig?: SingleRetrievalConfig
+}
const queryModeOptions: KnowledgeRetrievalQueryMode[] = ['agent', 'custom']
@@ -75,6 +99,11 @@ const createDefaultRetrievalConfig = (): MultipleRetrievalConfig => ({
reranking_enable: false,
})
+const createDefaultMetadataFilteringConditions = (): MetadataFilteringConditions => ({
+ logical_operator: LogicalOperator.and,
+ conditions: [],
+})
+
const createDatasetFromRef = (dataset: AgentKnowledgeDatasetConfig, index: number): DataSet => {
const id = dataset.id ?? dataset.name ?? `dataset-${index}`
const name = dataset.name ?? id
@@ -150,6 +179,33 @@ const getSelectedDatasets = (item?: AgentKnowledgeRetrievalItem) => (
item?.selectedDatasets ?? item?.datasetRefs?.map(createDatasetFromRef) ?? []
)
+const getDialogName = (
+ item: AgentKnowledgeRetrievalItem | undefined,
+ initialName: string | undefined,
+ fallbackName: string,
+) => item?.name ?? initialName ?? fallbackName
+
+const createDialogState = (
+ item: AgentKnowledgeRetrievalItem | undefined,
+ initialName: string | undefined,
+ fallbackName: string,
+ hydrationKey: string,
+): KnowledgeRetrievalDialogState => ({
+ customQuery: item?.customQuery ?? '',
+ hydratedKey: hydrationKey,
+ isEditingName: false,
+ metadataFilterMode: item?.metadataFilterMode ?? WorkflowMetadataFilteringModeEnum.disabled,
+ metadataFilteringConditions: item?.metadataFilteringConditions ?? createDefaultMetadataFilteringConditions(),
+ metadataModelConfig: item?.metadataModelConfig,
+ multipleRetrievalConfig: item?.multipleRetrievalConfig ?? createDefaultRetrievalConfig(),
+ name: getDialogName(item, initialName, fallbackName),
+ queryMode: item?.queryMode ?? 'agent',
+ rerankModelOpen: false,
+ retrievalMode: item?.retrievalMode ?? RETRIEVE_TYPE.multiWay,
+ selectedDatasets: getSelectedDatasets(item),
+ singleRetrievalConfig: item?.singleRetrievalConfig,
+})
+
const createMetadataCondition = ({ id, name, type }: MetadataInDoc): MetadataFilteringCondition => ({
id: globalThis.crypto?.randomUUID?.() ?? `${Date.now()}`,
metadata_id: id,
@@ -174,22 +230,70 @@ export function AgentKnowledgeRetrievalDialog({
}) {
const { t } = useTranslation('agentV2')
const docLink = useDocLink()
- const [name, setName] = useState(() => item?.name ?? initialName ?? t('agentDetail.configure.knowledgeRetrieval.retrievalOne'))
- const [isEditingName, setIsEditingName] = useState(false)
+ const retrievals = useAtomValue(agentComposerKnowledgeRetrievalsAtom)
+ const getValidationMessage = useKnowledgeValidationMessage()
+ const fallbackName = t('agentDetail.configure.knowledgeRetrieval.retrievalOne')
+ const hydrationKey = open ? (item?.id ?? initialName ?? 'new') : null
+ const [dialogState, setDialogState] = useState(() => createDialogState(item, initialName, fallbackName, hydrationKey ?? 'new'))
const nameInputRef = useRef<HTMLInputElement>(null)
- const [queryMode, setQueryMode] = useState<KnowledgeRetrievalQueryMode>(item?.queryMode ?? 'agent')
- const [customQuery, setCustomQuery] = useState(item?.customQuery ?? '')
- const [selectedDatasets, setSelectedDatasets] = useState<DataSet[]>(() => getSelectedDatasets(item))
- const [retrievalMode, setRetrievalMode] = useState(item?.retrievalMode ?? RETRIEVE_TYPE.multiWay)
- const [multipleRetrievalConfig, setMultipleRetrievalConfig] = useState(item?.multipleRetrievalConfig ?? createDefaultRetrievalConfig)
- const [rerankModelOpen, setRerankModelOpen] = useState(false)
- const [metadataFilterMode, setMetadataFilterMode] = useState<MetadataFilteringModeEnum>(item?.metadataFilterMode ?? WorkflowMetadataFilteringModeEnum.disabled)
- const [metadataFilteringConditions, setMetadataFilteringConditions] = useState(item?.metadataFilteringConditions ?? {
- logical_operator: LogicalOperator.and,
- conditions: [] as MetadataFilteringCondition[],
- })
- const [metadataModelConfig, setMetadataModelConfig] = useState<ModelConfig | undefined>(item?.metadataModelConfig)
const queryModeLabelId = 'agent-knowledge-retrieval-query-mode-label'
+ const {
+ customQuery,
+ hydratedKey,
+ isEditingName,
+ metadataFilterMode,
+ metadataFilteringConditions,
+ metadataModelConfig,
+ multipleRetrievalConfig,
+ name,
+ queryMode,
+ rerankModelOpen,
+ retrievalMode,
+ selectedDatasets,
+ singleRetrievalConfig,
+ } = dialogState
+ const patchDialogState = (patch: Partial<KnowledgeRetrievalDialogState>) => {
+ setDialogState(current => ({
+ ...current,
+ ...patch,
+ }))
+ }
+ const setMetadataFilteringConditions = (update: SetStateAction<MetadataFilteringConditions>) => {
+ setDialogState((current) => {
+ const nextMetadataFilteringConditions = typeof update === 'function'
+ ? update(current.metadataFilteringConditions)
+ : update
+
+ return {
+ ...current,
+ metadataFilteringConditions: nextMetadataFilteringConditions,
+ }
+ })
+ }
+ const setMetadataModelConfig = (update: SetStateAction<ModelConfig | undefined>) => {
+ setDialogState((current) => {
+ const nextMetadataModelConfig = typeof update === 'function'
+ ? update(current.metadataModelConfig)
+ : update
+
+ return {
+ ...current,
+ metadataModelConfig: nextMetadataModelConfig,
+ }
+ })
+ }
+ const setSingleRetrievalConfig = (update: SetStateAction<SingleRetrievalConfig | undefined>) => {
+ setDialogState((current) => {
+ const nextSingleRetrievalConfig = typeof update === 'function'
+ ? update(current.singleRetrievalConfig)
+ : update
+
+ return {
+ ...current,
+ singleRetrievalConfig: nextSingleRetrievalConfig,
+ }
+ })
+ }
const updateItem = (patch: Partial<AgentKnowledgeRetrievalItem>) => {
if (!item)
return
@@ -202,6 +306,7 @@ export function AgentKnowledgeRetrievalDialog({
selectedDatasets,
retrievalMode,
multipleRetrievalConfig,
+ singleRetrievalConfig,
metadataFilterMode,
metadataFilteringConditions,
metadataModelConfig,
@@ -216,6 +321,26 @@ export function AgentKnowledgeRetrievalDialog({
return intersectionBy(...datasetsWithMetadata.map(dataset => dataset.doc_metadata!), 'name')
}, [selectedDatasets])
+ const validation = useMemo(() => validateKnowledgeRetrievals(retrievals), [retrievals])
+ const itemValidation = item ? validation.byId[item.id] : undefined
+ const nameError = getValidationMessage(itemValidation?.name)
+ const datasetsError = getValidationMessage(itemValidation?.datasets)
+ const queryError = getValidationMessage(itemValidation?.query)
+ const retrievalError = getValidationMessage(itemValidation?.retrieval)
+ const metadataError = getValidationMessage(itemValidation?.metadata)
+
+ useEffect(() => {
+ if (hydratedKey !== hydrationKey) {
+ // eslint-disable-next-line react/set-state-in-effect
+ setDialogState(current => hydrationKey
+ ? createDialogState(item, initialName, fallbackName, hydrationKey)
+ : {
+ ...current,
+ hydratedKey: null,
+ isEditingName: false,
+ })
+ }
+ }, [fallbackName, hydratedKey, hydrationKey, initialName, item])
useEffect(() => {
if (!isEditingName)
@@ -227,7 +352,11 @@ export function AgentKnowledgeRetrievalDialog({
return (
<Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent className="flex h-[520px] max-h-[calc(100dvh-2rem)] w-[400px] flex-col overflow-hidden p-0">
+ <DialogContent
+ backdropProps={{ forceRender: true }}
+ backdropClassName="fixed"
+ className="flex h-[520px] max-h-[calc(100dvh-2rem)] w-[400px] flex-col overflow-hidden p-0"
+ >
<DialogTitle className="sr-only">
{t('agentDetail.configure.knowledgeRetrieval.dialog.title')}
</DialogTitle>
@@ -238,17 +367,18 @@ export function AgentKnowledgeRetrievalDialog({
<Input
ref={nameInputRef}
aria-label={t('agentDetail.configure.knowledgeRetrieval.dialog.nameLabel')}
+ aria-invalid={nameError ? true : undefined}
className="h-7 min-w-0 flex-1 rounded-md px-1 py-0 system-xl-semibold text-text-primary"
value={name}
- onBlur={() => setIsEditingName(false)}
+ onBlur={() => patchDialogState({ isEditingName: false })}
onChange={(event) => {
const nextName = event.currentTarget.value
- setName(nextName)
+ patchDialogState({ name: nextName })
updateItem({ name: nextName })
}}
onKeyDown={(event) => {
if (event.key === 'Enter')
- setIsEditingName(false)
+ patchDialogState({ isEditingName: false })
}}
/>
)
@@ -256,7 +386,7 @@ export function AgentKnowledgeRetrievalDialog({
<button
type="button"
className="flex h-7 min-w-0 flex-1 items-center rounded-md px-1 py-0 text-left system-xl-semibold text-text-primary hover:bg-components-input-bg-hover focus-visible:border focus-visible:border-components-input-border-active focus-visible:bg-components-input-bg-active focus-visible:shadow-xs focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"
- onClick={() => setIsEditingName(true)}
+ onClick={() => patchDialogState({ isEditingName: true })}
>
<span className="min-w-0 truncate">
{name}
@@ -265,6 +395,11 @@ export function AgentKnowledgeRetrievalDialog({
)}
<DialogCloseButton className="static size-7 shrink-0 rounded-md" />
</div>
+ {nameError && (
+ <div role="alert" className="px-4 pt-1 system-xs-regular text-text-destructive">
+ {nameError}
+ </div>
+ )}
<div className="flex min-h-0 flex-1 flex-col gap-1 py-2">
<div className="flex flex-col gap-1 px-4 py-2">
@@ -277,7 +412,7 @@ export function AgentKnowledgeRetrievalDialog({
value={queryMode}
onValueChange={(nextMode) => {
if (nextMode) {
- setQueryMode(nextMode)
+ patchDialogState({ queryMode: nextMode })
updateItem({ queryMode: nextMode })
}
}}
@@ -302,11 +437,12 @@ export function AgentKnowledgeRetrievalDialog({
<div className="pt-1">
<Textarea
aria-label={t('agentDetail.configure.knowledgeRetrieval.dialog.query.customInputLabel')}
+ aria-invalid={queryError ? true : undefined}
className="h-20 resize-none rounded-lg px-3 py-2 system-sm-regular"
placeholder={t('agentDetail.configure.knowledgeRetrieval.dialog.query.customPlaceholder')}
value={customQuery}
onValueChange={(nextQuery) => {
- setCustomQuery(nextQuery)
+ patchDialogState({ customQuery: nextQuery })
updateItem({ customQuery: nextQuery })
}}
/>
@@ -314,6 +450,11 @@ export function AgentKnowledgeRetrievalDialog({
<p className="system-xs-regular text-text-tertiary">
{t('agentDetail.configure.knowledgeRetrieval.dialog.query.customDescription')}
</p>
+ {queryError && (
+ <p role="alert" className="system-xs-regular text-text-destructive">
+ {queryError}
+ </p>
+ )}
</>
)
: (
@@ -333,19 +474,49 @@ export function AgentKnowledgeRetrievalDialog({
payload={{
retrieval_mode: retrievalMode,
multiple_retrieval_config: multipleRetrievalConfig,
+ single_retrieval_config: singleRetrievalConfig,
}}
onRetrievalModeChange={(nextRetrievalMode) => {
- setRetrievalMode(nextRetrievalMode)
+ patchDialogState({ retrievalMode: nextRetrievalMode })
updateItem({ retrievalMode: nextRetrievalMode })
}}
onMultipleRetrievalConfigChange={(nextMultipleRetrievalConfig) => {
- setMultipleRetrievalConfig(nextMultipleRetrievalConfig)
+ patchDialogState({ multipleRetrievalConfig: nextMultipleRetrievalConfig })
updateItem({ multipleRetrievalConfig: nextMultipleRetrievalConfig })
}}
+ singleRetrievalModelConfig={singleRetrievalConfig?.model}
+ onSingleRetrievalModelChange={(model) => {
+ setSingleRetrievalConfig((current) => {
+ const nextSingleRetrievalConfig = {
+ model: {
+ provider: model.provider,
+ name: model.modelId,
+ mode: model.mode ?? current?.model.mode ?? AppModeEnum.CHAT,
+ completion_params: current?.model.completion_params ?? { temperature: 0.7 },
+ },
+ }
+ updateItem({ singleRetrievalConfig: nextSingleRetrievalConfig })
+ return nextSingleRetrievalConfig
+ })
+ }}
+ onSingleRetrievalModelParamsChange={(completionParams) => {
+ setSingleRetrievalConfig((current) => {
+ const nextSingleRetrievalConfig = {
+ model: {
+ provider: current?.model.provider ?? '',
+ name: current?.model.name ?? '',
+ mode: current?.model.mode ?? AppModeEnum.CHAT,
+ completion_params: completionParams,
+ },
+ }
+ updateItem({ singleRetrievalConfig: nextSingleRetrievalConfig })
+ return nextSingleRetrievalConfig
+ })
+ }}
readonly={!selectedDatasets.length}
modal
rerankModalOpen={rerankModelOpen}
- onRerankModelOpenChange={setRerankModelOpen}
+ onRerankModelOpenChange={nextOpen => patchDialogState({ rerankModelOpen: nextOpen })}
selectedDatasets={selectedDatasets}
/>
<div className="h-3 w-px bg-divider-regular" />
@@ -353,21 +524,31 @@ export function AgentKnowledgeRetrievalDialog({
selectedIds={selectedDatasets.map(dataset => dataset.id)}
modal
onChange={(nextDatasets) => {
- setSelectedDatasets(nextDatasets)
+ patchDialogState({ selectedDatasets: nextDatasets })
updateItem({ selectedDatasets: nextDatasets })
}}
/>
</div>
)}
>
- <DatasetList
- list={selectedDatasets}
- onChange={setSelectedDatasets}
- settingsDrawerBackdropClassName="bg-background-overlay"
- settingsDrawerBackdropForceRender
- settingsDrawerPopupClassName="data-[swipe-direction=right]:top-6 data-[swipe-direction=right]:bottom-6"
- settingsModalHeight="100%"
- />
+ <>
+ <DatasetList
+ list={selectedDatasets}
+ onChange={(nextDatasets) => {
+ patchDialogState({ selectedDatasets: nextDatasets })
+ updateItem({ selectedDatasets: nextDatasets })
+ }}
+ settingsDrawerBackdropClassName="bg-background-overlay"
+ settingsDrawerBackdropForceRender
+ settingsDrawerPopupClassName="data-[swipe-direction=right]:top-6 data-[swipe-direction=right]:bottom-6"
+ settingsModalHeight="100%"
+ />
+ {(datasetsError || retrievalError) && (
+ <div role="alert" className="pt-2 system-xs-regular text-text-destructive">
+ {datasetsError ?? retrievalError}
+ </div>
+ )}
+ </>
</Field>
</div>
@@ -378,7 +559,7 @@ export function AgentKnowledgeRetrievalDialog({
metadataFilterMode={metadataFilterMode}
metadataFilteringConditions={metadataFilteringConditions}
handleMetadataFilterModeChange={(nextMode) => {
- setMetadataFilterMode(nextMode)
+ patchDialogState({ metadataFilterMode: nextMode })
updateItem({ metadataFilterMode: nextMode })
}}
handleAddCondition={(metadataItem) => {
@@ -449,6 +630,11 @@ export function AgentKnowledgeRetrievalDialog({
})
}}
/>
+ {metadataError && (
+ <div role="alert" className="px-4 pt-2 system-xs-regular text-text-destructive">
+ {metadataError}
+ </div>
+ )}
</div>
</div>
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/index.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/index.tsx
index 5f65302b23a..a51945bdbf5 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/index.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/index.tsx
@@ -113,7 +113,6 @@ export function AgentKnowledgeRetrieval() {
))}
</ConfigureSection>
<AgentKnowledgeRetrievalDialog
- key={editingRetrieval?.id ?? 'add'}
item={editingRetrieval ?? undefined}
initialName={editingRetrieval ? (editingRetrieval.name ?? (editingRetrieval.nameKey ? t(editingRetrieval.nameKey) : editingRetrieval.id)) : undefined}
onItemChange={updateRetrieval}
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/hooks.ts b/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/hooks.ts
new file mode 100644
index 00000000000..9b27c010bef
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/hooks.ts
@@ -0,0 +1,105 @@
+'use client'
+
+import type { ToolWithProvider } from '@/app/components/workflow/types'
+import type { AgentTool } from '@/features/agent-v2/agent-composer/form-state'
+import { useMemo } from 'react'
+import { API_PREFIX } from '@/config'
+import { useSelector } from '@/context/app-context'
+import useTheme from '@/hooks/use-theme'
+import {
+ useAllBuiltInTools,
+ useAllCustomTools,
+ useAllMCPTools,
+ useAllWorkflowTools,
+} from '@/service/use-tools'
+import { Theme } from '@/types/app'
+import { basePath } from '@/utils/var'
+
+type ProviderTool = Extract<AgentTool, { kind: 'provider' }>
+
+const hasUrlProtocol = (value: string) => /^[a-z][a-z\d+.-]*:/i.test(value)
+
+function normalizeProviderIcon(
+ icon: ToolWithProvider['icon'] | undefined,
+ workspaceId: string,
+) {
+ if (!icon || typeof icon !== 'string')
+ return icon
+
+ if (hasUrlProtocol(icon))
+ return icon
+
+ if (icon.startsWith('/')) {
+ if (basePath && !icon.startsWith(`${basePath}/`))
+ return `${basePath}${icon}`
+
+ return icon
+ }
+
+ if (!workspaceId)
+ return icon
+
+ return `${API_PREFIX}/workspaces/current/plugin/icon?tenant_id=${workspaceId}&filename=${icon}`
+}
+
+function getProviderByTool(
+ providerById: Map<string, ToolWithProvider>,
+ tool: ProviderTool,
+) {
+ return providerById.get(tool.id)
+ ?? providerById.get(tool.name)
+}
+
+function createProviderMap(providers: ToolWithProvider[]) {
+ const providerById = new Map<string, ToolWithProvider>()
+
+ providers.forEach((provider) => {
+ providerById.set(provider.id, provider)
+ providerById.set(provider.name, provider)
+ if (provider.plugin_id) {
+ providerById.set(provider.plugin_id, provider)
+ providerById.set(`${provider.plugin_id}/${provider.name}`, provider)
+ }
+ })
+
+ return providerById
+}
+
+export function useAgentPromptToolIconResolver() {
+ const { theme } = useTheme()
+ const currentWorkspaceId = useSelector(s => s.currentWorkspace.id)
+ const { data: builtInTools } = useAllBuiltInTools()
+ const { data: customTools } = useAllCustomTools()
+ const { data: workflowTools } = useAllWorkflowTools()
+ const { data: mcpTools } = useAllMCPTools()
+
+ const providerById = useMemo(() => {
+ const allProviders = [
+ ...(Array.isArray(builtInTools) ? builtInTools : []),
+ ...(Array.isArray(customTools) ? customTools : []),
+ ...(Array.isArray(workflowTools) ? workflowTools : []),
+ ...(Array.isArray(mcpTools) ? mcpTools : []),
+ ]
+
+ return createProviderMap(allProviders)
+ }, [builtInTools, customTools, mcpTools, workflowTools])
+
+ return useMemo(() => ({
+ getProviderIcon: (provider: ToolWithProvider) => {
+ const rawIcon = theme === Theme.dark && provider.icon_dark ? provider.icon_dark : provider.icon
+ return normalizeProviderIcon(rawIcon, currentWorkspaceId)
+ },
+ getProviderIcons: (provider: ToolWithProvider) => ({
+ icon: normalizeProviderIcon(provider.icon, currentWorkspaceId),
+ iconDark: normalizeProviderIcon(provider.icon_dark, currentWorkspaceId),
+ }),
+ getConfiguredToolIcon: (tool: ProviderTool) => {
+ const provider = getProviderByTool(providerById, tool)
+ const rawIcon = theme === Theme.dark && (tool.iconDark ?? provider?.icon_dark)
+ ? tool.iconDark ?? provider?.icon_dark
+ : tool.icon ?? provider?.icon
+
+ return normalizeProviderIcon(rawIcon, currentWorkspaceId)
+ },
+ }), [currentWorkspaceId, providerById, theme])
+}
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/index.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/index.tsx
index 8ca5b8f5efb..332f2c9300f 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
@@ -3,7 +3,7 @@
import type { KeyboardEvent, MouseEvent, PointerEvent as ReactPointerEvent } from 'react'
import type { SlashMenuCategory, SlashMenuView } from './slash'
import type { RosterReferenceToken } from '@/app/components/base/prompt-editor/plugins/roster-reference-block/utils'
-import type { AgentTool } from '@/features/agent-v2/agent-composer/form-state'
+import type { AgentProviderTool, AgentTool } from '@/features/agent-v2/agent-composer/form-state'
import { cn } from '@langgenius/dify-ui/cn'
import { Kbd } from '@langgenius/dify-ui/kbd'
import { toast } from '@langgenius/dify-ui/toast'
@@ -19,11 +19,12 @@ import { BlockEnum } from '@/app/components/workflow/types'
import { agentComposerKnowledgeRetrievalsAtom } from '@/features/agent-v2/agent-composer/store-modules/knowledge'
import { agentComposerPromptAtom } from '@/features/agent-v2/agent-composer/store-modules/prompt'
import { agentComposerToolsAtom } from '@/features/agent-v2/agent-composer/store-modules/tools'
-import useTheme from '@/hooks/use-theme'
-import { Theme } from '@/types/app'
+import { ENABLE_AGENT_CLI_TOOLS } from '@/features/agent-v2/agent-detail/configure/feature-flags'
import { useAgentOrchestrateAddActions } from '../add-actions-context'
+import { AgentConfigureTipContent } from '../common/tip-content'
import { useAgentDriveFiles, useAgentDriveSkills } from '../drive-context'
import { useAgentOrchestrateReadOnly } from '../read-only-context'
+import { useAgentPromptToolIconResolver } from './hooks'
import { replaceTrailingSlashWithToken } from './options'
import { AgentPromptSlashMenu } from './slash'
@@ -71,12 +72,12 @@ function getProviderToolFromToken(token: RosterReferenceToken, tools: AgentTool[
function AgentPromptRosterReferenceIcon({
token,
tools,
+ getConfiguredToolIcon,
}: {
token: RosterReferenceToken
tools: AgentTool[]
+ getConfiguredToolIcon: (tool: AgentProviderTool) => AgentProviderTool['icon']
}) {
- const { theme } = useTheme()
-
if (token.kind === 'cli_tool') {
return (
<span
@@ -90,7 +91,7 @@ function AgentPromptRosterReferenceIcon({
if (!providerTool || providerTool.kind !== 'provider')
return null
- const icon = theme === Theme.dark && providerTool.iconDark ? providerTool.iconDark : providerTool.icon
+ const icon = getConfiguredToolIcon(providerTool)
if (icon) {
return (
@@ -153,6 +154,7 @@ export function AgentPromptEditor() {
const { skills } = useAgentDriveSkills()
const { files } = useAgentDriveFiles()
const [tools, setTools] = useAtom(agentComposerToolsAtom)
+ const { getConfiguredToolIcon } = useAgentPromptToolIconResolver()
const retrievals = useAtomValue(agentComposerKnowledgeRetrievalsAtom)
const addActions = useAgentOrchestrateAddActions()
const isHydrated = useIsHydrated()
@@ -261,11 +263,20 @@ export function AgentPromptEditor() {
}
const renderRosterReferenceIcon = useCallback((token: RosterReferenceToken) => {
+ if (!ENABLE_AGENT_CLI_TOOLS && token.kind === 'cli_tool')
+ return null
+
if (token.kind !== 'tool' && token.kind !== 'tool-all' && token.kind !== 'cli_tool')
return null
- return <AgentPromptRosterReferenceIcon token={token} tools={tools} />
- }, [tools])
+ return (
+ <AgentPromptRosterReferenceIcon
+ token={token}
+ tools={tools}
+ getConfiguredToolIcon={getConfiguredToolIcon}
+ />
+ )
+ }, [getConfiguredToolIcon, tools])
useEffect(() => {
if (!isSlashMenuOpen)
@@ -320,7 +331,7 @@ export function AgentPromptEditor() {
{t('agentDetail.configure.prompt.label')}
</h3>
<Infotip aria-label={promptTip} popupClassName="max-w-64">
- {promptTip}
+ <AgentConfigureTipContent type="prompt" />
</Infotip>
</div>
<Tooltip>
@@ -407,7 +418,7 @@ export function AgentPromptEditor() {
files={files}
tools={tools}
onToolsChange={setTools}
- onAddCliTool={addActions.cli}
+ onAddCliTool={ENABLE_AGENT_CLI_TOOLS ? addActions.cli : undefined}
onAddFile={addActions.files}
onAddKnowledge={addActions.knowledge}
onAddSkill={addActions.skills}
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/slash.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/slash.tsx
index 9aee10696ef..fe06ac81533 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
@@ -14,8 +14,11 @@ import { useTranslation } from 'react-i18next'
import { getMarketplaceCategoryUrl } from '@/app/components/plugins/marketplace/utils'
import { PluginCategoryEnum } from '@/app/components/plugins/types'
import { CollectionType } from '@/app/components/tools/types'
+import BlockIcon from '@/app/components/workflow/block-icon'
import { ToolTypeEnum as ToolTabEnum } from '@/app/components/workflow/block-selector/types'
+import { BlockEnum } from '@/app/components/workflow/types'
import { useGetLanguage } from '@/context/i18n'
+import { ENABLE_AGENT_CLI_TOOLS } from '@/features/agent-v2/agent-detail/configure/feature-flags'
import {
useAllBuiltInTools,
useAllCustomTools,
@@ -23,6 +26,7 @@ import {
useAllWorkflowTools,
} from '@/service/use-tools'
import { addProviderTools } from '../tools/hooks'
+import { useAgentPromptToolIconResolver } from './hooks'
export type SlashMenuView = 'main' | 'skills' | 'files' | 'tools' | 'knowledge'
@@ -170,14 +174,16 @@ export function AgentPromptSlashMenu({
{view === 'tools'
? (
<AgentPromptToolFooter
- onAddCliTool={() => {
- onAddCliTool?.({
- onAdded: (item) => {
- if (isCliToolItem(item))
- onSelect(createReferenceToken('cli_tool', item.id, item.name))
- },
- })
- }}
+ onAddCliTool={ENABLE_AGENT_CLI_TOOLS
+ ? () => {
+ onAddCliTool?.({
+ onAdded: (item) => {
+ if (isCliToolItem(item))
+ onSelect(createReferenceToken('cli_tool', item.id, item.name))
+ },
+ })
+ }
+ : undefined}
/>
)
: (
@@ -275,13 +281,19 @@ function AgentPromptToolRows({
}) {
const { t } = useTranslation('agentV2')
const language = useGetLanguage()
+ const {
+ getProviderIcon,
+ getProviderIcons,
+ } = useAgentPromptToolIconResolver()
const [activeTab, setActiveTab] = useState<ToolPromptTab>('all')
const [expandedProviderIds, setExpandedProviderIds] = useState<Set<string>>(() => new Set())
const { data: builtInTools = [] } = useAllBuiltInTools()
const { data: customTools = [] } = useAllCustomTools()
const { data: workflowTools = [] } = useAllWorkflowTools()
const { data: mcpTools = [] } = useAllMCPTools()
- const configuredCliTools = configuredTools.filter(tool => tool.kind === 'cli')
+ const configuredCliTools = ENABLE_AGENT_CLI_TOOLS
+ ? configuredTools.filter(tool => tool.kind === 'cli')
+ : []
const availableProviders = useMemo(() => {
if (activeTab === 'all')
return [...builtInTools, ...workflowTools, ...customTools, ...mcpTools]
@@ -304,7 +316,9 @@ function AgentPromptToolRows({
{ key: ToolTabEnum.Workflow, label: t('agentDetail.configure.tools.toolTabs.workflow') },
{ key: ToolTabEnum.Custom, label: t('agentDetail.configure.tools.toolTabs.custom') },
{ key: ToolTabEnum.MCP, label: t('agentDetail.configure.tools.toolTabs.mcp') },
- { key: 'cli' as const, label: t('agentDetail.configure.tools.toolTabs.cli') },
+ ...(ENABLE_AGENT_CLI_TOOLS
+ ? [{ key: 'cli' as const, label: t('agentDetail.configure.tools.toolTabs.cli') }]
+ : []),
]
const selectTools = (tools: AgentProviderToolDefaultValue[]) => {
@@ -324,12 +338,14 @@ function AgentPromptToolRows({
}
const handleSelectProvider = (provider: ToolWithProvider) => {
- selectTools(provider.tools.map(tool => toToolDefaultValue(provider, tool, language)))
+ const { icon, iconDark } = getProviderIcons(provider)
+ selectTools(provider.tools.map(tool => toToolDefaultValue(provider, tool, language, icon, iconDark)))
onSelect(createReferenceToken('tool', `${provider.id}/*`, getProviderLabel(provider, language)))
}
const handleSelectTool = (provider: ToolWithProvider, tool: Tool) => {
- const selectedTool = toToolDefaultValue(provider, tool, language)
+ const { icon, iconDark } = getProviderIcons(provider)
+ const selectedTool = toToolDefaultValue(provider, tool, language, icon, iconDark)
selectTools([selectedTool])
onSelect(createReferenceToken('tool', `${provider.id}/${tool.name}`, selectedTool.tool_label))
}
@@ -368,16 +384,15 @@ function AgentPromptToolRows({
selectedTools={selectedTools}
language={language}
isExpanded={expandedProviderIds.has(provider.id)}
+ getProviderIcon={getProviderIcon}
onClick={() => handleSelectProvider(provider)}
onToggle={() => toggleProvider(provider.id)}
/>
{expandedProviderIds.has(provider.id) && provider.tools.map(tool => (
<AgentPromptProviderToolActionRow
key={tool.name}
- provider={provider}
tool={tool}
language={language}
- selectedTools={selectedTools}
onClick={() => handleSelectTool(provider, tool)}
/>
))}
@@ -418,6 +433,8 @@ function toToolDefaultValue(
provider: ToolWithProvider,
tool: Tool,
language: string,
+ providerIcon: ToolWithProvider['icon'] | undefined,
+ providerIconDark: ToolWithProvider['icon'] | undefined,
): AgentProviderToolDefaultValue {
const params: Record<string, string> = {}
tool.parameters?.forEach((parameter) => {
@@ -435,8 +452,8 @@ function toToolDefaultValue(
provider_show_name: providerLabel,
plugin_id: provider.plugin_id,
plugin_unique_identifier: provider.plugin_unique_identifier,
- provider_icon: provider.icon,
- provider_icon_dark: provider.icon_dark,
+ provider_icon: providerIcon,
+ provider_icon_dark: providerIconDark,
tool_name: tool.name,
tool_label: label,
tool_description: description,
@@ -481,6 +498,7 @@ function AgentPromptProviderToolRow({
selectedTools,
language,
isExpanded,
+ getProviderIcon,
onClick,
onToggle,
}: {
@@ -489,6 +507,7 @@ function AgentPromptProviderToolRow({
selectedTools: ToolValue[]
language: string
isExpanded: boolean
+ getProviderIcon: (provider: ToolWithProvider) => ToolWithProvider['icon'] | undefined
onClick: () => void
onToggle: () => void
}) {
@@ -496,27 +515,27 @@ function AgentPromptProviderToolRow({
const providerLabel = getProviderLabel(provider, language)
return (
- <div className="flex h-7 w-full items-center gap-px overflow-hidden rounded-md">
+ <div className="group flex h-7 w-full items-center gap-px overflow-hidden rounded-md">
<button
type="button"
- className="flex min-w-0 flex-1 items-center gap-1.5 rounded-l-md py-1 pr-1 pl-2 text-left hover:bg-state-base-hover focus-visible:bg-state-base-hover focus-visible:outline-hidden"
+ className="flex min-w-0 flex-1 items-center gap-1.5 rounded-l-md py-1 pr-1 pl-2 text-left group-hover:bg-state-base-hover focus-visible:bg-state-base-hover focus-visible:outline-hidden"
onClick={onClick}
>
- <span className="flex size-5 shrink-0 items-center justify-center overflow-hidden rounded-md border-[0.5px] border-effects-icon-border bg-background-default-dodge">
- <AgentPromptProviderIcon provider={provider} />
+ <AgentPromptProviderIcon provider={provider} getProviderIcon={getProviderIcon} />
+ <span className="flex min-w-0 flex-1 items-center">
+ <span className="min-w-0 truncate system-sm-regular text-text-secondary">{providerLabel}</span>
+ {selectedToolsCount > 0 && selectedToolsCount < provider.tools.length && (
+ <span className="ml-1.5 shrink-0 rounded-[5px] border border-divider-deep bg-components-badge-bg-dimm px-1 py-0.5 system-2xs-medium-uppercase text-text-tertiary">
+ {selectedToolsCount}
+ </span>
+ )}
</span>
- <span className="min-w-0 flex-1 truncate system-sm-regular text-text-secondary">{providerLabel}</span>
- {selectedToolsCount > 0 && selectedToolsCount < provider.tools.length && (
- <span className="shrink-0 rounded-[5px] border border-divider-deep bg-components-badge-bg-dimm px-1 py-0.5 system-2xs-medium-uppercase text-text-tertiary">
- {selectedToolsCount}
- </span>
- )}
<span className="shrink-0 system-xs-regular text-text-quaternary">{typeLabel}</span>
</button>
<button
type="button"
aria-label={providerLabel}
- className="flex size-7 shrink-0 items-center justify-center rounded-r-md text-text-tertiary hover:bg-state-base-hover-subtle focus-visible:bg-state-base-hover-subtle focus-visible:outline-hidden"
+ className="flex size-7 shrink-0 items-center justify-center rounded-r-md text-text-tertiary group-hover:bg-state-base-hover hover:bg-state-base-hover focus-visible:bg-state-base-hover focus-visible:outline-hidden"
onClick={onToggle}
>
<span aria-hidden className={`${isExpanded ? 'i-ri-arrow-down-s-line' : 'i-ri-arrow-right-s-line'} size-4`} />
@@ -527,23 +546,20 @@ function AgentPromptProviderToolRow({
function AgentPromptProviderIcon({
provider,
+ getProviderIcon,
}: {
provider: ToolWithProvider
+ getProviderIcon: (provider: ToolWithProvider) => ToolWithProvider['icon'] | undefined
}) {
- if (typeof provider.icon === 'string') {
- return provider.icon.startsWith('/') || provider.icon.startsWith('http')
- ? <img src={provider.icon} alt="" className="size-full object-cover" />
- : <span aria-hidden className="i-custom-public-other-default-tool-icon size-3.5 text-text-tertiary" />
- }
+ const icon = getProviderIcon(provider)
return (
- <span
- aria-hidden
- className="flex size-full items-center justify-center text-xs"
- style={{ backgroundColor: provider.icon?.background }}
- >
- {provider.icon?.content}
- </span>
+ <BlockIcon
+ className="shrink-0"
+ type={BlockEnum.Tool}
+ size="sm"
+ toolIcon={icon}
+ />
)
}
@@ -565,33 +581,29 @@ function AgentPromptToolFooter({
<span aria-hidden className="i-ri-store-2-line size-4 shrink-0 text-text-secondary" />
<span className="system-sm-regular text-text-secondary">{t('findMoreInMarketplace', { ns: 'plugin' })}</span>
</a>
- <button
- type="button"
- className="flex h-7 w-full items-center gap-1.5 rounded-md px-2 text-left hover:bg-state-base-hover focus-visible:bg-state-base-hover focus-visible:outline-hidden"
- onClick={onAddCliTool}
- >
- <span aria-hidden className="i-ri-add-line size-4 shrink-0 text-text-secondary" />
- <span className="system-sm-regular text-text-secondary">{t('agentDetail.configure.tools.cliDialog.title', { ns: 'agentV2' })}</span>
- </button>
+ {onAddCliTool && (
+ <button
+ type="button"
+ className="flex h-7 w-full items-center gap-1.5 rounded-md px-2 text-left hover:bg-state-base-hover focus-visible:bg-state-base-hover focus-visible:outline-hidden"
+ onClick={onAddCliTool}
+ >
+ <span aria-hidden className="i-ri-add-line size-4 shrink-0 text-text-secondary" />
+ <span className="system-sm-regular text-text-secondary">{t('agentDetail.configure.tools.cliDialog.title', { ns: 'agentV2' })}</span>
+ </button>
+ )}
</div>
)
}
function AgentPromptProviderToolActionRow({
- provider,
tool,
language,
- selectedTools,
onClick,
}: {
- provider: ToolWithProvider
tool: Tool
language: string
- selectedTools: ToolValue[]
onClick: () => void
}) {
- const selected = isToolSelected(selectedTools, provider, tool)
-
return (
<button
type="button"
@@ -603,7 +615,6 @@ function AgentPromptProviderToolActionRow({
<span className="min-w-0 flex-1 truncate system-sm-regular text-text-secondary">
{getLocalizedText(tool.label, language) || tool.name}
</span>
- {selected && <span aria-hidden className="i-ri-check-line size-3.5 shrink-0 text-text-tertiary" />}
</span>
</button>
)
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.tsx
index 44a4e9fdf8f..34c8cc1f6c4 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,8 +1,7 @@
'use client'
-import type { AgentConfigSnapshotDetailResponse, AgentConfigSnapshotSummaryResponse, AgentReferencingWorkflowResponse, AgentReferencingWorkflowsResponse, AgentSoulConfig } from '@dify/contracts/api/console/agent/types.gen'
+import type { AgentConfigSnapshotSummaryResponse, AgentReferencingWorkflowResponse, AgentReferencingWorkflowsResponse } 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 { CollapsiblePanel, CollapsibleRoot } from '@langgenius/dify-ui/collapsible'
import { Kbd, KbdGroup } from '@langgenius/dify-ui/kbd'
@@ -10,9 +9,12 @@ import { StatusDot } from '@langgenius/dify-ui/status-dot'
import { toast } from '@langgenius/dify-ui/toast'
import { formatForDisplay, useHotkey } from '@tanstack/react-hotkeys'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
+import { useAtomValue } from 'jotai'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
-import { useConfigPublishPayload, useHasAgentComposerUnpublishedChanges } from '@/features/agent-v2/agent-composer/store'
+import { useKnowledgeValidationMessage, validateKnowledgeRetrievals } from '@/features/agent-v2/agent-composer/knowledge-validation'
+import { hasAgentComposerUnpublishedChangesAtom } from '@/features/agent-v2/agent-composer/store'
+import { agentComposerKnowledgeRetrievalsAtom } from '@/features/agent-v2/agent-composer/store-modules/knowledge'
import { useFormatTimeFromNow } from '@/hooks/use-format-time-from-now'
import useTimestamp from '@/hooks/use-timestamp'
import { consoleQuery } from '@/service/client'
@@ -20,11 +22,6 @@ import { AgentPublishImpactDetails } from './publish-impact-details'
const PUBLISH_AGENT_HOTKEY = 'Mod+Shift+P' satisfies RegisterableHotkey
-export type AgentConfigurePublishPayload = {
- agent_id: string
- config_snapshot: AgentSoulConfig
-}
-
type AgentConfigurePublishState = 'draft' | 'publishing' | 'published' | 'unpublished'
type PublishBarMode = { status: 'compact' }
@@ -34,16 +31,11 @@ type AgentConfigurePublishBarProps = {
agentId: string
activeConfigIsPublished?: boolean
activeConfigSnapshot?: AgentConfigSnapshotSummaryResponse | null
- agentSoulConfig?: AgentConfigSnapshotDetailResponse['config_snapshot']
agentName?: string | null
- currentModel?: {
- provider: string
- model: string
- }
draftSavedAt?: number
isPublishing?: boolean
selectedVersionSnapshot?: AgentConfigSnapshotSummaryResponse | null
- onPublish?: (payload: AgentConfigurePublishPayload) => void | Promise<void>
+ onPublish?: () => void | Promise<void>
onExitVersions?: () => void
onOpenVersions: () => void
}
@@ -62,10 +54,16 @@ function getPublishState({
if (isPublishing)
return 'publishing'
+ if (activeConfigIsPublished)
+ return 'published'
+
+ if (isDirty)
+ return 'unpublished'
+
if (!activeConfigSnapshot)
return 'draft'
- if (!activeConfigIsPublished || isDirty)
+ if (!activeConfigIsPublished)
return 'unpublished'
return 'published'
@@ -85,9 +83,7 @@ export function AgentConfigurePublishBar({
agentId,
activeConfigIsPublished,
activeConfigSnapshot,
- agentSoulConfig,
agentName,
- currentModel,
draftSavedAt,
isPublishing = false,
selectedVersionSnapshot,
@@ -100,12 +96,10 @@ export function AgentConfigurePublishBar({
const { formatTimeFromNow } = useFormatTimeFromNow()
const queryClient = useQueryClient()
const [publishBarMode, setPublishBarMode] = useState<PublishBarMode>({ status: 'compact' })
- const hasUnpublishedChanges = useHasAgentComposerUnpublishedChanges()
- const publishPayload = useConfigPublishPayload({
- agentId,
- baseConfig: agentSoulConfig,
- currentModel,
- })
+ const hasUnpublishedChanges = useAtomValue(hasAgentComposerUnpublishedChangesAtom)
+ const knowledgeRetrievals = useAtomValue(agentComposerKnowledgeRetrievalsAtom)
+ const knowledgeValidation = validateKnowledgeRetrievals(knowledgeRetrievals)
+ const getValidationMessage = useKnowledgeValidationMessage()
const publishableState = getPublishState({
activeConfigIsPublished,
activeConfigSnapshot,
@@ -119,6 +113,7 @@ export function AgentConfigurePublishBar({
isPublishing,
})
const publishIsAvailable = !isPublishing && (publishableState === 'draft' || publishableState === 'unpublished')
+ const publishValidationMessage = getValidationMessage(knowledgeValidation.firstIssue?.code)
const workflowReferencesQueryOptions = consoleQuery.agent.byAgentId.referencingWorkflows.get.queryOptions({
input: {
params: {
@@ -131,7 +126,7 @@ export function AgentConfigurePublishBar({
enabled: publishIsAvailable && !selectedVersionSnapshot,
})
const restoreVersionMutation = useMutation(consoleQuery.agent.byAgentId.versions.byVersionId.restore.post.mutationOptions())
- const canPublish = publishIsAvailable
+ const canPublish = publishIsAvailable && knowledgeValidation.isValid
const handleRestoreVersion = (versionId: string) => {
if (restoreVersionMutation.isPending)
@@ -178,7 +173,7 @@ export function AgentConfigurePublishBar({
if (!canPublish)
return
- await onPublish?.(publishPayload)
+ await onPublish?.()
setPublishBarMode({ status: 'compact' })
}
@@ -275,57 +270,36 @@ export function AgentConfigurePublishBar({
const currentStateMeta = stateMeta[publishState]
const isConfirmingImpact = publishBarMode.status === 'confirmingImpact' && (canPublish || isPublishing)
const impactReferences = publishBarMode.status === 'confirmingImpact' ? publishBarMode.references : []
+ const effectiveMetaLabel = publishValidationMessage && publishIsAvailable
+ ? publishValidationMessage
+ : currentStateMeta.metaLabel
return (
- <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"
+ <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]"
>
- <div
- 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)]"
+ <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={effectiveMetaLabel}
+ showShortcut={currentStateMeta.showShortcut}
+ statusLabel={currentStateMeta.statusLabel}
+ canPublish={canPublish}
+ onCancelImpact={() => setPublishBarMode({ status: 'compact' })}
+ onOpenVersions={onOpenVersions}
+ onPublishRequest={handlePublishRequest}
/>
- <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>
+ </CollapsibleRoot>
)
}
@@ -423,45 +397,43 @@ function AgentVersionRestoreBar({
: 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 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>
- <Button
- type="button"
- variant="primary"
- disabled={!onRestoreVersion}
- loading={isRestoring}
- className="h-8 rounded-lg px-3"
- onClick={() => onRestoreVersion?.(version.id)}
- >
- {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>
+ {(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>
- </PublishBarBottomActions>
+ <Button
+ type="button"
+ variant="primary"
+ disabled={!onRestoreVersion}
+ loading={isRestoring}
+ className="h-8 rounded-lg px-3"
+ onClick={() => onRestoreVersion?.(version.id)}
+ >
+ {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>
)
}
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/__tests__/index.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/__tests__/index.spec.tsx
index 7b08b75080e..9cb27c1736e 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
@@ -2,10 +2,12 @@ import { toast } from '@langgenius/dify-ui/toast'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { useAtomValue } from 'jotai'
import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { formStateToAgentSoulConfig } from '@/features/agent-v2/agent-composer/conversions'
import { defaultAgentSoulConfigFormState } from '@/features/agent-v2/agent-composer/form-state'
import { AgentComposerProvider } from '@/features/agent-v2/agent-composer/provider'
-import { useAgentComposerConfigSnapshot } from '@/features/agent-v2/agent-composer/store'
+import { agentComposerDraftAtom } from '@/features/agent-v2/agent-composer/store'
import { AgentDriveApiContextProvider } from '../../drive-context'
import { AgentOrchestrateReadOnlyContext } from '../../read-only-context'
import { AgentSkills } from '../index'
@@ -126,6 +128,22 @@ vi.mock('@/service/client', () => ({
const agentSkillsDraft = {
...defaultAgentSoulConfigFormState,
+ skills: [
+ {
+ archiveKey: 'tender-analyzer/.DIFY-SKILL-FULL.zip',
+ description: 'Extracts tender requirements and scoring criteria.',
+ id: 'tender-analyzer/SKILL.md',
+ name: 'Tender Analyzer',
+ path: 'tender-analyzer',
+ skillMdKey: 'tender-analyzer/SKILL.md',
+ },
+ {
+ id: 'meeting-brief/SKILL.md',
+ name: 'Meeting Brief',
+ path: 'meeting-brief',
+ skillMdKey: 'meeting-brief/SKILL.md',
+ },
+ ],
} satisfies typeof defaultAgentSoulConfigFormState
function renderAgentSkills() {
@@ -191,7 +209,8 @@ function renderReadonlyAgentSkills() {
}
function ConfigSnapshotProbe() {
- const configSnapshot = useAgentComposerConfigSnapshot({})
+ const draft = useAtomValue(agentComposerDraftAtom)
+ const configSnapshot = formStateToAgentSoulConfig({ formState: draft })
return (
<pre data-testid="config-snapshot-probe">
@@ -490,19 +509,10 @@ describe('AgentSkills', () => {
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 () => {
+ it('should use workflow node drive routes for skill preview in inline workflow mode', async () => {
renderWorkflowAgentSkills()
- expect(mocks.driveSkillsQueryOptions).toHaveBeenCalledWith({
- input: {
- params: {
- app_id: 'app-1',
- },
- query: {
- node_id: 'node-1',
- },
- },
- })
+ expect(mocks.driveSkillsQueryOptions).not.toHaveBeenCalled()
fireEvent.click(screen.getByRole('button', {
name: 'Tender Analyzer',
@@ -677,6 +687,56 @@ describe('AgentSkills', () => {
expect(vi.mocked(toast.success)).toHaveBeenCalledWith('agentV2.agentDetail.configure.skills.upload.success')
})
+ it('should upload a dropped skill package through the drive-backed endpoint', 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'],
+ })
+
+ renderAgentSkills()
+
+ await user.click(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.skills.add' }))
+
+ const uploadArea = screen.getByRole('group', { name: 'agentV2.agentDetail.configure.skills.upload.title' })
+ const file = new File(['skill'], 'invoice-helper.skill', { type: 'application/zip' })
+ fireEvent.dragEnter(uploadArea, {
+ dataTransfer: {
+ files: [file],
+ types: ['Files'],
+ },
+ })
+ fireEvent.drop(uploadArea, {
+ dataTransfer: {
+ files: [file],
+ types: ['Files'],
+ },
+ })
+ await user.click(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.skills.upload.action' }))
+
+ await waitFor(() => {
+ expect(uploadSkill.mock.calls[0]?.[0]).toEqual({
+ body: {
+ file,
+ },
+ params: {
+ agent_id: 'agent-1',
+ },
+ })
+ })
+ })
+
it('should refresh the rendered skill list after delete succeeds', async () => {
const driveSkills = [
{
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/index.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/skills/index.tsx
index 0d4e49eda33..8461138cd30 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
@@ -3,14 +3,17 @@
import type { AgentOrchestrateAddActionOptions } from '../add-actions-context'
import type { AgentSkill } from '@/features/agent-v2/agent-composer/form-state'
import { useMutation } from '@tanstack/react-query'
+import { useAtomValue, useSetAtom } from 'jotai'
import { useCallback, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
+import { agentComposerSkillsAtom } 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 { AgentConfigureTipContent } from '../common/tip-content'
+import { useAgentDriveApiContext } from '../drive-context'
import { AgentSkillItem } from './item'
import { AgentSkillUploadDialog } from './upload-dialog'
@@ -21,7 +24,8 @@ export function AgentSkills() {
const [isUploadOpen, setIsUploadOpen] = useState(false)
const promptAddCallbackRef = useRef<AgentOrchestrateAddActionOptions['onAdded']>(undefined)
const apiContext = useAgentDriveApiContext()
- const { query: skillsQuery, skills } = useAgentDriveSkills()
+ const skills = useAtomValue(agentComposerSkillsAtom)
+ const setSkills = useSetAtom(agentComposerSkillsAtom)
const { mutate: deleteAgentSkill } = useMutation(consoleQuery.agent.byAgentId.skills.bySlug.delete.mutationOptions())
const { mutate: deleteAppSkill } = useMutation(consoleQuery.apps.byAppId.agent.skills.bySlug.delete.mutationOptions())
@@ -32,10 +36,13 @@ export function AgentSkills() {
useRegisterAgentOrchestrateAddAction('skills', handleOpenUpload)
const handleUploaded = useCallback((skill: AgentSkill) => {
- void skillsQuery.refetch()
+ setSkills(skills => [
+ ...skills.filter(item => item.id !== skill.id),
+ skill,
+ ])
promptAddCallbackRef.current?.(skill)
promptAddCallbackRef.current = undefined
- }, [skillsQuery])
+ }, [setSkills])
const handleUploadOpenChange = useCallback((open: boolean) => {
if (!open)
@@ -50,7 +57,7 @@ export function AgentSkills() {
return
const onSuccess = () => {
- void skillsQuery.refetch()
+ setSkills(skills => skills.filter(item => item.id !== skillId))
}
if (apiContext.workflow) {
deleteAppSkill({
@@ -71,7 +78,7 @@ export function AgentSkills() {
slug: skillSlug,
},
}, { onSuccess })
- }, [apiContext, deleteAgentSkill, deleteAppSkill, skills, skillsQuery])
+ }, [apiContext, deleteAgentSkill, deleteAppSkill, setSkills, skills])
return (
<>
@@ -79,7 +86,7 @@ export function AgentSkills() {
label={t('agentDetail.configure.skills.label')}
labelId="agent-configure-skills-label"
panelId={skillsListId}
- tip={skillsTip}
+ tip={<AgentConfigureTipContent type="skills" />}
tipAriaLabel={skillsTip}
rootClassName="border-b border-divider-subtle pt-4"
panelContentClassName="flex flex-col gap-1 pb-4"
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.tsx
index 94c66e4b951..82d328cd78d 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
@@ -2,6 +2,7 @@
import type { PostAgentByAgentIdSkillsUploadResponse } from '@dify/contracts/api/console/agent/types.gen'
import type { PostAppsByAppIdAgentSkillsUploadResponse } from '@dify/contracts/api/console/apps/types.gen'
+import type { ChangeEvent, DragEvent } from 'react'
import type { AgentDriveApiContext } from '../drive-context'
import type { AgentSkill } from '@/features/agent-v2/agent-composer/form-state'
import { Button } from '@langgenius/dify-ui/button'
@@ -47,6 +48,10 @@ function isSupportedSkillPackage(file: File) {
return skillPackageExtensions.some(extension => fileName.endsWith(extension))
}
+function hasDraggedFiles(event: DragEvent<HTMLDivElement>) {
+ return Array.from(event.dataTransfer.types).includes('Files')
+}
+
function AgentSkillPackageUploader({
file,
onChange,
@@ -56,6 +61,7 @@ function AgentSkillPackageUploader({
}) {
const { t } = useTranslation('agentV2')
const fileInputRef = useRef<HTMLInputElement>(null)
+ const dragDepthRef = useRef(0)
const [dragging, setDragging] = useState(false)
const setUploadFiles = (files: File[]) => {
@@ -68,22 +74,63 @@ function AgentSkillPackageUploader({
onChange(uploadFile)
}
- const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
+ const handleFileChange = (event: ChangeEvent<HTMLInputElement>) => {
const files = Array.from(event.target.files ?? [])
event.target.value = ''
setUploadFiles(files)
}
- const handleDrop = (event: React.DragEvent<HTMLDivElement>) => {
+ const handleDragEnter = (event: DragEvent<HTMLDivElement>) => {
+ if (!hasDraggedFiles(event))
+ return
+
+ event.preventDefault()
+ event.stopPropagation()
+ dragDepthRef.current += 1
+ setDragging(true)
+ }
+
+ const handleDragOver = (event: DragEvent<HTMLDivElement>) => {
+ if (!hasDraggedFiles(event))
+ return
+
+ event.preventDefault()
+ event.dataTransfer.dropEffect = 'copy'
+ }
+
+ const handleDragLeave = (event: DragEvent<HTMLDivElement>) => {
+ if (!hasDraggedFiles(event))
+ return
+
+ event.preventDefault()
+ event.stopPropagation()
+ dragDepthRef.current = Math.max(0, dragDepthRef.current - 1)
+ if (dragDepthRef.current === 0)
+ setDragging(false)
+ }
+
+ const handleDrop = (event: DragEvent<HTMLDivElement>) => {
+ if (!hasDraggedFiles(event))
+ return
+
event.preventDefault()
event.stopPropagation()
+ dragDepthRef.current = 0
setDragging(false)
setUploadFiles(Array.from(event.dataTransfer.files))
}
return (
- <div className="mt-6">
+ <div
+ className="mt-6"
+ role="group"
+ aria-label={t('agentDetail.configure.skills.upload.title')}
+ onDragEnter={handleDragEnter}
+ onDragOver={handleDragOver}
+ onDragLeave={handleDragLeave}
+ onDrop={handleDrop}
+ >
<input
ref={fileInputRef}
className="hidden"
@@ -97,13 +144,6 @@ function AgentSkillPackageUploader({
'relative flex h-16 items-center rounded-[10px] border border-dashed border-components-dropzone-border bg-components-dropzone-bg text-sm font-normal',
dragging && 'border-components-dropzone-border-accent bg-components-dropzone-bg-accent',
)}
- onDragEnter={(event) => {
- event.preventDefault()
- setDragging(true)
- }}
- onDragOver={event => event.preventDefault()}
- onDragLeave={() => setDragging(false)}
- onDrop={handleDrop}
>
<div className="flex w-full items-center justify-center space-x-2">
<span aria-hidden className="i-ri-upload-cloud-2-line size-6 text-text-tertiary" />
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.tsx
index 801033033cc..4b59db51a42 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
@@ -291,7 +291,7 @@ describe('AgentTools', () => {
expect(screen.queryByText('DuckDuckGo')).not.toBeInTheDocument()
expect(screen.queryByText('DuckDuckGo Search')).not.toBeInTheDocument()
- expect(screen.getByText('Lark CLI')).toBeInTheDocument()
+ expect(screen.queryByText('Lark CLI')).not.toBeInTheDocument()
})
it('should keep the add trigger mounted while the tool picker is open', async () => {
@@ -301,6 +301,9 @@ describe('AgentTools', () => {
await user.click(screen.getByRole('button', {
name: 'agentV2.agentDetail.configure.tools.add',
}))
+ expect(screen.queryByRole('button', {
+ name: /agentV2\.agentDetail\.configure\.tools\.addMenu\.cliTool\.label/,
+ })).not.toBeInTheDocument()
await user.click(screen.getByRole('button', {
name: /agentV2\.agentDetail\.configure\.tools\.addMenu\.tool\.label/,
}))
@@ -340,30 +343,16 @@ describe('AgentTools', () => {
})).not.toBeInTheDocument()
})
- it('should keep CLI tool row actions out of layout until hover or focus', () => {
+ it('should hide CLI tool rows while CLI tools are disabled', () => {
renderAgentTools()
- const editButton = screen.getByRole('button', {
+ expect(screen.queryByText('Lark CLI')).not.toBeInTheDocument()
+ expect(screen.queryByRole('button', {
name: 'agentV2.agentDetail.configure.tools.editAction:{"name":"Lark CLI"}',
- })
- const removeButton = screen.getByRole('button', {
+ })).not.toBeInTheDocument()
+ expect(screen.queryByRole('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',
- )
+ })).not.toBeInTheDocument()
})
})
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/index.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/index.tsx
index 7c8a12e8ca4..61dfcc1b9f9 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/index.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/index.tsx
@@ -12,6 +12,7 @@ import { useTranslation } from 'react-i18next'
import { ToolPickerContent } from '@/app/components/workflow/block-selector/tool-picker'
import { useGetLanguage } from '@/context/i18n'
import { useSetProviderToolCredential } from '@/features/agent-v2/agent-composer/store-modules/tools'
+import { ENABLE_AGENT_CLI_TOOLS } from '@/features/agent-v2/agent-detail/configure/feature-flags'
import {
useAllBuiltInTools,
useAllCustomTools,
@@ -22,6 +23,7 @@ import { useRegisterAgentOrchestrateAddAction } from '../add-actions-context'
import { ConfigureSectionAddButton } from '../common/add-button'
import { ConfigureSectionEmpty } from '../common/empty'
import { ConfigureSection } from '../common/section'
+import { AgentConfigureTipContent } from '../common/tip-content'
import { useAgentOrchestrateReadOnly } from '../read-only-context'
import { CliToolDialog } from './cli-tool/dialog'
import { AgentCliToolItem } from './cli-tool/item'
@@ -300,13 +302,15 @@ function AddToolMenu({
description={t('agentDetail.configure.tools.addMenu.tool.description')}
onClick={openToolPicker}
/>
- <AddToolMenuItem
- iconClassName="i-ri-terminal-box-line"
- label={t('agentDetail.configure.tools.addMenu.cliTool.label')}
- badge={t('agentDetail.configure.tools.addMenu.cliTool.badge')}
- description={t('agentDetail.configure.tools.addMenu.cliTool.description')}
- onClick={openCliToolDialog}
- />
+ {ENABLE_AGENT_CLI_TOOLS && (
+ <AddToolMenuItem
+ iconClassName="i-ri-terminal-box-line"
+ label={t('agentDetail.configure.tools.addMenu.cliTool.label')}
+ badge={t('agentDetail.configure.tools.addMenu.cliTool.badge')}
+ description={t('agentDetail.configure.tools.addMenu.cliTool.description')}
+ onClick={openCliToolDialog}
+ />
+ )}
</>
)
: (
@@ -349,14 +353,22 @@ export function AgentTools() {
handleCliDialogOpenChange,
closeProviderSettingsDialog,
} = useAgentToolsOperations()
- const displayTools = useDisplayTools(tools, providerById)
+ const visibleTools = useMemo(
+ () => ENABLE_AGENT_CLI_TOOLS ? tools : tools.filter(tool => tool.kind !== 'cli'),
+ [tools],
+ )
+ const displayTools = useDisplayTools(visibleTools, providerById)
+ const displayToolById = useMemo(
+ () => new Map(displayTools.map(tool => [tool.id, tool])),
+ [displayTools],
+ )
useEffect(() => {
if (readOnly)
return
let shouldSyncCredentials = false
- const nextTools = tools.map((tool, index) => {
- const displayTool = displayTools[index]
+ const nextTools = tools.map((tool) => {
+ const displayTool = displayToolById.get(tool.id)
if (tool.kind !== 'provider' || displayTool?.kind !== 'provider')
return tool
@@ -382,7 +394,7 @@ export function AgentTools() {
if (shouldSyncCredentials)
setTools(nextTools)
- }, [displayTools, readOnly, setTools, tools])
+ }, [displayToolById, readOnly, setTools, tools])
const promptAddCallbackRef = useRef<AgentOrchestrateAddActionOptions['onAdded']>(undefined)
const openCliToolDialogFromPrompt = useCallback((options?: AgentOrchestrateAddActionOptions) => {
promptAddCallbackRef.current = options?.onAdded
@@ -400,7 +412,10 @@ export function AgentTools() {
promptAddCallbackRef.current = undefined
handleCliDialogOpenChange(open)
}, [handleCliDialogOpenChange])
- useRegisterAgentOrchestrateAddAction('cli', openCliToolDialogFromPrompt)
+ useRegisterAgentOrchestrateAddAction(
+ 'cli',
+ ENABLE_AGENT_CLI_TOOLS ? openCliToolDialogFromPrompt : () => {},
+ )
const toolsTip = t('agentDetail.configure.tools.tip')
const toolsListId = 'agent-configure-tools-list'
const settingTargetCollection = settingTarget
@@ -414,7 +429,7 @@ export function AgentTools() {
label={t('agentDetail.configure.tools.label')}
labelId="agent-configure-tools-label"
panelId={toolsListId}
- tip={toolsTip}
+ tip={<AgentConfigureTipContent type="tools" />}
tipAriaLabel={toolsTip}
rootClassName="border-b border-divider-subtle pt-4"
panelContentClassName="flex flex-col gap-1 pb-4"
@@ -455,15 +470,17 @@ export function AgentTools() {
collection={settingTargetCollection}
onClose={closeProviderSettingsDialog}
/>
- <CliToolDialog
- key={`${editingCliTool?.id ?? 'add'}:${isCliToolDialogOpen ? 'open' : 'closed'}`}
- mode={editingCliTool ? 'edit' : 'add'}
- tool={editingCliTool}
- onDeleteCliTool={deleteCliTool}
- onSaveCliTool={handleCliDialogSaveWithPromptInsert}
- open={isCliToolDialogOpen}
- onOpenChange={handleCliDialogOpenChangeWithPromptInsert}
- />
+ {ENABLE_AGENT_CLI_TOOLS && (
+ <CliToolDialog
+ key={`${editingCliTool?.id ?? 'add'}:${isCliToolDialogOpen ? 'open' : 'closed'}`}
+ mode={editingCliTool ? 'edit' : 'add'}
+ tool={editingCliTool}
+ onDeleteCliTool={deleteCliTool}
+ onSaveCliTool={handleCliDialogSaveWithPromptInsert}
+ open={isCliToolDialogOpen}
+ onOpenChange={handleCliDialogOpenChangeWithPromptInsert}
+ />
+ )}
</>
)
}
diff --git a/web/features/agent-v2/agent-detail/configure/components/page-loading.tsx b/web/features/agent-v2/agent-detail/configure/components/page-loading.tsx
new file mode 100644
index 00000000000..61229fc4e12
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/configure/components/page-loading.tsx
@@ -0,0 +1,19 @@
+'use client'
+
+import Loading from '@/app/components/base/loading'
+
+export function AgentConfigurePageLoading({
+ label,
+}: {
+ label: string
+}) {
+ return (
+ <section
+ aria-label={label}
+ aria-busy
+ className="flex h-full min-w-0 flex-1 bg-background-body"
+ >
+ <Loading type="app" />
+ </section>
+ )
+}
diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/chat.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/chat.spec.tsx
index a2c46b70026..599654c5245 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
@@ -2,9 +2,11 @@ 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 { SupportUploadFileTypes } from '@/app/components/workflow/types'
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'
+import { TransferMethod } from '@/types/app'
+import { AgentChatRuntime } from '../chat-runtime'
const useChatMock = vi.hoisted(() => vi.fn())
const handleSendMock = vi.hoisted(() => vi.fn())
@@ -103,7 +105,7 @@ vi.mock('@/service/client', () => ({
},
}))
-function renderPreviewChat(props?: Partial<ComponentProps<typeof AgentPreviewChat>>) {
+function renderPreviewChat(props?: Partial<ComponentProps<typeof AgentChatRuntime>>) {
const store = createStore()
const queryClient = new QueryClient({
defaultOptions: {
@@ -121,9 +123,11 @@ function renderPreviewChat(props?: Partial<ComponentProps<typeof AgentPreviewCha
return render(
<QueryClientProvider client={queryClient}>
<JotaiProvider store={store}>
- <AgentPreviewChat
+ <AgentChatRuntime
agentId="agent-1"
clearChatList={false}
+ inputPlaceholder="Message agent"
+ renderEmptyState={() => null}
onClearChatListChange={vi.fn()}
{...props}
/>
@@ -165,7 +169,7 @@ describe('AgentPreviewChat', () => {
})
renderPreviewChat({
- debugConversationId: 'debug-conversation-1',
+ conversationId: 'debug-conversation-1',
})
await waitFor(() => expect(useChatMock).toHaveBeenCalled())
@@ -265,4 +269,60 @@ describe('AgentPreviewChat', () => {
await waitFor(() => expect(saveDraftBeforeRun).toHaveBeenCalledTimes(1))
expect(handleSendMock).not.toHaveBeenCalled()
})
+
+ it('should send build chat with the debug build draft type', async () => {
+ renderPreviewChat({
+ draftType: 'debug_build',
+ })
+
+ fireEvent.click(screen.getByRole('button', { name: 'send' }))
+
+ await waitFor(() => expect(handleSendMock).toHaveBeenCalledTimes(1))
+ expect(handleSendMock).toHaveBeenCalledWith(
+ 'agent/agent-1/chat-messages',
+ expect.objectContaining({
+ draft_type: 'debug_build',
+ }),
+ expect.any(Object),
+ )
+ })
+
+ it('should keep preview file upload disabled by default', async () => {
+ renderPreviewChat()
+
+ await waitFor(() => expect(useChatMock).toHaveBeenCalled())
+
+ const config = useChatMock.mock.calls.at(-1)?.[0]
+ expect(config.file_upload).toEqual(expect.objectContaining({
+ enabled: false,
+ allowed_file_upload_methods: [TransferMethod.local_file, TransferMethod.remote_url],
+ }))
+ })
+
+ it('should enable build chat file upload when chat features file upload is enabled', async () => {
+ renderPreviewChat({
+ agentSoulConfig: {
+ app_features: {
+ file_upload: {
+ enabled: true,
+ },
+ },
+ },
+ })
+
+ await waitFor(() => expect(useChatMock).toHaveBeenCalled())
+
+ const config = useChatMock.mock.calls.at(-1)?.[0]
+ expect(config.file_upload).toEqual(expect.objectContaining({
+ enabled: true,
+ allowed_file_types: [SupportUploadFileTypes.image],
+ allowed_file_upload_methods: [TransferMethod.local_file, TransferMethod.remote_url],
+ number_limits: 3,
+ }))
+ expect(config.file_upload.image).toEqual(expect.objectContaining({
+ enabled: true,
+ transfer_methods: [TransferMethod.local_file, TransferMethod.remote_url],
+ number_limits: 3,
+ }))
+ })
})
diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/header.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/header.spec.tsx
new file mode 100644
index 00000000000..7f0465f9b01
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/configure/components/preview/__tests__/header.spec.tsx
@@ -0,0 +1,83 @@
+import { render, screen, within } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { AgentPreviewHeader } from '../header'
+
+function renderHeader({
+ mode = 'preview',
+ previewEnabled = true,
+ onModeChange = vi.fn(),
+ onToggleChatFeatures = vi.fn(),
+ onOpenWorkingDirectory = vi.fn(),
+ onRefresh = vi.fn(),
+}: {
+ mode?: 'build' | 'preview'
+ previewEnabled?: boolean
+ onModeChange?: (mode: 'build' | 'preview') => void
+ onToggleChatFeatures?: () => void
+ onOpenWorkingDirectory?: () => void
+ onRefresh?: () => void
+} = {}) {
+ render(
+ <AgentPreviewHeader
+ mode={mode}
+ previewEnabled={previewEnabled}
+ isChatFeaturesOpen={false}
+ onModeChange={onModeChange}
+ onToggleChatFeatures={onToggleChatFeatures}
+ onOpenWorkingDirectory={onOpenWorkingDirectory}
+ onRefresh={onRefresh}
+ />,
+ )
+}
+
+describe('AgentPreviewHeader', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('should emit refresh from the restart button', async () => {
+ const user = userEvent.setup()
+ const onRefresh = vi.fn()
+ renderHeader({ mode: 'build', onRefresh })
+
+ await user.click(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.preview.restart' }))
+
+ expect(onRefresh).toHaveBeenCalledTimes(1)
+ })
+
+ it('should show chat features in build mode', async () => {
+ const user = userEvent.setup()
+ const onToggleChatFeatures = vi.fn()
+ renderHeader({ mode: 'build', onToggleChatFeatures })
+
+ await user.click(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.preview.chatFeatures' }))
+
+ expect(onToggleChatFeatures).toHaveBeenCalledTimes(1)
+ })
+
+ it('should open the working directory from the build header', async () => {
+ const user = userEvent.setup()
+ const onOpenWorkingDirectory = vi.fn()
+ renderHeader({ mode: 'build', onOpenWorkingDirectory })
+
+ await user.click(screen.getByRole('button', { name: 'agentV2.agentDetail.configure.workingDirectory.open' }))
+
+ expect(onOpenWorkingDirectory).toHaveBeenCalledTimes(1)
+ })
+
+ it('should disable preview mode when preview is unavailable', async () => {
+ const user = userEvent.setup()
+ const onModeChange = vi.fn()
+ renderHeader({
+ mode: 'build',
+ previewEnabled: false,
+ onModeChange,
+ })
+
+ const modeControl = screen.getByRole('group', { name: 'agentV2.agentDetail.configure.rightPanel.modeLabel' })
+
+ await user.click(within(modeControl).getByRole('button', { name: /agentV2\.agentDetail\.configure\.rightPanel\.preview/ }))
+
+ expect(onModeChange).not.toHaveBeenCalled()
+ })
+})
diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/build-background.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/build-background.tsx
new file mode 100644
index 00000000000..bb57bff650e
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/configure/components/preview/build-background.tsx
@@ -0,0 +1,71 @@
+import { cn } from '@langgenius/dify-ui/cn'
+
+const buildPanelGridColumnCount = 384
+const buildPanelGridRowCount = 32
+
+function getBuildPanelGridCellOpacity(row: number, column: number) {
+ const seed = Math.sin((row + 1) * 12.9898 + (column + 1) * 78.233) * 43758.5453
+ const noise = seed - Math.floor(seed)
+ const verticalProgress = row / (buildPanelGridRowCount - 1)
+ const densityThreshold = 0.26 + verticalProgress * 0.72
+ const horizontalWeight = Math.min(1, column / 160)
+ const verticalWeight = (1 - verticalProgress) ** 1.7
+
+ if (noise < densityThreshold)
+ return 0
+
+ return Number(Math.min(0.272, (0.032 + noise * 0.058 + horizontalWeight * 0.09) * verticalWeight).toFixed(3))
+}
+
+const buildPanelGridCells = Array.from(
+ { length: buildPanelGridColumnCount * buildPanelGridRowCount },
+ (_, index) => {
+ const row = Math.floor(index / buildPanelGridColumnCount)
+ const column = index % buildPanelGridColumnCount
+ const opacity = getBuildPanelGridCellOpacity(row, column)
+
+ return {
+ id: `build-panel-grid-cell-${row}-${column}`,
+ column: column + 1,
+ opacity,
+ row: row + 1,
+ }
+ },
+).filter(cell => cell.opacity > 0)
+
+function AgentBuildPanelGrid({
+ className,
+}: {
+ className?: string
+}) {
+ return (
+ <div className={cn('grid grid-cols-[repeat(384,4px)] grid-rows-[repeat(32,4px)] gap-0.5 opacity-70', className)}>
+ {buildPanelGridCells.map(cell => (
+ <span
+ key={cell.id}
+ className="rounded-[1px] bg-[#98A2B2]"
+ style={{ gridColumn: `${cell.column}`, gridRow: `${cell.row}`, opacity: cell.opacity }}
+ />
+ ))}
+ </div>
+ )
+}
+
+export function AgentBuildPanelBackground({
+ visible,
+}: {
+ visible: boolean
+}) {
+ return (
+ <div
+ aria-hidden
+ className={cn(
+ 'pointer-events-none absolute inset-0 z-0 overflow-hidden rounded-[inherit] opacity-0 transition-opacity duration-150 motion-reduce:transition-none',
+ visible && 'opacity-100',
+ )}
+ >
+ <AgentBuildPanelGrid className="absolute top-0 left-0" />
+ <AgentBuildPanelGrid className="absolute bottom-0 left-0 origin-center scale-y-[-1]" />
+ </div>
+ )
+}
diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/build-chat.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/build-chat.tsx
new file mode 100644
index 00000000000..dc99fcb5a58
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/configure/components/preview/build-chat.tsx
@@ -0,0 +1,70 @@
+'use client'
+
+import type { AgentChatRuntimeEmptyStateProps, AgentChatRuntimeProps } from './chat-runtime'
+import { useTranslation } from 'react-i18next'
+import { AgentChatRuntime } from './chat-runtime'
+
+const buildIconGridCellOpacities = [
+ '0 0 0.093 0.166 0 0 0.155 0',
+ '0 0.159 0.145 0.159 0.135 0.179 0.128 0.105',
+ '0.091 0 0.161 0.187 0.102 0 0.111 0',
+ '0.148 0.159 0 0 0.195 0.158 0.342 0.128',
+ '0.169 0.132 0 0.115 0.112 0.319 0.218 0.199',
+ '0.241 0.206 0.124 0.181 0.212 0.211 0.315 0.127',
+ '0.133 0.21 0.166 0.476 0.167 0.22 0.136 0.246',
+ '0 0.132 0.151 0.146 0.276 0.256 0.269 0',
+].flatMap(row => row.split(' ').map(Number))
+
+const buildIconGridCells = buildIconGridCellOpacities.map((opacity, index) => ({
+ id: `build-icon-cell-${Math.floor(index / 8)}-${index % 8}`,
+ opacity,
+}))
+
+type AgentBuildChatProps = Omit<AgentChatRuntimeProps, 'inputPlaceholder' | 'renderEmptyState' | 'sendButtonLabel'>
+
+function AgentBuildChatEmptyState({
+ inputNode,
+}: AgentChatRuntimeEmptyStateProps) {
+ const { t } = useTranslation('agentV2')
+
+ return (
+ <div className="flex h-full items-center justify-center">
+ <div className="flex w-full max-w-150 flex-col items-start p-3 text-left">
+ <div className="dify-blue-glass-surface relative flex h-[50px] w-12 items-center justify-center rounded-xl p-2">
+ <div className="absolute inset-x-px inset-y-0.5 grid grid-cols-[repeat(8,4px)] grid-rows-[repeat(8,4px)] gap-0.5 opacity-25">
+ {buildIconGridCells.map(cell => (
+ <span
+ key={cell.id}
+ className={cell.opacity > 0 ? 'rounded-[1px] bg-[#98A2B2]' : 'invisible'}
+ style={{ opacity: cell.opacity }}
+ />
+ ))}
+ </div>
+ <span aria-hidden className="absolute i-ri-hammer-line size-5 text-saas-dify-blue-inverted" />
+ </div>
+ <div className="mt-3 max-w-full truncate system-md-medium text-text-secondary">
+ {t('agentDetail.configure.build.empty.title')}
+ </div>
+ <p className="mt-1 max-w-full body-md-regular text-text-tertiary">
+ {t('agentDetail.configure.build.empty.description')}
+ </p>
+ {inputNode}
+ </div>
+ </div>
+ )
+}
+
+export function AgentBuildChat(props: AgentBuildChatProps) {
+ const { t } = useTranslation('agentV2')
+
+ return (
+ <AgentChatRuntime
+ {...props}
+ inputPlaceholder={t('agentDetail.configure.build.inputPlaceholder')}
+ sendButtonLabel={t('agentDetail.configure.build.startBuild')}
+ renderEmptyState={(emptyStateProps: AgentChatRuntimeEmptyStateProps) => (
+ <AgentBuildChatEmptyState {...emptyStateProps} />
+ )}
+ />
+ )
+}
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-runtime.tsx
similarity index 74%
rename from web/features/agent-v2/agent-detail/configure/components/preview/chat.tsx
rename to web/features/agent-v2/agent-detail/configure/components/preview/chat-runtime.tsx
index 9ad0555d196..e48f23c92d4 100644
--- a/web/features/agent-v2/agent-detail/configure/components/preview/chat.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/preview/chat-runtime.tsx
@@ -8,8 +8,12 @@ import type {
AgentThought,
MessageDetailResponse,
} from '@dify/contracts/api/console/agent/types.gen'
+import type {
+ ReactNode,
+} from 'react'
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 { FileUpload } from '@/app/components/base/features/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'
@@ -20,8 +24,7 @@ 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 ChatInputArea from '@/app/components/base/chat/chat/chat-input-area'
import { useChat } from '@/app/components/base/chat/chat/hooks'
import { buildChatItemTree, getLastAnswer, isValidGeneratedAnswer } from '@/app/components/base/chat/utils'
import { getProcessedFilesFromResponse } from '@/app/components/base/file-uploader/utils'
@@ -29,11 +32,12 @@ 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 { InputVarType, SupportUploadFileTypes } from '@/app/components/workflow/types'
import { DEFAULT_CHAT_PROMPT_CONFIG, DEFAULT_COMPLETION_PROMPT_CONFIG } from '@/config'
import { useAppContext } from '@/context/app-context'
import { agentComposerModelAtom } from '@/features/agent-v2/agent-composer/store-modules/model'
import { agentComposerPromptAtom } from '@/features/agent-v2/agent-composer/store-modules/prompt'
+import { ENABLE_AGENT_CLI_TOOLS } from '@/features/agent-v2/agent-detail/configure/feature-flags'
import { PromptMode } from '@/models/debug'
import dynamic from '@/next/dynamic'
import { consoleClient } from '@/service/client'
@@ -67,6 +71,7 @@ const defaultSystemParameters: ChatConfig['system_parameters'] = {
}
const disabledFileUploadConfig = {
+ enabled: false,
allowed_file_upload_methods: [TransferMethod.local_file, TransferMethod.remote_url],
allowed_file_types: [],
fileUploadConfig: defaultSystemParameters,
@@ -83,6 +88,39 @@ const disabledFileUploadConfig = {
fileUploadConfig: ChatConfig['system_parameters']
}
+const defaultFileUploadMethods = [TransferMethod.local_file, TransferMethod.remote_url]
+
+const toPreviewFileUploadConfig = (fileUpload: FileUpload | undefined) => {
+ if (!fileUpload?.enabled)
+ return disabledFileUploadConfig
+
+ const allowedFileUploadMethods = fileUpload.allowed_file_upload_methods?.length
+ ? fileUpload.allowed_file_upload_methods
+ : defaultFileUploadMethods
+ const numberLimits = fileUpload.number_limits ?? fileUpload.image?.number_limits ?? 3
+
+ return {
+ ...disabledFileUploadConfig,
+ ...fileUpload,
+ enabled: true,
+ allowed_file_types: fileUpload.allowed_file_types?.length
+ ? fileUpload.allowed_file_types
+ : [SupportUploadFileTypes.image],
+ allowed_file_upload_methods: allowedFileUploadMethods,
+ number_limits: numberLimits,
+ fileUploadConfig: fileUpload.fileUploadConfig ?? defaultSystemParameters,
+ image: {
+ ...disabledFileUploadConfig.image,
+ ...fileUpload.image,
+ enabled: fileUpload.image?.enabled ?? true,
+ transfer_methods: fileUpload.image?.transfer_methods?.length
+ ? fileUpload.image.transfer_methods
+ : allowedFileUploadMethods,
+ number_limits: numberLimits,
+ },
+ } as ChatConfig['file_upload']
+}
+
const getModelSettings = (agentSoulConfig?: AgentSoulConfig) => agentSoulConfig?.model?.model_settings ?? {}
const toEnabledConfig = (config?: { enabled?: boolean } | null) => ({
@@ -140,6 +178,34 @@ const toCliTool = (tool: AgentCliToolConfig) => ({
enabled: tool.enabled ?? true,
})
+const toLegacyPreviewDatasetConfigs = (
+ knowledge?: AgentSoulConfig['knowledge'],
+): NonNullable<ChatConfig['dataset_configs']> => {
+ // Temporary preview adapter: composer state is knowledge.sets, but this
+ // legacy chat preview contract still accepts one flat dataset_configs block.
+ // Preview currently flattens the first configured set only.
+ const previewKnowledgeSet = knowledge?.sets?.[0]
+ const datasets = previewKnowledgeSet?.datasets ?? []
+ const retrieval = previewKnowledgeSet?.retrieval
+
+ return {
+ retrieval_model: retrieval?.mode === 'single' ? RETRIEVE_TYPE.oneWay : RETRIEVE_TYPE.multiWay,
+ reranking_model: {
+ reranking_provider_name: retrieval?.reranking_model?.provider ?? '',
+ reranking_model_name: retrieval?.reranking_model?.model ?? '',
+ },
+ top_k: retrieval?.top_k ?? 4,
+ score_threshold_enabled: retrieval?.score_threshold !== undefined && retrieval?.score_threshold !== null,
+ score_threshold: retrieval?.score_threshold ?? 0.8,
+ datasets: {
+ datasets: datasets.map(dataset => ({
+ enabled: true,
+ id: dataset.id ?? '',
+ })).filter(dataset => dataset.id),
+ },
+ }
+}
+
const stopAgentChatMessageResponding = (agentId: string, taskId: string) => {
return consoleClient.agent.byAgentId.chatMessages.byTaskId.stop.post({
params: {
@@ -289,9 +355,8 @@ const buildChatConfig = ({
}): AgentPreviewChatConfig => {
const modelSettings = getModelSettings(agentSoulConfig)
const appFeatures = agentSoulConfig?.app_features ?? {}
- const datasets = agentSoulConfig?.knowledge?.datasets ?? []
const difyTools = agentSoulConfig?.tools?.dify_tools ?? []
- const cliTools = agentSoulConfig?.tools?.cli_tools ?? []
+ const cliTools = ENABLE_AGENT_CLI_TOOLS ? (agentSoulConfig?.tools?.cli_tools ?? []) : []
return {
pre_prompt: prompt || agentSoulConfig?.prompt?.system_prompt || '',
@@ -348,71 +413,42 @@ const buildChatConfig = ({
echo: false,
},
},
- dataset_configs: {
- retrieval_model: RETRIEVE_TYPE.multiWay,
- reranking_model: {
- reranking_provider_name: '',
- reranking_model_name: '',
- },
- top_k: agentSoulConfig?.knowledge?.query_config?.top_k ?? 4,
- score_threshold_enabled: agentSoulConfig?.knowledge?.query_config?.score_threshold_enabled ?? false,
- score_threshold: agentSoulConfig?.knowledge?.query_config?.score_threshold ?? 0.8,
- datasets: {
- datasets: datasets.map(dataset => ({
- enabled: true,
- id: dataset.id ?? '',
- })).filter(dataset => dataset.id),
- },
- },
- file_upload: disabledFileUploadConfig,
+ dataset_configs: toLegacyPreviewDatasetConfigs(agentSoulConfig?.knowledge),
+ file_upload: toPreviewFileUploadConfig(appFeatures.file_upload as FileUpload | undefined),
system_parameters: defaultSystemParameters,
supportCitationHitInfo: true,
}
}
-function AgentPreviewChatEmptyState({
- agentIcon,
- agentIconBackground,
- agentIconType,
- agentName,
- hasInstructions,
-}: {
+export type AgentChatRuntimeEmptyStateProps = {
agentIcon?: string | null
agentIconBackground?: string | null
agentIconType?: AgentIconType | null
agentName?: string
hasInstructions: boolean
-}) {
- const { t } = useTranslation('agentV2')
- const imageUrl = (agentIconType === 'image' || agentIconType === 'link') ? agentIcon : undefined
- const iconType = imageUrl ? 'image' : agentIconType
+ inputNode: ReactNode
+}
- return (
- <div className="pointer-events-none absolute inset-x-12 bottom-[calc(27%+84px)] flex flex-col items-center text-center">
- <AppIcon
- size="xxl"
- rounded
- iconType={iconType}
- icon={agentIcon ?? undefined}
- background={agentIconBackground}
- imageUrl={imageUrl}
- className="bg-background-default"
- />
- <div className="mt-3 max-w-full truncate system-md-semibold text-text-secondary">
- {agentName || t('agentDetail.configure.preview.empty.defaultAgentName')}
- </div>
- <div className="mt-4 h-px w-73 max-w-full bg-divider-subtle" />
- <div className="mt-5 max-w-91 body-md-regular text-text-tertiary">
- <p>{t('agentDetail.configure.preview.empty.description')}</p>
- {!hasInstructions && (
- <p>{t('agentDetail.configure.preview.empty.noInstructionsDescription')}</p>
- )}
- </div>
- </div>
- )
+export type AgentChatRuntimeProps = {
+ agentId: string
+ agentIcon?: string | null
+ agentIconBackground?: string | null
+ agentIconType?: AgentIconType | null
+ agentName?: string
+ agentSoulConfig?: AgentSoulConfig
+ clearChatList: boolean
+ conversationId?: string | null
+ draftType?: 'debug_build'
+ inputPlaceholder: string
+ sendButtonLabel?: string
+ renderEmptyState: (props: AgentChatRuntimeEmptyStateProps) => ReactNode
+ onClearChatListChange: (clearChatList: boolean) => void
+ onConversationComplete?: (conversationId: string) => void
+ onConversationIdChange?: (conversationId: string) => void
+ onSaveDraftBeforeRun?: () => Promise<void>
}
-export function AgentPreviewChat({
+export function AgentChatRuntime({
agentId,
agentIcon,
agentIconBackground,
@@ -420,32 +456,27 @@ export function AgentPreviewChat({
agentName,
agentSoulConfig,
clearChatList,
- debugConversationId,
+ conversationId,
+ draftType,
+ inputPlaceholder,
+ sendButtonLabel,
+ renderEmptyState,
onClearChatListChange,
+ onConversationComplete,
+ onConversationIdChange,
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>
-}) {
+}: AgentChatRuntimeProps) {
const historyQuery = useQuery({
- queryKey: ['agent-preview-debug-conversation', agentId, debugConversationId],
- queryFn: () => fetchAgentConversationMessages(agentId, debugConversationId!),
- enabled: !!debugConversationId,
+ queryKey: ['agent-chat-conversation-messages', agentId, conversationId],
+ queryFn: () => fetchAgentConversationMessages(agentId, conversationId!),
+ enabled: !!conversationId,
})
const initialChatTree = useMemo(
() => getFormattedAgentDebugChatTree(historyQuery.data?.data ?? []),
[historyQuery.data?.data],
)
- if (debugConversationId && historyQuery.isPending) {
+ if (conversationId && historyQuery.isPending) {
return (
<div className="flex h-full items-center justify-center">
<Loading type="app" />
@@ -455,7 +486,7 @@ export function AgentPreviewChat({
return (
<AgentPreviewChatSession
- key={`${debugConversationId ?? 'new'}-${historyQuery.dataUpdatedAt}`}
+ key={`${conversationId ?? 'new'}-${historyQuery.dataUpdatedAt}`}
agentId={agentId}
agentIcon={agentIcon}
agentIconBackground={agentIconBackground}
@@ -463,9 +494,15 @@ export function AgentPreviewChat({
agentName={agentName}
agentSoulConfig={agentSoulConfig}
clearChatList={clearChatList}
- debugConversationId={debugConversationId}
+ conversationId={conversationId}
+ draftType={draftType}
initialChatTree={initialChatTree}
+ inputPlaceholder={inputPlaceholder}
+ sendButtonLabel={sendButtonLabel}
+ renderEmptyState={renderEmptyState}
onClearChatListChange={onClearChatListChange}
+ onConversationComplete={onConversationComplete}
+ onConversationIdChange={onConversationIdChange}
onSaveDraftBeforeRun={onSaveDraftBeforeRun}
/>
)
@@ -479,9 +516,15 @@ function AgentPreviewChatSession({
agentName,
agentSoulConfig,
clearChatList,
- debugConversationId,
+ conversationId,
+ draftType,
initialChatTree,
+ inputPlaceholder,
+ sendButtonLabel,
+ renderEmptyState,
onClearChatListChange,
+ onConversationComplete,
+ onConversationIdChange,
onSaveDraftBeforeRun,
}: {
agentId: string
@@ -491,9 +534,15 @@ function AgentPreviewChatSession({
agentName?: string
agentSoulConfig?: AgentSoulConfig
clearChatList: boolean
- debugConversationId?: string | null
+ conversationId?: string | null
+ draftType?: 'debug_build'
initialChatTree: ChatItemInTree[]
+ inputPlaceholder: string
+ sendButtonLabel?: string
+ renderEmptyState: (props: AgentChatRuntimeEmptyStateProps) => ReactNode
onClearChatListChange: (clearChatList: boolean) => void
+ onConversationComplete?: (conversationId: string) => void
+ onConversationIdChange?: (conversationId: string) => void
onSaveDraftBeforeRun?: () => Promise<void>
}) {
const { userProfile } = useAppContext()
@@ -536,7 +585,7 @@ function AgentPreviewChatSession({
},
clearChatList,
onClearChatListChange,
- debugConversationId ?? undefined,
+ conversationId ?? undefined,
)
const doSend: OnSend = useCallback(async (message, files, isRegenerate = false, parentAnswer: ChatItem | null = null) => {
@@ -555,6 +604,8 @@ function AgentPreviewChatSession({
inputs,
parent_message_id: (isRegenerate ? parentAnswer?.id : getLastAnswer(chatList)?.id) || null,
}
+ if (draftType)
+ data.draft_type = draftType
if (files?.length && supportVision)
data.files = files
@@ -565,9 +616,13 @@ function AgentPreviewChatSession({
{
onGetConversationMessages: conversationId => fetchAgentConversationMessages(agentId, conversationId),
onGetSuggestedQuestions: responseItemId => fetchAgentSuggestedQuestions(agentId, responseItemId),
+ onConversationComplete: (conversationId) => {
+ onConversationIdChange?.(conversationId)
+ onConversationComplete?.(conversationId)
+ },
},
)
- }, [agentId, chatList, config.model.name, config.model.provider, handleSend, inputs, onSaveDraftBeforeRun, textGenerationModelList])
+ }, [agentId, chatList, config.model.name, config.model.provider, draftType, handleSend, inputs, onConversationComplete, onConversationIdChange, onSaveDraftBeforeRun, textGenerationModelList])
const doRegenerate = useCallback((chatItem: ChatItem, editedQuestion?: { message: string, files?: FileEntity[] }) => {
const question = editedQuestion ? chatItem : chatList.find(item => item.id === chatItem.parentMessageId)
@@ -584,26 +639,45 @@ function AgentPreviewChatSession({
}, [chatList, doSend])
const isEmptyChat = chatList.length === 0
const hasInstructions = !!config.pre_prompt.trim()
+ const emptyChatInputNode = (
+ <div className="pointer-events-auto mt-5 w-full">
+ <ChatInputArea
+ botName={agentName || 'Agent'}
+ customPlaceholder={inputPlaceholder}
+ disabled={isResponding}
+ showFileUpload={false}
+ visionConfig={config.file_upload}
+ speechToTextConfig={config.speech_to_text}
+ onSend={doSend}
+ inputs={inputs}
+ inputsForm={inputsForm}
+ sendButtonLabel={sendButtonLabel}
+ />
+ </div>
+ )
return (
<Chat
config={config}
chatList={chatList}
isResponding={isResponding}
- chatNode={isEmptyChat && (
- <AgentPreviewChatEmptyState
- agentIcon={agentIcon}
- agentIconBackground={agentIconBackground}
- agentIconType={agentIconType}
- agentName={agentName}
- hasInstructions={hasInstructions}
- />
- )}
- chatContainerClassName={cn('pt-6', isEmptyChat ? 'px-12' : 'px-3')}
+ chatNode={isEmptyChat
+ ? renderEmptyState({
+ agentIcon,
+ agentIconBackground,
+ agentIconType,
+ agentName,
+ hasInstructions,
+ inputNode: emptyChatInputNode,
+ })
+ : null}
+ chatContainerClassName={cn('pt-6', isEmptyChat ? 'px-12 pt-2 !pb-[88px]' : 'px-3')}
chatFooterClassName={cn(
- 'pb-0',
- isEmptyChat ? '!bottom-[27%] px-12 pt-3' : 'px-3 pt-10',
+ '!bottom-2 pb-0',
+ isEmptyChat ? 'hidden' : 'px-3 pt-10',
)}
+ inputPlaceholder={inputPlaceholder}
+ sendButtonLabel={sendButtonLabel}
showFileUpload={false}
suggestedQuestions={suggestedQuestions}
onSend={doSend}
@@ -612,6 +686,7 @@ function AgentPreviewChatSession({
onRegenerate={doRegenerate}
switchSibling={siblingMessageId => setTargetMessageId(siblingMessageId)}
onStopResponding={handleStop}
+ noChatInput={isEmptyChat}
showPromptLog
questionIcon={<Avatar avatar={userProfile.avatar_url} name={userProfile.name} size="xl" />}
onAnnotationEdited={handleAnnotationEdited}
diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/header.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/header.tsx
index 2598949ba21..c4f9e954f0b 100644
--- a/web/features/agent-v2/agent-detail/configure/components/preview/header.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/preview/header.tsx
@@ -1,46 +1,163 @@
-'use client'
-
+import type { ReactNode } from 'react'
import { cn } from '@langgenius/dify-ui/cn'
+import { SegmentedControl, SegmentedControlDivider, SegmentedControlItem } from '@langgenius/dify-ui/segmented-control'
import { useTranslation } from 'react-i18next'
+import { Infotip } from '@/app/components/base/infotip'
+import { useDocLink } from '@/context/i18n'
+
+type AgentConfigureRightPanelMode = 'build' | 'preview'
+
+function AgentModeTipSection({
+ iconClassName,
+ title,
+ children,
+}: {
+ iconClassName: string
+ title: string
+ children: string
+}) {
+ return (
+ <div className="flex flex-col gap-1">
+ <div className="flex items-start gap-1.5">
+ <span aria-hidden className={cn('size-4 shrink-0 text-text-primary', iconClassName)} />
+ <div className="system-sm-medium-uppercase text-text-primary">{title}</div>
+ </div>
+ <div className="system-xs-regular text-text-secondary">{children}</div>
+ </div>
+ )
+}
export function AgentPreviewHeader({
+ mode,
+ previewEnabled,
isChatFeaturesOpen,
+ onModeChange,
onToggleChatFeatures,
- onRestart,
+ onOpenWorkingDirectory,
+ onRefresh,
+ refreshDisabled,
+ showChatFeaturesAction = true,
+ trailingAction,
}: {
+ mode: AgentConfigureRightPanelMode
+ previewEnabled: boolean
isChatFeaturesOpen: boolean
+ onModeChange: (mode: AgentConfigureRightPanelMode) => void
onToggleChatFeatures: () => void
- onRestart: () => void
+ onOpenWorkingDirectory: () => void
+ onRefresh: () => void
+ refreshDisabled?: boolean
+ showChatFeaturesAction?: boolean
+ trailingAction?: ReactNode
}) {
const { t } = useTranslation('agentV2')
+ const docLink = useDocLink()
+ const buildLabel = t('agentDetail.configure.rightPanel.build')
+ const buildTipBody = t('agentDetail.configure.rightPanel.buildTipBody')
+ const previewLabel = t('agentDetail.configure.rightPanel.preview')
+ const previewTipBody = t('agentDetail.configure.rightPanel.previewTipBody')
+ const learnMoreLabel = t('agentDetail.configure.rightPanel.learnMore')
+ const modeTip = `${buildLabel}. ${buildTipBody} ${previewLabel}. ${previewTipBody} ${learnMoreLabel}`
return (
- <div className="flex h-12 shrink-0 items-center gap-3 py-3 pr-3 pl-6">
- <h2 className="min-w-0 flex-1 truncate title-xl-semi-bold text-text-primary">
- {t('agentDetail.configure.preview.title')}
- </h2>
- <div className="flex shrink-0 items-center gap-1">
- <button
- type="button"
- onClick={onRestart}
- className="flex size-6 items-center justify-center rounded-md p-0.5 text-text-tertiary hover:bg-state-base-hover hover:text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"
- aria-label={t('agentDetail.configure.preview.restart')}
+ <div className="relative z-1 flex h-12 shrink-0 items-center justify-between gap-3 px-4 py-2">
+ <div className="flex min-w-0 flex-1 items-center gap-2">
+ <SegmentedControl<AgentConfigureRightPanelMode>
+ value={[mode]}
+ onValueChange={(value) => {
+ const nextMode = value[0]
+ if (nextMode && (nextMode !== 'preview' || previewEnabled))
+ onModeChange(nextMode)
+ }}
+ aria-label={t('agentDetail.configure.rightPanel.modeLabel')}
>
- <span aria-hidden className="i-custom-vender-other-replay-line size-4" />
- </button>
- <button
- type="button"
- aria-pressed={isChatFeaturesOpen}
- onClick={onToggleChatFeatures}
- className={cn(
- 'flex h-8 items-center justify-center gap-0.5 rounded-lg px-3 py-2 text-text-tertiary hover:bg-state-base-hover hover:text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden',
- isChatFeaturesOpen && 'bg-state-base-hover text-text-secondary',
- )}
- aria-label={t('agentDetail.configure.preview.chatFeatures')}
+ <SegmentedControlItem<AgentConfigureRightPanelMode> value="build" className="uppercase">
+ <span aria-hidden className="i-custom-vender-agent-v2-configure-build size-4" />
+ {t('agentDetail.configure.rightPanel.build')}
+ </SegmentedControlItem>
+ <SegmentedControlItem<AgentConfigureRightPanelMode>
+ value="preview"
+ disabled={!previewEnabled}
+ className="uppercase"
+ >
+ <span aria-hidden className="i-custom-vender-agent-v2-configure-preview size-4" />
+ {t('agentDetail.configure.rightPanel.preview')}
+ </SegmentedControlItem>
+ </SegmentedControl>
+ <Infotip
+ aria-label={modeTip}
+ placement="bottom"
+ sideOffset={2}
+ className="size-5 rounded-md"
+ iconClassName="size-4 text-text-tertiary"
+ popupClassName="w-60 max-w-60 rounded-xl bg-components-tooltip-bg px-4 py-3.5 text-start text-text-secondary backdrop-blur-[5px]"
>
- <span aria-hidden className="i-ri-apps-2-add-line size-4" />
- <span className="px-0.5 system-sm-medium">{t('agentDetail.configure.preview.chatFeatures')}</span>
- </button>
+ <div className="flex flex-col gap-2">
+ <div className="flex flex-col gap-3">
+ <AgentModeTipSection iconClassName="i-custom-vender-agent-v2-configure-build" title={buildLabel}>
+ {buildTipBody}
+ </AgentModeTipSection>
+ <AgentModeTipSection iconClassName="i-custom-vender-agent-v2-configure-preview" title={previewLabel}>
+ {previewTipBody}
+ </AgentModeTipSection>
+ </div>
+ <a
+ href={docLink('/use-dify/build/agent')}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="body-xs-regular text-text-accent hover:underline"
+ >
+ {learnMoreLabel}
+ </a>
+ </div>
+ </Infotip>
+ </div>
+ <div className="flex shrink-0 items-center">
+ <div className="flex items-center gap-2">
+ <button
+ type="button"
+ onClick={onRefresh}
+ disabled={refreshDisabled}
+ className="flex size-6 items-center justify-center rounded-md p-0.5 text-text-tertiary hover:bg-state-base-hover hover:text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden disabled:cursor-not-allowed disabled:opacity-50"
+ aria-label={t('agentDetail.configure.preview.restart')}
+ >
+ <span aria-hidden className="i-custom-vender-other-replay-line size-4" />
+ </button>
+ {mode === 'build' && (
+ <button
+ type="button"
+ onClick={onOpenWorkingDirectory}
+ className="flex size-6 items-center justify-center rounded-md p-0.5 text-text-tertiary hover:bg-state-base-hover hover:text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"
+ aria-label={t('agentDetail.configure.workingDirectory.open')}
+ >
+ <span aria-hidden className="i-ri-folder-3-line size-4" />
+ </button>
+ )}
+ </div>
+ {showChatFeaturesAction && (
+ <>
+ <SegmentedControlDivider className="mx-3" />
+ <button
+ type="button"
+ aria-pressed={isChatFeaturesOpen}
+ onClick={onToggleChatFeatures}
+ className={cn(
+ 'flex h-8 items-center justify-center gap-1 rounded-lg px-2 py-2 text-text-tertiary hover:bg-state-base-hover hover:text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden',
+ isChatFeaturesOpen && 'bg-state-base-hover text-text-secondary',
+ )}
+ aria-label={t('agentDetail.configure.preview.chatFeatures')}
+ >
+ <span aria-hidden className="i-ri-chat-settings-line size-4" />
+ <span className="px-0.5 system-sm-medium">{t('agentDetail.configure.preview.chatFeatures')}</span>
+ </button>
+ </>
+ )}
+ {trailingAction != null && (
+ <>
+ <SegmentedControlDivider className="mx-3" />
+ {trailingAction}
+ </>
+ )}
</div>
</div>
)
diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/preview-chat.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/preview-chat.tsx
new file mode 100644
index 00000000000..a112cac7f3a
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/configure/components/preview/preview-chat.tsx
@@ -0,0 +1,68 @@
+'use client'
+
+import type { AgentChatRuntimeEmptyStateProps, AgentChatRuntimeProps } from './chat-runtime'
+import { useTranslation } from 'react-i18next'
+import AppIcon from '@/app/components/base/app-icon'
+import { AgentChatRuntime } from './chat-runtime'
+
+type AgentPreviewChatProps = Omit<AgentChatRuntimeProps, 'inputPlaceholder' | 'renderEmptyState'>
+
+function AgentPreviewChatEmptyState({
+ agentIcon,
+ agentIconBackground,
+ agentIconType,
+ agentName,
+ hasInstructions,
+ inputNode,
+}: AgentChatRuntimeEmptyStateProps) {
+ const { t } = useTranslation('agentV2')
+ const imageUrl = (agentIconType === 'image' || agentIconType === 'link') ? agentIcon : undefined
+ const iconType = imageUrl ? 'image' : agentIconType
+
+ return (
+ <div className="flex h-full items-center justify-center">
+ <div className="flex w-full max-w-150 flex-col items-start p-3 text-left">
+ <AppIcon
+ size="xxl"
+ rounded
+ iconType={iconType}
+ icon={agentIcon ?? undefined}
+ background={agentIconBackground}
+ imageUrl={imageUrl}
+ className="bg-background-default"
+ />
+ <div className="mt-3 max-w-full truncate system-md-medium text-text-secondary">
+ {t('agentDetail.configure.preview.empty.title', {
+ name: agentName || t('agentDetail.configure.preview.empty.defaultAgentName'),
+ })}
+ </div>
+ <p className="mt-1 max-w-full body-md-regular text-text-tertiary">
+ {t('agentDetail.configure.preview.empty.description')}
+ </p>
+ {!hasInstructions && (
+ <p className="mt-1 max-w-full body-md-regular text-text-tertiary">
+ {t('agentDetail.configure.preview.empty.noInstructionsDescription')}
+ </p>
+ )}
+ {inputNode}
+ </div>
+ </div>
+ )
+}
+
+export function AgentPreviewChat(props: AgentPreviewChatProps) {
+ const { t } = useTranslation('agentV2')
+ const agentName = props.agentName || t('agentDetail.configure.preview.empty.defaultAgentName')
+
+ return (
+ <AgentChatRuntime
+ {...props}
+ inputPlaceholder={t('agentDetail.configure.preview.inputPlaceholder', {
+ name: agentName,
+ })}
+ renderEmptyState={emptyStateProps => (
+ <AgentPreviewChatEmptyState {...emptyStateProps} />
+ )}
+ />
+ )
+}
diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/right-panel-chat.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/right-panel-chat.tsx
new file mode 100644
index 00000000000..1455ec5e06b
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/configure/components/preview/right-panel-chat.tsx
@@ -0,0 +1,53 @@
+'use client'
+
+import type { AgentSoulConfig } from '@dify/contracts/api/console/agent/types.gen'
+import { useAgentPreviewSoulConfig } from '../../hooks'
+import { AgentBuildChat } from './build-chat'
+import { AgentPreviewChat } from './preview-chat'
+
+export type AgentConfigureRightPanelMode = 'build' | 'preview'
+export type AgentConfigureConversationIds = Record<AgentConfigureRightPanelMode, string | null>
+
+export function AgentConfigureRightPanelChat({
+ agentSoulConfig,
+ conversationIds,
+ mode,
+ onConversationComplete,
+ onConversationIdChange,
+ ...props
+}: Omit<Parameters<typeof AgentPreviewChat>[0], 'agentSoulConfig' | 'conversationId' | 'onConversationComplete' | 'onConversationIdChange'> & {
+ agentSoulConfig?: AgentSoulConfig
+ conversationIds: AgentConfigureConversationIds
+ mode: AgentConfigureRightPanelMode
+ onConversationComplete?: (mode: AgentConfigureRightPanelMode) => void
+ onConversationIdChange: (mode: AgentConfigureRightPanelMode, conversationId: string) => void
+}) {
+ const previewAgentSoulConfig = useAgentPreviewSoulConfig(agentSoulConfig)
+ const conversationId = conversationIds[mode]
+ const handleConversationIdChange = (newConversationId: string) => {
+ onConversationIdChange(mode, newConversationId)
+ }
+ const handleConversationComplete = () => {
+ onConversationComplete?.(mode)
+ }
+
+ return mode === 'build'
+ ? (
+ <AgentBuildChat
+ {...props}
+ conversationId={conversationId}
+ agentSoulConfig={previewAgentSoulConfig}
+ onConversationComplete={handleConversationComplete}
+ onConversationIdChange={handleConversationIdChange}
+ />
+ )
+ : (
+ <AgentPreviewChat
+ {...props}
+ conversationId={conversationId}
+ agentSoulConfig={previewAgentSoulConfig}
+ onConversationComplete={handleConversationComplete}
+ onConversationIdChange={handleConversationIdChange}
+ />
+ )
+}
diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/use-working-directory-panel.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/use-working-directory-panel.tsx
new file mode 100644
index 00000000000..3369c94b576
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/configure/components/preview/use-working-directory-panel.tsx
@@ -0,0 +1,24 @@
+'use client'
+
+import type { ReactNode } from 'react'
+import { useState } from 'react'
+import { AgentWorkingDirectoryPanel } from './working-directory-panel'
+
+export function useAgentWorkingDirectoryPanel(): {
+ closeWorkingDirectory: () => void
+ openWorkingDirectory: () => void
+ panel: ReactNode
+} {
+ const [open, setOpen] = useState(false)
+
+ return {
+ closeWorkingDirectory: () => setOpen(false),
+ openWorkingDirectory: () => setOpen(true),
+ panel: (
+ <AgentWorkingDirectoryPanel
+ open={open}
+ onOpenChange={setOpen}
+ />
+ ),
+ }
+}
diff --git a/web/features/agent-v2/agent-detail/configure/components/preview/working-directory-panel.tsx b/web/features/agent-v2/agent-detail/configure/components/preview/working-directory-panel.tsx
new file mode 100644
index 00000000000..4773d6d2f9f
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/configure/components/preview/working-directory-panel.tsx
@@ -0,0 +1,124 @@
+'use client'
+
+import type { AgentFileNode } from '@/features/agent-v2/agent-composer/form-state'
+import {
+ Drawer,
+ DrawerBackdrop,
+ DrawerCloseButton,
+ DrawerContent,
+ DrawerDescription,
+ DrawerPopup,
+ DrawerPortal,
+ DrawerTitle,
+ DrawerViewport,
+} from '@langgenius/dify-ui/drawer'
+import { FileTreeFile } from '@langgenius/dify-ui/file-tree'
+import { useTranslation } from 'react-i18next'
+import { AgentFileTree } from '../orchestrate/files/tree'
+
+type AgentWorkingDirectoryPanelProps = {
+ onOpenChange: (open: boolean) => void
+ open: boolean
+}
+
+const workingDirectoryFiles: AgentFileNode[] = [
+ {
+ id: 'working-directory/_index.json',
+ name: '_index.json',
+ icon: 'json',
+ driveKey: 'working-directory/_index.json',
+ },
+ {
+ id: 'working-directory/web-game',
+ name: 'web-game',
+ icon: 'folder',
+ driveKey: 'working-directory/web-game',
+ children: [
+ {
+ id: 'working-directory/web-game/public',
+ name: 'public',
+ icon: 'folder',
+ driveKey: 'working-directory/web-game/public',
+ },
+ {
+ id: 'working-directory/web-game/assets',
+ name: 'assets',
+ icon: 'folder',
+ driveKey: 'working-directory/web-game/assets',
+ },
+ {
+ id: 'working-directory/web-game/src',
+ name: 'src',
+ icon: 'folder',
+ driveKey: 'working-directory/web-game/src',
+ },
+ {
+ id: 'working-directory/web-game/styles',
+ name: 'styles',
+ icon: 'folder',
+ driveKey: 'working-directory/web-game/styles',
+ },
+ {
+ id: 'working-directory/web-game/README.md',
+ name: 'README.md',
+ icon: 'markdown',
+ driveKey: 'working-directory/web-game/README.md',
+ },
+ ],
+ },
+]
+
+const selectedWorkingDirectoryFileId = 'working-directory/web-game/README.md'
+
+export function AgentWorkingDirectoryPanel({
+ onOpenChange,
+ open,
+}: AgentWorkingDirectoryPanelProps) {
+ const { t } = useTranslation('agentV2')
+ const { t: tCommon } = useTranslation('common')
+
+ return (
+ <Drawer open={open} onOpenChange={onOpenChange} swipeDirection="right">
+ <DrawerPortal>
+ <DrawerBackdrop forceRender className="fixed bg-transparent" />
+ <DrawerViewport>
+ <DrawerPopup className="data-[swipe-direction=right]:top-2 data-[swipe-direction=right]:bottom-2 data-[swipe-direction=right]:h-auto data-[swipe-direction=right]:w-[360px]">
+ <DrawerContent className="flex min-h-0 flex-1 flex-col p-0 pb-0">
+ <div className="flex shrink-0 items-start gap-2 px-4 pt-3 pb-2">
+ <div className="min-w-0 flex-1">
+ <DrawerTitle className="truncate system-xl-semibold text-text-primary">
+ {t('agentDetail.configure.workingDirectory.title')}
+ </DrawerTitle>
+ <DrawerDescription className="body-xs-regular text-text-tertiary">
+ {t('agentDetail.configure.workingDirectory.description')}
+ </DrawerDescription>
+ </div>
+ <DrawerCloseButton
+ aria-label={tCommon('operation.close')}
+ className="size-6 rounded-md p-0.5"
+ />
+ </div>
+ <AgentFileTree
+ files={workingDirectoryFiles}
+ selectedFileId={selectedWorkingDirectoryFileId}
+ treeLabel={t('agentDetail.configure.workingDirectory.treeLabel')}
+ className="min-h-0 flex-1 px-3 py-1"
+ scrollAreaClassName="flex-1"
+ rootClassName="p-0"
+ listClassName="gap-px"
+ renderFile={({ selected, children }) => (
+ <FileTreeFile selected={selected}>
+ {children}
+ {selected && (
+ <span aria-hidden className="ms-auto i-ri-more-fill flex size-5 shrink-0 items-center justify-center text-text-tertiary" />
+ )}
+ </FileTreeFile>
+ )}
+ />
+ </DrawerContent>
+ </DrawerPopup>
+ </DrawerViewport>
+ </DrawerPortal>
+ </Drawer>
+ )
+}
diff --git a/web/features/agent-v2/agent-detail/configure/components/workspace.tsx b/web/features/agent-v2/agent-detail/configure/components/workspace.tsx
new file mode 100644
index 00000000000..9f116d77c7d
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/configure/components/workspace.tsx
@@ -0,0 +1,59 @@
+'use client'
+
+import type { ReactNode } from 'react'
+import { cn } from '@langgenius/dify-ui/cn'
+import { useTranslation } from 'react-i18next'
+
+type AgentConfigureWorkspaceProps = {
+ 'aria-busy'?: boolean
+ 'className'?: string
+ 'leftPanel': ReactNode
+ 'rightPanel': ReactNode
+ 'sidePanels'?: ReactNode
+}
+
+export function AgentConfigureWorkspace({
+ 'aria-busy': ariaBusy,
+ className,
+ leftPanel,
+ rightPanel,
+ sidePanels,
+}: AgentConfigureWorkspaceProps) {
+ const { t } = useTranslation('agentV2')
+
+ return (
+ <section
+ aria-label={t('agentDetail.sections.configure')}
+ aria-busy={ariaBusy}
+ className={cn('flex h-full min-w-0 flex-1 gap-1 overflow-hidden bg-background-body p-1', className)}
+ >
+ {leftPanel}
+ <div className="flex min-w-105 flex-1 gap-1 overflow-hidden">
+ {rightPanel}
+ {sidePanels}
+ </div>
+ </section>
+ )
+}
+
+type AgentConfigurePreviewSurfaceProps = {
+ background?: ReactNode
+ chat: ReactNode
+ header: ReactNode
+}
+
+export function AgentConfigurePreviewSurface({
+ background,
+ chat,
+ header,
+}: AgentConfigurePreviewSurfaceProps) {
+ return (
+ <div className="relative isolate flex min-w-105 flex-1 flex-col overflow-hidden rounded-lg border-[0.5px] border-components-panel-border bg-linear-to-b from-background-gradient-bg-fill-chat-bg-1 to-background-gradient-bg-fill-chat-bg-2 shadow-xl shadow-shadow-shadow-5">
+ {background}
+ {header}
+ <div className="relative z-1 min-h-0 flex-1">
+ {chat}
+ </div>
+ </div>
+ )
+}
diff --git a/web/features/agent-v2/agent-detail/configure/feature-flags.ts b/web/features/agent-v2/agent-detail/configure/feature-flags.ts
new file mode 100644
index 00000000000..0769fc6f597
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/configure/feature-flags.ts
@@ -0,0 +1 @@
+export const ENABLE_AGENT_CLI_TOOLS = false
diff --git a/web/features/agent-v2/agent-detail/configure/hooks.ts b/web/features/agent-v2/agent-detail/configure/hooks.ts
new file mode 100644
index 00000000000..dfdf4c7d8da
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/configure/hooks.ts
@@ -0,0 +1,93 @@
+'use client'
+
+import type { AgentConfigSnapshotDetailResponse, AgentSoulConfig } from '@dify/contracts/api/console/agent/types.gen'
+import { skipToken, useQuery } from '@tanstack/react-query'
+import { useAtom, useAtomValue } from 'jotai'
+import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
+import { useDefaultModel, useTextGenerationCurrentProviderAndModelAndModelList } from '@/app/components/header/account-setting/model-provider-page/hooks'
+import { agentComposerAppFeaturesAtom } from '@/features/agent-v2/agent-composer/store-modules/app-features'
+import { agentComposerModelAtom } from '@/features/agent-v2/agent-composer/store-modules/model'
+import { consoleQuery } from '@/service/client'
+
+export function useAgentConfigureData(agentId: string, selectedVersionId: string | null) {
+ const agentQuery = useQuery(consoleQuery.agent.byAgentId.get.queryOptions({
+ input: {
+ params: {
+ agent_id: agentId,
+ },
+ },
+ }))
+ const composerQuery = useQuery(consoleQuery.agent.byAgentId.composer.get.queryOptions({
+ input: {
+ params: {
+ agent_id: agentId,
+ },
+ },
+ }))
+ const publishedVersionId = composerQuery.data?.active_config_snapshot?.id
+ const shouldLoadPublishedVersion = !selectedVersionId && !composerQuery.data?.agent_soul
+ const versionIdToLoad = selectedVersionId ?? (shouldLoadPublishedVersion ? publishedVersionId : undefined)
+ const shouldLoadVersion = !!versionIdToLoad
+ const versionQuery = useQuery(consoleQuery.agent.byAgentId.versions.byVersionId.get.queryOptions({
+ input: versionIdToLoad
+ ? {
+ params: {
+ agent_id: agentId,
+ version_id: versionIdToLoad,
+ },
+ }
+ : skipToken,
+ }))
+ const versionDetail = versionQuery.data as AgentConfigSnapshotDetailResponse | undefined
+ 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,
+ shouldLoadVersion,
+ selectedVersionId,
+ activeVersionId,
+ activeConfigSnapshot,
+ agentSoulConfig,
+ }
+}
+
+export function useAgentConfigureModelOptions() {
+ const [model, setModel] = useAtom(agentComposerModelAtom)
+ const {
+ data: defaultTextGenerationModel,
+ } = useDefaultModel(ModelTypeEnum.textGeneration)
+ const defaultModel = defaultTextGenerationModel
+ ? {
+ provider: defaultTextGenerationModel.provider.provider,
+ model: defaultTextGenerationModel.model,
+ }
+ : undefined
+ const currentModel = model ?? defaultModel
+ const {
+ textGenerationModelList,
+ } = useTextGenerationCurrentProviderAndModelAndModelList(currentModel)
+
+ return {
+ currentModel,
+ setConfigureModel: setModel,
+ textGenerationModelList,
+ }
+}
+
+export function useAgentPreviewSoulConfig(
+ agentSoulConfig: AgentSoulConfig | undefined,
+) {
+ const draftAppFeatures = useAtomValue(agentComposerAppFeaturesAtom)
+
+ if (!agentSoulConfig || !draftAppFeatures)
+ return agentSoulConfig
+
+ return {
+ ...agentSoulConfig,
+ app_features: draftAppFeatures,
+ }
+}
diff --git a/web/features/agent-v2/agent-detail/configure/page.tsx b/web/features/agent-v2/agent-detail/configure/page.tsx
index c242a28061f..75339f7d2e9 100644
--- a/web/features/agent-v2/agent-detail/configure/page.tsx
+++ b/web/features/agent-v2/agent-detail/configure/page.tsx
@@ -1,24 +1,10 @@
'use client'
-import type { AgentConfigSnapshotDetailResponse, AgentIconType, AgentSoulConfig } from '@dify/contracts/api/console/agent/types.gen'
-import { skipToken, useQuery } from '@tanstack/react-query'
-import { useAtom, useAtomValue } from 'jotai'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
-import Loading from '@/app/components/base/loading'
-import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
-import { useDefaultModel, useTextGenerationCurrentProviderAndModelAndModelList } from '@/app/components/header/account-setting/model-provider-page/hooks'
-import { AgentComposerProvider } from '@/features/agent-v2/agent-composer/provider'
-import { useHydrateAgentSoulConfigDraft } from '@/features/agent-v2/agent-composer/store'
-import { agentComposerAppFeaturesAtom } from '@/features/agent-v2/agent-composer/store-modules/app-features'
-import { agentComposerModelAtom } from '@/features/agent-v2/agent-composer/store-modules/model'
-import { consoleQuery } from '@/service/client'
-import { AgentOrchestratePanel } from './components/orchestrate'
-import { AgentPreviewChat } from './components/preview/chat'
-import { AgentChatFeaturesPanel } from './components/preview/chat-features-panel'
-import { AgentPreviewHeader } from './components/preview/header'
-import { AgentPreviewVersionsPanel } from './components/preview/versions-panel'
-import { useAgentConfigureSync } from './use-agent-configure-sync'
+import { AgentConfigureComposerScope } from './components/composer-session'
+import { AgentConfigurePageLoading } from './components/page-loading'
+import { useAgentConfigureData } from './hooks'
type AgentConfigurePageProps = {
agentId: string
@@ -28,9 +14,7 @@ export function AgentConfigurePage({
agentId,
}: AgentConfigurePageProps) {
return (
- <AgentComposerProvider>
- <AgentConfigurePageContent agentId={agentId} />
- </AgentComposerProvider>
+ <AgentConfigurePageContent agentId={agentId} />
)
}
@@ -39,6 +23,7 @@ function AgentConfigurePageContent({
}: AgentConfigurePageProps) {
const { t } = useTranslation('agentV2')
const [selectedVersionId, setSelectedVersionId] = useState<string | null>(null)
+ const [composerRebaseRevision, setComposerRebaseRevision] = useState(0)
const configureData = useAgentConfigureData(agentId, selectedVersionId)
const isConfigureDataPending = configureData.agentQuery.isPending
|| configureData.composerQuery.isPending
@@ -46,234 +31,17 @@ function AgentConfigurePageContent({
if (isConfigureDataPending) {
return (
- <section
- aria-label={t('agentDetail.sections.configure')}
- aria-busy
- className="flex h-full min-w-0 flex-1 items-center justify-center p-1"
- >
- <Loading type="app" />
- </section>
+ <AgentConfigurePageLoading label={t('agentDetail.sections.configure')} />
)
}
return (
- <AgentConfigurePageLoadedContent
+ <AgentConfigureComposerScope
agentId={agentId}
+ composerRebaseRevision={composerRebaseRevision}
configureData={configureData}
+ onComposerRebase={() => setComposerRebaseRevision(revision => revision + 1)}
onSelectVersion={setSelectedVersionId}
/>
)
}
-
-function AgentConfigurePageLoadedContent({
- agentId,
- configureData,
- onSelectVersion,
-}: AgentConfigurePageProps & {
- configureData: ReturnType<typeof useAgentConfigureData>
- onSelectVersion: (versionId: string | null) => void
-}) {
- const { t } = useTranslation('agentV2')
- const [showChatFeatures, setShowChatFeatures] = useState(false)
- const [showPreviewVersions, setShowPreviewVersions] = useState(false)
- const [clearPreviewChat, setClearPreviewChat] = useState(false)
- const {
- agentQuery,
- composerQuery,
- versionQuery,
- selectedVersionId,
- activeVersionId,
- activeConfigSnapshot,
- agentSoulConfig,
- } = configureData
- const agentIconType = agentQuery.data?.icon_type as AgentIconType | null | undefined
- const isViewingVersion = !!selectedVersionId
-
- useHydrateAgentSoulConfigDraft({
- agentId,
- activeVersionId,
- config: agentSoulConfig,
- })
- const {
- currentModel,
- setConfigureModel,
- textGenerationModelList,
- } = useAgentConfigureModelOptions()
- const {
- draftSavedAt,
- isPublishing,
- publishDraft,
- saveDraft,
- } = useAgentConfigureSync({
- agentId,
- baseConfig: agentSoulConfig,
- currentModel,
- enabled: composerQuery.isSuccess && !selectedVersionId,
- })
-
- return (
- <section
- aria-label={t('agentDetail.sections.configure')}
- aria-busy={agentQuery.isFetching}
- className="flex h-full min-w-0 flex-1 gap-1 overflow-hidden p-1"
- >
- <AgentOrchestratePanel
- agentId={agentId}
- activeConfigIsPublished={agentQuery.data?.active_config_is_published}
- activeConfigSnapshot={activeConfigSnapshot}
- agentSoulConfig={agentSoulConfig}
- agentName={agentQuery.data?.name}
- currentModel={currentModel}
- textGenerationModelList={textGenerationModelList}
- draftSavedAt={draftSavedAt}
- isPublishing={isPublishing}
- readOnly={isViewingVersion}
- selectedVersionSnapshot={isViewingVersion ? activeConfigSnapshot : undefined}
- onSelectModel={setConfigureModel}
- onPublish={publishDraft}
- onOpenVersions={() => setShowPreviewVersions(true)}
- onExitVersions={() => onSelectVersion(null)}
- />
-
- {/* Preview area */}
- <div className="flex min-w-105 flex-1 gap-1 overflow-hidden">
- <div className="flex min-w-105 flex-1 flex-col overflow-hidden rounded-lg bg-background-gradient-bg-fill-chat-bg-2 shadow-xl shadow-shadow-shadow-5">
- <AgentPreviewHeader
- isChatFeaturesOpen={showChatFeatures}
- onToggleChatFeatures={() => setShowChatFeatures(open => !open)}
- onRestart={() => setClearPreviewChat(true)}
- />
-
- <div className="min-h-0 flex-1">
- <AgentPreviewChatWithDraftConfig
- agentId={agentId}
- agentIcon={agentQuery.data?.icon}
- agentIconBackground={agentQuery.data?.icon_background}
- agentIconType={agentIconType}
- agentName={agentQuery.data?.name}
- agentSoulConfig={agentSoulConfig}
- clearChatList={clearPreviewChat}
- debugConversationId={agentQuery.data?.debug_conversation_id}
- onClearChatListChange={setClearPreviewChat}
- onSaveDraftBeforeRun={saveDraft}
- />
- </div>
- </div>
-
- {showPreviewVersions && (
- <AgentPreviewVersionsPanel
- agentId={agentId}
- activeVersionId={activeVersionId}
- onSelectVersion={onSelectVersion}
- onClose={() => setShowPreviewVersions(false)}
- />
- )}
- <AgentChatFeaturesPanel
- show={showChatFeatures}
- appFeatures={agentSoulConfig?.app_features}
- disabled={versionQuery.isPending}
- onClose={() => setShowChatFeatures(false)}
- />
- </div>
- </section>
- )
-}
-
-function AgentPreviewChatWithDraftConfig({
- agentSoulConfig,
- ...props
-}: Omit<Parameters<typeof AgentPreviewChat>[0], 'agentSoulConfig'> & {
- agentSoulConfig?: AgentSoulConfig
-}) {
- const draftAppFeatures = useAtomValue(agentComposerAppFeaturesAtom)
- const previewAgentSoulConfig = getPreviewAgentSoulConfig(agentSoulConfig, draftAppFeatures)
-
- return (
- <AgentPreviewChat
- {...props}
- agentSoulConfig={previewAgentSoulConfig}
- />
- )
-}
-
-function useAgentConfigureData(agentId: string, selectedVersionId: string | null) {
- const agentQuery = useQuery(consoleQuery.agent.byAgentId.get.queryOptions({
- input: {
- params: {
- agent_id: agentId,
- },
- },
- }))
- const composerQuery = useQuery(consoleQuery.agent.byAgentId.composer.get.queryOptions({
- input: {
- params: {
- agent_id: agentId,
- },
- },
- }))
- const publishedVersionId = composerQuery.data?.active_config_snapshot?.id
- const shouldLoadPublishedVersion = !selectedVersionId && !composerQuery.data?.agent_soul
- const versionIdToLoad = selectedVersionId ?? (shouldLoadPublishedVersion ? publishedVersionId : undefined)
- const shouldLoadVersion = !!versionIdToLoad
- const versionQuery = useQuery(consoleQuery.agent.byAgentId.versions.byVersionId.get.queryOptions({
- input: versionIdToLoad
- ? {
- params: {
- agent_id: agentId,
- version_id: versionIdToLoad,
- },
- }
- : skipToken,
- }))
- const versionDetail = versionQuery.data as AgentConfigSnapshotDetailResponse | undefined
- 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,
- shouldLoadVersion,
- selectedVersionId,
- activeVersionId,
- activeConfigSnapshot,
- agentSoulConfig,
- }
-}
-
-function useAgentConfigureModelOptions() {
- const [model, setModel] = useAtom(agentComposerModelAtom)
- const {
- data: defaultTextGenerationModel,
- } = useDefaultModel(ModelTypeEnum.textGeneration)
- const defaultModel = defaultTextGenerationModel
- ? {
- provider: defaultTextGenerationModel.provider.provider,
- model: defaultTextGenerationModel.model,
- }
- : undefined
- const currentModel = model ?? defaultModel
- const {
- textGenerationModelList,
- } = useTextGenerationCurrentProviderAndModelAndModelList(currentModel)
-
- return {
- currentModel,
- setConfigureModel: setModel,
- textGenerationModelList,
- }
-}
-
-function getPreviewAgentSoulConfig(
- agentSoulConfig: AgentSoulConfig | undefined,
- draftAppFeatures: AgentSoulConfig['app_features'] | undefined,
-) {
- if (!agentSoulConfig || !draftAppFeatures)
- return agentSoulConfig
-
- return {
- ...agentSoulConfig,
- app_features: draftAppFeatures,
- }
-}
diff --git a/web/features/agent-v2/agent-detail/configure/use-agent-build-draft-run.ts b/web/features/agent-v2/agent-detail/configure/use-agent-build-draft-run.ts
new file mode 100644
index 00000000000..7db81165711
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/configure/use-agent-build-draft-run.ts
@@ -0,0 +1,54 @@
+'use client'
+
+import { useMutation, useQueryClient } from '@tanstack/react-query'
+import { useCallback } from 'react'
+import { consoleQuery } from '@/service/client'
+
+export type AgentConfigureSoulSource = 'draft' | 'build-draft' | 'view-version'
+
+export function usePrepareAgentBuildDraftBeforeRun({
+ agentId,
+ isBuildDraftActive,
+ saveDraft,
+ setSoulSourceOverride,
+}: {
+ agentId?: string
+ isBuildDraftActive: boolean
+ saveDraft: () => Promise<unknown>
+ setSoulSourceOverride?: (source: AgentConfigureSoulSource) => void
+}) {
+ const queryClient = useQueryClient()
+ const buildDraftQueryOptions = consoleQuery.agent.byAgentId.buildDraft.get.queryOptions({
+ input: {
+ params: {
+ agent_id: agentId ?? '',
+ },
+ },
+ })
+ const checkoutBuildDraftMutation = useMutation(consoleQuery.agent.byAgentId.buildDraft.checkout.post.mutationOptions())
+ const { mutateAsync: checkoutBuildDraft, isPending: isCheckingOutBuildDraft } = checkoutBuildDraftMutation
+
+ const prepareBuildDraftBeforeRun = useCallback(async () => {
+ if (!agentId)
+ return
+
+ if (!isBuildDraftActive)
+ await saveDraft()
+
+ const buildDraft = await checkoutBuildDraft({
+ params: {
+ agent_id: agentId,
+ },
+ body: {
+ force: false,
+ },
+ })
+ queryClient.setQueryData(buildDraftQueryOptions.queryKey, buildDraft)
+ setSoulSourceOverride?.('build-draft')
+ }, [agentId, buildDraftQueryOptions.queryKey, checkoutBuildDraft, isBuildDraftActive, queryClient, saveDraft, setSoulSourceOverride])
+
+ return {
+ isCheckingOutBuildDraft,
+ prepareBuildDraftBeforeRun,
+ }
+}
diff --git a/web/features/agent-v2/agent-detail/configure/use-agent-configure-build-draft.ts b/web/features/agent-v2/agent-detail/configure/use-agent-configure-build-draft.ts
new file mode 100644
index 00000000000..033d4796ef7
--- /dev/null
+++ b/web/features/agent-v2/agent-detail/configure/use-agent-configure-build-draft.ts
@@ -0,0 +1,219 @@
+'use client'
+
+import type { AgentSoulConfig } from '@dify/contracts/api/console/agent/types.gen'
+import { toast } from '@langgenius/dify-ui/toast'
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { agentSoulConfigToFormState } from '@/features/agent-v2/agent-composer/conversions'
+import { consoleQuery } from '@/service/client'
+import { agentConfigureConsoleQuery } from './build-draft-query'
+import { usePrepareAgentBuildDraftBeforeRun } from './use-agent-build-draft-run'
+
+export type AgentConfigureSoulSource = 'draft' | 'build-draft' | 'view-version'
+
+const isNotFoundResponse = (error: unknown) => error instanceof Response && error.status === 404
+
+export function useAgentConfigureBuildDraftData({
+ agentId,
+ activeVersionId,
+ composerAgentSoulConfig,
+ isViewingVersion,
+ normalAgentSoulConfig,
+}: {
+ agentId: string
+ activeVersionId: string | null | undefined
+ composerAgentSoulConfig?: AgentSoulConfig
+ isViewingVersion: boolean
+ normalAgentSoulConfig?: AgentSoulConfig
+}) {
+ const shouldSilenceBuildDraftCheckRef = useRef(true)
+ const [soulSourceOverride, setSoulSourceOverride] = useState<AgentConfigureSoulSource | null>(null)
+ const buildDraftQueryInput = {
+ params: {
+ agent_id: agentId,
+ },
+ }
+ const buildDraftQueryOptions = agentConfigureConsoleQuery.agent.byAgentId.buildDraft.get.queryOptions({
+ input: {
+ params: buildDraftQueryInput.params,
+ },
+ context: {},
+ })
+ const silentBuildDraftQueryOptions = agentConfigureConsoleQuery.agent.byAgentId.buildDraft.get.queryOptions({
+ input: {
+ params: buildDraftQueryInput.params,
+ },
+ context: {
+ silent: true,
+ },
+ queryKey: buildDraftQueryOptions.queryKey,
+ })
+ const buildDraftQuery = useQuery({
+ ...buildDraftQueryOptions,
+ enabled: !isViewingVersion && soulSourceOverride !== 'draft' && soulSourceOverride !== 'view-version',
+ queryFn: async (context) => {
+ try {
+ const queryOptions = shouldSilenceBuildDraftCheckRef.current
+ ? silentBuildDraftQueryOptions
+ : buildDraftQueryOptions
+
+ shouldSilenceBuildDraftCheckRef.current = false
+ return await queryOptions.queryFn(context)
+ }
+ catch (error) {
+ if (isNotFoundResponse(error))
+ setSoulSourceOverride('draft')
+ throw error
+ }
+ },
+ retry: false,
+ })
+ const {
+ data: buildDraftData,
+ dataUpdatedAt: buildDraftDataUpdatedAt,
+ error: buildDraftError,
+ isError: isBuildDraftError,
+ isPending: isBuildDraftPending,
+ refetch: refetchBuildDraft,
+ } = buildDraftQuery
+ const buildDraftNotFound = isNotFoundResponse(buildDraftError)
+ const soulSource: AgentConfigureSoulSource = isViewingVersion
+ ? 'view-version'
+ : soulSourceOverride ?? (!buildDraftNotFound && !!buildDraftData && !isBuildDraftError ? 'build-draft' : 'draft')
+ const isBuildDraftActive = soulSource === 'build-draft'
+ const buildDraftAgentSoulConfig = buildDraftData?.agent_soul as AgentSoulConfig | undefined
+ const visibleAgentSoulConfig = isBuildDraftActive ? buildDraftAgentSoulConfig : normalAgentSoulConfig
+ const buildDraftChangesCount = useMemo(() => {
+ if (!buildDraftAgentSoulConfig || !composerAgentSoulConfig)
+ return 0
+
+ const normalDraft = agentSoulConfigToFormState(composerAgentSoulConfig)
+ const buildDraft = agentSoulConfigToFormState(buildDraftAgentSoulConfig)
+
+ return (Object.keys(buildDraft) as Array<keyof typeof buildDraft>)
+ .filter(key => JSON.stringify(buildDraft[key]) !== JSON.stringify(normalDraft[key]))
+ .length
+ }, [buildDraftAgentSoulConfig, composerAgentSoulConfig])
+
+ return {
+ activeVersionId: isBuildDraftActive ? `build-draft:${buildDraftDataUpdatedAt}` : activeVersionId,
+ agentSoulConfig: visibleAgentSoulConfig,
+ changesCount: buildDraftChangesCount,
+ isActive: isBuildDraftActive,
+ isPending: !isViewingVersion && soulSourceOverride !== 'draft' && soulSourceOverride !== 'view-version' && isBuildDraftPending,
+ refetch: refetchBuildDraft,
+ setSoulSourceOverride,
+ soulSource,
+ }
+}
+
+export function useAgentConfigureBuildDraftActions({
+ agentId,
+ isActive,
+ refetchBuildDraft,
+ refetchComposer,
+ resetBuildChatSession,
+ saveDraft,
+ onComposerRebased,
+ setSoulSourceOverride,
+}: {
+ agentId: string
+ isActive: boolean
+ refetchBuildDraft: () => Promise<unknown>
+ refetchComposer: () => Promise<unknown>
+ resetBuildChatSession: () => Promise<void>
+ saveDraft: () => Promise<void>
+ onComposerRebased?: () => void
+ setSoulSourceOverride: (source: AgentConfigureSoulSource | null) => void
+}) {
+ const { t: tCommon } = useTranslation('common')
+ const queryClient = useQueryClient()
+ const buildDraftRefreshTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
+ const buildDraftQueryOptions = consoleQuery.agent.byAgentId.buildDraft.get.queryOptions({
+ input: {
+ params: {
+ agent_id: agentId,
+ },
+ },
+ })
+ const applyBuildDraftMutation = useMutation(consoleQuery.agent.byAgentId.buildDraft.apply.post.mutationOptions())
+ const discardBuildDraftMutation = useMutation(consoleQuery.agent.byAgentId.buildDraft.delete.mutationOptions())
+ const { mutateAsync: applyBuildDraftRequest, isPending: isApplyingBuildDraft } = applyBuildDraftMutation
+ const { mutateAsync: discardBuildDraftRequest, isPending: isDiscardingBuildDraft } = discardBuildDraftMutation
+ const { prepareBuildDraftBeforeRun } = usePrepareAgentBuildDraftBeforeRun({
+ agentId,
+ isBuildDraftActive: isActive,
+ saveDraft,
+ setSoulSourceOverride,
+ })
+
+ const refreshBuildDraftAfterBuildChat = useCallback((onRefreshed?: () => void) => {
+ if (buildDraftRefreshTimerRef.current)
+ clearTimeout(buildDraftRefreshTimerRef.current)
+
+ buildDraftRefreshTimerRef.current = setTimeout(async () => {
+ buildDraftRefreshTimerRef.current = null
+ await refetchBuildDraft()
+ onRefreshed?.()
+ }, 1000)
+ }, [refetchBuildDraft])
+
+ const exitBuildDraftMode = useCallback(async (shouldRefetchComposer: boolean) => {
+ await resetBuildChatSession().catch(() => undefined)
+ setSoulSourceOverride('draft')
+ queryClient.removeQueries({
+ queryKey: buildDraftQueryOptions.queryKey,
+ })
+ if (shouldRefetchComposer) {
+ await refetchComposer()
+ onComposerRebased?.()
+ }
+ }, [buildDraftQueryOptions.queryKey, onComposerRebased, queryClient, refetchComposer, resetBuildChatSession, setSoulSourceOverride])
+
+ const applyBuildDraft = async () => {
+ try {
+ await applyBuildDraftRequest({
+ params: {
+ agent_id: agentId,
+ },
+ })
+ await exitBuildDraftMode(true)
+ toast.success(tCommon('api.actionSuccess'))
+ }
+ catch {
+ toast.error(tCommon('api.actionFailed'))
+ }
+ }
+
+ const discardBuildDraft = async () => {
+ try {
+ await discardBuildDraftRequest({
+ params: {
+ agent_id: agentId,
+ },
+ })
+ await exitBuildDraftMode(false)
+ toast.success(tCommon('api.actionSuccess'))
+ }
+ catch {
+ toast.error(tCommon('api.actionFailed'))
+ }
+ }
+
+ useEffect(() => {
+ return () => {
+ if (buildDraftRefreshTimerRef.current)
+ clearTimeout(buildDraftRefreshTimerRef.current)
+ }
+ }, [])
+
+ return {
+ applyBuildDraft,
+ discardBuildDraft,
+ isApplyingBuildDraft,
+ isDiscardingBuildDraft,
+ prepareBuildDraftBeforeRun,
+ refreshBuildDraftAfterBuildChat,
+ }
+}
diff --git a/web/features/agent-v2/agent-detail/configure/use-agent-configure-sync.ts b/web/features/agent-v2/agent-detail/configure/use-agent-configure-sync.ts
index 3987df0e16b..8b34801f177 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
@@ -1,13 +1,17 @@
'use client'
-import type { AgentSoulConfig, ComposerSaveStrategy } from '@dify/contracts/api/console/agent/types.gen'
+import type { AgentAppDetailWithSite, AgentSoulConfig } from '@dify/contracts/api/console/agent/types.gen'
import type { DefaultModel } from '@/app/components/header/account-setting/model-provider-page/declarations'
+import type { AgentSoulConfigFormState } from '@/features/agent-v2/agent-composer/form-state'
+import { toast } from '@langgenius/dify-ui/toast'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { debounce } from 'es-toolkit/compat'
import { useSetAtom, useStore } from 'jotai'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import { useTranslation } from 'react-i18next'
import { useSerialAsyncCallback } from '@/app/components/workflow/hooks/use-serial-async-callback'
-import { agentSoulConfigToFormState, formStateToAgentSoulConfig } from '@/features/agent-v2/agent-composer/conversions'
+import { formStateToAgentSoulConfig } from '@/features/agent-v2/agent-composer/conversions'
+import { validateKnowledgeRetrievals } from '@/features/agent-v2/agent-composer/knowledge-validation'
import {
agentComposerDraftAtom,
agentComposerOriginalConfigAtom,
@@ -19,9 +23,10 @@ import { consoleQuery } from '@/service/client'
const DRAFT_AUTOSAVE_WAIT = 5000
-type AgentConfigurePublishPayload = {
- agent_id: string
- config_snapshot: AgentSoulConfig
+class InvalidKnowledgeConfigurationError extends Error {
+ constructor() {
+ super('Agent knowledge retrieval configuration is invalid.')
+ }
}
export function useAgentConfigureSync({
@@ -35,16 +40,19 @@ export function useAgentConfigureSync({
currentModel?: DefaultModel
enabled: boolean
}) {
+ const { t: tCommon } = useTranslation('common')
const queryClient = useQueryClient()
const store = useStore()
const setOriginalConfig = useSetAtom(agentComposerOriginalConfigAtom)
const setOriginalDraft = useSetAtom(agentComposerOriginalDraftAtom)
const setPublishedDraft = useSetAtom(agentComposerPublishedDraftAtom)
const [draftSavedAt, setDraftSavedAt] = useState<number | undefined>(undefined)
+ const [isPublishInFlight, setIsPublishInFlight] = useState(false)
const baseConfigRef = useRef(baseConfig)
const currentModelRef = useRef(currentModel)
const enabledRef = useRef(enabled)
const lastAutosavedDraftKeyRef = useRef<string | undefined>(undefined)
+ const publishInFlightRef = useRef(false)
baseConfigRef.current = baseConfig
currentModelRef.current = currentModel
@@ -56,44 +64,8 @@ export function useAgentConfigureSync({
currentModel: currentModelRef.current,
}), [store])
- 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 composerMutation = saveStrategy === 'save_as_new_version'
- ? publishComposerMutation
- : saveComposerMutation
- const composerState = await composerMutation.mutateAsync({
- params: {
- agent_id: agentId,
- },
- body: {
- variant: 'agent_app',
- save_strategy: saveStrategy,
- agent_soul: configSnapshot,
- },
- })
-
- if (saveStrategy === 'save_to_current_version') {
- setOriginalDraft(agentSoulConfigToFormState(configSnapshot))
- setDraftSavedAt(Date.now())
- lastAutosavedDraftKeyRef.current = savedDraftKey
- return
- }
-
- queryClient.setQueryData(
- consoleQuery.agent.byAgentId.composer.get.queryKey({ input: { params: { agent_id: agentId } } }),
- composerState,
- )
- queryClient.setQueryData(
+ const markActiveConfigUnpublished = useCallback(() => {
+ queryClient.setQueryData<AgentAppDetailWithSite | undefined>(
consoleQuery.agent.byAgentId.get.queryKey({ input: { params: { agent_id: agentId } } }),
(agentDetail) => {
if (!agentDetail)
@@ -101,23 +73,66 @@ export function useAgentConfigureSync({
return {
...agentDetail,
- active_config_is_published: true,
+ active_config_is_published: false,
}
},
)
- void queryClient.invalidateQueries({
- queryKey: consoleQuery.agent.byAgentId.versions.get.key(),
- })
- setOriginalConfig(composerState.agent_soul)
- const publishedDraft = agentSoulConfigToFormState(composerState.agent_soul)
- setOriginalDraft(publishedDraft)
- setPublishedDraft(publishedDraft)
+ }, [agentId, queryClient])
+
+ const {
+ mutateAsync: saveComposerDraft,
+ } = useMutation(
+ consoleQuery.agent.byAgentId.composer.put.mutationOptions(),
+ )
+ const {
+ isPending: isPublishingAgent,
+ mutateAsync: publishAgent,
+ } = useMutation(
+ consoleQuery.agent.byAgentId.publish.post.mutationOptions(),
+ )
+
+ const saveComposer = useSerialAsyncCallback(async ({
+ configSnapshot,
+ draftBaseline,
+ }: {
+ configSnapshot: AgentSoulConfig
+ draftBaseline: AgentSoulConfigFormState
+ }) => {
+ const savedDraftKey = JSON.stringify(configSnapshot)
+ try {
+ await saveComposerDraft({
+ params: {
+ agent_id: agentId,
+ },
+ body: {
+ variant: 'agent_app',
+ save_strategy: 'save_to_current_version',
+ agent_soul: configSnapshot,
+ },
+ })
+ }
+ catch {
+ // Draft sync follows workflow autosave behavior: save failures are silent and keep the local draft intact.
+ return false
+ }
+
+ markActiveConfigUnpublished()
+ setOriginalDraft(draftBaseline)
+ setDraftSavedAt(Date.now())
lastAutosavedDraftKeyRef.current = savedDraftKey
+ return true
})
const latestDraftSaveRef = useRef<() => void>(() => undefined)
latestDraftSaveRef.current = () => {
- void saveComposer('save_to_current_version', getAgentSoulDraft())
+ const draft = store.get(agentComposerDraftAtom)
+ if (!validateKnowledgeRetrievals(draft.knowledgeRetrievals).isValid)
+ return
+
+ void saveComposer({
+ configSnapshot: getAgentSoulDraft(),
+ draftBaseline: draft,
+ })
}
const debouncedSaveDraft = useMemo(() => debounce(() => {
@@ -128,18 +143,34 @@ export function useAgentConfigureSync({
if (!enabledRef.current)
return
+ const draft = store.get(agentComposerDraftAtom)
+ if (!validateKnowledgeRetrievals(draft.knowledgeRetrievals).isValid)
+ throw new InvalidKnowledgeConfigurationError()
+
debouncedSaveDraft.cancel?.()
- await saveComposer('save_to_current_version', getAgentSoulDraft())
- }, [debouncedSaveDraft, getAgentSoulDraft, saveComposer])
+ await saveComposer({
+ configSnapshot: getAgentSoulDraft(),
+ draftBaseline: draft,
+ })
+ }, [debouncedSaveDraft, getAgentSoulDraft, saveComposer, store])
useEffect(() => {
return store.sub(agentComposerDraftAtom, () => {
const agentSoulDraft = getAgentSoulDraft()
const agentSoulDraftKey = JSON.stringify(agentSoulDraft)
+ const isDirty = store.get(isAgentComposerDirtyAtom)
if (
!enabledRef.current
- || !store.get(isAgentComposerDirtyAtom)
+ || !isDirty
+ ) {
+ return
+ }
+
+ markActiveConfigUnpublished()
+
+ if (
+ !validateKnowledgeRetrievals(store.get(agentComposerDraftAtom).knowledgeRetrievals).isValid
|| lastAutosavedDraftKeyRef.current === agentSoulDraftKey
) {
return
@@ -147,7 +178,7 @@ export function useAgentConfigureSync({
debouncedSaveDraft()
})
- }, [debouncedSaveDraft, getAgentSoulDraft, store])
+ }, [debouncedSaveDraft, getAgentSoulDraft, markActiveConfigUnpublished, store])
useEffect(() => {
return () => {
@@ -155,19 +186,69 @@ export function useAgentConfigureSync({
}
}, [debouncedSaveDraft])
- const publishDraft = useCallback(async (payload: AgentConfigurePublishPayload) => {
- debouncedSaveDraft.cancel?.()
+ const publishDraft = useCallback(async () => {
+ if (publishInFlightRef.current)
+ return
+
+ const draft = store.get(agentComposerDraftAtom)
+ if (!validateKnowledgeRetrievals(draft.knowledgeRetrievals).isValid)
+ throw new InvalidKnowledgeConfigurationError()
+
+ publishInFlightRef.current = true
+ setIsPublishInFlight(true)
try {
- await saveComposer('save_as_new_version', payload.config_snapshot)
+ debouncedSaveDraft.cancel?.()
+ const configSnapshot = formStateToAgentSoulConfig({
+ baseConfig: baseConfigRef.current,
+ formState: draft,
+ currentModel: currentModelRef.current,
+ })
+ const saved = await saveComposer({
+ configSnapshot,
+ draftBaseline: draft,
+ })
+ if (!saved)
+ return
+
+ await publishAgent({
+ params: {
+ agent_id: agentId,
+ },
+ body: {},
+ })
+ queryClient.setQueryData(
+ consoleQuery.agent.byAgentId.get.queryKey({ input: { params: { agent_id: agentId } } }),
+ (agentDetail) => {
+ if (!agentDetail)
+ return agentDetail
+
+ return {
+ ...agentDetail,
+ active_config_is_published: true,
+ }
+ },
+ )
+ 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(),
+ })
+ setOriginalConfig(configSnapshot)
+ const publishedDraft = draft
+ setOriginalDraft(publishedDraft)
+ setPublishedDraft(publishedDraft)
+ toast.success(tCommon('api.actionSuccess'))
}
- catch {
- // Draft sync follows workflow autosave behavior: save failures are silent and keep the local draft intact.
+ finally {
+ publishInFlightRef.current = false
+ setIsPublishInFlight(false)
}
- }, [debouncedSaveDraft, saveComposer])
+ }, [agentId, debouncedSaveDraft, publishAgent, queryClient, saveComposer, setOriginalConfig, setOriginalDraft, setPublishedDraft, store, tCommon])
return {
draftSavedAt,
- isPublishing: publishComposerMutation.isPending,
+ isPublishing: isPublishInFlight || isPublishingAgent,
publishDraft,
saveDraft,
}
diff --git a/web/features/agent-v2/agent-detail/navigation.tsx b/web/features/agent-v2/agent-detail/navigation.tsx
index 44295e2ff31..3f68a409702 100644
--- a/web/features/agent-v2/agent-detail/navigation.tsx
+++ b/web/features/agent-v2/agent-detail/navigation.tsx
@@ -47,8 +47,8 @@ const createAgentNavIcon = (iconClassName: string) => {
return AgentNavIcon
}
-const terminalWindowLineIcon = createAgentNavIcon('i-ri-terminal-window-line')
-const terminalWindowFillIcon = createAgentNavIcon('i-ri-terminal-window-fill')
+const configureIcon = createAgentNavIcon('i-custom-vender-agent-v2-configure')
+const configureActiveIcon = createAgentNavIcon('i-custom-vender-agent-v2-configure-active')
const accessPointIcon = createAgentNavIcon('i-custom-vender-agent-v2-access-point')
const fileListLineIcon = createAgentNavIcon('i-ri-file-list-3-line')
const fileListFillIcon = createAgentNavIcon('i-ri-file-list-3-fill')
@@ -59,8 +59,8 @@ const getAgentDetailNavigation = (agentId: string): AgentDetailNavItem[] => [
{
labelKey: 'agentDetail.sections.configure',
href: getAgentDetailPath(agentId, 'configure'),
- icon: terminalWindowLineIcon,
- activeIcon: terminalWindowFillIcon,
+ icon: configureIcon,
+ activeIcon: configureActiveIcon,
},
{
labelKey: 'agentDetail.sections.access',
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.tsx
index 559cfb41f1b..3c06e441635 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, waitFor, within } from '@testing-library/react'
+import { act, render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { CreateAgentDialog } from '../create-agent-dialog'
@@ -12,6 +12,8 @@ const toastMock = vi.hoisted(() => ({
success: vi.fn(),
}))
+const routerPushMock = vi.hoisted(() => vi.fn())
+
vi.mock('@tanstack/react-query', () => ({
useMutation: () => ({
isPending: mutationMock.isPending,
@@ -23,6 +25,12 @@ vi.mock('@langgenius/dify-ui/toast', () => ({
toast: toastMock,
}))
+vi.mock('@/next/navigation', () => ({
+ useRouter: () => ({
+ push: routerPushMock,
+ }),
+}))
+
vi.mock('@/service/client', () => ({
consoleQuery: {
agent: {
@@ -67,6 +75,26 @@ describe('CreateAgentDialog', () => {
expect(mutationOptions).not.toHaveProperty('onError')
})
+ it('navigates to the new agent configure page after creating an agent', async () => {
+ const user = userEvent.setup()
+ render(<CreateAgentDialog />)
+
+ await user.click(screen.getByRole('button', { name: /agentV2\.roster\.createAgent/ }))
+
+ const dialog = await screen.findByRole('dialog', { name: 'agentV2.roster.createDialog.title' })
+ await user.type(within(dialog).getByRole('textbox', { name: 'agentV2.roster.createForm.nameLabel' }), 'Research Agent')
+ await user.type(within(dialog).getByRole('textbox', { name: 'agentV2.roster.createForm.roleLabel' }), 'Research Assistant')
+ await user.click(within(dialog).getByRole('button', { name: 'common.operation.create' }))
+
+ const mutationOptions = mutationMock.mutate.mock.calls[0]?.[1]
+ await act(async () => {
+ mutationOptions.onSuccess({ id: 'agent-1' })
+ })
+
+ expect(toastMock.success).toHaveBeenCalledWith('agentV2.roster.createSuccess')
+ expect(routerPushMock).toHaveBeenCalledWith('/roster/agent/agent-1/configure')
+ })
+
it('shows a field error when creating with an empty name', async () => {
const user = userEvent.setup()
render(<CreateAgentDialog />)
diff --git a/web/features/agent-v2/roster/components/__tests__/roster-toolbar.spec.tsx b/web/features/agent-v2/roster/components/__tests__/roster-toolbar.spec.tsx
index 6b215aa1b3c..7756f2cc23e 100644
--- a/web/features/agent-v2/roster/components/__tests__/roster-toolbar.spec.tsx
+++ b/web/features/agent-v2/roster/components/__tests__/roster-toolbar.spec.tsx
@@ -1,9 +1,15 @@
import type { RosterFilterValue } from '../roster-filter'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
-import { render, screen } from '@testing-library/react'
+import { render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { RosterToolbar } from '../roster-toolbar'
+vi.mock('@/next/navigation', () => ({
+ useRouter: () => ({
+ push: vi.fn(),
+ }),
+}))
+
const renderToolbar = ({
filter = 'all',
onFilterChange = vi.fn(),
@@ -48,16 +54,12 @@ describe('RosterToolbar', () => {
it('renders stable filter count badges and omits the all count', () => {
renderToolbar()
- expect(screen.getByRole('button', { name: /agentV2\.roster\.filters\.all/ })).not.toHaveTextContent('3')
-
- expect(screen.getByText('1').parentElement).toHaveClass(
- 'min-w-4',
- 'shrink-0',
- 'border-divider-deep',
- 'py-0.5',
- 'system-2xs-medium-uppercase',
- 'tabular-nums',
- )
- expect(screen.getByText('1')).toHaveClass('min-w-px', 'flex-1', 'text-center')
+ const allFilter = screen.getByRole('button', { name: /agentV2\.roster\.filters\.all/ })
+ const publishedFilter = screen.getByRole('button', { name: /agentV2\.roster\.filters\.published/ })
+ const draftsFilter = screen.getByRole('button', { name: /agentV2\.roster\.filters\.drafts/ })
+
+ expect(allFilter).not.toHaveTextContent('3')
+ expect(within(publishedFilter).getByText('1')).toBeInTheDocument()
+ expect(within(draftsFilter).getByText('2')).toBeInTheDocument()
})
})
diff --git a/web/features/agent-v2/roster/components/agent-form.ts b/web/features/agent-v2/roster/components/agent-form.ts
index cf738afbb31..93ec852d776 100644
--- a/web/features/agent-v2/roster/components/agent-form.ts
+++ b/web/features/agent-v2/roster/components/agent-form.ts
@@ -1,4 +1,3 @@
-import type { AgentAppPartial } from '@dify/contracts/api/console/agent/types.gen'
import type { AppIconSelection } from '@/app/components/base/app-icon-picker'
export type AgentFormValues = {
@@ -19,7 +18,13 @@ export const defaultAgentIcon = {
background: '#F5F3FF',
} satisfies AppIconSelection
-export const createAgentIconSelection = (agent: AgentAppPartial): AgentIconSelection => {
+type AgentIconSource = {
+ icon?: string | null
+ icon_background?: string | null
+ icon_type?: string | null
+}
+
+export const createAgentIconSelection = (agent: AgentIconSource): AgentIconSelection => {
if (agent.icon_type === 'image' && agent.icon) {
return {
type: 'image',
diff --git a/web/features/agent-v2/roster/components/agent-roster-list.tsx b/web/features/agent-v2/roster/components/agent-roster-list.tsx
index 46f36effd9c..9dd4cd43d10 100644
--- a/web/features/agent-v2/roster/components/agent-roster-list.tsx
+++ b/web/features/agent-v2/roster/components/agent-roster-list.tsx
@@ -43,19 +43,21 @@ function AgentRosterSkeleton() {
{skeletonRows.map(row => (
<div key={row} className="relative h-36.5 rounded-xl border-[0.5px] border-components-card-border bg-components-card-bg shadow-xs shadow-shadow-shadow-3">
<div className="flex items-center gap-3 pt-3.5 pr-4 pb-2 pl-3.5">
- <SkeletonRectangle className="my-0 size-12 shrink-0 animate-pulse rounded-full" />
- <div className="min-w-0 flex-1 space-y-2.5 py-px">
- <SkeletonRectangle className="my-0 h-4 w-36 max-w-full animate-pulse rounded-md" />
- <SkeletonRectangle className="my-0 h-3 w-20 max-w-full animate-pulse rounded-md" />
+ <SkeletonRectangle className="my-0 size-12 shrink-0 rounded-full opacity-20" />
+ <div className="flex min-w-0 flex-1 flex-col gap-1.5 py-1">
+ <SkeletonRectangle className="my-0 h-3 w-36 max-w-full rounded-md opacity-20" />
+ <SkeletonRectangle className="my-0 h-2 w-20 max-w-full rounded-md opacity-12" />
</div>
</div>
<div className="px-4 py-1">
- <SkeletonRectangle className="my-0 h-3 w-full animate-pulse rounded-md" />
- <SkeletonRectangle className="mt-2 mb-0 h-3 w-3/4 animate-pulse rounded-md" />
+ <div className="flex min-h-8 flex-col gap-2 py-0.5">
+ <SkeletonRectangle className="my-0 h-2 w-full rounded-md opacity-12" />
+ <SkeletonRectangle className="my-0 h-2 w-3/4 rounded-md opacity-10" />
+ </div>
</div>
<div className="flex items-center pt-2 pr-3 pb-3 pl-4">
- <SkeletonRectangle className="my-0 h-4 w-6 animate-pulse rounded-md" />
- <SkeletonRectangle className="my-0 ml-2.5 h-4 w-28 animate-pulse rounded-md" />
+ <SkeletonRectangle className="my-0 h-3 w-6 rounded-md opacity-12" />
+ <SkeletonRectangle className="my-0 ml-2.5 h-3 w-28 rounded-md opacity-10" />
</div>
</div>
))}
diff --git a/web/features/agent-v2/roster/components/create-agent-dialog.tsx b/web/features/agent-v2/roster/components/create-agent-dialog.tsx
index 8d31016c54c..e515184091e 100644
--- a/web/features/agent-v2/roster/components/create-agent-dialog.tsx
+++ b/web/features/agent-v2/roster/components/create-agent-dialog.tsx
@@ -10,13 +10,16 @@ import { useMutation } from '@tanstack/react-query'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import AppIconPicker from '@/app/components/base/app-icon-picker'
+import { useRouter } from '@/next/navigation'
import { consoleQuery } from '@/service/client'
+import { getAgentDetailPath } from '../../agent-detail/routes'
import { defaultAgentIcon } from './agent-form'
import { AgentFormFields } from './agent-form-fields'
export function CreateAgentDialog() {
const { t } = useTranslation('agentV2')
const { t: tCommon } = useTranslation('common')
+ const router = useRouter()
const [open, setOpen] = useState(false)
const [formKey, setFormKey] = useState(0)
const [name, setName] = useState('')
@@ -59,9 +62,10 @@ export function CreateAgentDialog() {
createAgentMutation.mutate({
body,
}, {
- onSuccess: () => {
+ onSuccess: (createdAgent) => {
toast.success(t('roster.createSuccess'))
handleOpenChange(false)
+ router.push(getAgentDetailPath(createdAgent.id, 'configure'))
},
})
}
diff --git a/web/hooks/use-timestamp.spec.ts b/web/hooks/use-timestamp.spec.ts
index 22fb5f50163..ab8127b88ce 100644
--- a/web/hooks/use-timestamp.spec.ts
+++ b/web/hooks/use-timestamp.spec.ts
@@ -1,4 +1,8 @@
+import type { ReactNode } from 'react'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { renderHook } from '@testing-library/react'
+import { createElement } from 'react'
+import { userProfileQueryOptions } from '@/features/account-profile/client'
import { createAccountProfileQueryWrapper } from '@/test/account-profile-query'
import useTimestamp from './use-timestamp'
@@ -21,6 +25,22 @@ vi.mock('@/context/app-context', () => ({
})),
}))
+const createEmptyQueryWrapper = () => {
+ const queryClient = new QueryClient({
+ defaultOptions: {
+ queries: {
+ retry: false,
+ },
+ },
+ })
+
+ function EmptyQueryWrapper({ children }: { children: ReactNode }) {
+ return createElement(QueryClientProvider, { client: queryClient }, children)
+ }
+
+ return { queryClient, wrapper: EmptyQueryWrapper }
+}
+
describe('useTimestamp', () => {
describe('formatTime', () => {
it('should format unix timestamp correctly', () => {
@@ -63,4 +83,14 @@ describe('useTimestamp', () => {
.toBe('20:00')
})
})
+
+ it('should not request account profile when timezone is provided', () => {
+ const { queryClient, wrapper } = createEmptyQueryWrapper()
+
+ const { result } = renderHook(() => useTimestamp({ timezone: 'UTC' }), { wrapper })
+
+ expect(result.current.formatTime(1704132000, 'YYYY-MM-DD HH:mm')).toBe('2024-01-01 18:00')
+ expect(queryClient.isFetching({ queryKey: userProfileQueryOptions().queryKey })).toBe(0)
+ expect(queryClient.getQueryState(userProfileQueryOptions().queryKey)?.fetchStatus).toBe('idle')
+ })
})
diff --git a/web/hooks/use-timestamp.ts b/web/hooks/use-timestamp.ts
index a872b4c8528..96eeae9dd52 100644
--- a/web/hooks/use-timestamp.ts
+++ b/web/hooks/use-timestamp.ts
@@ -9,19 +9,29 @@ import { userProfileQueryOptions } from '@/features/account-profile/client'
dayjs.extend(utc)
dayjs.extend(timezone)
-const useTimestamp = () => {
- const { data: timezone } = useQuery({
+type UseTimestampOptions = {
+ timezone?: string
+}
+
+const getBrowserTimezone = () => {
+ return Intl.DateTimeFormat().resolvedOptions().timeZone
+}
+
+const useTimestamp = ({ timezone: timezoneOverride }: UseTimestampOptions = {}) => {
+ const { data: accountTimezone } = useQuery({
...userProfileQueryOptions(),
select: data => data.profile.timezone ?? undefined,
+ enabled: timezoneOverride === undefined,
})
+ const resolvedTimezone = timezoneOverride ?? accountTimezone ?? getBrowserTimezone()
const formatTime = useCallback((value: number, format: string) => {
- return dayjs.unix(value).tz(timezone).format(format)
- }, [timezone])
+ return dayjs.unix(value).tz(resolvedTimezone).format(format)
+ }, [resolvedTimezone])
const formatDate = useCallback((value: string, format: string) => {
- return dayjs(value).tz(timezone).format(format)
- }, [timezone])
+ return dayjs(value).tz(resolvedTimezone).format(format)
+ }, [resolvedTimezone])
return { formatTime, formatDate }
}
diff --git a/web/i18n/ar-TN/agent-v-2.json b/web/i18n/ar-TN/agent-v-2.json
index 9c196dc9f89..6cad6af8872 100644
--- a/web/i18n/ar-TN/agent-v-2.json
+++ b/web/i18n/ar-TN/agent-v-2.json
@@ -49,14 +49,27 @@
"agentDetail.configure.advancedSettings.envEditor.keyPlaceholder": "Key",
"agentDetail.configure.advancedSettings.envEditor.label": "Env Editor",
"agentDetail.configure.advancedSettings.envEditor.revealValue": "إظهار قيمة {{key}}",
+ "agentDetail.configure.advancedSettings.envEditor.richTip": "يعمل وكيلك في بيئة Linux. يمكنك إعداد التكوينات أو الأسرار مسبقًا بتعريف متغيرات البيئة هنا.\n\nبدلاً من ذلك، يمكنك دائمًا إعداد الأشياء عبر محادثة Build. راجع <docLink>المستندات</docLink>.",
"agentDetail.configure.advancedSettings.envEditor.scopeColumn": "Scope",
"agentDetail.configure.advancedSettings.envEditor.scopePlain": "Plain",
"agentDetail.configure.advancedSettings.envEditor.scopeSecret": "Secret",
"agentDetail.configure.advancedSettings.envEditor.scopeSelector": "اختر نطاق متغير البيئة",
- "agentDetail.configure.advancedSettings.envEditor.tip": "متغيرات البيئة المتاحة لهذا الوكيل في وقت التشغيل.",
+ "agentDetail.configure.advancedSettings.envEditor.tip": "يعمل وكيلك في بيئة Linux. يمكنك إعداد التكوينات أو الأسرار مسبقًا بتعريف متغيرات البيئة هنا. بدلاً من ذلك، يمكنك دائمًا إعداد الأشياء عبر محادثة Build. راجع المستندات.",
+ "agentDetail.configure.advancedSettings.envEditor.toggle": "تبديل Env Editor",
"agentDetail.configure.advancedSettings.envEditor.valueColumn": "Value",
"agentDetail.configure.advancedSettings.envEditor.valuePlaceholder": "Value",
"agentDetail.configure.advancedSettings.label": "الإعدادات المتقدمة",
+ "agentDetail.configure.advancedSettings.toggle": "تبديل الإعدادات المتقدمة",
+ "agentDetail.configure.build.empty.description": "صِف ما تريده وسيتم ملء النموذج على اليسار أثناء المحادثة.",
+ "agentDetail.configure.build.empty.title": "ابنِ وكيلك عبر الدردشة",
+ "agentDetail.configure.build.inputPlaceholder": "صِف ما يجب أن يفعله وكيلك",
+ "agentDetail.configure.build.startBuild": "ابدأ البناء",
+ "agentDetail.configure.buildDraft.changes": "{{count}} تغييرات للتطبيق",
+ "agentDetail.configure.buildDraft.discard": "تجاهل",
+ "agentDetail.configure.buildDraft.modeBadge": "وضع البناء",
+ "agentDetail.configure.buildDraft.modeDescription": "أنت في وضع البناء. شكّل هذا الإعداد عبر الدردشة على اليمين، ثم طبّق.",
+ "agentDetail.configure.buildDraft.noChanges": "لا توجد تغييرات للتطبيق",
+ "agentDetail.configure.buildDraft.title": "مسودة البناء",
"agentDetail.configure.chatFeatures.description": "شكّل تجربة الدردشة للمستخدم النهائي على Web app وأسطح الدردشة.",
"agentDetail.configure.chatFeatures.title": "ميزات الدردشة",
"agentDetail.configure.files.add": "إضافة ملف",
@@ -67,7 +80,8 @@
"agentDetail.configure.files.preview.failed": "فشل تحميل المعاينة.",
"agentDetail.configure.files.preview.unsupported": "هذا الملف لا يدعم المعاينة.",
"agentDetail.configure.files.remove": "إزالة {{name}}",
- "agentDetail.configure.files.tip": "الملفات التي يمكن لهذا الوكيل استخدامها أثناء تنسيق المهام.",
+ "agentDetail.configure.files.tip": "زوّد وكيلك بأي مثال أو إرشاد أو مجرد حامل للمعلومات يكون طويلاً جداً بحيث لا يناسب البرومبت. أشر إليه صراحةً باستخدام / في البرومبت.",
+ "agentDetail.configure.files.toggle": "تبديل الملفات",
"agentDetail.configure.files.treeLabel": "ملفات الوكيل",
"agentDetail.configure.files.upload.action": "تحميل",
"agentDetail.configure.files.upload.browse": "استعراض",
@@ -113,8 +127,11 @@
"agentDetail.configure.orchestrate": "تنسيق",
"agentDetail.configure.preview.chatFeatures": "ميزات الدردشة",
"agentDetail.configure.preview.empty.defaultAgentName": "وكيل",
- "agentDetail.configure.preview.empty.description": "أرسل رسالة لاختبار المسودة الحالية.",
+ "agentDetail.configure.preview.empty.description": "شغّل الوكيل كمحادثة مكتملة، تمامًا كما سيختبرها المستخدمون بعد النشر.",
"agentDetail.configure.preview.empty.noInstructionsDescription": "لا توجد تعليمات بعد، لذلك تأتي الردود من النموذج البسيط.",
+ "agentDetail.configure.preview.empty.title": "معاينة {{name}}",
+ "agentDetail.configure.preview.endUserAuth": "مصادقة المستخدم النهائي",
+ "agentDetail.configure.preview.inputPlaceholder": "إرسال رسالة إلى {{name}}",
"agentDetail.configure.preview.restart": "إعادة تشغيل المعاينة",
"agentDetail.configure.preview.title": "معاينة",
"agentDetail.configure.prompt.copied": "تم نسخ المطالبة",
@@ -128,7 +145,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "اكتب التعليمات هنا،",
- "agentDetail.configure.prompt.tip": "حدّد كيف يجب أن يفسر هذا الوكيل المدخلات، ويستدعي الأدوات، وينتج المخرجات.",
+ "agentDetail.configure.prompt.tip": "عرّف دور الوكيل وصف مهمته المعتادة. استخدم / للإشارة صراحةً إلى المهارات والملفات والأدوات واسترجاع المعرفة.",
"agentDetail.configure.publishBar.draft": "مسودة",
"agentDetail.configure.publishBar.publishUpdate": "نشر التحديث",
"agentDetail.configure.publishBar.published": "تم النشر",
@@ -147,6 +164,14 @@
"agentDetail.configure.publishImpact.title": "{{action}} إلى {{name}}",
"agentDetail.configure.publishImpact.workflowCount_one": "{{count}} سير عمل",
"agentDetail.configure.publishImpact.workflowCount_other": "{{count}} سير عمل",
+ "agentDetail.configure.rightPanel.build": "بناء",
+ "agentDetail.configure.rightPanel.buildTipBody": "يضبط Build الوكيل عبر الدردشة. صف ما تريده وسيملأ الإعدادات على اليسار.",
+ "agentDetail.configure.rightPanel.buildTipTitle": "ابنِ وكيلك عبر الدردشة",
+ "agentDetail.configure.rightPanel.learnMore": "معرفة المزيد",
+ "agentDetail.configure.rightPanel.modeLabel": "وضع تكوين الوكيل",
+ "agentDetail.configure.rightPanel.preview": "معاينة",
+ "agentDetail.configure.rightPanel.previewTipBody": "يشغل Preview الوكيل المكتمل كما سيراه المستخدمون، مع ردود واضحة وميزات الدردشة.",
+ "agentDetail.configure.rightPanel.previewTipTitle": "عاين وكيلك",
"agentDetail.configure.skills.add": "إضافة مهارة",
"agentDetail.configure.skills.detail.contentRegion": "محتوى تفاصيل المهارة",
"agentDetail.configure.skills.detail.fileCount": "{{count}} ملفات",
@@ -156,7 +181,9 @@
"agentDetail.configure.skills.itemType": "مهارة",
"agentDetail.configure.skills.label": "المهارات",
"agentDetail.configure.skills.remove": "إزالة {{name}}",
- "agentDetail.configure.skills.tip": "المهارات التي يمكن لهذا الوكيل استخدامها أثناء تنسيق المهام.",
+ "agentDetail.configure.skills.richTip": "زوّد وكيلك بقدرات معيارية. راجع <docLink>الوثائق</docLink>. أشر إليها صراحةً باستخدام / في البرومبت.",
+ "agentDetail.configure.skills.tip": "زوّد وكيلك بقدرات معيارية. راجع الوثائق. أشر إليها صراحةً باستخدام / في البرومبت.",
+ "agentDetail.configure.skills.toggle": "تبديل المهارات",
"agentDetail.configure.skills.upload.action": "تحميل",
"agentDetail.configure.skills.upload.browse": "استعراض",
"agentDetail.configure.skills.upload.description": "قم بتحميل حزمة .zip أو .skill لهذا الوكيل.",
@@ -166,6 +193,7 @@
"agentDetail.configure.skills.upload.invalidFile": "قم بتحميل ملف .zip أو .skill.",
"agentDetail.configure.skills.upload.success": "تم تحميل المهارة.",
"agentDetail.configure.skills.upload.title": "تحميل مهارة",
+ "agentDetail.configure.title": "تكوين",
"agentDetail.configure.tools.add": "إضافة أداة",
"agentDetail.configure.tools.addMenu.cliTool.badge": "للمطورين",
"agentDetail.configure.tools.addMenu.cliTool.description": "ثبّت برنامج سطر أوامر يقوم الوكيل بتشغيله في sandbox الخاص به. يحتاج إلى تثبيت وعادةً إلى API Key.",
@@ -179,7 +207,7 @@
"agentDetail.configure.tools.cliDialog.env.optional": "(اختياري)",
"agentDetail.configure.tools.cliDialog.installCommand.description": "Sandboxed · يعمل مرة واحدة عند أول استدعاء",
"agentDetail.configure.tools.cliDialog.installCommand.label": "أمر التثبيت",
- "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "الصق أمر التثبيت هنا، مثل npm install -g @lark/cli · brew install jq",
+ "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "الصق أمر التثبيت هنا، مثل npx -y @playwright/mcp@latest · uv tool install httpie",
"agentDetail.configure.tools.cliDialog.installCommand.required": "أمر التثبيت مطلوب.",
"agentDetail.configure.tools.cliDialog.learnMore": "اعرف المزيد عن أداة CLI",
"agentDetail.configure.tools.cliDialog.name.label": "اسم أداة CLI",
@@ -196,13 +224,19 @@
"agentDetail.configure.tools.moreActions": "إجراءات أخرى لـ {{name}}",
"agentDetail.configure.tools.removeAction": "إزالة {{name}}",
"agentDetail.configure.tools.removeProvider": "إزالة جميع الأدوات",
- "agentDetail.configure.tools.tip": "الأدوات التي يمكن لهذا الوكيل استدعاؤها أثناء تنسيق المهام.",
+ "agentDetail.configure.tools.richTip": "زوّد وكيلك بإضافات Dify. راجع <pluginDocLink>الوثائق</pluginDocLink>. أشر إليها صراحةً باستخدام / في البرومبت.\nبدلاً من ذلك، يمكنك دائماً إخبار الوكيل بتثبيت أدوات أخرى والمصادقة عليها (مثل MCPs وأدوات CLI) عبر دردشة Build. لاحظ أن الأدوات التي يتم تكوينها عبر دردشات Build لن تظهر هنا، لكنها ستظل متاحة لوكيلك لاحقاً. راجع <buildDocLink>الوثائق</buildDocLink>.",
+ "agentDetail.configure.tools.tip": "زوّد وكيلك بإضافات Dify. راجع الوثائق. أشر إليها صراحةً باستخدام / في البرومبت. بدلاً من ذلك، يمكنك دائماً إخبار الوكيل بتثبيت أدوات أخرى والمصادقة عليها (مثل MCPs وأدوات CLI) عبر دردشة Build. لاحظ أن الأدوات التي يتم تكوينها عبر دردشات Build لن تظهر هنا، لكنها ستظل متاحة لوكيلك لاحقاً. راجع الوثائق.",
+ "agentDetail.configure.tools.toggle": "تبديل الأدوات",
"agentDetail.configure.tools.toolTabs.all": "الكل",
"agentDetail.configure.tools.toolTabs.cli": "CLI",
"agentDetail.configure.tools.toolTabs.custom": "مخصص",
"agentDetail.configure.tools.toolTabs.mcp": "MCP",
"agentDetail.configure.tools.toolTabs.plugins": "المكونات الإضافية",
"agentDetail.configure.tools.toolTabs.workflow": "Workflow",
+ "agentDetail.configure.workingDirectory.description": "الملفات التي يقرأها الوكيل ويكتبها أثناء التشغيل. كل ما ينشئه، مثل qna_report.pdf، يظهر هنا.",
+ "agentDetail.configure.workingDirectory.open": "فتح دليل العمل",
+ "agentDetail.configure.workingDirectory.title": "دليل العمل",
+ "agentDetail.configure.workingDirectory.treeLabel": "ملفات دليل العمل",
"agentDetail.documentTitle": "وكيل",
"agentDetail.logs.description": "تسجل السجلات الكاملة حالة تشغيل التطبيق، بما في ذلك مدخلات المستخدم وردود الوكيل والتخطيط واستخدامات الأدوات.",
"agentDetail.logs.empty": "لم يتم العثور على سجلات",
@@ -279,7 +313,7 @@
"agentDetail.navigationLabel": "تنقّل الوكيل",
"agentDetail.publish": "نشر",
"agentDetail.sections.access": "نقطة الوصول",
- "agentDetail.sections.configure": "تنسيق",
+ "agentDetail.sections.configure": "تكوين",
"agentDetail.sections.logs": "السجلات",
"agentDetail.sections.monitoring": "المراقبة",
"agentDetail.title": "وكيل",
@@ -334,6 +368,11 @@
"roster.nodeSelector.startFromScratch": "البدء من الصفر",
"roster.references.label": "سير العمل الذي يستخدم {{name}}",
"roster.references.trigger": "سير العمل الذي يستخدم {{name}}",
+ "roster.saveToRoster": "Save to Agent Console",
+ "roster.saveToRosterDialog.description": "Save this inline setup as a reusable roster agent.",
+ "roster.saveToRosterDialog.title": "Save to Agent Console",
+ "roster.saveToRosterForm.changeIcon": "Change roster agent icon",
+ "roster.saveToRosterSuccess": "Agent saved to roster.",
"roster.searchLabel": "البحث عن الوكلاء",
"roster.searchPlaceholder": "ابحث عن الوكلاء بالاسم…",
"roster.tabs.agent": "وكيل",
diff --git a/web/i18n/ar-TN/common.json b/web/i18n/ar-TN/common.json
index 55b42215431..6c1a766379b 100644
--- a/web/i18n/ar-TN/common.json
+++ b/web/i18n/ar-TN/common.json
@@ -288,6 +288,7 @@
"menus.exploreMarketplace": "استكشاف السوق",
"menus.plugins": "الإضافات",
"menus.roster": "قائمة الوكلاء",
+ "menus.status": "بيتا",
"menus.tools": "الأدوات",
"model.capabilities": "قدرات متعددة الوسائط",
"model.params.stop_sequencesPlaceholder": "أدخل التسلسل واضغط على Tab",
diff --git a/web/i18n/ar-TN/workflow.json b/web/i18n/ar-TN/workflow.json
index 6e97214e2d0..1f4c5ac9c31 100644
--- a/web/i18n/ar-TN/workflow.json
+++ b/web/i18n/ar-TN/workflow.json
@@ -464,7 +464,7 @@
"nodes.agent.task.label": "مهمة الوكيل",
"nodes.agent.task.mention": "إشارة",
"nodes.agent.task.placeholder": "صف ما يجب على هذا الوكيل القيام به...",
- "nodes.agent.task.tooltip": "حدّد تعليمات المهمة التي يجب على هذا الوكيل اتباعها في سير العمل هذا.",
+ "nodes.agent.task.tooltip": "موجّه إضافي لمساعدة الوكيل على معالجة هذه العقدة بالتحديد. استخدم / للإشارة صراحةً إلى المتغيرات.\nإذا تم تكوينه بشكل صحيح، فقد تتمكن من الوثوق بالوكيل ليكتشف الأمور بنفسه.",
"nodes.agent.toolNotAuthorizedTooltip": "{{tool}} غير مخول",
"nodes.agent.toolNotInstallTooltip": "{{tool}} غير مثبت",
"nodes.agent.toolbox": "صندوق الأدوات",
diff --git a/web/i18n/de-DE/agent-v-2.json b/web/i18n/de-DE/agent-v-2.json
index d469f83c9f7..93bf09131c0 100644
--- a/web/i18n/de-DE/agent-v-2.json
+++ b/web/i18n/de-DE/agent-v-2.json
@@ -49,14 +49,27 @@
"agentDetail.configure.advancedSettings.envEditor.keyPlaceholder": "Key",
"agentDetail.configure.advancedSettings.envEditor.label": "Env Editor",
"agentDetail.configure.advancedSettings.envEditor.revealValue": "Wert von {{key}} anzeigen",
+ "agentDetail.configure.advancedSettings.envEditor.richTip": "Dein Agent läuft in einer Linux-Umgebung. Du kannst Konfigurationen oder Secrets vorab festlegen, indem du hier Umgebungsvariablen definierst.\n\nAlternativ kannst du die Einrichtung jederzeit über einen Build-Chat vornehmen. Siehe <docLink>Dokumentation</docLink>.",
"agentDetail.configure.advancedSettings.envEditor.scopeColumn": "Scope",
"agentDetail.configure.advancedSettings.envEditor.scopePlain": "Plain",
"agentDetail.configure.advancedSettings.envEditor.scopeSecret": "Secret",
"agentDetail.configure.advancedSettings.envEditor.scopeSelector": "Geltungsbereich der Umgebungsvariable auswählen",
- "agentDetail.configure.advancedSettings.envEditor.tip": "Umgebungsvariablen, die diesem Agenten zur Laufzeit zur Verfügung stehen.",
+ "agentDetail.configure.advancedSettings.envEditor.tip": "Dein Agent läuft in einer Linux-Umgebung. Du kannst Konfigurationen oder Secrets vorab festlegen, indem du hier Umgebungsvariablen definierst. Alternativ kannst du die Einrichtung jederzeit über einen Build-Chat vornehmen. Siehe Dokumentation.",
+ "agentDetail.configure.advancedSettings.envEditor.toggle": "Env Editor umschalten",
"agentDetail.configure.advancedSettings.envEditor.valueColumn": "Value",
"agentDetail.configure.advancedSettings.envEditor.valuePlaceholder": "Value",
"agentDetail.configure.advancedSettings.label": "Erweiterte Einstellungen",
+ "agentDetail.configure.advancedSettings.toggle": "Erweiterte Einstellungen umschalten",
+ "agentDetail.configure.build.empty.description": "Beschreiben Sie, was Sie möchten, und das Formular links wird während des Chats ausgefüllt.",
+ "agentDetail.configure.build.empty.title": "Agent per Chat erstellen",
+ "agentDetail.configure.build.inputPlaceholder": "Beschreiben Sie, was Ihr Agent tun soll",
+ "agentDetail.configure.build.startBuild": "Build starten",
+ "agentDetail.configure.buildDraft.changes": "{{count}} Änderungen anzuwenden",
+ "agentDetail.configure.buildDraft.discard": "Verwerfen",
+ "agentDetail.configure.buildDraft.modeBadge": "Build-Modus",
+ "agentDetail.configure.buildDraft.modeDescription": "Sie sind im Build-Modus. Formen Sie diese Einrichtung über den Chat rechts und wenden Sie sie dann an.",
+ "agentDetail.configure.buildDraft.noChanges": "Keine Änderungen anzuwenden",
+ "agentDetail.configure.buildDraft.title": "Build-Entwurf",
"agentDetail.configure.chatFeatures.description": "Gestalten Sie das Chat-Erlebnis für Endnutzer in Ihrer Webapp und in Chat-Oberflächen.",
"agentDetail.configure.chatFeatures.title": "Chat-Funktionen",
"agentDetail.configure.files.add": "Datei hinzufügen",
@@ -67,7 +80,8 @@
"agentDetail.configure.files.preview.failed": "Vorschau konnte nicht geladen werden.",
"agentDetail.configure.files.preview.unsupported": "Für diese Datei wird keine Vorschau unterstützt.",
"agentDetail.configure.files.remove": "{{name}} entfernen",
- "agentDetail.configure.files.tip": "Dateien, die dieser Agent bei der Orchestrierung von Aufgaben verwenden kann.",
+ "agentDetail.configure.files.tip": "Stellen Sie Ihrem Agenten Beispiele, Richtlinien oder einfach Informationen bereit, die zu lang für den Prompt sind. Verweisen Sie im Prompt explizit mit / darauf.",
+ "agentDetail.configure.files.toggle": "Dateien umschalten",
"agentDetail.configure.files.treeLabel": "Agentendateien",
"agentDetail.configure.files.upload.action": "Hochladen",
"agentDetail.configure.files.upload.browse": "durchsuchen",
@@ -113,8 +127,11 @@
"agentDetail.configure.orchestrate": "Orchestrieren",
"agentDetail.configure.preview.chatFeatures": "Chat-Funktionen",
"agentDetail.configure.preview.empty.defaultAgentName": "Agent",
- "agentDetail.configure.preview.empty.description": "Senden Sie eine Nachricht, um den aktuellen Entwurf zu testen.",
+ "agentDetail.configure.preview.empty.description": "Führen Sie den Agenten als fertigen Chat aus, genau wie Benutzer ihn nach der Veröffentlichung erleben.",
"agentDetail.configure.preview.empty.noInstructionsDescription": "Noch keine Anweisungen, daher kommen die Antworten vom reinen Modell.",
+ "agentDetail.configure.preview.empty.title": "{{name}} in der Vorschau anzeigen",
+ "agentDetail.configure.preview.endUserAuth": "Endbenutzer-Authentifizierung",
+ "agentDetail.configure.preview.inputPlaceholder": "Nachricht an {{name}}",
"agentDetail.configure.preview.restart": "Vorschau neu starten",
"agentDetail.configure.preview.title": "Vorschau",
"agentDetail.configure.prompt.copied": "Prompt kopiert",
@@ -128,7 +145,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "Anweisungen hier eintragen,",
- "agentDetail.configure.prompt.tip": "Definieren Sie, wie dieser Agent Eingaben interpretiert, Tools aufruft und Ausgaben erzeugt.",
+ "agentDetail.configure.prompt.tip": "Definieren Sie die Rolle des Agenten und beschreiben Sie seine typische Aufgabe. Verwenden Sie /, um explizit auf Skills, Dateien, Tools und Wissensabrufe zu verweisen.",
"agentDetail.configure.publishBar.draft": "Entwurf",
"agentDetail.configure.publishBar.publishUpdate": "Update veröffentlichen",
"agentDetail.configure.publishBar.published": "Veröffentlicht",
@@ -147,6 +164,14 @@
"agentDetail.configure.publishImpact.title": "{{action}} für {{name}}",
"agentDetail.configure.publishImpact.workflowCount_one": "{{count}} Workflow",
"agentDetail.configure.publishImpact.workflowCount_other": "{{count}} Workflows",
+ "agentDetail.configure.rightPanel.build": "Erstellen",
+ "agentDetail.configure.rightPanel.buildTipBody": "Build richtet den Agenten per Chat ein. Beschreibe, was du möchtest, und die Einrichtung links wird ausgefüllt.",
+ "agentDetail.configure.rightPanel.buildTipTitle": "Baue deinen Agenten per Chat",
+ "agentDetail.configure.rightPanel.learnMore": "Mehr erfahren",
+ "agentDetail.configure.rightPanel.modeLabel": "Agent-Konfigurationsmodus",
+ "agentDetail.configure.rightPanel.preview": "Vorschau",
+ "agentDetail.configure.rightPanel.previewTipBody": "Preview führt den fertigen Agenten so aus, wie deine Benutzer ihn sehen, mit klaren Antworten und Chat-Funktionen.",
+ "agentDetail.configure.rightPanel.previewTipTitle": "Agenten vorschauen",
"agentDetail.configure.skills.add": "Skill hinzufügen",
"agentDetail.configure.skills.detail.contentRegion": "Skill-Detailinhalt",
"agentDetail.configure.skills.detail.fileCount": "{{count}} DATEIEN",
@@ -156,7 +181,9 @@
"agentDetail.configure.skills.itemType": "Skill",
"agentDetail.configure.skills.label": "Skills",
"agentDetail.configure.skills.remove": "{{name}} entfernen",
- "agentDetail.configure.skills.tip": "Skills, die dieser Agent bei der Orchestrierung von Aufgaben verwenden kann.",
+ "agentDetail.configure.skills.richTip": "Statten Sie Ihren Agenten mit modularen Fähigkeiten aus. Siehe <docLink>Dokumentation</docLink>. Verweisen Sie im Prompt explizit mit / darauf.",
+ "agentDetail.configure.skills.tip": "Statten Sie Ihren Agenten mit modularen Fähigkeiten aus. Siehe Dokumentation. Verweisen Sie im Prompt explizit mit / darauf.",
+ "agentDetail.configure.skills.toggle": "Skills umschalten",
"agentDetail.configure.skills.upload.action": "Hochladen",
"agentDetail.configure.skills.upload.browse": "durchsuchen",
"agentDetail.configure.skills.upload.description": "Laden Sie ein .zip- oder .skill-Paket für diesen Agenten hoch.",
@@ -166,6 +193,7 @@
"agentDetail.configure.skills.upload.invalidFile": "Bitte eine .zip- oder .skill-Datei hochladen.",
"agentDetail.configure.skills.upload.success": "Skill hochgeladen.",
"agentDetail.configure.skills.upload.title": "Skill hochladen",
+ "agentDetail.configure.title": "Konfigurieren",
"agentDetail.configure.tools.add": "Tool hinzufügen",
"agentDetail.configure.tools.addMenu.cliTool.badge": "Für Entwickler",
"agentDetail.configure.tools.addMenu.cliTool.description": "Installieren Sie ein Befehlszeilenprogramm, das der Agent in seiner Sandbox ausführt. Benötigt eine Installation und in der Regel API-Keys.",
@@ -179,7 +207,7 @@
"agentDetail.configure.tools.cliDialog.env.optional": "(optional)",
"agentDetail.configure.tools.cliDialog.installCommand.description": "In der Sandbox · läuft einmal beim ersten Aufruf",
"agentDetail.configure.tools.cliDialog.installCommand.label": "Installationsbefehl",
- "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "Fügen Sie hier Ihren Installationsbefehl ein, z. B. npm install -g @lark/cli · brew install jq",
+ "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "Fügen Sie hier Ihren Installationsbefehl ein, z. B. npx -y @playwright/mcp@latest · uv tool install httpie",
"agentDetail.configure.tools.cliDialog.installCommand.required": "Installationsbefehl ist erforderlich.",
"agentDetail.configure.tools.cliDialog.learnMore": "Mehr über CLI-Tool erfahren",
"agentDetail.configure.tools.cliDialog.name.label": "Name des CLI-Tools",
@@ -196,13 +224,19 @@
"agentDetail.configure.tools.moreActions": "Weitere Aktionen für {{name}}",
"agentDetail.configure.tools.removeAction": "{{name}} entfernen",
"agentDetail.configure.tools.removeProvider": "Alle Tools entfernen",
- "agentDetail.configure.tools.tip": "Tools, die dieser Agent bei der Orchestrierung von Aufgaben aufrufen kann.",
+ "agentDetail.configure.tools.richTip": "Statten Sie Ihren Agenten mit Dify-Plugins aus. Siehe <pluginDocLink>Dokumentation</pluginDocLink>. Verweisen Sie im Prompt explizit mit / darauf.\nAlternativ können Sie den Agenten jederzeit über einen Build-Chat anweisen, andere Tools (z. B. MCPs und CLI-Tools) zu installieren und zu authentifizieren. Beachten Sie, dass über Build-Chats konfigurierte Tools hier NICHT angezeigt werden, Ihrem Agenten künftig aber weiterhin zur Verfügung stehen. Siehe <buildDocLink>Dokumentation</buildDocLink>.",
+ "agentDetail.configure.tools.tip": "Statten Sie Ihren Agenten mit Dify-Plugins aus. Siehe Dokumentation. Verweisen Sie im Prompt explizit mit / darauf. Alternativ können Sie den Agenten jederzeit über einen Build-Chat anweisen, andere Tools (z. B. MCPs und CLI-Tools) zu installieren und zu authentifizieren. Beachten Sie, dass über Build-Chats konfigurierte Tools hier NICHT angezeigt werden, Ihrem Agenten künftig aber weiterhin zur Verfügung stehen. Siehe Dokumentation.",
+ "agentDetail.configure.tools.toggle": "Tools umschalten",
"agentDetail.configure.tools.toolTabs.all": "Alle",
"agentDetail.configure.tools.toolTabs.cli": "CLI",
"agentDetail.configure.tools.toolTabs.custom": "Benutzerdefiniert",
"agentDetail.configure.tools.toolTabs.mcp": "MCP",
"agentDetail.configure.tools.toolTabs.plugins": "Plugins",
"agentDetail.configure.tools.toolTabs.workflow": "Workflow",
+ "agentDetail.configure.workingDirectory.description": "Dateien, die der Agent während der Ausführung liest und schreibt. Alles, was er erzeugt, z. B. qna_report.pdf, erscheint hier.",
+ "agentDetail.configure.workingDirectory.open": "Arbeitsverzeichnis öffnen",
+ "agentDetail.configure.workingDirectory.title": "Arbeitsverzeichnis",
+ "agentDetail.configure.workingDirectory.treeLabel": "Dateien im Arbeitsverzeichnis",
"agentDetail.documentTitle": "Agent",
"agentDetail.logs.description": "Vollständige Logs zeichnen den Laufzeitstatus der Anwendung auf, einschließlich Benutzereingaben, Agentenantworten, Planung und Tool-Nutzung.",
"agentDetail.logs.empty": "Keine Logs gefunden",
@@ -279,7 +313,7 @@
"agentDetail.navigationLabel": "Agenten-Navigation",
"agentDetail.publish": "Veröffentlichen",
"agentDetail.sections.access": "Zugangspunkt",
- "agentDetail.sections.configure": "Orchestrieren",
+ "agentDetail.sections.configure": "Konfigurieren",
"agentDetail.sections.logs": "Logs",
"agentDetail.sections.monitoring": "Monitoring",
"agentDetail.title": "Agent",
@@ -334,6 +368,11 @@
"roster.nodeSelector.startFromScratch": "Von Grund auf starten",
"roster.references.label": "Workflows, die {{name}} verwenden",
"roster.references.trigger": "Workflows, die {{name}} verwenden",
+ "roster.saveToRoster": "Save to Agent Console",
+ "roster.saveToRosterDialog.description": "Save this inline setup as a reusable roster agent.",
+ "roster.saveToRosterDialog.title": "Save to Agent Console",
+ "roster.saveToRosterForm.changeIcon": "Change roster agent icon",
+ "roster.saveToRosterSuccess": "Agent saved to roster.",
"roster.searchLabel": "Agenten suchen",
"roster.searchPlaceholder": "Agenten nach Namen suchen…",
"roster.tabs.agent": "Agent",
diff --git a/web/i18n/de-DE/common.json b/web/i18n/de-DE/common.json
index 31bc0e14ea0..836d9094974 100644
--- a/web/i18n/de-DE/common.json
+++ b/web/i18n/de-DE/common.json
@@ -288,6 +288,7 @@
"menus.exploreMarketplace": "Marketplace erkunden",
"menus.plugins": "Integrationen",
"menus.roster": "Agent-Verzeichnis",
+ "menus.status": "Beta",
"menus.tools": "Werkzeuge",
"model.capabilities": "Multimodale Fähigkeiten",
"model.params.stop_sequencesPlaceholder": "Sequenz eingeben und Tab drücken",
diff --git a/web/i18n/de-DE/workflow.json b/web/i18n/de-DE/workflow.json
index 8da99b5e473..757b0f47627 100644
--- a/web/i18n/de-DE/workflow.json
+++ b/web/i18n/de-DE/workflow.json
@@ -464,7 +464,7 @@
"nodes.agent.task.label": "Agentenaufgabe",
"nodes.agent.task.mention": "Erwähnen",
"nodes.agent.task.placeholder": "Beschreiben Sie, was dieser Agent tun soll...",
- "nodes.agent.task.tooltip": "Definieren Sie die Aufgabenanweisungen, denen dieser Agent in diesem Workflow folgen soll.",
+ "nodes.agent.task.tooltip": "Zusätzlicher Prompt, der dem Agenten hilft, genau diesen Knoten zu bearbeiten. Verwende /, um explizit auf Variablen zu verweisen.\nWenn dies richtig konfiguriert ist, kannst du deinem Agenten möglicherweise vertrauen, die Dinge selbst herauszufinden.",
"nodes.agent.toolNotAuthorizedTooltip": "{{tool}} Nicht autorisiert",
"nodes.agent.toolNotInstallTooltip": "{{tool}} ist nicht installiert",
"nodes.agent.toolbox": "Werkzeugkasten",
diff --git a/web/i18n/en-US/agent-v-2.json b/web/i18n/en-US/agent-v-2.json
index 4d716b2ea86..bdcc044a1fb 100644
--- a/web/i18n/en-US/agent-v-2.json
+++ b/web/i18n/en-US/agent-v-2.json
@@ -49,14 +49,27 @@
"agentDetail.configure.advancedSettings.envEditor.keyPlaceholder": "Key",
"agentDetail.configure.advancedSettings.envEditor.label": "Env Editor",
"agentDetail.configure.advancedSettings.envEditor.revealValue": "Reveal {{key}} value",
+ "agentDetail.configure.advancedSettings.envEditor.richTip": "Your agent runs in a Linux environment. You can preset configs or secrets by defining environmental variables here.\n\nAlternatively, you can always have things set up via a Build chat. Refer to <docLink>docs</docLink>.",
"agentDetail.configure.advancedSettings.envEditor.scopeColumn": "Scope",
"agentDetail.configure.advancedSettings.envEditor.scopePlain": "Plain",
"agentDetail.configure.advancedSettings.envEditor.scopeSecret": "Secret",
"agentDetail.configure.advancedSettings.envEditor.scopeSelector": "Select environment variable scope",
- "agentDetail.configure.advancedSettings.envEditor.tip": "Environment variables available to this agent at runtime.",
+ "agentDetail.configure.advancedSettings.envEditor.tip": "Your agent runs in a Linux environment. You can preset configs or secrets by defining environmental variables here. Alternatively, you can always have things set up via a Build chat. Refer to docs.",
+ "agentDetail.configure.advancedSettings.envEditor.toggle": "Toggle env editor",
"agentDetail.configure.advancedSettings.envEditor.valueColumn": "Value",
"agentDetail.configure.advancedSettings.envEditor.valuePlaceholder": "Value",
"agentDetail.configure.advancedSettings.label": "Advanced Settings",
+ "agentDetail.configure.advancedSettings.toggle": "Toggle advanced settings",
+ "agentDetail.configure.build.empty.description": "Describe what you want and it fills in the form on the left as you go.",
+ "agentDetail.configure.build.empty.title": "Build your agent by chatting",
+ "agentDetail.configure.build.inputPlaceholder": "Describe what your agent should do",
+ "agentDetail.configure.build.startBuild": "Start build",
+ "agentDetail.configure.buildDraft.changes": "{{count}} changes to apply",
+ "agentDetail.configure.buildDraft.discard": "Discard",
+ "agentDetail.configure.buildDraft.modeBadge": "Build mode",
+ "agentDetail.configure.buildDraft.modeDescription": "You're in build mode. Shape this setup through the chat on the right, then Apply.",
+ "agentDetail.configure.buildDraft.noChanges": "No changes to apply",
+ "agentDetail.configure.buildDraft.title": "Build draft",
"agentDetail.configure.chatFeatures.description": "Shape the end-user chat experience on your web app and chat surfaces.",
"agentDetail.configure.chatFeatures.title": "Chat Features",
"agentDetail.configure.files.add": "Add file",
@@ -67,7 +80,8 @@
"agentDetail.configure.files.preview.failed": "Failed to load preview.",
"agentDetail.configure.files.preview.unsupported": "Preview is not supported for this file.",
"agentDetail.configure.files.remove": "Remove {{name}}",
- "agentDetail.configure.files.tip": "Files this agent can use while orchestrating tasks.",
+ "agentDetail.configure.files.tip": "Provide your agent with any example, guideline or simply a bearer of information that is too long for prompt. Make explicit reference with / in Prompt.",
+ "agentDetail.configure.files.toggle": "Toggle files",
"agentDetail.configure.files.treeLabel": "Agent files",
"agentDetail.configure.files.upload.action": "Upload",
"agentDetail.configure.files.upload.browse": "browse",
@@ -113,8 +127,11 @@
"agentDetail.configure.orchestrate": "Orchestrate",
"agentDetail.configure.preview.chatFeatures": "Chat Features",
"agentDetail.configure.preview.empty.defaultAgentName": "Agent",
- "agentDetail.configure.preview.empty.description": "Send a message to test the current draft.",
+ "agentDetail.configure.preview.empty.description": "Run the agent as a finished chat, exactly how people will experience it once published.",
"agentDetail.configure.preview.empty.noInstructionsDescription": "No instructions yet, so replies come from the plain model.",
+ "agentDetail.configure.preview.empty.title": "Preview {{name}}",
+ "agentDetail.configure.preview.endUserAuth": "End-user authentication",
+ "agentDetail.configure.preview.inputPlaceholder": "Message {{name}}",
"agentDetail.configure.preview.restart": "Restart preview",
"agentDetail.configure.preview.title": "Preview",
"agentDetail.configure.prompt.copied": "Prompt copied",
@@ -128,7 +145,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "Write instructions here,",
- "agentDetail.configure.prompt.tip": "Define how this agent should interpret inputs, call tools, and produce outputs.",
+ "agentDetail.configure.prompt.tip": "Define the agent's role and describe its typical task. Use / to make explicit reference to Skills, Files, Tools and Knowledge Retrievals.",
"agentDetail.configure.publishBar.draft": "Draft",
"agentDetail.configure.publishBar.publishUpdate": "Publish update",
"agentDetail.configure.publishBar.published": "Published",
@@ -147,6 +164,14 @@
"agentDetail.configure.publishImpact.title": "{{action}} to {{name}}",
"agentDetail.configure.publishImpact.workflowCount_one": "{{count}} workflow",
"agentDetail.configure.publishImpact.workflowCount_other": "{{count}} workflows",
+ "agentDetail.configure.rightPanel.build": "Build",
+ "agentDetail.configure.rightPanel.buildTipBody": "Build sets up the agent by chatting. Describe what you want and it fills in the setup on the left.",
+ "agentDetail.configure.rightPanel.buildTipTitle": "Build your agent via chat",
+ "agentDetail.configure.rightPanel.learnMore": "Learn more",
+ "agentDetail.configure.rightPanel.modeLabel": "Agent configuration mode",
+ "agentDetail.configure.rightPanel.preview": "Preview",
+ "agentDetail.configure.rightPanel.previewTipBody": "Preview runs the finished agent the way your users will see it, with clean replies and chat features.",
+ "agentDetail.configure.rightPanel.previewTipTitle": "Preview your agent",
"agentDetail.configure.skills.add": "Add skill",
"agentDetail.configure.skills.detail.contentRegion": "Skill detail content",
"agentDetail.configure.skills.detail.fileCount": "{{count}} FILES",
@@ -156,7 +181,9 @@
"agentDetail.configure.skills.itemType": "Skill",
"agentDetail.configure.skills.label": "Skills",
"agentDetail.configure.skills.remove": "Remove {{name}}",
- "agentDetail.configure.skills.tip": "Skills this agent can use while orchestrating tasks.",
+ "agentDetail.configure.skills.richTip": "Equip your agent with modular capabilities. Refer to <docLink>docs</docLink>. Make explicit reference with / in Prompt.",
+ "agentDetail.configure.skills.tip": "Equip your agent with modular capabilities. Refer to docs. Make explicit reference with / in Prompt.",
+ "agentDetail.configure.skills.toggle": "Toggle skills",
"agentDetail.configure.skills.upload.action": "Upload",
"agentDetail.configure.skills.upload.browse": "browse",
"agentDetail.configure.skills.upload.description": "Upload a .zip or .skill package for this agent.",
@@ -166,6 +193,7 @@
"agentDetail.configure.skills.upload.invalidFile": "Upload a .zip or .skill file.",
"agentDetail.configure.skills.upload.success": "Skill uploaded.",
"agentDetail.configure.skills.upload.title": "Upload skill",
+ "agentDetail.configure.title": "Configure",
"agentDetail.configure.tools.add": "Add tool",
"agentDetail.configure.tools.addMenu.cliTool.badge": "For developers",
"agentDetail.configure.tools.addMenu.cliTool.description": "Install a command line program the agent runs in its sandbox. Needs install and usually API keys.",
@@ -179,7 +207,7 @@
"agentDetail.configure.tools.cliDialog.env.optional": "(optional)",
"agentDetail.configure.tools.cliDialog.installCommand.description": "Sandboxed · runs once on first invocation",
"agentDetail.configure.tools.cliDialog.installCommand.label": "Install Command",
- "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "Paste your install command here, e.g. npm install -g @lark/cli · brew install jq",
+ "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "Paste your install command here, e.g. npx -y @playwright/mcp@latest · uv tool install httpie",
"agentDetail.configure.tools.cliDialog.installCommand.required": "Install command is required.",
"agentDetail.configure.tools.cliDialog.learnMore": "Learn more about CLI Tool",
"agentDetail.configure.tools.cliDialog.name.label": "CLI Tool Name",
@@ -196,13 +224,19 @@
"agentDetail.configure.tools.moreActions": "More actions for {{name}}",
"agentDetail.configure.tools.removeAction": "Remove {{name}}",
"agentDetail.configure.tools.removeProvider": "Remove all tools",
- "agentDetail.configure.tools.tip": "Tools this agent can call while orchestrating tasks.",
+ "agentDetail.configure.tools.richTip": "Equip your agent with Dify's plugins. Refer to <pluginDocLink>docs</pluginDocLink>. Make explicit reference with / in Prompt.\nAlternatively, you can always tell the agent to install and authenticate other tools (e.g. MCPs & CLI tools) via a Build chat. Note that tools configured via Build chats will NOT show up here, although they will still be available to your agent going forward. Refer to <buildDocLink>docs</buildDocLink>.",
+ "agentDetail.configure.tools.tip": "Equip your agent with Dify's plugins. Refer to docs. Make explicit reference with / in Prompt. Alternatively, you can always tell the agent to install and authenticate other tools (e.g. MCPs & CLI tools) via a Build chat. Note that tools configured via Build chats will NOT show up here, although they will still be available to your agent going forward. Refer to docs.",
+ "agentDetail.configure.tools.toggle": "Toggle tools",
"agentDetail.configure.tools.toolTabs.all": "All",
"agentDetail.configure.tools.toolTabs.cli": "CLI",
"agentDetail.configure.tools.toolTabs.custom": "Custom",
"agentDetail.configure.tools.toolTabs.mcp": "MCP",
"agentDetail.configure.tools.toolTabs.plugins": "Plugins",
"agentDetail.configure.tools.toolTabs.workflow": "Workflow",
+ "agentDetail.configure.workingDirectory.description": "Files the agent reads and writes as it runs. Anything it generates, like qna_report.pdf, shows up here.",
+ "agentDetail.configure.workingDirectory.open": "Open working directory",
+ "agentDetail.configure.workingDirectory.title": "Working directory",
+ "agentDetail.configure.workingDirectory.treeLabel": "Working directory files",
"agentDetail.documentTitle": "Agent",
"agentDetail.logs.description": "Full logs record the running status of the application, including user inputs, agent replies, planning and tool uses.",
"agentDetail.logs.empty": "No logs found",
@@ -279,7 +313,7 @@
"agentDetail.navigationLabel": "Agent navigation",
"agentDetail.publish": "Publish",
"agentDetail.sections.access": "Access Point",
- "agentDetail.sections.configure": "Orchestrate",
+ "agentDetail.sections.configure": "Configure",
"agentDetail.sections.logs": "Logs",
"agentDetail.sections.monitoring": "Monitoring",
"agentDetail.title": "Agent",
@@ -334,6 +368,11 @@
"roster.nodeSelector.startFromScratch": "Start from Scratch",
"roster.references.label": "Workflows using {{name}}",
"roster.references.trigger": "Workflows using {{name}}",
+ "roster.saveToRoster": "Save to Agent Console",
+ "roster.saveToRosterDialog.description": "Save this inline setup as a reusable roster agent.",
+ "roster.saveToRosterDialog.title": "Save to Agent Console",
+ "roster.saveToRosterForm.changeIcon": "Change roster agent icon",
+ "roster.saveToRosterSuccess": "Agent saved to roster.",
"roster.searchLabel": "Search agents",
"roster.searchPlaceholder": "Search agents by name…",
"roster.tabs.agent": "Agent",
diff --git a/web/i18n/en-US/common.json b/web/i18n/en-US/common.json
index 21d3b03df40..bf15b3ff4df 100644
--- a/web/i18n/en-US/common.json
+++ b/web/i18n/en-US/common.json
@@ -288,6 +288,7 @@
"menus.exploreMarketplace": "Explore Marketplace",
"menus.plugins": "Integrations",
"menus.roster": "Roster",
+ "menus.status": "beta",
"menus.tools": "Tools",
"model.capabilities": "MultiModal Capabilities",
"model.params.stop_sequencesPlaceholder": "Enter sequence and press Tab",
diff --git a/web/i18n/en-US/workflow.json b/web/i18n/en-US/workflow.json
index ea7845f63a2..e511d29b854 100644
--- a/web/i18n/en-US/workflow.json
+++ b/web/i18n/en-US/workflow.json
@@ -464,7 +464,7 @@
"nodes.agent.task.label": "Agent task",
"nodes.agent.task.mention": "Mention",
"nodes.agent.task.placeholder": "Describe what this agent should do...",
- "nodes.agent.task.tooltip": "Define the task instructions this agent should follow in this workflow.",
+ "nodes.agent.task.tooltip": "Additional prompt to help agent handle this very node. Use / to make explicit reference to variables.\nIf configured properly, you could be able to trust your agent to figure things out itself.",
"nodes.agent.toolNotAuthorizedTooltip": "{{tool}} Not Authorized",
"nodes.agent.toolNotInstallTooltip": "{{tool}} is not installed",
"nodes.agent.toolbox": "toolbox",
diff --git a/web/i18n/es-ES/agent-v-2.json b/web/i18n/es-ES/agent-v-2.json
index 1c70128f99e..e50e8c89b6d 100644
--- a/web/i18n/es-ES/agent-v-2.json
+++ b/web/i18n/es-ES/agent-v-2.json
@@ -49,14 +49,27 @@
"agentDetail.configure.advancedSettings.envEditor.keyPlaceholder": "Key",
"agentDetail.configure.advancedSettings.envEditor.label": "Env Editor",
"agentDetail.configure.advancedSettings.envEditor.revealValue": "Mostrar valor de {{key}}",
+ "agentDetail.configure.advancedSettings.envEditor.richTip": "Tu agente se ejecuta en un entorno Linux. Puedes predefinir configuraciones o secretos definiendo variables de entorno aquí.\n\nComo alternativa, siempre puedes configurarlo mediante un chat de Build. Consulta la <docLink>documentación</docLink>.",
"agentDetail.configure.advancedSettings.envEditor.scopeColumn": "Scope",
"agentDetail.configure.advancedSettings.envEditor.scopePlain": "Plain",
"agentDetail.configure.advancedSettings.envEditor.scopeSecret": "Secret",
"agentDetail.configure.advancedSettings.envEditor.scopeSelector": "Seleccionar alcance de la variable de entorno",
- "agentDetail.configure.advancedSettings.envEditor.tip": "Variables de entorno disponibles para este agente en tiempo de ejecución.",
+ "agentDetail.configure.advancedSettings.envEditor.tip": "Tu agente se ejecuta en un entorno Linux. Puedes predefinir configuraciones o secretos definiendo variables de entorno aquí. Como alternativa, siempre puedes configurarlo mediante un chat de Build. Consulta la documentación.",
+ "agentDetail.configure.advancedSettings.envEditor.toggle": "Alternar Env Editor",
"agentDetail.configure.advancedSettings.envEditor.valueColumn": "Value",
"agentDetail.configure.advancedSettings.envEditor.valuePlaceholder": "Value",
"agentDetail.configure.advancedSettings.label": "Configuración avanzada",
+ "agentDetail.configure.advancedSettings.toggle": "Alternar configuración avanzada",
+ "agentDetail.configure.build.empty.description": "Describe lo que quieres y se irá completando el formulario de la izquierda mientras avanzas.",
+ "agentDetail.configure.build.empty.title": "Crea tu agente chateando",
+ "agentDetail.configure.build.inputPlaceholder": "Describe qué debe hacer tu agente",
+ "agentDetail.configure.build.startBuild": "Iniciar compilación",
+ "agentDetail.configure.buildDraft.changes": "{{count}} cambios por aplicar",
+ "agentDetail.configure.buildDraft.discard": "Descartar",
+ "agentDetail.configure.buildDraft.modeBadge": "Modo build",
+ "agentDetail.configure.buildDraft.modeDescription": "Estás en modo build. Ajusta esta configuración con el chat de la derecha y luego aplica los cambios.",
+ "agentDetail.configure.buildDraft.noChanges": "No hay cambios por aplicar",
+ "agentDetail.configure.buildDraft.title": "Borrador de compilación",
"agentDetail.configure.chatFeatures.description": "Da forma a la experiencia de chat del usuario final en tu webapp y superficies de chat.",
"agentDetail.configure.chatFeatures.title": "Funciones de chat",
"agentDetail.configure.files.add": "Agregar archivo",
@@ -67,7 +80,8 @@
"agentDetail.configure.files.preview.failed": "Error al cargar la vista previa.",
"agentDetail.configure.files.preview.unsupported": "Este archivo no admite vista previa.",
"agentDetail.configure.files.remove": "Eliminar {{name}}",
- "agentDetail.configure.files.tip": "Archivos que este agente puede usar al orquestar tareas.",
+ "agentDetail.configure.files.tip": "Proporciona a tu agente cualquier ejemplo, guía o simplemente un soporte de información que sea demasiado largo para el prompt. Haz referencia explícita con / en el prompt.",
+ "agentDetail.configure.files.toggle": "Alternar archivos",
"agentDetail.configure.files.treeLabel": "Archivos del agente",
"agentDetail.configure.files.upload.action": "Subir",
"agentDetail.configure.files.upload.browse": "examinar",
@@ -113,8 +127,11 @@
"agentDetail.configure.orchestrate": "Orquestar",
"agentDetail.configure.preview.chatFeatures": "Funciones de chat",
"agentDetail.configure.preview.empty.defaultAgentName": "Agente",
- "agentDetail.configure.preview.empty.description": "Envía un mensaje para probar el borrador actual.",
+ "agentDetail.configure.preview.empty.description": "Ejecuta el agente como un chat terminado, exactamente como lo verán las personas cuando se publique.",
"agentDetail.configure.preview.empty.noInstructionsDescription": "Aún no hay instrucciones, así que las respuestas vendrán del modelo sin configurar.",
+ "agentDetail.configure.preview.empty.title": "Vista previa de {{name}}",
+ "agentDetail.configure.preview.endUserAuth": "Autenticación de usuario final",
+ "agentDetail.configure.preview.inputPlaceholder": "Enviar mensaje a {{name}}",
"agentDetail.configure.preview.restart": "Reiniciar vista previa",
"agentDetail.configure.preview.title": "Vista previa",
"agentDetail.configure.prompt.copied": "Prompt copiado",
@@ -128,7 +145,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "Escribe las instrucciones aquí,",
- "agentDetail.configure.prompt.tip": "Define cómo este agente debe interpretar las entradas, invocar herramientas y producir salidas.",
+ "agentDetail.configure.prompt.tip": "Define el rol del agente y describe su tarea habitual. Usa / para hacer referencia explícita a habilidades, archivos, herramientas y recuperaciones de conocimiento.",
"agentDetail.configure.publishBar.draft": "Borrador",
"agentDetail.configure.publishBar.publishUpdate": "Publicar actualización",
"agentDetail.configure.publishBar.published": "Publicado",
@@ -147,6 +164,14 @@
"agentDetail.configure.publishImpact.title": "{{action}} en {{name}}",
"agentDetail.configure.publishImpact.workflowCount_one": "{{count}} flujo de trabajo",
"agentDetail.configure.publishImpact.workflowCount_other": "{{count}} flujos de trabajo",
+ "agentDetail.configure.rightPanel.build": "Crear",
+ "agentDetail.configure.rightPanel.buildTipBody": "Build configura el agente mediante chat. Describe lo que quieres y completará la configuración de la izquierda.",
+ "agentDetail.configure.rightPanel.buildTipTitle": "Construye tu agente mediante chat",
+ "agentDetail.configure.rightPanel.learnMore": "Más información",
+ "agentDetail.configure.rightPanel.modeLabel": "Modo de configuración del agente",
+ "agentDetail.configure.rightPanel.preview": "Vista previa",
+ "agentDetail.configure.rightPanel.previewTipBody": "Preview ejecuta el agente terminado como lo verán tus usuarios, con respuestas claras y funciones de chat.",
+ "agentDetail.configure.rightPanel.previewTipTitle": "Previsualiza tu agente",
"agentDetail.configure.skills.add": "Agregar habilidad",
"agentDetail.configure.skills.detail.contentRegion": "Contenido de los detalles de la habilidad",
"agentDetail.configure.skills.detail.fileCount": "{{count}} ARCHIVOS",
@@ -156,7 +181,9 @@
"agentDetail.configure.skills.itemType": "Habilidad",
"agentDetail.configure.skills.label": "Habilidades",
"agentDetail.configure.skills.remove": "Eliminar {{name}}",
- "agentDetail.configure.skills.tip": "Habilidades que este agente puede usar al orquestar tareas.",
+ "agentDetail.configure.skills.richTip": "Equipa a tu agente con capacidades modulares. Consulta la <docLink>documentación</docLink>. Haz referencia explícita con / en el prompt.",
+ "agentDetail.configure.skills.tip": "Equipa a tu agente con capacidades modulares. Consulta la documentación. Haz referencia explícita con / en el prompt.",
+ "agentDetail.configure.skills.toggle": "Alternar habilidades",
"agentDetail.configure.skills.upload.action": "Subir",
"agentDetail.configure.skills.upload.browse": "examinar",
"agentDetail.configure.skills.upload.description": "Sube un paquete .zip o .skill para este agente.",
@@ -166,6 +193,7 @@
"agentDetail.configure.skills.upload.invalidFile": "Sube un archivo .zip o .skill.",
"agentDetail.configure.skills.upload.success": "Habilidad subida.",
"agentDetail.configure.skills.upload.title": "Subir habilidad",
+ "agentDetail.configure.title": "Configurar",
"agentDetail.configure.tools.add": "Agregar herramienta",
"agentDetail.configure.tools.addMenu.cliTool.badge": "Para desarrolladores",
"agentDetail.configure.tools.addMenu.cliTool.description": "Instala un programa de línea de comandos que el agente ejecuta en su sandbox. Requiere instalación y normalmente claves API.",
@@ -179,7 +207,7 @@
"agentDetail.configure.tools.cliDialog.env.optional": "(opcional)",
"agentDetail.configure.tools.cliDialog.installCommand.description": "En sandbox · se ejecuta una vez en la primera invocación",
"agentDetail.configure.tools.cliDialog.installCommand.label": "Comando de instalación",
- "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "Pega tu comando de instalación aquí, p. ej. npm install -g @lark/cli · brew install jq",
+ "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "Pega tu comando de instalación aquí, p. ej. npx -y @playwright/mcp@latest · uv tool install httpie",
"agentDetail.configure.tools.cliDialog.installCommand.required": "El comando de instalación es obligatorio.",
"agentDetail.configure.tools.cliDialog.learnMore": "Más información sobre la herramienta CLI",
"agentDetail.configure.tools.cliDialog.name.label": "Nombre de la herramienta CLI",
@@ -196,13 +224,19 @@
"agentDetail.configure.tools.moreActions": "Más acciones para {{name}}",
"agentDetail.configure.tools.removeAction": "Eliminar {{name}}",
"agentDetail.configure.tools.removeProvider": "Eliminar todas las herramientas",
- "agentDetail.configure.tools.tip": "Herramientas que este agente puede invocar al orquestar tareas.",
+ "agentDetail.configure.tools.richTip": "Equipa a tu agente con los plugins de Dify. Consulta la <pluginDocLink>documentación</pluginDocLink>. Haz referencia explícita con / en el prompt.\nComo alternativa, siempre puedes indicar al agente que instale y autentique otras herramientas (por ejemplo, MCPs y herramientas CLI) mediante un chat de Build. Ten en cuenta que las herramientas configuradas mediante chats de Build NO aparecerán aquí, aunque seguirán estando disponibles para tu agente en adelante. Consulta la <buildDocLink>documentación</buildDocLink>.",
+ "agentDetail.configure.tools.tip": "Equipa a tu agente con los plugins de Dify. Consulta la documentación. Haz referencia explícita con / en el prompt. Como alternativa, siempre puedes indicar al agente que instale y autentique otras herramientas (por ejemplo, MCPs y herramientas CLI) mediante un chat de Build. Ten en cuenta que las herramientas configuradas mediante chats de Build NO aparecerán aquí, aunque seguirán estando disponibles para tu agente en adelante. Consulta la documentación.",
+ "agentDetail.configure.tools.toggle": "Alternar herramientas",
"agentDetail.configure.tools.toolTabs.all": "Todas",
"agentDetail.configure.tools.toolTabs.cli": "CLI",
"agentDetail.configure.tools.toolTabs.custom": "Personalizado",
"agentDetail.configure.tools.toolTabs.mcp": "MCP",
"agentDetail.configure.tools.toolTabs.plugins": "Plugins",
"agentDetail.configure.tools.toolTabs.workflow": "Workflow",
+ "agentDetail.configure.workingDirectory.description": "Archivos que el agente lee y escribe mientras se ejecuta. Todo lo que genere, como qna_report.pdf, aparecerá aquí.",
+ "agentDetail.configure.workingDirectory.open": "Abrir directorio de trabajo",
+ "agentDetail.configure.workingDirectory.title": "Directorio de trabajo",
+ "agentDetail.configure.workingDirectory.treeLabel": "Archivos del directorio de trabajo",
"agentDetail.documentTitle": "Agente",
"agentDetail.logs.description": "Los registros completos registran el estado de ejecución de la aplicación, incluidas las entradas del usuario, las respuestas del agente, la planificación y los usos de herramientas.",
"agentDetail.logs.empty": "No se encontraron registros",
@@ -279,7 +313,7 @@
"agentDetail.navigationLabel": "Navegación del agente",
"agentDetail.publish": "Publicar",
"agentDetail.sections.access": "Punto de acceso",
- "agentDetail.sections.configure": "Orquestar",
+ "agentDetail.sections.configure": "Configurar",
"agentDetail.sections.logs": "Registros",
"agentDetail.sections.monitoring": "Monitoreo",
"agentDetail.title": "Agente",
@@ -334,6 +368,11 @@
"roster.nodeSelector.startFromScratch": "Empezar desde cero",
"roster.references.label": "Flujos de trabajo que usan {{name}}",
"roster.references.trigger": "Flujos de trabajo que usan {{name}}",
+ "roster.saveToRoster": "Save to Agent Console",
+ "roster.saveToRosterDialog.description": "Save this inline setup as a reusable roster agent.",
+ "roster.saveToRosterDialog.title": "Save to Agent Console",
+ "roster.saveToRosterForm.changeIcon": "Change roster agent icon",
+ "roster.saveToRosterSuccess": "Agent saved to roster.",
"roster.searchLabel": "Buscar agentes",
"roster.searchPlaceholder": "Buscar agentes por nombre…",
"roster.tabs.agent": "Agente",
diff --git a/web/i18n/es-ES/common.json b/web/i18n/es-ES/common.json
index 48624fcdde1..f2c5ad385a4 100644
--- a/web/i18n/es-ES/common.json
+++ b/web/i18n/es-ES/common.json
@@ -288,6 +288,7 @@
"menus.exploreMarketplace": "Explora el mercado",
"menus.plugins": "Integraciones",
"menus.roster": "Directorio de agentes",
+ "menus.status": "beta",
"menus.tools": "Herramientas",
"model.capabilities": "Capacidades multimodales",
"model.params.stop_sequencesPlaceholder": "Ingresa la secuencia y presiona Tab",
diff --git a/web/i18n/es-ES/workflow.json b/web/i18n/es-ES/workflow.json
index 9b76c288493..e15ca03bca7 100644
--- a/web/i18n/es-ES/workflow.json
+++ b/web/i18n/es-ES/workflow.json
@@ -464,7 +464,7 @@
"nodes.agent.task.label": "Tarea del agente",
"nodes.agent.task.mention": "Mencionar",
"nodes.agent.task.placeholder": "Describe lo que este agente debe hacer...",
- "nodes.agent.task.tooltip": "Define las instrucciones de la tarea que este agente debe seguir en este flujo de trabajo.",
+ "nodes.agent.task.tooltip": "Prompt adicional para ayudar al agente a gestionar este nodo en concreto. Usa / para hacer referencia explícita a variables.\nSi está configurado correctamente, podrías confiar en que tu agente resuelva las cosas por sí mismo.",
"nodes.agent.toolNotAuthorizedTooltip": "{{tool}} No autorizado",
"nodes.agent.toolNotInstallTooltip": "{{tool}} no está instalada",
"nodes.agent.toolbox": "caja de herramientas",
diff --git a/web/i18n/fa-IR/agent-v-2.json b/web/i18n/fa-IR/agent-v-2.json
index 24a58c86371..dde594814e2 100644
--- a/web/i18n/fa-IR/agent-v-2.json
+++ b/web/i18n/fa-IR/agent-v-2.json
@@ -49,14 +49,27 @@
"agentDetail.configure.advancedSettings.envEditor.keyPlaceholder": "Key",
"agentDetail.configure.advancedSettings.envEditor.label": "Env Editor",
"agentDetail.configure.advancedSettings.envEditor.revealValue": "نمایش مقدار {{key}}",
+ "agentDetail.configure.advancedSettings.envEditor.richTip": "عامل شما در یک محیط Linux اجرا می‌شود. می‌توانید با تعریف متغیرهای محیطی در اینجا، پیکربندی‌ها یا اسرار را از قبل تنظیم کنید.\n\nهمچنین همیشه می‌توانید تنظیمات را از طریق گفتگوی Build انجام دهید. به <docLink>مستندات</docLink> مراجعه کنید.",
"agentDetail.configure.advancedSettings.envEditor.scopeColumn": "Scope",
"agentDetail.configure.advancedSettings.envEditor.scopePlain": "Plain",
"agentDetail.configure.advancedSettings.envEditor.scopeSecret": "Secret",
"agentDetail.configure.advancedSettings.envEditor.scopeSelector": "انتخاب دامنه متغیر محیطی",
- "agentDetail.configure.advancedSettings.envEditor.tip": "متغیرهای محیطی در دسترس این عامل در زمان اجرا.",
+ "agentDetail.configure.advancedSettings.envEditor.tip": "عامل شما در یک محیط Linux اجرا می‌شود. می‌توانید با تعریف متغیرهای محیطی در اینجا، پیکربندی‌ها یا اسرار را از قبل تنظیم کنید. همچنین همیشه می‌توانید تنظیمات را از طریق گفتگوی Build انجام دهید. به مستندات مراجعه کنید.",
+ "agentDetail.configure.advancedSettings.envEditor.toggle": "تغییر Env Editor",
"agentDetail.configure.advancedSettings.envEditor.valueColumn": "Value",
"agentDetail.configure.advancedSettings.envEditor.valuePlaceholder": "Value",
"agentDetail.configure.advancedSettings.label": "تنظیمات پیشرفته",
+ "agentDetail.configure.advancedSettings.toggle": "تغییر تنظیمات پیشرفته",
+ "agentDetail.configure.build.empty.description": "آنچه می‌خواهید را توضیح دهید تا فرم سمت چپ در طول گفتگو تکمیل شود.",
+ "agentDetail.configure.build.empty.title": "عامل خود را با چت بسازید",
+ "agentDetail.configure.build.inputPlaceholder": "توضیح دهید عامل شما باید چه کاری انجام دهد",
+ "agentDetail.configure.build.startBuild": "شروع ساخت",
+ "agentDetail.configure.buildDraft.changes": "{{count}} تغییر برای اعمال",
+ "agentDetail.configure.buildDraft.discard": "رد کردن",
+ "agentDetail.configure.buildDraft.modeBadge": "حالت ساخت",
+ "agentDetail.configure.buildDraft.modeDescription": "شما در حالت ساخت هستید. این تنظیمات را از طریق چت سمت راست شکل دهید، سپس اعمال کنید.",
+ "agentDetail.configure.buildDraft.noChanges": "تغییری برای اعمال وجود ندارد",
+ "agentDetail.configure.buildDraft.title": "پیش نویس ساخت",
"agentDetail.configure.chatFeatures.description": "تجربه چت کاربر نهایی را در Web app و سطوح چت خود شکل دهید.",
"agentDetail.configure.chatFeatures.title": "ویژگی‌های چت",
"agentDetail.configure.files.add": "افزودن فایل",
@@ -67,7 +80,8 @@
"agentDetail.configure.files.preview.failed": "بارگذاری پیش‌نمایش ناموفق بود.",
"agentDetail.configure.files.preview.unsupported": "این فایل از پیش‌نمایش پشتیبانی نمی‌کند.",
"agentDetail.configure.files.remove": "حذف {{name}}",
- "agentDetail.configure.files.tip": "فایل‌هایی که این عامل هنگام هماهنگی وظایف می‌تواند استفاده کند.",
+ "agentDetail.configure.files.tip": "هر نمونه، دستورالعمل یا حامل اطلاعاتی را که برای پرامپت بیش از حد طولانی است در اختیار عامل قرار دهید. با / در پرامپت به‌صورت صریح به آن ارجاع دهید.",
+ "agentDetail.configure.files.toggle": "تغییر فایل‌ها",
"agentDetail.configure.files.treeLabel": "فایل‌های عامل",
"agentDetail.configure.files.upload.action": "بارگذاری",
"agentDetail.configure.files.upload.browse": "مرور",
@@ -113,8 +127,11 @@
"agentDetail.configure.orchestrate": "هماهنگ‌سازی",
"agentDetail.configure.preview.chatFeatures": "ویژگی‌های چت",
"agentDetail.configure.preview.empty.defaultAgentName": "عامل",
- "agentDetail.configure.preview.empty.description": "برای آزمایش پیش‌نویس فعلی یک پیام ارسال کنید.",
+ "agentDetail.configure.preview.empty.description": "عامل را مثل یک چت نهایی اجرا کنید، دقیقاً همان‌طور که کاربران پس از انتشار تجربه می‌کنند.",
"agentDetail.configure.preview.empty.noInstructionsDescription": "هنوز دستورالعملی وجود ندارد، بنابراین پاسخ‌ها از مدل ساده می‌آیند.",
+ "agentDetail.configure.preview.empty.title": "پیش‌نمایش {{name}}",
+ "agentDetail.configure.preview.endUserAuth": "احراز هویت کاربر نهایی",
+ "agentDetail.configure.preview.inputPlaceholder": "ارسال پیام به {{name}}",
"agentDetail.configure.preview.restart": "راه‌اندازی مجدد پیش‌نمایش",
"agentDetail.configure.preview.title": "پیش‌نمایش",
"agentDetail.configure.prompt.copied": "پرامپت کپی شد",
@@ -128,7 +145,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "دستورالعمل‌ها را اینجا بنویسید،",
- "agentDetail.configure.prompt.tip": "تعریف کنید این عامل چگونه ورودی‌ها را تفسیر کند، ابزارها را فراخوانی کند و خروجی تولید کند.",
+ "agentDetail.configure.prompt.tip": "نقش عامل را تعریف کنید و وظیفه معمول آن را شرح دهید. برای ارجاع صریح به مهارت‌ها، فایل‌ها، ابزارها و بازیابی‌های دانش از / استفاده کنید.",
"agentDetail.configure.publishBar.draft": "پیش‌نویس",
"agentDetail.configure.publishBar.publishUpdate": "انتشار به‌روزرسانی",
"agentDetail.configure.publishBar.published": "منتشر شد",
@@ -147,6 +164,14 @@
"agentDetail.configure.publishImpact.title": "{{action}} به {{name}}",
"agentDetail.configure.publishImpact.workflowCount_one": "{{count}} گردش کار",
"agentDetail.configure.publishImpact.workflowCount_other": "{{count}} گردش کار",
+ "agentDetail.configure.rightPanel.build": "ساخت",
+ "agentDetail.configure.rightPanel.buildTipBody": "Build عامل را از طریق گفتگو تنظیم می‌کند. آنچه می‌خواهید را توضیح دهید تا تنظیمات سمت چپ تکمیل شود.",
+ "agentDetail.configure.rightPanel.buildTipTitle": "عامل خود را از طریق گفتگو بسازید",
+ "agentDetail.configure.rightPanel.learnMore": "بیشتر بدانید",
+ "agentDetail.configure.rightPanel.modeLabel": "حالت پیکربندی عامل",
+ "agentDetail.configure.rightPanel.preview": "پیش‌نمایش",
+ "agentDetail.configure.rightPanel.previewTipBody": "Preview عامل تکمیل‌شده را همان‌طور که کاربران می‌بینند اجرا می‌کند، با پاسخ‌های تمیز و قابلیت‌های گفتگو.",
+ "agentDetail.configure.rightPanel.previewTipTitle": "پیش‌نمایش عامل",
"agentDetail.configure.skills.add": "افزودن مهارت",
"agentDetail.configure.skills.detail.contentRegion": "محتوای جزئیات مهارت",
"agentDetail.configure.skills.detail.fileCount": "{{count}} فایل",
@@ -156,7 +181,9 @@
"agentDetail.configure.skills.itemType": "مهارت",
"agentDetail.configure.skills.label": "مهارت‌ها",
"agentDetail.configure.skills.remove": "حذف {{name}}",
- "agentDetail.configure.skills.tip": "مهارت‌هایی که این عامل هنگام هماهنگی وظایف می‌تواند استفاده کند.",
+ "agentDetail.configure.skills.richTip": "عامل خود را به قابلیت‌های ماژولار مجهز کنید. به <docLink>مستندات</docLink> مراجعه کنید. با / در پرامپت به‌صورت صریح ارجاع دهید.",
+ "agentDetail.configure.skills.tip": "عامل خود را به قابلیت‌های ماژولار مجهز کنید. به مستندات مراجعه کنید. با / در پرامپت به‌صورت صریح ارجاع دهید.",
+ "agentDetail.configure.skills.toggle": "تغییر مهارت‌ها",
"agentDetail.configure.skills.upload.action": "بارگذاری",
"agentDetail.configure.skills.upload.browse": "مرور",
"agentDetail.configure.skills.upload.description": "یک بسته .zip یا .skill برای این عامل بارگذاری کنید.",
@@ -166,6 +193,7 @@
"agentDetail.configure.skills.upload.invalidFile": "یک فایل .zip یا .skill بارگذاری کنید.",
"agentDetail.configure.skills.upload.success": "مهارت بارگذاری شد.",
"agentDetail.configure.skills.upload.title": "بارگذاری مهارت",
+ "agentDetail.configure.title": "پیکربندی",
"agentDetail.configure.tools.add": "افزودن ابزار",
"agentDetail.configure.tools.addMenu.cliTool.badge": "برای توسعه‌دهندگان",
"agentDetail.configure.tools.addMenu.cliTool.description": "یک برنامه خط فرمان نصب کنید که عامل آن را در sandbox خود اجرا می‌کند. به نصب و معمولاً API Key نیاز دارد.",
@@ -179,7 +207,7 @@
"agentDetail.configure.tools.cliDialog.env.optional": "(اختیاری)",
"agentDetail.configure.tools.cliDialog.installCommand.description": "Sandboxed · در اولین فراخوانی یک بار اجرا می‌شود",
"agentDetail.configure.tools.cliDialog.installCommand.label": "فرمان نصب",
- "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "فرمان نصب خود را اینجا بچسبانید، مثلاً npm install -g @lark/cli · brew install jq",
+ "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "فرمان نصب خود را اینجا بچسبانید، مثلاً npx -y @playwright/mcp@latest · uv tool install httpie",
"agentDetail.configure.tools.cliDialog.installCommand.required": "فرمان نصب الزامی است.",
"agentDetail.configure.tools.cliDialog.learnMore": "اطلاعات بیشتر درباره ابزار CLI",
"agentDetail.configure.tools.cliDialog.name.label": "نام ابزار CLI",
@@ -196,13 +224,19 @@
"agentDetail.configure.tools.moreActions": "اقدامات بیشتر برای {{name}}",
"agentDetail.configure.tools.removeAction": "حذف {{name}}",
"agentDetail.configure.tools.removeProvider": "حذف همه ابزارها",
- "agentDetail.configure.tools.tip": "ابزارهایی که این عامل هنگام هماهنگی وظایف می‌تواند فراخوانی کند.",
+ "agentDetail.configure.tools.richTip": "عامل خود را به افزونه‌های Dify مجهز کنید. به <pluginDocLink>مستندات</pluginDocLink> مراجعه کنید. با / در پرامپت به‌صورت صریح ارجاع دهید.\nهمچنین همیشه می‌توانید از طریق چت Build به عامل بگویید ابزارهای دیگر (مانند MCPها و ابزارهای CLI) را نصب و احراز هویت کند. توجه کنید ابزارهایی که از طریق چت‌های Build پیکربندی می‌شوند اینجا نمایش داده نمی‌شوند، اما همچنان در ادامه برای عامل شما در دسترس خواهند بود. به <buildDocLink>مستندات</buildDocLink> مراجعه کنید.",
+ "agentDetail.configure.tools.tip": "عامل خود را به افزونه‌های Dify مجهز کنید. به مستندات مراجعه کنید. با / در پرامپت به‌صورت صریح ارجاع دهید. همچنین همیشه می‌توانید از طریق چت Build به عامل بگویید ابزارهای دیگر (مانند MCPها و ابزارهای CLI) را نصب و احراز هویت کند. توجه کنید ابزارهایی که از طریق چت‌های Build پیکربندی می‌شوند اینجا نمایش داده نمی‌شوند، اما همچنان در ادامه برای عامل شما در دسترس خواهند بود. به مستندات مراجعه کنید.",
+ "agentDetail.configure.tools.toggle": "تغییر ابزارها",
"agentDetail.configure.tools.toolTabs.all": "همه",
"agentDetail.configure.tools.toolTabs.cli": "CLI",
"agentDetail.configure.tools.toolTabs.custom": "سفارشی",
"agentDetail.configure.tools.toolTabs.mcp": "MCP",
"agentDetail.configure.tools.toolTabs.plugins": "افزونه‌ها",
"agentDetail.configure.tools.toolTabs.workflow": "Workflow",
+ "agentDetail.configure.workingDirectory.description": "فایل‌هایی که عامل هنگام اجرا می‌خواند و می‌نویسد. هر چیزی که تولید کند، مثل qna_report.pdf، اینجا نمایش داده می‌شود.",
+ "agentDetail.configure.workingDirectory.open": "باز کردن پوشه کاری",
+ "agentDetail.configure.workingDirectory.title": "پوشه کاری",
+ "agentDetail.configure.workingDirectory.treeLabel": "فایل‌های پوشه کاری",
"agentDetail.documentTitle": "عامل",
"agentDetail.logs.description": "گزارش‌های کامل وضعیت اجرای برنامه را ثبت می‌کنند، از جمله ورودی‌های کاربر، پاسخ‌های عامل، برنامه‌ریزی و استفاده از ابزار.",
"agentDetail.logs.empty": "هیچ گزارشی یافت نشد",
@@ -279,7 +313,7 @@
"agentDetail.navigationLabel": "ناوبری عامل",
"agentDetail.publish": "انتشار",
"agentDetail.sections.access": "نقطه دسترسی",
- "agentDetail.sections.configure": "هماهنگ‌سازی",
+ "agentDetail.sections.configure": "پیکربندی",
"agentDetail.sections.logs": "گزارش‌ها",
"agentDetail.sections.monitoring": "نظارت",
"agentDetail.title": "عامل",
@@ -334,6 +368,11 @@
"roster.nodeSelector.startFromScratch": "از صفر شروع کنید",
"roster.references.label": "گردش‌های کار با استفاده از {{name}}",
"roster.references.trigger": "گردش‌های کار با استفاده از {{name}}",
+ "roster.saveToRoster": "Save to Agent Console",
+ "roster.saveToRosterDialog.description": "Save this inline setup as a reusable roster agent.",
+ "roster.saveToRosterDialog.title": "Save to Agent Console",
+ "roster.saveToRosterForm.changeIcon": "Change roster agent icon",
+ "roster.saveToRosterSuccess": "Agent saved to roster.",
"roster.searchLabel": "جستجوی عوامل",
"roster.searchPlaceholder": "جستجوی عوامل بر اساس نام…",
"roster.tabs.agent": "عامل",
diff --git a/web/i18n/fa-IR/common.json b/web/i18n/fa-IR/common.json
index 56ff2f80cbb..94cd6ceb8cb 100644
--- a/web/i18n/fa-IR/common.json
+++ b/web/i18n/fa-IR/common.json
@@ -288,6 +288,7 @@
"menus.exploreMarketplace": "بازار را کاوش کنید",
"menus.plugins": "یکپارچه‌سازی‌ها",
"menus.roster": "فهرست عامل‌ها",
+ "menus.status": "بتا",
"menus.tools": "ابزارها",
"model.capabilities": "قابلیت های چند وجهی",
"model.params.stop_sequencesPlaceholder": "توالی را وارد کنید و Tab را فشار دهید",
diff --git a/web/i18n/fa-IR/workflow.json b/web/i18n/fa-IR/workflow.json
index 2676e5a08eb..88a68150568 100644
--- a/web/i18n/fa-IR/workflow.json
+++ b/web/i18n/fa-IR/workflow.json
@@ -464,7 +464,7 @@
"nodes.agent.task.label": "وظیفه عامل",
"nodes.agent.task.mention": "اشاره",
"nodes.agent.task.placeholder": "شرح دهید این عامل باید چه کاری انجام دهد...",
- "nodes.agent.task.tooltip": "دستورالعمل‌های وظیفه‌ای را که این عامل باید در این گردش کار دنبال کند تعریف کنید.",
+ "nodes.agent.task.tooltip": "پرامپت اضافی برای کمک به عامل در مدیریت همین گره. از / برای ارجاع صریح به متغیرها استفاده کنید.\nاگر به‌درستی پیکربندی شود، می‌توانید به عامل خود اعتماد کنید تا خودش مسائل را حل کند.",
"nodes.agent.toolNotAuthorizedTooltip": "{{tool}} مجوز ندارد",
"nodes.agent.toolNotInstallTooltip": "{{tool}} نصب نشده است",
"nodes.agent.toolbox": "جعبه ابزار",
diff --git a/web/i18n/fr-FR/agent-v-2.json b/web/i18n/fr-FR/agent-v-2.json
index 4ee8718b48e..f7f678e06ae 100644
--- a/web/i18n/fr-FR/agent-v-2.json
+++ b/web/i18n/fr-FR/agent-v-2.json
@@ -49,14 +49,27 @@
"agentDetail.configure.advancedSettings.envEditor.keyPlaceholder": "Key",
"agentDetail.configure.advancedSettings.envEditor.label": "Env Editor",
"agentDetail.configure.advancedSettings.envEditor.revealValue": "Afficher la valeur de {{key}}",
+ "agentDetail.configure.advancedSettings.envEditor.richTip": "Votre agent s’exécute dans un environnement Linux. Vous pouvez prédéfinir des configurations ou des secrets en définissant ici des variables d’environnement.\n\nVous pouvez aussi toujours faire la configuration via un chat Build. Consultez la <docLink>documentation</docLink>.",
"agentDetail.configure.advancedSettings.envEditor.scopeColumn": "Scope",
"agentDetail.configure.advancedSettings.envEditor.scopePlain": "Plain",
"agentDetail.configure.advancedSettings.envEditor.scopeSecret": "Secret",
"agentDetail.configure.advancedSettings.envEditor.scopeSelector": "Sélectionner la portée de la variable d’environnement",
- "agentDetail.configure.advancedSettings.envEditor.tip": "Variables d’environnement disponibles pour cet agent au moment de l’exécution.",
+ "agentDetail.configure.advancedSettings.envEditor.tip": "Votre agent s’exécute dans un environnement Linux. Vous pouvez prédéfinir des configurations ou des secrets en définissant ici des variables d’environnement. Vous pouvez aussi toujours faire la configuration via un chat Build. Consultez la documentation.",
+ "agentDetail.configure.advancedSettings.envEditor.toggle": "Basculer Env Editor",
"agentDetail.configure.advancedSettings.envEditor.valueColumn": "Value",
"agentDetail.configure.advancedSettings.envEditor.valuePlaceholder": "Value",
"agentDetail.configure.advancedSettings.label": "Paramètres avancés",
+ "agentDetail.configure.advancedSettings.toggle": "Basculer les paramètres avancés",
+ "agentDetail.configure.build.empty.description": "Décrivez ce que vous voulez et le formulaire de gauche se remplit au fil de la conversation.",
+ "agentDetail.configure.build.empty.title": "Créez votre agent par chat",
+ "agentDetail.configure.build.inputPlaceholder": "Décrivez ce que votre agent doit faire",
+ "agentDetail.configure.build.startBuild": "Démarrer la création",
+ "agentDetail.configure.buildDraft.changes": "{{count}} modifications à appliquer",
+ "agentDetail.configure.buildDraft.discard": "Ignorer",
+ "agentDetail.configure.buildDraft.modeBadge": "Mode build",
+ "agentDetail.configure.buildDraft.modeDescription": "Vous êtes en mode build. Ajustez cette configuration avec le chat à droite, puis appliquez.",
+ "agentDetail.configure.buildDraft.noChanges": "Aucune modification à appliquer",
+ "agentDetail.configure.buildDraft.title": "Brouillon de build",
"agentDetail.configure.chatFeatures.description": "Façonnez l’expérience de chat de l’utilisateur final sur votre webapp et vos surfaces de chat.",
"agentDetail.configure.chatFeatures.title": "Fonctionnalités de chat",
"agentDetail.configure.files.add": "Ajouter un fichier",
@@ -67,7 +80,8 @@
"agentDetail.configure.files.preview.failed": "Échec du chargement de l’aperçu.",
"agentDetail.configure.files.preview.unsupported": "Ce fichier ne prend pas en charge l’aperçu.",
"agentDetail.configure.files.remove": "Supprimer {{name}}",
- "agentDetail.configure.files.tip": "Fichiers que cet agent peut utiliser lors de l’orchestration des tâches.",
+ "agentDetail.configure.files.tip": "Fournissez à votre agent tout exemple, consigne ou simple support d’information trop long pour le prompt. Référencez-le explicitement avec / dans le prompt.",
+ "agentDetail.configure.files.toggle": "Basculer les fichiers",
"agentDetail.configure.files.treeLabel": "Fichiers de l’agent",
"agentDetail.configure.files.upload.action": "Téléverser",
"agentDetail.configure.files.upload.browse": "parcourir",
@@ -113,8 +127,11 @@
"agentDetail.configure.orchestrate": "Orchestrer",
"agentDetail.configure.preview.chatFeatures": "Fonctionnalités de chat",
"agentDetail.configure.preview.empty.defaultAgentName": "Agent",
- "agentDetail.configure.preview.empty.description": "Envoyez un message pour tester le brouillon actuel.",
+ "agentDetail.configure.preview.empty.description": "Exécutez l’agent comme un chat finalisé, exactement comme les utilisateurs le verront une fois publié.",
"agentDetail.configure.preview.empty.noInstructionsDescription": "Pas encore d’instructions, donc les réponses proviennent du modèle brut.",
+ "agentDetail.configure.preview.empty.title": "Aperçu de {{name}}",
+ "agentDetail.configure.preview.endUserAuth": "Authentification de l’utilisateur final",
+ "agentDetail.configure.preview.inputPlaceholder": "Envoyer un message à {{name}}",
"agentDetail.configure.preview.restart": "Redémarrer l’aperçu",
"agentDetail.configure.preview.title": "Aperçu",
"agentDetail.configure.prompt.copied": "Prompt copié",
@@ -128,7 +145,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "Écrivez les instructions ici,",
- "agentDetail.configure.prompt.tip": "Définissez comment cet agent doit interpréter les entrées, appeler les outils et produire les sorties.",
+ "agentDetail.configure.prompt.tip": "Définissez le rôle de l’agent et décrivez sa tâche habituelle. Utilisez / pour faire explicitement référence aux compétences, fichiers, outils et récupérations de connaissances.",
"agentDetail.configure.publishBar.draft": "Brouillon",
"agentDetail.configure.publishBar.publishUpdate": "Publier la mise à jour",
"agentDetail.configure.publishBar.published": "Publié",
@@ -147,6 +164,14 @@
"agentDetail.configure.publishImpact.title": "{{action}} pour {{name}}",
"agentDetail.configure.publishImpact.workflowCount_one": "{{count}} workflow",
"agentDetail.configure.publishImpact.workflowCount_other": "{{count}} workflows",
+ "agentDetail.configure.rightPanel.build": "Créer",
+ "agentDetail.configure.rightPanel.buildTipBody": "Build configure l’agent par chat. Décrivez ce que vous voulez et il remplit la configuration à gauche.",
+ "agentDetail.configure.rightPanel.buildTipTitle": "Construire votre agent par chat",
+ "agentDetail.configure.rightPanel.learnMore": "En savoir plus",
+ "agentDetail.configure.rightPanel.modeLabel": "Mode de configuration de l’agent",
+ "agentDetail.configure.rightPanel.preview": "Aperçu",
+ "agentDetail.configure.rightPanel.previewTipBody": "Preview exécute l’agent final comme vos utilisateurs le verront, avec des réponses claires et les fonctions de chat.",
+ "agentDetail.configure.rightPanel.previewTipTitle": "Prévisualiser votre agent",
"agentDetail.configure.skills.add": "Ajouter une compétence",
"agentDetail.configure.skills.detail.contentRegion": "Contenu des détails de la compétence",
"agentDetail.configure.skills.detail.fileCount": "{{count}} FICHIERS",
@@ -156,7 +181,9 @@
"agentDetail.configure.skills.itemType": "Compétence",
"agentDetail.configure.skills.label": "Compétences",
"agentDetail.configure.skills.remove": "Supprimer {{name}}",
- "agentDetail.configure.skills.tip": "Compétences que cet agent peut utiliser lors de l’orchestration des tâches.",
+ "agentDetail.configure.skills.richTip": "Équipez votre agent de capacités modulaires. Consultez la <docLink>documentation</docLink>. Référencez-les explicitement avec / dans le prompt.",
+ "agentDetail.configure.skills.tip": "Équipez votre agent de capacités modulaires. Consultez la documentation. Référencez-les explicitement avec / dans le prompt.",
+ "agentDetail.configure.skills.toggle": "Basculer les compétences",
"agentDetail.configure.skills.upload.action": "Téléverser",
"agentDetail.configure.skills.upload.browse": "parcourir",
"agentDetail.configure.skills.upload.description": "Téléversez un paquet .zip ou .skill pour cet agent.",
@@ -166,6 +193,7 @@
"agentDetail.configure.skills.upload.invalidFile": "Téléversez un fichier .zip ou .skill.",
"agentDetail.configure.skills.upload.success": "Compétence téléversée.",
"agentDetail.configure.skills.upload.title": "Téléverser une compétence",
+ "agentDetail.configure.title": "Configurer",
"agentDetail.configure.tools.add": "Ajouter un outil",
"agentDetail.configure.tools.addMenu.cliTool.badge": "Pour les développeurs",
"agentDetail.configure.tools.addMenu.cliTool.description": "Installez un programme en ligne de commande que l’agent exécute dans son sandbox. Nécessite une installation et généralement des clés API.",
@@ -179,7 +207,7 @@
"agentDetail.configure.tools.cliDialog.env.optional": "(facultatif)",
"agentDetail.configure.tools.cliDialog.installCommand.description": "Sandboxé · s’exécute une fois lors du premier appel",
"agentDetail.configure.tools.cliDialog.installCommand.label": "Commande d’installation",
- "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "Collez votre commande d’installation ici, p. ex. npm install -g @lark/cli · brew install jq",
+ "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "Collez votre commande d’installation ici, p. ex. npx -y @playwright/mcp@latest · uv tool install httpie",
"agentDetail.configure.tools.cliDialog.installCommand.required": "La commande d’installation est requise.",
"agentDetail.configure.tools.cliDialog.learnMore": "En savoir plus sur l’outil CLI",
"agentDetail.configure.tools.cliDialog.name.label": "Nom de l’outil CLI",
@@ -196,13 +224,19 @@
"agentDetail.configure.tools.moreActions": "Plus d’actions pour {{name}}",
"agentDetail.configure.tools.removeAction": "Supprimer {{name}}",
"agentDetail.configure.tools.removeProvider": "Supprimer tous les outils",
- "agentDetail.configure.tools.tip": "Outils que cet agent peut appeler lors de l’orchestration des tâches.",
+ "agentDetail.configure.tools.richTip": "Équipez votre agent avec les plugins de Dify. Consultez la <pluginDocLink>documentation</pluginDocLink>. Référencez-les explicitement avec / dans le prompt.\nVous pouvez aussi toujours demander à l’agent d’installer et d’authentifier d’autres outils (par exemple des MCPs et des outils CLI) via un chat Build. Notez que les outils configurés via les chats Build n’apparaîtront PAS ici, même s’ils resteront disponibles pour votre agent par la suite. Consultez la <buildDocLink>documentation</buildDocLink>.",
+ "agentDetail.configure.tools.tip": "Équipez votre agent avec les plugins de Dify. Consultez la documentation. Référencez-les explicitement avec / dans le prompt. Vous pouvez aussi toujours demander à l’agent d’installer et d’authentifier d’autres outils (par exemple des MCPs et des outils CLI) via un chat Build. Notez que les outils configurés via les chats Build n’apparaîtront PAS ici, même s’ils resteront disponibles pour votre agent par la suite. Consultez la documentation.",
+ "agentDetail.configure.tools.toggle": "Basculer les outils",
"agentDetail.configure.tools.toolTabs.all": "Tous",
"agentDetail.configure.tools.toolTabs.cli": "CLI",
"agentDetail.configure.tools.toolTabs.custom": "Personnalisé",
"agentDetail.configure.tools.toolTabs.mcp": "MCP",
"agentDetail.configure.tools.toolTabs.plugins": "Plugins",
"agentDetail.configure.tools.toolTabs.workflow": "Workflow",
+ "agentDetail.configure.workingDirectory.description": "Fichiers que l’agent lit et écrit pendant son exécution. Tout ce qu’il génère, comme qna_report.pdf, apparaît ici.",
+ "agentDetail.configure.workingDirectory.open": "Ouvrir le répertoire de travail",
+ "agentDetail.configure.workingDirectory.title": "Répertoire de travail",
+ "agentDetail.configure.workingDirectory.treeLabel": "Fichiers du répertoire de travail",
"agentDetail.documentTitle": "Agent",
"agentDetail.logs.description": "Les journaux complets enregistrent l’état d’exécution de l’application, y compris les entrées des utilisateurs, les réponses de l’agent, la planification et l’utilisation des outils.",
"agentDetail.logs.empty": "Aucun journal trouvé",
@@ -279,7 +313,7 @@
"agentDetail.navigationLabel": "Navigation de l’agent",
"agentDetail.publish": "Publier",
"agentDetail.sections.access": "Point d’accès",
- "agentDetail.sections.configure": "Orchestrer",
+ "agentDetail.sections.configure": "Configurer",
"agentDetail.sections.logs": "Journaux",
"agentDetail.sections.monitoring": "Surveillance",
"agentDetail.title": "Agent",
@@ -334,6 +368,11 @@
"roster.nodeSelector.startFromScratch": "Partir de zéro",
"roster.references.label": "Workflows utilisant {{name}}",
"roster.references.trigger": "Workflows utilisant {{name}}",
+ "roster.saveToRoster": "Save to Agent Console",
+ "roster.saveToRosterDialog.description": "Save this inline setup as a reusable roster agent.",
+ "roster.saveToRosterDialog.title": "Save to Agent Console",
+ "roster.saveToRosterForm.changeIcon": "Change roster agent icon",
+ "roster.saveToRosterSuccess": "Agent saved to roster.",
"roster.searchLabel": "Rechercher des agents",
"roster.searchPlaceholder": "Rechercher des agents par nom…",
"roster.tabs.agent": "Agent",
diff --git a/web/i18n/fr-FR/common.json b/web/i18n/fr-FR/common.json
index 4f025ba7c98..5a89527c4cd 100644
--- a/web/i18n/fr-FR/common.json
+++ b/web/i18n/fr-FR/common.json
@@ -288,6 +288,7 @@
"menus.exploreMarketplace": "Explorer Marketplace",
"menus.plugins": "Intégrations",
"menus.roster": "Répertoire des agents",
+ "menus.status": "bêta",
"menus.tools": "Outils",
"model.capabilities": "Capacités multimodales",
"model.params.stop_sequencesPlaceholder": "Entrez la séquence et appuyez sur Tab",
diff --git a/web/i18n/fr-FR/workflow.json b/web/i18n/fr-FR/workflow.json
index 19ea55eca76..44727994911 100644
--- a/web/i18n/fr-FR/workflow.json
+++ b/web/i18n/fr-FR/workflow.json
@@ -464,7 +464,7 @@
"nodes.agent.task.label": "Tâche de l’agent",
"nodes.agent.task.mention": "Mentionner",
"nodes.agent.task.placeholder": "Décrivez ce que cet agent doit faire...",
- "nodes.agent.task.tooltip": "Définissez les instructions de tâche que cet agent doit suivre dans ce workflow.",
+ "nodes.agent.task.tooltip": "Prompt supplémentaire pour aider l’agent à traiter ce nœud précis. Utilisez / pour faire explicitement référence aux variables.\nSi la configuration est correcte, vous pourriez faire confiance à votre agent pour comprendre les choses par lui-même.",
"nodes.agent.toolNotAuthorizedTooltip": "{{tool}} Non autorisé",
"nodes.agent.toolNotInstallTooltip": "{{tool}} n’est pas installé",
"nodes.agent.toolbox": "boîte à outils",
diff --git a/web/i18n/hi-IN/agent-v-2.json b/web/i18n/hi-IN/agent-v-2.json
index afcd83c11d1..1ee1b9cb965 100644
--- a/web/i18n/hi-IN/agent-v-2.json
+++ b/web/i18n/hi-IN/agent-v-2.json
@@ -49,14 +49,27 @@
"agentDetail.configure.advancedSettings.envEditor.keyPlaceholder": "Key",
"agentDetail.configure.advancedSettings.envEditor.label": "Env Editor",
"agentDetail.configure.advancedSettings.envEditor.revealValue": "{{key}} मान दिखाएँ",
+ "agentDetail.configure.advancedSettings.envEditor.richTip": "आपका एजेंट Linux environment में चलता है। आप यहां environmental variables परिभाषित करके configs या secrets preset कर सकते हैं।\n\nवैकल्पिक रूप से, आप Build chat के माध्यम से भी चीजें set up करवा सकते हैं। <docLink>docs</docLink> देखें।",
"agentDetail.configure.advancedSettings.envEditor.scopeColumn": "Scope",
"agentDetail.configure.advancedSettings.envEditor.scopePlain": "Plain",
"agentDetail.configure.advancedSettings.envEditor.scopeSecret": "Secret",
"agentDetail.configure.advancedSettings.envEditor.scopeSelector": "पर्यावरण चर का दायरा चुनें",
- "agentDetail.configure.advancedSettings.envEditor.tip": "रनटाइम पर इस एजेंट के लिए उपलब्ध पर्यावरण चर।",
+ "agentDetail.configure.advancedSettings.envEditor.tip": "आपका एजेंट Linux environment में चलता है। आप यहां environmental variables परिभाषित करके configs या secrets preset कर सकते हैं। वैकल्पिक रूप से, आप Build chat के माध्यम से भी चीजें set up करवा सकते हैं। docs देखें।",
+ "agentDetail.configure.advancedSettings.envEditor.toggle": "Env Editor टॉगल करें",
"agentDetail.configure.advancedSettings.envEditor.valueColumn": "Value",
"agentDetail.configure.advancedSettings.envEditor.valuePlaceholder": "Value",
"agentDetail.configure.advancedSettings.label": "उन्नत सेटिंग्स",
+ "agentDetail.configure.advancedSettings.toggle": "उन्नत सेटिंग्स टॉगल करें",
+ "agentDetail.configure.build.empty.description": "आप जो चाहते हैं उसका वर्णन करें और बाईं ओर का फ़ॉर्म बातचीत के साथ भरता जाएगा।",
+ "agentDetail.configure.build.empty.title": "चैट करके अपना एजेंट बनाएं",
+ "agentDetail.configure.build.inputPlaceholder": "बताएं कि आपका एजेंट क्या करे",
+ "agentDetail.configure.build.startBuild": "बिल्ड शुरू करें",
+ "agentDetail.configure.buildDraft.changes": "{{count}} बदलाव लागू करने हैं",
+ "agentDetail.configure.buildDraft.discard": "छोड़ें",
+ "agentDetail.configure.buildDraft.modeBadge": "बिल्ड मोड",
+ "agentDetail.configure.buildDraft.modeDescription": "आप बिल्ड मोड में हैं। दाईं ओर की चैट से इस सेटअप को आकार दें, फिर लागू करें।",
+ "agentDetail.configure.buildDraft.noChanges": "लागू करने के लिए कोई बदलाव नहीं",
+ "agentDetail.configure.buildDraft.title": "बिल्ड ड्राफ्ट",
"agentDetail.configure.chatFeatures.description": "अपने Web app और चैट सतहों पर अंतिम-उपयोगकर्ता चैट अनुभव को आकार दें।",
"agentDetail.configure.chatFeatures.title": "चैट सुविधाएँ",
"agentDetail.configure.files.add": "फ़ाइल जोड़ें",
@@ -67,7 +80,8 @@
"agentDetail.configure.files.preview.failed": "पूर्वावलोकन लोड करने में विफल।",
"agentDetail.configure.files.preview.unsupported": "यह फ़ाइल पूर्वावलोकन का समर्थन नहीं करती।",
"agentDetail.configure.files.remove": "{{name}} हटाएँ",
- "agentDetail.configure.files.tip": "इस एजेंट द्वारा कार्यों को व्यवस्थित करते समय उपयोग की जा सकने वाली फ़ाइलें।",
+ "agentDetail.configure.files.tip": "अपने एजेंट को कोई उदाहरण, दिशा-निर्देश या ऐसी जानकारी दें जो प्रॉम्प्ट के लिए बहुत लंबी हो। प्रॉम्प्ट में / का उपयोग करके स्पष्ट संदर्भ दें।",
+ "agentDetail.configure.files.toggle": "फ़ाइलें टॉगल करें",
"agentDetail.configure.files.treeLabel": "एजेंट फ़ाइलें",
"agentDetail.configure.files.upload.action": "अपलोड करें",
"agentDetail.configure.files.upload.browse": "ब्राउज़ करें",
@@ -113,8 +127,11 @@
"agentDetail.configure.orchestrate": "व्यवस्थित करें",
"agentDetail.configure.preview.chatFeatures": "चैट सुविधाएँ",
"agentDetail.configure.preview.empty.defaultAgentName": "एजेंट",
- "agentDetail.configure.preview.empty.description": "वर्तमान ड्राफ्ट का परीक्षण करने के लिए एक संदेश भेजें।",
+ "agentDetail.configure.preview.empty.description": "एजेंट को तैयार चैट की तरह चलाएं, ठीक वैसे जैसे लोग प्रकाशित होने के बाद अनुभव करेंगे।",
"agentDetail.configure.preview.empty.noInstructionsDescription": "अभी तक कोई निर्देश नहीं, इसलिए उत्तर सामान्य मॉडल से आते हैं।",
+ "agentDetail.configure.preview.empty.title": "{{name}} का पूर्वावलोकन",
+ "agentDetail.configure.preview.endUserAuth": "अंतिम-उपयोगकर्ता प्रमाणीकरण",
+ "agentDetail.configure.preview.inputPlaceholder": "{{name}} को संदेश भेजें",
"agentDetail.configure.preview.restart": "पूर्वावलोकन पुनः आरंभ करें",
"agentDetail.configure.preview.title": "पूर्वावलोकन",
"agentDetail.configure.prompt.copied": "प्रॉम्प्ट कॉपी हो गया",
@@ -128,7 +145,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "यहाँ निर्देश लिखें,",
- "agentDetail.configure.prompt.tip": "परिभाषित करें कि यह एजेंट इनपुट की व्याख्या कैसे करे, उपकरण कैसे कॉल करे और आउटपुट कैसे उत्पन्न करे।",
+ "agentDetail.configure.prompt.tip": "एजेंट की भूमिका परिभाषित करें और उसके सामान्य कार्य का वर्णन करें। Skills, Files, Tools और Knowledge Retrievals का स्पष्ट संदर्भ देने के लिए / का उपयोग करें।",
"agentDetail.configure.publishBar.draft": "ड्राफ्ट",
"agentDetail.configure.publishBar.publishUpdate": "अपडेट प्रकाशित करें",
"agentDetail.configure.publishBar.published": "प्रकाशित",
@@ -147,6 +164,14 @@
"agentDetail.configure.publishImpact.title": "{{name}} पर {{action}}",
"agentDetail.configure.publishImpact.workflowCount_one": "{{count}} वर्कफ़्लो",
"agentDetail.configure.publishImpact.workflowCount_other": "{{count}} वर्कफ़्लो",
+ "agentDetail.configure.rightPanel.build": "बिल्ड",
+ "agentDetail.configure.rightPanel.buildTipBody": "Build chat के ज़रिए agent सेट करता है। आप जो चाहते हैं उसे बताएं और यह बाईं ओर की setup भर देता है।",
+ "agentDetail.configure.rightPanel.buildTipTitle": "Chat के ज़रिए अपना agent बनाएं",
+ "agentDetail.configure.rightPanel.learnMore": "और जानें",
+ "agentDetail.configure.rightPanel.modeLabel": "एजेंट कॉन्फ़िगरेशन मोड",
+ "agentDetail.configure.rightPanel.preview": "पूर्वावलोकन",
+ "agentDetail.configure.rightPanel.previewTipBody": "Preview तैयार agent को वैसे चलाता है जैसे आपके users उसे देखेंगे, साफ replies और chat features के साथ।",
+ "agentDetail.configure.rightPanel.previewTipTitle": "अपने agent का preview करें",
"agentDetail.configure.skills.add": "कौशल जोड़ें",
"agentDetail.configure.skills.detail.contentRegion": "कौशल विवरण सामग्री",
"agentDetail.configure.skills.detail.fileCount": "{{count}} फ़ाइलें",
@@ -156,7 +181,9 @@
"agentDetail.configure.skills.itemType": "कौशल",
"agentDetail.configure.skills.label": "कौशल",
"agentDetail.configure.skills.remove": "{{name}} हटाएँ",
- "agentDetail.configure.skills.tip": "इस एजेंट द्वारा कार्यों को व्यवस्थित करते समय उपयोग किए जा सकने वाले कौशल।",
+ "agentDetail.configure.skills.richTip": "अपने एजेंट को मॉड्यूलर क्षमताओं से लैस करें। <docLink>दस्तावेज़</docLink> देखें। प्रॉम्प्ट में / का उपयोग करके स्पष्ट संदर्भ दें।",
+ "agentDetail.configure.skills.tip": "अपने एजेंट को मॉड्यूलर क्षमताओं से लैस करें। दस्तावेज़ देखें। प्रॉम्प्ट में / का उपयोग करके स्पष्ट संदर्भ दें।",
+ "agentDetail.configure.skills.toggle": "कौशल टॉगल करें",
"agentDetail.configure.skills.upload.action": "अपलोड करें",
"agentDetail.configure.skills.upload.browse": "ब्राउज़ करें",
"agentDetail.configure.skills.upload.description": "इस एजेंट के लिए .zip या .skill पैकेज अपलोड करें।",
@@ -166,6 +193,7 @@
"agentDetail.configure.skills.upload.invalidFile": "एक .zip या .skill फ़ाइल अपलोड करें।",
"agentDetail.configure.skills.upload.success": "कौशल अपलोड हो गया।",
"agentDetail.configure.skills.upload.title": "कौशल अपलोड करें",
+ "agentDetail.configure.title": "कॉन्फ़िगर करें",
"agentDetail.configure.tools.add": "उपकरण जोड़ें",
"agentDetail.configure.tools.addMenu.cliTool.badge": "डेवलपर्स के लिए",
"agentDetail.configure.tools.addMenu.cliTool.description": "एक कमांड लाइन प्रोग्राम स्थापित करें जिसे एजेंट अपने सैंडबॉक्स में चलाता है। स्थापना और आमतौर पर API Key की आवश्यकता होती है।",
@@ -179,7 +207,7 @@
"agentDetail.configure.tools.cliDialog.env.optional": "(वैकल्पिक)",
"agentDetail.configure.tools.cliDialog.installCommand.description": "सैंडबॉक्स में · पहली कॉल पर एक बार चलता है",
"agentDetail.configure.tools.cliDialog.installCommand.label": "स्थापना कमांड",
- "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "अपनी स्थापना कमांड यहाँ चिपकाएँ, उदा. npm install -g @lark/cli · brew install jq",
+ "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "अपनी स्थापना कमांड यहाँ चिपकाएँ, उदा. npx -y @playwright/mcp@latest · uv tool install httpie",
"agentDetail.configure.tools.cliDialog.installCommand.required": "स्थापना कमांड आवश्यक है।",
"agentDetail.configure.tools.cliDialog.learnMore": "CLI उपकरण के बारे में और जानें",
"agentDetail.configure.tools.cliDialog.name.label": "CLI उपकरण का नाम",
@@ -196,13 +224,19 @@
"agentDetail.configure.tools.moreActions": "{{name}} के लिए और क्रियाएँ",
"agentDetail.configure.tools.removeAction": "{{name}} हटाएँ",
"agentDetail.configure.tools.removeProvider": "सभी उपकरण हटाएँ",
- "agentDetail.configure.tools.tip": "इस एजेंट द्वारा कार्यों को व्यवस्थित करते समय कॉल किए जा सकने वाले उपकरण।",
+ "agentDetail.configure.tools.richTip": "अपने एजेंट को Dify के प्लगइन से लैस करें। <pluginDocLink>दस्तावेज़</pluginDocLink> देखें। प्रॉम्प्ट में / का उपयोग करके स्पष्ट संदर्भ दें।\nवैकल्पिक रूप से, आप Build chat के माध्यम से एजेंट को अन्य टूल (जैसे MCPs और CLI tools) इंस्टॉल और प्रमाणित करने के लिए हमेशा कह सकते हैं। ध्यान दें कि Build chats के माध्यम से कॉन्फ़िगर किए गए टूल यहां दिखाई नहीं देंगे, हालांकि वे आगे भी आपके एजेंट के लिए उपलब्ध रहेंगे। <buildDocLink>दस्तावेज़</buildDocLink> देखें।",
+ "agentDetail.configure.tools.tip": "अपने एजेंट को Dify के प्लगइन से लैस करें। दस्तावेज़ देखें। प्रॉम्प्ट में / का उपयोग करके स्पष्ट संदर्भ दें। वैकल्पिक रूप से, आप Build chat के माध्यम से एजेंट को अन्य टूल (जैसे MCPs और CLI tools) इंस्टॉल और प्रमाणित करने के लिए हमेशा कह सकते हैं। ध्यान दें कि Build chats के माध्यम से कॉन्फ़िगर किए गए टूल यहां दिखाई नहीं देंगे, हालांकि वे आगे भी आपके एजेंट के लिए उपलब्ध रहेंगे। दस्तावेज़ देखें।",
+ "agentDetail.configure.tools.toggle": "उपकरण टॉगल करें",
"agentDetail.configure.tools.toolTabs.all": "सभी",
"agentDetail.configure.tools.toolTabs.cli": "CLI",
"agentDetail.configure.tools.toolTabs.custom": "कस्टम",
"agentDetail.configure.tools.toolTabs.mcp": "MCP",
"agentDetail.configure.tools.toolTabs.plugins": "एकीकरण",
"agentDetail.configure.tools.toolTabs.workflow": "Workflow",
+ "agentDetail.configure.workingDirectory.description": "एजेंट चलते समय जिन फाइलों को पढ़ता और लिखता है। वह जो भी बनाता है, जैसे qna_report.pdf, यहां दिखता है।",
+ "agentDetail.configure.workingDirectory.open": "वर्किंग डायरेक्टरी खोलें",
+ "agentDetail.configure.workingDirectory.title": "वर्किंग डायरेक्टरी",
+ "agentDetail.configure.workingDirectory.treeLabel": "वर्किंग डायरेक्टरी फाइलें",
"agentDetail.documentTitle": "एजेंट",
"agentDetail.logs.description": "पूर्ण लॉग एप्लिकेशन की चल रही स्थिति को रिकॉर्ड करते हैं, जिसमें उपयोगकर्ता इनपुट, एजेंट उत्तर, योजना और उपकरण उपयोग शामिल हैं।",
"agentDetail.logs.empty": "कोई लॉग नहीं मिला",
@@ -279,7 +313,7 @@
"agentDetail.navigationLabel": "एजेंट नेविगेशन",
"agentDetail.publish": "प्रकाशित करें",
"agentDetail.sections.access": "एक्सेस पॉइंट",
- "agentDetail.sections.configure": "व्यवस्थित करें",
+ "agentDetail.sections.configure": "कॉन्फ़िगर करें",
"agentDetail.sections.logs": "लॉग",
"agentDetail.sections.monitoring": "निगरानी",
"agentDetail.title": "एजेंट",
@@ -334,6 +368,11 @@
"roster.nodeSelector.startFromScratch": "शुरुआत से आरंभ करें",
"roster.references.label": "{{name}} का उपयोग करने वाले वर्कफ़्लो",
"roster.references.trigger": "{{name}} का उपयोग करने वाले वर्कफ़्लो",
+ "roster.saveToRoster": "Save to Agent Console",
+ "roster.saveToRosterDialog.description": "Save this inline setup as a reusable roster agent.",
+ "roster.saveToRosterDialog.title": "Save to Agent Console",
+ "roster.saveToRosterForm.changeIcon": "Change roster agent icon",
+ "roster.saveToRosterSuccess": "Agent saved to roster.",
"roster.searchLabel": "एजेंट खोजें",
"roster.searchPlaceholder": "नाम से एजेंट खोजें…",
"roster.tabs.agent": "एजेंट",
diff --git a/web/i18n/hi-IN/common.json b/web/i18n/hi-IN/common.json
index d51a8c07d95..0fb4e519896 100644
--- a/web/i18n/hi-IN/common.json
+++ b/web/i18n/hi-IN/common.json
@@ -288,6 +288,7 @@
"menus.exploreMarketplace": "मार्केटप्लेस का अन्वेषण करें",
"menus.plugins": "एकीकरण",
"menus.roster": "एजेंट सूची",
+ "menus.status": "बीटा",
"menus.tools": "उपकरण",
"model.capabilities": "मल्टीमोडल क्षमताएँ",
"model.params.stop_sequencesPlaceholder": "अनुक्रम दर्ज करें और टैब दबाएं",
diff --git a/web/i18n/hi-IN/workflow.json b/web/i18n/hi-IN/workflow.json
index f009a7348ad..2151812482f 100644
--- a/web/i18n/hi-IN/workflow.json
+++ b/web/i18n/hi-IN/workflow.json
@@ -464,7 +464,7 @@
"nodes.agent.task.label": "एजेंट कार्य",
"nodes.agent.task.mention": "उल्लेख करें",
"nodes.agent.task.placeholder": "वर्णन करें कि यह एजेंट क्या करे...",
- "nodes.agent.task.tooltip": "इस वर्कफ़्लो में इस एजेंट द्वारा पालन किए जाने वाले कार्य निर्देश परिभाषित करें।",
+ "nodes.agent.task.tooltip": "इस node को संभालने में agent की मदद के लिए अतिरिक्त prompt। Variables का स्पष्ट reference देने के लिए / का उपयोग करें।\nयदि सही तरह से configured हो, तो आप अपने agent पर भरोसा कर सकते हैं कि वह चीज़ें खुद समझ लेगा।",
"nodes.agent.toolNotAuthorizedTooltip": "{{tool}} अधिकृत नहीं है",
"nodes.agent.toolNotInstallTooltip": "{{tool}} स्थापित नहीं है",
"nodes.agent.toolbox": "टूलबॉक्स",
diff --git a/web/i18n/id-ID/agent-v-2.json b/web/i18n/id-ID/agent-v-2.json
index bdb5897a775..2b32917a870 100644
--- a/web/i18n/id-ID/agent-v-2.json
+++ b/web/i18n/id-ID/agent-v-2.json
@@ -49,14 +49,27 @@
"agentDetail.configure.advancedSettings.envEditor.keyPlaceholder": "Key",
"agentDetail.configure.advancedSettings.envEditor.label": "Env Editor",
"agentDetail.configure.advancedSettings.envEditor.revealValue": "Tampilkan nilai {{key}}",
+ "agentDetail.configure.advancedSettings.envEditor.richTip": "Agen Anda berjalan di lingkungan Linux. Anda dapat menyiapkan konfigurasi atau rahasia dengan mendefinisikan variabel lingkungan di sini.\n\nSebagai alternatif, Anda selalu dapat menyiapkannya melalui chat Build. Lihat <docLink>dokumentasi</docLink>.",
"agentDetail.configure.advancedSettings.envEditor.scopeColumn": "Scope",
"agentDetail.configure.advancedSettings.envEditor.scopePlain": "Plain",
"agentDetail.configure.advancedSettings.envEditor.scopeSecret": "Secret",
"agentDetail.configure.advancedSettings.envEditor.scopeSelector": "Pilih cakupan variabel lingkungan",
- "agentDetail.configure.advancedSettings.envEditor.tip": "Variabel lingkungan yang tersedia untuk agen ini saat dijalankan.",
+ "agentDetail.configure.advancedSettings.envEditor.tip": "Agen Anda berjalan di lingkungan Linux. Anda dapat menyiapkan konfigurasi atau rahasia dengan mendefinisikan variabel lingkungan di sini. Sebagai alternatif, Anda selalu dapat menyiapkannya melalui chat Build. Lihat dokumentasi.",
+ "agentDetail.configure.advancedSettings.envEditor.toggle": "Alihkan Env Editor",
"agentDetail.configure.advancedSettings.envEditor.valueColumn": "Value",
"agentDetail.configure.advancedSettings.envEditor.valuePlaceholder": "Value",
"agentDetail.configure.advancedSettings.label": "Pengaturan Lanjutan",
+ "agentDetail.configure.advancedSettings.toggle": "Alihkan pengaturan lanjutan",
+ "agentDetail.configure.build.empty.description": "Jelaskan yang Anda inginkan dan formulir di kiri akan terisi seiring percakapan.",
+ "agentDetail.configure.build.empty.title": "Bangun agen Anda lewat chat",
+ "agentDetail.configure.build.inputPlaceholder": "Jelaskan apa yang harus dilakukan agen Anda",
+ "agentDetail.configure.build.startBuild": "Mulai build",
+ "agentDetail.configure.buildDraft.changes": "{{count}} perubahan untuk diterapkan",
+ "agentDetail.configure.buildDraft.discard": "Buang",
+ "agentDetail.configure.buildDraft.modeBadge": "Mode build",
+ "agentDetail.configure.buildDraft.modeDescription": "Anda berada dalam mode build. Bentuk pengaturan ini lewat chat di kanan, lalu terapkan.",
+ "agentDetail.configure.buildDraft.noChanges": "Tidak ada perubahan untuk diterapkan",
+ "agentDetail.configure.buildDraft.title": "Draf build",
"agentDetail.configure.chatFeatures.description": "Bentuk pengalaman chat pengguna akhir di Web app dan permukaan chat Anda.",
"agentDetail.configure.chatFeatures.title": "Fitur Chat",
"agentDetail.configure.files.add": "Tambahkan file",
@@ -67,7 +80,8 @@
"agentDetail.configure.files.preview.failed": "Gagal memuat pratinjau.",
"agentDetail.configure.files.preview.unsupported": "File ini tidak mendukung pratinjau.",
"agentDetail.configure.files.remove": "Hapus {{name}}",
- "agentDetail.configure.files.tip": "File yang dapat digunakan agen ini saat mengorkestrasi tugas.",
+ "agentDetail.configure.files.tip": "Berikan agen Anda contoh, panduan, atau sekadar pembawa informasi yang terlalu panjang untuk prompt. Buat referensi eksplisit dengan / di Prompt.",
+ "agentDetail.configure.files.toggle": "Alihkan file",
"agentDetail.configure.files.treeLabel": "File agen",
"agentDetail.configure.files.upload.action": "Unggah",
"agentDetail.configure.files.upload.browse": "telusuri",
@@ -113,8 +127,11 @@
"agentDetail.configure.orchestrate": "Orkestrasi",
"agentDetail.configure.preview.chatFeatures": "Fitur Chat",
"agentDetail.configure.preview.empty.defaultAgentName": "Agen",
- "agentDetail.configure.preview.empty.description": "Kirim pesan untuk menguji draf saat ini.",
+ "agentDetail.configure.preview.empty.description": "Jalankan agen sebagai chat final, persis seperti yang akan dialami orang setelah diterbitkan.",
"agentDetail.configure.preview.empty.noInstructionsDescription": "Belum ada instruksi, jadi balasan datang dari model polos.",
+ "agentDetail.configure.preview.empty.title": "Pratinjau {{name}}",
+ "agentDetail.configure.preview.endUserAuth": "Autentikasi pengguna akhir",
+ "agentDetail.configure.preview.inputPlaceholder": "Kirim pesan ke {{name}}",
"agentDetail.configure.preview.restart": "Mulai ulang pratinjau",
"agentDetail.configure.preview.title": "Pratinjau",
"agentDetail.configure.prompt.copied": "Prompt disalin",
@@ -128,7 +145,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "Tulis instruksi di sini,",
- "agentDetail.configure.prompt.tip": "Tentukan bagaimana agen ini harus menafsirkan input, memanggil alat, dan menghasilkan output.",
+ "agentDetail.configure.prompt.tip": "Tentukan peran agen dan jelaskan tugas umumnya. Gunakan / untuk membuat referensi eksplisit ke Skills, Files, Tools, dan Knowledge Retrievals.",
"agentDetail.configure.publishBar.draft": "Draf",
"agentDetail.configure.publishBar.publishUpdate": "Terbitkan pembaruan",
"agentDetail.configure.publishBar.published": "Diterbitkan",
@@ -147,6 +164,14 @@
"agentDetail.configure.publishImpact.title": "{{action}} ke {{name}}",
"agentDetail.configure.publishImpact.workflowCount_one": "{{count}} alur kerja",
"agentDetail.configure.publishImpact.workflowCount_other": "{{count}} alur kerja",
+ "agentDetail.configure.rightPanel.build": "Bangun",
+ "agentDetail.configure.rightPanel.buildTipBody": "Build menyiapkan agent lewat chat. Jelaskan yang Anda inginkan dan pengaturan di sebelah kiri akan terisi.",
+ "agentDetail.configure.rightPanel.buildTipTitle": "Bangun agen Anda lewat chat",
+ "agentDetail.configure.rightPanel.learnMore": "Pelajari selengkapnya",
+ "agentDetail.configure.rightPanel.modeLabel": "Mode konfigurasi agen",
+ "agentDetail.configure.rightPanel.preview": "Pratinjau",
+ "agentDetail.configure.rightPanel.previewTipBody": "Preview menjalankan agent yang sudah selesai seperti yang akan dilihat pengguna, dengan balasan rapi dan fitur chat.",
+ "agentDetail.configure.rightPanel.previewTipTitle": "Pratinjau agen Anda",
"agentDetail.configure.skills.add": "Tambahkan keterampilan",
"agentDetail.configure.skills.detail.contentRegion": "Konten detail keterampilan",
"agentDetail.configure.skills.detail.fileCount": "{{count}} FILE",
@@ -156,7 +181,9 @@
"agentDetail.configure.skills.itemType": "Keterampilan",
"agentDetail.configure.skills.label": "Keterampilan",
"agentDetail.configure.skills.remove": "Hapus {{name}}",
- "agentDetail.configure.skills.tip": "Keterampilan yang dapat digunakan agen ini saat mengorkestrasi tugas.",
+ "agentDetail.configure.skills.richTip": "Lengkapi agen Anda dengan kemampuan modular. Lihat <docLink>dokumentasi</docLink>. Buat referensi eksplisit dengan / di Prompt.",
+ "agentDetail.configure.skills.tip": "Lengkapi agen Anda dengan kemampuan modular. Lihat dokumentasi. Buat referensi eksplisit dengan / di Prompt.",
+ "agentDetail.configure.skills.toggle": "Alihkan keterampilan",
"agentDetail.configure.skills.upload.action": "Unggah",
"agentDetail.configure.skills.upload.browse": "telusuri",
"agentDetail.configure.skills.upload.description": "Unggah paket .zip atau .skill untuk agen ini.",
@@ -166,6 +193,7 @@
"agentDetail.configure.skills.upload.invalidFile": "Unggah file .zip atau .skill.",
"agentDetail.configure.skills.upload.success": "Keterampilan diunggah.",
"agentDetail.configure.skills.upload.title": "Unggah keterampilan",
+ "agentDetail.configure.title": "Konfigurasi",
"agentDetail.configure.tools.add": "Tambahkan alat",
"agentDetail.configure.tools.addMenu.cliTool.badge": "Untuk pengembang",
"agentDetail.configure.tools.addMenu.cliTool.description": "Pasang program command line yang dijalankan agen di sandbox-nya. Memerlukan instalasi dan biasanya API Key.",
@@ -179,7 +207,7 @@
"agentDetail.configure.tools.cliDialog.env.optional": "(opsional)",
"agentDetail.configure.tools.cliDialog.installCommand.description": "Sandbox · berjalan sekali pada pemanggilan pertama",
"agentDetail.configure.tools.cliDialog.installCommand.label": "Perintah Instalasi",
- "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "Tempel perintah instalasi Anda di sini, misalnya npm install -g @lark/cli · brew install jq",
+ "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "Tempel perintah instalasi Anda di sini, misalnya npx -y @playwright/mcp@latest · uv tool install httpie",
"agentDetail.configure.tools.cliDialog.installCommand.required": "Perintah instalasi diperlukan.",
"agentDetail.configure.tools.cliDialog.learnMore": "Pelajari lebih lanjut tentang Alat CLI",
"agentDetail.configure.tools.cliDialog.name.label": "Nama Alat CLI",
@@ -196,13 +224,19 @@
"agentDetail.configure.tools.moreActions": "Tindakan lainnya untuk {{name}}",
"agentDetail.configure.tools.removeAction": "Hapus {{name}}",
"agentDetail.configure.tools.removeProvider": "Hapus semua alat",
- "agentDetail.configure.tools.tip": "Alat yang dapat dipanggil agen ini saat mengorkestrasi tugas.",
+ "agentDetail.configure.tools.richTip": "Lengkapi agen Anda dengan plugin Dify. Lihat <pluginDocLink>dokumentasi</pluginDocLink>. Buat referensi eksplisit dengan / di Prompt.\nAtau, Anda selalu dapat meminta agen untuk menginstal dan mengautentikasi alat lain (misalnya MCPs dan CLI tools) melalui Build chat. Perhatikan bahwa alat yang dikonfigurasi melalui Build chats TIDAK akan muncul di sini, meskipun tetap tersedia untuk agen Anda ke depannya. Lihat <buildDocLink>dokumentasi</buildDocLink>.",
+ "agentDetail.configure.tools.tip": "Lengkapi agen Anda dengan plugin Dify. Lihat dokumentasi. Buat referensi eksplisit dengan / di Prompt. Atau, Anda selalu dapat meminta agen untuk menginstal dan mengautentikasi alat lain (misalnya MCPs dan CLI tools) melalui Build chat. Perhatikan bahwa alat yang dikonfigurasi melalui Build chats TIDAK akan muncul di sini, meskipun tetap tersedia untuk agen Anda ke depannya. Lihat dokumentasi.",
+ "agentDetail.configure.tools.toggle": "Alihkan alat",
"agentDetail.configure.tools.toolTabs.all": "Semua",
"agentDetail.configure.tools.toolTabs.cli": "CLI",
"agentDetail.configure.tools.toolTabs.custom": "Kustom",
"agentDetail.configure.tools.toolTabs.mcp": "MCP",
"agentDetail.configure.tools.toolTabs.plugins": "Plugin",
"agentDetail.configure.tools.toolTabs.workflow": "Workflow",
+ "agentDetail.configure.workingDirectory.description": "File yang dibaca dan ditulis agent saat berjalan. Semua yang dibuatnya, seperti qna_report.pdf, muncul di sini.",
+ "agentDetail.configure.workingDirectory.open": "Buka direktori kerja",
+ "agentDetail.configure.workingDirectory.title": "Direktori kerja",
+ "agentDetail.configure.workingDirectory.treeLabel": "File direktori kerja",
"agentDetail.documentTitle": "Agen",
"agentDetail.logs.description": "Log lengkap mencatat status berjalan aplikasi, termasuk input pengguna, balasan agen, perencanaan, dan penggunaan alat.",
"agentDetail.logs.empty": "Tidak ada log ditemukan",
@@ -279,7 +313,7 @@
"agentDetail.navigationLabel": "Navigasi agen",
"agentDetail.publish": "Terbitkan",
"agentDetail.sections.access": "Titik Akses",
- "agentDetail.sections.configure": "Orkestrasi",
+ "agentDetail.sections.configure": "Konfigurasikan",
"agentDetail.sections.logs": "Log",
"agentDetail.sections.monitoring": "Pemantauan",
"agentDetail.title": "Agen",
@@ -334,6 +368,11 @@
"roster.nodeSelector.startFromScratch": "Mulai dari Awal",
"roster.references.label": "Alur kerja yang menggunakan {{name}}",
"roster.references.trigger": "Alur kerja yang menggunakan {{name}}",
+ "roster.saveToRoster": "Save to Agent Console",
+ "roster.saveToRosterDialog.description": "Save this inline setup as a reusable roster agent.",
+ "roster.saveToRosterDialog.title": "Save to Agent Console",
+ "roster.saveToRosterForm.changeIcon": "Change roster agent icon",
+ "roster.saveToRosterSuccess": "Agent saved to roster.",
"roster.searchLabel": "Cari agen",
"roster.searchPlaceholder": "Cari agen berdasarkan nama…",
"roster.tabs.agent": "Agen",
diff --git a/web/i18n/id-ID/common.json b/web/i18n/id-ID/common.json
index fbd92496052..022b998c80f 100644
--- a/web/i18n/id-ID/common.json
+++ b/web/i18n/id-ID/common.json
@@ -288,6 +288,7 @@
"menus.exploreMarketplace": "Jelajahi Marketplace",
"menus.plugins": "Integrasi",
"menus.roster": "Daftar Agen",
+ "menus.status": "beta",
"menus.tools": "Perkakas",
"model.capabilities": "Kemampuan MultiModal",
"model.params.stop_sequencesPlaceholder": "Masukkan urutan dan tekan Tab",
diff --git a/web/i18n/id-ID/workflow.json b/web/i18n/id-ID/workflow.json
index 39f1df2c5c7..0c701f16354 100644
--- a/web/i18n/id-ID/workflow.json
+++ b/web/i18n/id-ID/workflow.json
@@ -464,7 +464,7 @@
"nodes.agent.task.label": "Tugas agen",
"nodes.agent.task.mention": "Sebut",
"nodes.agent.task.placeholder": "Jelaskan apa yang harus dilakukan agen ini...",
- "nodes.agent.task.tooltip": "Tentukan instruksi tugas yang harus diikuti agen ini dalam alur kerja ini.",
+ "nodes.agent.task.tooltip": "Prompt tambahan untuk membantu agen menangani node ini. Gunakan / untuk merujuk variabel secara eksplisit.\nJika dikonfigurasi dengan benar, Anda dapat mempercayai agen untuk mencari tahu sendiri.",
"nodes.agent.toolNotAuthorizedTooltip": "{{tool}} Tidak Berwenang",
"nodes.agent.toolNotInstallTooltip": "{{tool}} tidak terpasang",
"nodes.agent.toolbox": "Toolbox",
diff --git a/web/i18n/it-IT/agent-v-2.json b/web/i18n/it-IT/agent-v-2.json
index eb6eb7c4191..a32cc79f03f 100644
--- a/web/i18n/it-IT/agent-v-2.json
+++ b/web/i18n/it-IT/agent-v-2.json
@@ -49,14 +49,27 @@
"agentDetail.configure.advancedSettings.envEditor.keyPlaceholder": "Key",
"agentDetail.configure.advancedSettings.envEditor.label": "Env Editor",
"agentDetail.configure.advancedSettings.envEditor.revealValue": "Mostra valore di {{key}}",
+ "agentDetail.configure.advancedSettings.envEditor.richTip": "Il tuo agente viene eseguito in un ambiente Linux. Puoi preimpostare configurazioni o segreti definendo qui le variabili d’ambiente.\n\nIn alternativa, puoi sempre configurare tutto tramite una chat Build. Consulta la <docLink>documentazione</docLink>.",
"agentDetail.configure.advancedSettings.envEditor.scopeColumn": "Scope",
"agentDetail.configure.advancedSettings.envEditor.scopePlain": "Plain",
"agentDetail.configure.advancedSettings.envEditor.scopeSecret": "Secret",
"agentDetail.configure.advancedSettings.envEditor.scopeSelector": "Seleziona ambito della variabile d’ambiente",
- "agentDetail.configure.advancedSettings.envEditor.tip": "Variabili d’ambiente disponibili per questo agente in fase di esecuzione.",
+ "agentDetail.configure.advancedSettings.envEditor.tip": "Il tuo agente viene eseguito in un ambiente Linux. Puoi preimpostare configurazioni o segreti definendo qui le variabili d’ambiente. In alternativa, puoi sempre configurare tutto tramite una chat Build. Consulta la documentazione.",
+ "agentDetail.configure.advancedSettings.envEditor.toggle": "Attiva/disattiva Env Editor",
"agentDetail.configure.advancedSettings.envEditor.valueColumn": "Value",
"agentDetail.configure.advancedSettings.envEditor.valuePlaceholder": "Value",
"agentDetail.configure.advancedSettings.label": "Impostazioni avanzate",
+ "agentDetail.configure.advancedSettings.toggle": "Attiva/disattiva impostazioni avanzate",
+ "agentDetail.configure.build.empty.description": "Descrivi ciò che vuoi e il modulo a sinistra verrà compilato man mano.",
+ "agentDetail.configure.build.empty.title": "Crea il tuo agente con la chat",
+ "agentDetail.configure.build.inputPlaceholder": "Descrivi cosa dovrebbe fare il tuo agente",
+ "agentDetail.configure.build.startBuild": "Avvia build",
+ "agentDetail.configure.buildDraft.changes": "{{count}} modifiche da applicare",
+ "agentDetail.configure.buildDraft.discard": "Scarta",
+ "agentDetail.configure.buildDraft.modeBadge": "Modalità build",
+ "agentDetail.configure.buildDraft.modeDescription": "Sei in modalità build. Modella questa configurazione tramite la chat a destra, poi applica.",
+ "agentDetail.configure.buildDraft.noChanges": "Nessuna modifica da applicare",
+ "agentDetail.configure.buildDraft.title": "Bozza di build",
"agentDetail.configure.chatFeatures.description": "Definisci l’esperienza di chat per l’utente finale sulla tua webapp e sulle superfici di chat.",
"agentDetail.configure.chatFeatures.title": "Funzionalità chat",
"agentDetail.configure.files.add": "Aggiungi file",
@@ -67,7 +80,8 @@
"agentDetail.configure.files.preview.failed": "Impossibile caricare l’anteprima.",
"agentDetail.configure.files.preview.unsupported": "Questo file non supporta l’anteprima.",
"agentDetail.configure.files.remove": "Rimuovi {{name}}",
- "agentDetail.configure.files.tip": "File che questo agente può utilizzare durante l’orchestrazione delle attività.",
+ "agentDetail.configure.files.tip": "Fornisci al tuo agente esempi, linee guida o semplicemente informazioni troppo lunghe per il prompt. Fai riferimento esplicito con / nel prompt.",
+ "agentDetail.configure.files.toggle": "Attiva/disattiva file",
"agentDetail.configure.files.treeLabel": "File dell’agente",
"agentDetail.configure.files.upload.action": "Carica",
"agentDetail.configure.files.upload.browse": "sfoglia",
@@ -113,8 +127,11 @@
"agentDetail.configure.orchestrate": "Orchestra",
"agentDetail.configure.preview.chatFeatures": "Funzionalità chat",
"agentDetail.configure.preview.empty.defaultAgentName": "Agente",
- "agentDetail.configure.preview.empty.description": "Invia un messaggio per testare la bozza corrente.",
+ "agentDetail.configure.preview.empty.description": "Esegui l’agente come una chat completa, esattamente come verrà vissuta dopo la pubblicazione.",
"agentDetail.configure.preview.empty.noInstructionsDescription": "Nessuna istruzione ancora, quindi le risposte arrivano dal modello puro.",
+ "agentDetail.configure.preview.empty.title": "Anteprima di {{name}}",
+ "agentDetail.configure.preview.endUserAuth": "Autenticazione utente finale",
+ "agentDetail.configure.preview.inputPlaceholder": "Invia un messaggio a {{name}}",
"agentDetail.configure.preview.restart": "Riavvia anteprima",
"agentDetail.configure.preview.title": "Anteprima",
"agentDetail.configure.prompt.copied": "Prompt copiato",
@@ -128,7 +145,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "Scrivi le istruzioni qui,",
- "agentDetail.configure.prompt.tip": "Definisci come questo agente deve interpretare gli input, chiamare gli strumenti e produrre output.",
+ "agentDetail.configure.prompt.tip": "Definisci il ruolo dell’agente e descrivi la sua attività tipica. Usa / per fare riferimento esplicito a abilità, file, strumenti e recuperi di conoscenza.",
"agentDetail.configure.publishBar.draft": "Bozza",
"agentDetail.configure.publishBar.publishUpdate": "Pubblica aggiornamento",
"agentDetail.configure.publishBar.published": "Pubblicato",
@@ -147,6 +164,14 @@
"agentDetail.configure.publishImpact.title": "{{action}} in {{name}}",
"agentDetail.configure.publishImpact.workflowCount_one": "{{count}} workflow",
"agentDetail.configure.publishImpact.workflowCount_other": "{{count}} workflow",
+ "agentDetail.configure.rightPanel.build": "Crea",
+ "agentDetail.configure.rightPanel.buildTipBody": "Build configura l’agente tramite chat. Descrivi cosa vuoi e compilerà la configurazione a sinistra.",
+ "agentDetail.configure.rightPanel.buildTipTitle": "Costruisci il tuo agente via chat",
+ "agentDetail.configure.rightPanel.learnMore": "Scopri di più",
+ "agentDetail.configure.rightPanel.modeLabel": "Modalità di configurazione agente",
+ "agentDetail.configure.rightPanel.preview": "Anteprima",
+ "agentDetail.configure.rightPanel.previewTipBody": "Preview esegue l’agente completato come lo vedranno gli utenti, con risposte pulite e funzionalità di chat.",
+ "agentDetail.configure.rightPanel.previewTipTitle": "Anteprima del tuo agente",
"agentDetail.configure.skills.add": "Aggiungi abilità",
"agentDetail.configure.skills.detail.contentRegion": "Contenuto dei dettagli dell’abilità",
"agentDetail.configure.skills.detail.fileCount": "{{count}} FILE",
@@ -156,7 +181,9 @@
"agentDetail.configure.skills.itemType": "Abilità",
"agentDetail.configure.skills.label": "Abilità",
"agentDetail.configure.skills.remove": "Rimuovi {{name}}",
- "agentDetail.configure.skills.tip": "Abilità che questo agente può utilizzare durante l’orchestrazione delle attività.",
+ "agentDetail.configure.skills.richTip": "Dota il tuo agente di capacità modulari. Consulta la <docLink>documentazione</docLink>. Fai riferimento esplicito con / nel prompt.",
+ "agentDetail.configure.skills.tip": "Dota il tuo agente di capacità modulari. Consulta la documentazione. Fai riferimento esplicito con / nel prompt.",
+ "agentDetail.configure.skills.toggle": "Attiva/disattiva abilità",
"agentDetail.configure.skills.upload.action": "Carica",
"agentDetail.configure.skills.upload.browse": "sfoglia",
"agentDetail.configure.skills.upload.description": "Carica un pacchetto .zip o .skill per questo agente.",
@@ -166,6 +193,7 @@
"agentDetail.configure.skills.upload.invalidFile": "Carica un file .zip o .skill.",
"agentDetail.configure.skills.upload.success": "Abilità caricata.",
"agentDetail.configure.skills.upload.title": "Carica abilità",
+ "agentDetail.configure.title": "Configura",
"agentDetail.configure.tools.add": "Aggiungi strumento",
"agentDetail.configure.tools.addMenu.cliTool.badge": "Per sviluppatori",
"agentDetail.configure.tools.addMenu.cliTool.description": "Installa un programma a riga di comando che l’agente esegue nel suo sandbox. Richiede installazione e di solito chiavi API.",
@@ -179,7 +207,7 @@
"agentDetail.configure.tools.cliDialog.env.optional": "(facoltativo)",
"agentDetail.configure.tools.cliDialog.installCommand.description": "In sandbox · eseguito una sola volta alla prima invocazione",
"agentDetail.configure.tools.cliDialog.installCommand.label": "Comando di installazione",
- "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "Incolla qui il tuo comando di installazione, ad esempio npm install -g @lark/cli · brew install jq",
+ "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "Incolla qui il tuo comando di installazione, ad esempio npx -y @playwright/mcp@latest · uv tool install httpie",
"agentDetail.configure.tools.cliDialog.installCommand.required": "Il comando di installazione è obbligatorio.",
"agentDetail.configure.tools.cliDialog.learnMore": "Scopri di più sullo strumento CLI",
"agentDetail.configure.tools.cliDialog.name.label": "Nome dello strumento CLI",
@@ -196,13 +224,19 @@
"agentDetail.configure.tools.moreActions": "Altre azioni per {{name}}",
"agentDetail.configure.tools.removeAction": "Rimuovi {{name}}",
"agentDetail.configure.tools.removeProvider": "Rimuovi tutti gli strumenti",
- "agentDetail.configure.tools.tip": "Strumenti che questo agente può chiamare durante l’orchestrazione delle attività.",
+ "agentDetail.configure.tools.richTip": "Dota il tuo agente dei plugin di Dify. Consulta la <pluginDocLink>documentazione</pluginDocLink>. Fai riferimento esplicito con / nel prompt.\nIn alternativa, puoi sempre dire all’agente di installare e autenticare altri strumenti (ad esempio MCPs e strumenti CLI) tramite una chat Build. Nota che gli strumenti configurati tramite chat Build NON appariranno qui, anche se resteranno disponibili per il tuo agente in futuro. Consulta la <buildDocLink>documentazione</buildDocLink>.",
+ "agentDetail.configure.tools.tip": "Dota il tuo agente dei plugin di Dify. Consulta la documentazione. Fai riferimento esplicito con / nel prompt. In alternativa, puoi sempre dire all’agente di installare e autenticare altri strumenti (ad esempio MCPs e strumenti CLI) tramite una chat Build. Nota che gli strumenti configurati tramite chat Build NON appariranno qui, anche se resteranno disponibili per il tuo agente in futuro. Consulta la documentazione.",
+ "agentDetail.configure.tools.toggle": "Attiva/disattiva strumenti",
"agentDetail.configure.tools.toolTabs.all": "Tutti",
"agentDetail.configure.tools.toolTabs.cli": "CLI",
"agentDetail.configure.tools.toolTabs.custom": "Personalizzato",
"agentDetail.configure.tools.toolTabs.mcp": "MCP",
"agentDetail.configure.tools.toolTabs.plugins": "Plugin",
"agentDetail.configure.tools.toolTabs.workflow": "Workflow",
+ "agentDetail.configure.workingDirectory.description": "File che l’agente legge e scrive durante l’esecuzione. Tutto ciò che genera, come qna_report.pdf, appare qui.",
+ "agentDetail.configure.workingDirectory.open": "Apri directory di lavoro",
+ "agentDetail.configure.workingDirectory.title": "Directory di lavoro",
+ "agentDetail.configure.workingDirectory.treeLabel": "File della directory di lavoro",
"agentDetail.documentTitle": "Agente",
"agentDetail.logs.description": "I log completi registrano lo stato di esecuzione dell’applicazione, inclusi input degli utenti, risposte dell’agente, pianificazione e uso degli strumenti.",
"agentDetail.logs.empty": "Nessun log trovato",
@@ -279,7 +313,7 @@
"agentDetail.navigationLabel": "Navigazione dell’agente",
"agentDetail.publish": "Pubblica",
"agentDetail.sections.access": "Punto di accesso",
- "agentDetail.sections.configure": "Orchestra",
+ "agentDetail.sections.configure": "Configura",
"agentDetail.sections.logs": "Log",
"agentDetail.sections.monitoring": "Monitoraggio",
"agentDetail.title": "Agente",
@@ -334,6 +368,11 @@
"roster.nodeSelector.startFromScratch": "Inizia da zero",
"roster.references.label": "Workflow che usano {{name}}",
"roster.references.trigger": "Workflow che usano {{name}}",
+ "roster.saveToRoster": "Save to Agent Console",
+ "roster.saveToRosterDialog.description": "Save this inline setup as a reusable roster agent.",
+ "roster.saveToRosterDialog.title": "Save to Agent Console",
+ "roster.saveToRosterForm.changeIcon": "Change roster agent icon",
+ "roster.saveToRosterSuccess": "Agent saved to roster.",
"roster.searchLabel": "Cerca agenti",
"roster.searchPlaceholder": "Cerca agenti per nome…",
"roster.tabs.agent": "Agente",
diff --git a/web/i18n/it-IT/common.json b/web/i18n/it-IT/common.json
index a109b817282..1f0bece9b05 100644
--- a/web/i18n/it-IT/common.json
+++ b/web/i18n/it-IT/common.json
@@ -288,6 +288,7 @@
"menus.exploreMarketplace": "Esplora il Marketplace",
"menus.plugins": "Integrazione",
"menus.roster": "Elenco agenti",
+ "menus.status": "beta",
"menus.tools": "Strumenti",
"model.capabilities": "Funzionalità multimodali",
"model.params.stop_sequencesPlaceholder": "Inserisci la sequenza e premi Tab",
diff --git a/web/i18n/it-IT/workflow.json b/web/i18n/it-IT/workflow.json
index 799dd96c967..5ea34524ed3 100644
--- a/web/i18n/it-IT/workflow.json
+++ b/web/i18n/it-IT/workflow.json
@@ -464,7 +464,7 @@
"nodes.agent.task.label": "Attività dell’agente",
"nodes.agent.task.mention": "Menziona",
"nodes.agent.task.placeholder": "Descrivi cosa deve fare questo agente...",
- "nodes.agent.task.tooltip": "Definisci le istruzioni dell’attività che questo agente deve seguire in questo workflow.",
+ "nodes.agent.task.tooltip": "Prompt aggiuntivo per aiutare l’agente a gestire proprio questo nodo. Usa / per fare riferimento esplicito alle variabili.\nSe configurato correttamente, potresti poterti fidare dell’agente perché capisca da solo cosa fare.",
"nodes.agent.toolNotAuthorizedTooltip": "{{tool}} Non autorizzato",
"nodes.agent.toolNotInstallTooltip": "{{tool}} non è installato",
"nodes.agent.toolbox": "cassetta degli attrezzi",
diff --git a/web/i18n/ja-JP/agent-v-2.json b/web/i18n/ja-JP/agent-v-2.json
index 45fea31963e..a70330a5e74 100644
--- a/web/i18n/ja-JP/agent-v-2.json
+++ b/web/i18n/ja-JP/agent-v-2.json
@@ -49,14 +49,27 @@
"agentDetail.configure.advancedSettings.envEditor.keyPlaceholder": "Key",
"agentDetail.configure.advancedSettings.envEditor.label": "Env Editor",
"agentDetail.configure.advancedSettings.envEditor.revealValue": "{{key}} の値を表示",
+ "agentDetail.configure.advancedSettings.envEditor.richTip": "エージェントは Linux 環境で実行されます。ここで環境変数を定義して、設定やシークレットを事前に指定できます。\n\nまた、Build チャット経由で設定することもできます。<docLink>ドキュメント</docLink>を参照してください。",
"agentDetail.configure.advancedSettings.envEditor.scopeColumn": "Scope",
"agentDetail.configure.advancedSettings.envEditor.scopePlain": "Plain",
"agentDetail.configure.advancedSettings.envEditor.scopeSecret": "Secret",
"agentDetail.configure.advancedSettings.envEditor.scopeSelector": "環境変数のスコープを選択",
- "agentDetail.configure.advancedSettings.envEditor.tip": "このエージェントが実行時に利用できる環境変数。",
+ "agentDetail.configure.advancedSettings.envEditor.tip": "エージェントは Linux 環境で実行されます。ここで環境変数を定義して、設定やシークレットを事前に指定できます。また、Build チャット経由で設定することもできます。ドキュメントを参照してください。",
+ "agentDetail.configure.advancedSettings.envEditor.toggle": "Env Editor の表示を切り替え",
"agentDetail.configure.advancedSettings.envEditor.valueColumn": "Value",
"agentDetail.configure.advancedSettings.envEditor.valuePlaceholder": "Value",
"agentDetail.configure.advancedSettings.label": "詳細設定",
+ "agentDetail.configure.advancedSettings.toggle": "詳細設定の表示を切り替え",
+ "agentDetail.configure.build.empty.description": "やりたいことを説明すると、左側のフォームが会話に合わせて入力されます。",
+ "agentDetail.configure.build.empty.title": "チャットでエージェントを作成",
+ "agentDetail.configure.build.inputPlaceholder": "エージェントに実行させたいことを説明",
+ "agentDetail.configure.build.startBuild": "ビルドを開始",
+ "agentDetail.configure.buildDraft.changes": "適用する変更 {{count}} 件",
+ "agentDetail.configure.buildDraft.discard": "破棄",
+ "agentDetail.configure.buildDraft.modeBadge": "ビルドモード",
+ "agentDetail.configure.buildDraft.modeDescription": "ビルドモードです。右側のチャットでこの設定を調整してから適用してください。",
+ "agentDetail.configure.buildDraft.noChanges": "適用する変更はありません",
+ "agentDetail.configure.buildDraft.title": "ビルドドラフト",
"agentDetail.configure.chatFeatures.description": "Web app やチャット画面でのエンドユーザー向けチャット体験を設定します。",
"agentDetail.configure.chatFeatures.title": "チャット機能",
"agentDetail.configure.files.add": "ファイルを追加",
@@ -67,7 +80,8 @@
"agentDetail.configure.files.preview.failed": "プレビューの読み込みに失敗しました。",
"agentDetail.configure.files.preview.unsupported": "ファイルはプレビューに対応していません。",
"agentDetail.configure.files.remove": "{{name}} を削除",
- "agentDetail.configure.files.tip": "このエージェントがタスクのオーケストレーション中に利用できるファイル。",
+ "agentDetail.configure.files.tip": "プロンプトには長すぎる例、ガイドライン、または情報そのものをエージェントに提供します。プロンプト内で / を使って明示的に参照してください。",
+ "agentDetail.configure.files.toggle": "ファイルの表示を切り替え",
"agentDetail.configure.files.treeLabel": "エージェントファイル",
"agentDetail.configure.files.upload.action": "アップロード",
"agentDetail.configure.files.upload.browse": "選択",
@@ -113,8 +127,11 @@
"agentDetail.configure.orchestrate": "オーケストレーション",
"agentDetail.configure.preview.chatFeatures": "チャット機能",
"agentDetail.configure.preview.empty.defaultAgentName": "エージェント",
- "agentDetail.configure.preview.empty.description": "メッセージを送信して現在のドラフトをテストします。",
+ "agentDetail.configure.preview.empty.description": "公開後にユーザーが体験する完成版のチャットとしてエージェントを実行します。",
"agentDetail.configure.preview.empty.noInstructionsDescription": "指示が設定されていないため、応答はプレーンなモデルから返ります。",
+ "agentDetail.configure.preview.empty.title": "{{name}} をプレビュー",
+ "agentDetail.configure.preview.endUserAuth": "エンドユーザー認証",
+ "agentDetail.configure.preview.inputPlaceholder": "{{name}} にメッセージを送信",
"agentDetail.configure.preview.restart": "プレビューを再開",
"agentDetail.configure.preview.title": "プレビュー",
"agentDetail.configure.prompt.copied": "プロンプトをコピーしました",
@@ -128,7 +145,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "ここに指示を記述してください、",
- "agentDetail.configure.prompt.tip": "このエージェントが入力をどう解釈し、ツールを呼び出し、出力を生成するかを定義します。",
+ "agentDetail.configure.prompt.tip": "エージェントの役割を定義し、通常のタスクを説明します。/ を使ってスキル、ファイル、ツール、ナレッジ検索を明示的に参照してください。",
"agentDetail.configure.publishBar.draft": "ドラフト",
"agentDetail.configure.publishBar.publishUpdate": "更新を公開",
"agentDetail.configure.publishBar.published": "公開済み",
@@ -147,6 +164,14 @@
"agentDetail.configure.publishImpact.title": "{{name}} に{{action}}",
"agentDetail.configure.publishImpact.workflowCount_one": "{{count}} 個のワークフロー",
"agentDetail.configure.publishImpact.workflowCount_other": "{{count}} 個のワークフロー",
+ "agentDetail.configure.rightPanel.build": "ビルド",
+ "agentDetail.configure.rightPanel.buildTipBody": "Build はチャットを通じてエージェントを設定します。やりたいことを説明すると、左側の設定が入力されます。",
+ "agentDetail.configure.rightPanel.buildTipTitle": "チャットでエージェントを構築",
+ "agentDetail.configure.rightPanel.learnMore": "詳しく見る",
+ "agentDetail.configure.rightPanel.modeLabel": "エージェント設定モード",
+ "agentDetail.configure.rightPanel.preview": "プレビュー",
+ "agentDetail.configure.rightPanel.previewTipBody": "Preview は完成したエージェントをユーザーに見える形で実行し、整った返信とチャット機能を確認できます。",
+ "agentDetail.configure.rightPanel.previewTipTitle": "エージェントをプレビュー",
"agentDetail.configure.skills.add": "スキルを追加",
"agentDetail.configure.skills.detail.contentRegion": "スキル詳細コンテンツ",
"agentDetail.configure.skills.detail.fileCount": "{{count}} 個のファイル",
@@ -156,7 +181,9 @@
"agentDetail.configure.skills.itemType": "スキル",
"agentDetail.configure.skills.label": "スキル",
"agentDetail.configure.skills.remove": "{{name}} を削除",
- "agentDetail.configure.skills.tip": "このエージェントがタスクのオーケストレーション中に利用できるスキル。",
+ "agentDetail.configure.skills.richTip": "エージェントにモジュール式の機能を装備します。<docLink>ドキュメント</docLink>を参照してください。プロンプト内で / を使って明示的に参照してください。",
+ "agentDetail.configure.skills.tip": "エージェントにモジュール式の機能を装備します。ドキュメントを参照してください。プロンプト内で / を使って明示的に参照してください。",
+ "agentDetail.configure.skills.toggle": "スキルの表示を切り替え",
"agentDetail.configure.skills.upload.action": "アップロード",
"agentDetail.configure.skills.upload.browse": "選択",
"agentDetail.configure.skills.upload.description": "このエージェント用の .zip または .skill パッケージをアップロードします。",
@@ -166,6 +193,7 @@
"agentDetail.configure.skills.upload.invalidFile": ".zip または .skill ファイルをアップロードしてください。",
"agentDetail.configure.skills.upload.success": "スキルをアップロードしました。",
"agentDetail.configure.skills.upload.title": "スキルをアップロード",
+ "agentDetail.configure.title": "設定",
"agentDetail.configure.tools.add": "ツールを追加",
"agentDetail.configure.tools.addMenu.cliTool.badge": "開発者向け",
"agentDetail.configure.tools.addMenu.cliTool.description": "エージェントがサンドボックス内で実行するコマンドラインプログラムをインストールします。インストールと通常 API Key が必要です。",
@@ -179,7 +207,7 @@
"agentDetail.configure.tools.cliDialog.env.optional": "(任意)",
"agentDetail.configure.tools.cliDialog.installCommand.description": "サンドボックス内で実行 · 初回呼び出し時に一度だけ実行",
"agentDetail.configure.tools.cliDialog.installCommand.label": "インストールコマンド",
- "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "インストールコマンドをここに貼り付け、例: npm install -g @lark/cli · brew install jq",
+ "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "インストールコマンドをここに貼り付け、例: npx -y @playwright/mcp@latest · uv tool install httpie",
"agentDetail.configure.tools.cliDialog.installCommand.required": "インストールコマンドを入力してください。",
"agentDetail.configure.tools.cliDialog.learnMore": "CLI ツールについて詳しく見る",
"agentDetail.configure.tools.cliDialog.name.label": "CLI ツール名",
@@ -196,13 +224,19 @@
"agentDetail.configure.tools.moreActions": "{{name}} のその他の操作",
"agentDetail.configure.tools.removeAction": "{{name}} を削除",
"agentDetail.configure.tools.removeProvider": "すべてのツールを削除",
- "agentDetail.configure.tools.tip": "このエージェントがタスクのオーケストレーション中に呼び出せるツール。",
+ "agentDetail.configure.tools.richTip": "エージェントに Dify のプラグインを装備します。<pluginDocLink>ドキュメント</pluginDocLink>を参照してください。プロンプト内で / を使って明示的に参照してください。\nまた、Build チャットを通じて、他のツール(MCPs や CLI ツールなど)のインストールと認証をエージェントに指示することもできます。Build チャットで設定したツールはここには表示されませんが、今後もエージェントで利用できます。<buildDocLink>ドキュメント</buildDocLink>を参照してください。",
+ "agentDetail.configure.tools.tip": "エージェントに Dify のプラグインを装備します。ドキュメントを参照してください。プロンプト内で / を使って明示的に参照してください。また、Build チャットを通じて、他のツール(MCPs や CLI ツールなど)のインストールと認証をエージェントに指示することもできます。Build チャットで設定したツールはここには表示されませんが、今後もエージェントで利用できます。ドキュメントを参照してください。",
+ "agentDetail.configure.tools.toggle": "ツールの表示を切り替え",
"agentDetail.configure.tools.toolTabs.all": "すべて",
"agentDetail.configure.tools.toolTabs.cli": "CLI",
"agentDetail.configure.tools.toolTabs.custom": "カスタム",
"agentDetail.configure.tools.toolTabs.mcp": "MCP",
"agentDetail.configure.tools.toolTabs.plugins": "プラグイン",
"agentDetail.configure.tools.toolTabs.workflow": "Workflow",
+ "agentDetail.configure.workingDirectory.description": "エージェントが実行中に読み書きするファイルです。qna_report.pdf など、生成されたものはここに表示されます。",
+ "agentDetail.configure.workingDirectory.open": "作業ディレクトリを開く",
+ "agentDetail.configure.workingDirectory.title": "作業ディレクトリ",
+ "agentDetail.configure.workingDirectory.treeLabel": "作業ディレクトリのファイル",
"agentDetail.documentTitle": "エージェント",
"agentDetail.logs.description": "完全なログには、ユーザー入力、エージェントの応答、計画、ツールの使用など、アプリケーションの実行状況が記録されます。",
"agentDetail.logs.empty": "ログが見つかりません",
@@ -279,7 +313,7 @@
"agentDetail.navigationLabel": "エージェントナビゲーション",
"agentDetail.publish": "公開",
"agentDetail.sections.access": "アクセスポイント",
- "agentDetail.sections.configure": "オーケストレーション",
+ "agentDetail.sections.configure": "設定",
"agentDetail.sections.logs": "ログ",
"agentDetail.sections.monitoring": "モニタリング",
"agentDetail.title": "エージェント",
@@ -334,6 +368,11 @@
"roster.nodeSelector.startFromScratch": "ゼロから始める",
"roster.references.label": "{{name}} を使用するワークフロー",
"roster.references.trigger": "{{name}} を使用するワークフロー",
+ "roster.saveToRoster": "Save to Agent Console",
+ "roster.saveToRosterDialog.description": "Save this inline setup as a reusable roster agent.",
+ "roster.saveToRosterDialog.title": "Save to Agent Console",
+ "roster.saveToRosterForm.changeIcon": "Change roster agent icon",
+ "roster.saveToRosterSuccess": "Agent saved to roster.",
"roster.searchLabel": "エージェントを検索",
"roster.searchPlaceholder": "エージェントを名前で検索…",
"roster.tabs.agent": "エージェント",
diff --git a/web/i18n/ja-JP/common.json b/web/i18n/ja-JP/common.json
index 8a5a1e217c6..8ba25af57c9 100644
--- a/web/i18n/ja-JP/common.json
+++ b/web/i18n/ja-JP/common.json
@@ -288,6 +288,7 @@
"menus.exploreMarketplace": "マーケットプレイスを探索する",
"menus.plugins": "インテグレーション",
"menus.roster": "エージェント名簿",
+ "menus.status": "ベータ版",
"menus.tools": "ツール",
"model.capabilities": "マルチモーダル機能",
"model.params.stop_sequencesPlaceholder": "シーケンスを入力してタブキーを押してください",
diff --git a/web/i18n/ja-JP/workflow.json b/web/i18n/ja-JP/workflow.json
index e292a8f772c..afca062d3a0 100644
--- a/web/i18n/ja-JP/workflow.json
+++ b/web/i18n/ja-JP/workflow.json
@@ -464,7 +464,7 @@
"nodes.agent.task.label": "Agent タスク",
"nodes.agent.task.mention": "メンション",
"nodes.agent.task.placeholder": "この Agent が行うべきことを記述してください...",
- "nodes.agent.task.tooltip": "この Agent がこのワークフロー内で従うべきタスク指示を定義します。",
+ "nodes.agent.task.tooltip": "このノードを処理するためにエージェントを補助する追加プロンプトです。変数を明示的に参照するには / を使用します。\n適切に設定されていれば、エージェントが自分で判断して進められると信頼できるようになります。",
"nodes.agent.toolNotAuthorizedTooltip": "{{tool}} 認可されていません",
"nodes.agent.toolNotInstallTooltip": "{{tool}}はインストールされていません",
"nodes.agent.toolbox": "ツールボックス",
diff --git a/web/i18n/ko-KR/agent-v-2.json b/web/i18n/ko-KR/agent-v-2.json
index 3341308a3d7..69f1e0ec3b1 100644
--- a/web/i18n/ko-KR/agent-v-2.json
+++ b/web/i18n/ko-KR/agent-v-2.json
@@ -49,14 +49,27 @@
"agentDetail.configure.advancedSettings.envEditor.keyPlaceholder": "Key",
"agentDetail.configure.advancedSettings.envEditor.label": "Env Editor",
"agentDetail.configure.advancedSettings.envEditor.revealValue": "{{key}} 값 표시",
+ "agentDetail.configure.advancedSettings.envEditor.richTip": "에이전트는 Linux 환경에서 실행됩니다. 여기에서 환경 변수를 정의하여 구성이나 시크릿을 미리 설정할 수 있습니다.\n\n또는 Build 채팅을 통해 언제든지 설정할 수 있습니다. <docLink>문서</docLink>를 참조하세요.",
"agentDetail.configure.advancedSettings.envEditor.scopeColumn": "Scope",
"agentDetail.configure.advancedSettings.envEditor.scopePlain": "Plain",
"agentDetail.configure.advancedSettings.envEditor.scopeSecret": "Secret",
"agentDetail.configure.advancedSettings.envEditor.scopeSelector": "환경 변수 범위 선택",
- "agentDetail.configure.advancedSettings.envEditor.tip": "이 에이전트가 런타임에 사용할 수 있는 환경 변수입니다.",
+ "agentDetail.configure.advancedSettings.envEditor.tip": "에이전트는 Linux 환경에서 실행됩니다. 여기에서 환경 변수를 정의하여 구성이나 시크릿을 미리 설정할 수 있습니다. 또는 Build 채팅을 통해 언제든지 설정할 수 있습니다. 문서를 참조하세요.",
+ "agentDetail.configure.advancedSettings.envEditor.toggle": "Env Editor 전환",
"agentDetail.configure.advancedSettings.envEditor.valueColumn": "Value",
"agentDetail.configure.advancedSettings.envEditor.valuePlaceholder": "Value",
"agentDetail.configure.advancedSettings.label": "고급 설정",
+ "agentDetail.configure.advancedSettings.toggle": "고급 설정 전환",
+ "agentDetail.configure.build.empty.description": "원하는 내용을 설명하면 대화에 맞춰 왼쪽 양식이 채워집니다.",
+ "agentDetail.configure.build.empty.title": "채팅으로 에이전트 만들기",
+ "agentDetail.configure.build.inputPlaceholder": "에이전트가 해야 할 일을 설명하세요",
+ "agentDetail.configure.build.startBuild": "빌드 시작",
+ "agentDetail.configure.buildDraft.changes": "적용할 변경 사항 {{count}}개",
+ "agentDetail.configure.buildDraft.discard": "폐기",
+ "agentDetail.configure.buildDraft.modeBadge": "빌드 모드",
+ "agentDetail.configure.buildDraft.modeDescription": "빌드 모드입니다. 오른쪽 채팅으로 이 설정을 다듬은 뒤 적용하세요.",
+ "agentDetail.configure.buildDraft.noChanges": "적용할 변경 사항 없음",
+ "agentDetail.configure.buildDraft.title": "빌드 초안",
"agentDetail.configure.chatFeatures.description": "Web app 및 채팅 화면에서의 최종 사용자 채팅 경험을 구성합니다.",
"agentDetail.configure.chatFeatures.title": "채팅 기능",
"agentDetail.configure.files.add": "파일 추가",
@@ -67,7 +80,8 @@
"agentDetail.configure.files.preview.failed": "미리보기를 불러오지 못했습니다.",
"agentDetail.configure.files.preview.unsupported": "이 파일은 미리보기를 지원하지 않습니다.",
"agentDetail.configure.files.remove": "{{name}} 제거",
- "agentDetail.configure.files.tip": "이 에이전트가 작업을 오케스트레이션할 때 사용할 수 있는 파일입니다.",
+ "agentDetail.configure.files.tip": "프롬프트에 넣기에는 너무 긴 예시, 가이드라인 또는 정보 자체를 에이전트에 제공합니다. 프롬프트에서 /로 명시적으로 참조하세요.",
+ "agentDetail.configure.files.toggle": "파일 전환",
"agentDetail.configure.files.treeLabel": "에이전트 파일",
"agentDetail.configure.files.upload.action": "업로드",
"agentDetail.configure.files.upload.browse": "찾아보기",
@@ -113,8 +127,11 @@
"agentDetail.configure.orchestrate": "오케스트레이션",
"agentDetail.configure.preview.chatFeatures": "채팅 기능",
"agentDetail.configure.preview.empty.defaultAgentName": "에이전트",
- "agentDetail.configure.preview.empty.description": "현재 초안을 테스트하려면 메시지를 보내세요.",
+ "agentDetail.configure.preview.empty.description": "게시 후 사용자가 경험할 완성된 채팅처럼 에이전트를 실행합니다.",
"agentDetail.configure.preview.empty.noInstructionsDescription": "아직 지시 사항이 없어 답변은 기본 모델에서 제공됩니다.",
+ "agentDetail.configure.preview.empty.title": "{{name}} 미리보기",
+ "agentDetail.configure.preview.endUserAuth": "최종 사용자 인증",
+ "agentDetail.configure.preview.inputPlaceholder": "{{name}}에게 메시지 보내기",
"agentDetail.configure.preview.restart": "미리보기 다시 시작",
"agentDetail.configure.preview.title": "미리보기",
"agentDetail.configure.prompt.copied": "프롬프트를 복사했습니다",
@@ -128,7 +145,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "여기에 지시 사항을 작성하세요,",
- "agentDetail.configure.prompt.tip": "이 에이전트가 입력을 어떻게 해석하고, 도구를 호출하며, 출력을 생성할지 정의합니다.",
+ "agentDetail.configure.prompt.tip": "에이전트의 역할을 정의하고 일반적인 작업을 설명합니다. /를 사용해 스킬, 파일, 도구, 지식 검색을 명시적으로 참조하세요.",
"agentDetail.configure.publishBar.draft": "초안",
"agentDetail.configure.publishBar.publishUpdate": "업데이트 게시",
"agentDetail.configure.publishBar.published": "게시됨",
@@ -147,6 +164,14 @@
"agentDetail.configure.publishImpact.title": "{{name}}에 {{action}}",
"agentDetail.configure.publishImpact.workflowCount_one": "워크플로 {{count}}개",
"agentDetail.configure.publishImpact.workflowCount_other": "워크플로 {{count}}개",
+ "agentDetail.configure.rightPanel.build": "빌드",
+ "agentDetail.configure.rightPanel.buildTipBody": "Build는 채팅으로 에이전트를 설정합니다. 원하는 내용을 설명하면 왼쪽 설정이 채워집니다.",
+ "agentDetail.configure.rightPanel.buildTipTitle": "채팅으로 에이전트 만들기",
+ "agentDetail.configure.rightPanel.learnMore": "자세히 알아보기",
+ "agentDetail.configure.rightPanel.modeLabel": "에이전트 구성 모드",
+ "agentDetail.configure.rightPanel.preview": "미리보기",
+ "agentDetail.configure.rightPanel.previewTipBody": "Preview는 사용자가 보게 될 방식으로 완성된 에이전트를 실행하며, 깔끔한 답변과 채팅 기능을 보여줍니다.",
+ "agentDetail.configure.rightPanel.previewTipTitle": "에이전트 미리보기",
"agentDetail.configure.skills.add": "스킬 추가",
"agentDetail.configure.skills.detail.contentRegion": "스킬 상세 내용",
"agentDetail.configure.skills.detail.fileCount": "파일 {{count}}개",
@@ -156,7 +181,9 @@
"agentDetail.configure.skills.itemType": "스킬",
"agentDetail.configure.skills.label": "스킬",
"agentDetail.configure.skills.remove": "{{name}} 제거",
- "agentDetail.configure.skills.tip": "이 에이전트가 작업을 오케스트레이션할 때 사용할 수 있는 스킬입니다.",
+ "agentDetail.configure.skills.richTip": "에이전트에 모듈형 기능을 갖추세요. <docLink>문서</docLink>를 참조하세요. 프롬프트에서 /로 명시적으로 참조하세요.",
+ "agentDetail.configure.skills.tip": "에이전트에 모듈형 기능을 갖추세요. 문서를 참조하세요. 프롬프트에서 /로 명시적으로 참조하세요.",
+ "agentDetail.configure.skills.toggle": "스킬 전환",
"agentDetail.configure.skills.upload.action": "업로드",
"agentDetail.configure.skills.upload.browse": "찾아보기",
"agentDetail.configure.skills.upload.description": "이 에이전트용 .zip 또는 .skill 패키지를 업로드합니다.",
@@ -166,6 +193,7 @@
"agentDetail.configure.skills.upload.invalidFile": ".zip 또는 .skill 파일을 업로드하세요.",
"agentDetail.configure.skills.upload.success": "스킬을 업로드했습니다.",
"agentDetail.configure.skills.upload.title": "스킬 업로드",
+ "agentDetail.configure.title": "구성",
"agentDetail.configure.tools.add": "도구 추가",
"agentDetail.configure.tools.addMenu.cliTool.badge": "개발자용",
"agentDetail.configure.tools.addMenu.cliTool.description": "에이전트가 샌드박스에서 실행할 명령줄 프로그램을 설치합니다. 설치가 필요하며 일반적으로 API Key 가 필요합니다.",
@@ -179,7 +207,7 @@
"agentDetail.configure.tools.cliDialog.env.optional": "(선택 사항)",
"agentDetail.configure.tools.cliDialog.installCommand.description": "샌드박스 실행 · 최초 호출 시 한 번 실행",
"agentDetail.configure.tools.cliDialog.installCommand.label": "설치 명령",
- "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "설치 명령을 여기에 붙여넣으세요. 예: npm install -g @lark/cli · brew install jq",
+ "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "설치 명령을 여기에 붙여넣으세요. 예: npx -y @playwright/mcp@latest · uv tool install httpie",
"agentDetail.configure.tools.cliDialog.installCommand.required": "설치 명령을 입력하세요.",
"agentDetail.configure.tools.cliDialog.learnMore": "CLI 도구에 대해 자세히 알아보기",
"agentDetail.configure.tools.cliDialog.name.label": "CLI 도구 이름",
@@ -196,13 +224,19 @@
"agentDetail.configure.tools.moreActions": "{{name}}의 추가 작업",
"agentDetail.configure.tools.removeAction": "{{name}} 제거",
"agentDetail.configure.tools.removeProvider": "모든 도구 제거",
- "agentDetail.configure.tools.tip": "이 에이전트가 작업을 오케스트레이션할 때 호출할 수 있는 도구입니다.",
+ "agentDetail.configure.tools.richTip": "에이전트에 Dify 플러그인을 갖추세요. <pluginDocLink>문서</pluginDocLink>를 참조하세요. 프롬프트에서 /로 명시적으로 참조하세요.\n또는 Build 채팅을 통해 에이전트에게 다른 도구(예: MCPs 및 CLI 도구)를 설치하고 인증하도록 지시할 수도 있습니다. Build 채팅에서 구성한 도구는 여기에 표시되지 않지만, 앞으로도 에이전트에서 계속 사용할 수 있습니다. <buildDocLink>문서</buildDocLink>를 참조하세요.",
+ "agentDetail.configure.tools.tip": "에이전트에 Dify 플러그인을 갖추세요. 문서를 참조하세요. 프롬프트에서 /로 명시적으로 참조하세요. 또는 Build 채팅을 통해 에이전트에게 다른 도구(예: MCPs 및 CLI 도구)를 설치하고 인증하도록 지시할 수도 있습니다. Build 채팅에서 구성한 도구는 여기에 표시되지 않지만, 앞으로도 에이전트에서 계속 사용할 수 있습니다. 문서를 참조하세요.",
+ "agentDetail.configure.tools.toggle": "도구 전환",
"agentDetail.configure.tools.toolTabs.all": "전체",
"agentDetail.configure.tools.toolTabs.cli": "CLI",
"agentDetail.configure.tools.toolTabs.custom": "사용자 지정",
"agentDetail.configure.tools.toolTabs.mcp": "MCP",
"agentDetail.configure.tools.toolTabs.plugins": "플러그인",
"agentDetail.configure.tools.toolTabs.workflow": "Workflow",
+ "agentDetail.configure.workingDirectory.description": "에이전트가 실행 중에 읽고 쓰는 파일입니다. qna_report.pdf 같은 생성 결과가 여기에 표시됩니다.",
+ "agentDetail.configure.workingDirectory.open": "작업 디렉터리 열기",
+ "agentDetail.configure.workingDirectory.title": "작업 디렉터리",
+ "agentDetail.configure.workingDirectory.treeLabel": "작업 디렉터리 파일",
"agentDetail.documentTitle": "에이전트",
"agentDetail.logs.description": "전체 로그는 사용자 입력, 에이전트 응답, 계획 및 도구 사용을 포함한 애플리케이션의 실행 상태를 기록합니다.",
"agentDetail.logs.empty": "로그가 없습니다",
@@ -279,7 +313,7 @@
"agentDetail.navigationLabel": "에이전트 탐색",
"agentDetail.publish": "게시",
"agentDetail.sections.access": "액세스 지점",
- "agentDetail.sections.configure": "오케스트레이션",
+ "agentDetail.sections.configure": "구성",
"agentDetail.sections.logs": "로그",
"agentDetail.sections.monitoring": "모니터링",
"agentDetail.title": "에이전트",
@@ -334,6 +368,11 @@
"roster.nodeSelector.startFromScratch": "처음부터 시작",
"roster.references.label": "{{name}}을(를) 사용하는 워크플로",
"roster.references.trigger": "{{name}}을(를) 사용하는 워크플로",
+ "roster.saveToRoster": "Save to Agent Console",
+ "roster.saveToRosterDialog.description": "Save this inline setup as a reusable roster agent.",
+ "roster.saveToRosterDialog.title": "Save to Agent Console",
+ "roster.saveToRosterForm.changeIcon": "Change roster agent icon",
+ "roster.saveToRosterSuccess": "Agent saved to roster.",
"roster.searchLabel": "에이전트 검색",
"roster.searchPlaceholder": "이름으로 에이전트 검색…",
"roster.tabs.agent": "에이전트",
diff --git a/web/i18n/ko-KR/common.json b/web/i18n/ko-KR/common.json
index 8c4e1165e31..b7a701c49b8 100644
--- a/web/i18n/ko-KR/common.json
+++ b/web/i18n/ko-KR/common.json
@@ -288,6 +288,7 @@
"menus.exploreMarketplace": "Marketplace 둘러보기",
"menus.plugins": "통합",
"menus.roster": "에이전트 명단",
+ "menus.status": "베타 버전",
"menus.tools": "도구",
"model.capabilities": "멀티모달 기능",
"model.params.stop_sequencesPlaceholder": "시퀀스를 입력하고 탭 키를 누르세요",
diff --git a/web/i18n/ko-KR/workflow.json b/web/i18n/ko-KR/workflow.json
index 06125ae5836..c2554902bea 100644
--- a/web/i18n/ko-KR/workflow.json
+++ b/web/i18n/ko-KR/workflow.json
@@ -464,7 +464,7 @@
"nodes.agent.task.label": "Agent 작업",
"nodes.agent.task.mention": "멘션",
"nodes.agent.task.placeholder": "이 Agent가 수행해야 할 작업을 설명하세요...",
- "nodes.agent.task.tooltip": "이 워크플로에서 이 Agent가 따라야 할 작업 지시 사항을 정의합니다.",
+ "nodes.agent.task.tooltip": "에이전트가 이 노드를 처리하도록 돕는 추가 프롬프트입니다. 변수를 명시적으로 참조하려면 / 를 사용하세요.\n올바르게 구성하면 에이전트가 스스로 판단하도록 신뢰할 수 있습니다.",
"nodes.agent.toolNotAuthorizedTooltip": "{{tool}} 권한이 부여되지 않음",
"nodes.agent.toolNotInstallTooltip": "{{tool}}이 설치되지 않았습니다.",
"nodes.agent.toolbox": "도구",
diff --git a/web/i18n/nl-NL/agent-v-2.json b/web/i18n/nl-NL/agent-v-2.json
index 71ef59a14e8..a31cc8f24a7 100644
--- a/web/i18n/nl-NL/agent-v-2.json
+++ b/web/i18n/nl-NL/agent-v-2.json
@@ -49,14 +49,27 @@
"agentDetail.configure.advancedSettings.envEditor.keyPlaceholder": "Key",
"agentDetail.configure.advancedSettings.envEditor.label": "Env Editor",
"agentDetail.configure.advancedSettings.envEditor.revealValue": "Waarde van {{key}} tonen",
+ "agentDetail.configure.advancedSettings.envEditor.richTip": "Je agent draait in een Linux-omgeving. Je kunt configuraties of geheimen vooraf instellen door hier omgevingsvariabelen te definiëren.\n\nJe kunt dit ook altijd laten instellen via een Build-chat. Zie de <docLink>documentatie</docLink>.",
"agentDetail.configure.advancedSettings.envEditor.scopeColumn": "Scope",
"agentDetail.configure.advancedSettings.envEditor.scopePlain": "Plain",
"agentDetail.configure.advancedSettings.envEditor.scopeSecret": "Secret",
"agentDetail.configure.advancedSettings.envEditor.scopeSelector": "Selecteer scope van omgevingsvariabele",
- "agentDetail.configure.advancedSettings.envEditor.tip": "Omgevingsvariabelen die tijdens runtime beschikbaar zijn voor deze agent.",
+ "agentDetail.configure.advancedSettings.envEditor.tip": "Je agent draait in een Linux-omgeving. Je kunt configuraties of geheimen vooraf instellen door hier omgevingsvariabelen te definiëren. Je kunt dit ook altijd laten instellen via een Build-chat. Zie de documentatie.",
+ "agentDetail.configure.advancedSettings.envEditor.toggle": "Env Editor in/uit",
"agentDetail.configure.advancedSettings.envEditor.valueColumn": "Value",
"agentDetail.configure.advancedSettings.envEditor.valuePlaceholder": "Value",
"agentDetail.configure.advancedSettings.label": "Geavanceerde instellingen",
+ "agentDetail.configure.advancedSettings.toggle": "Geavanceerde instellingen in/uit",
+ "agentDetail.configure.build.empty.description": "Beschrijf wat je wilt en het formulier links wordt gaandeweg ingevuld.",
+ "agentDetail.configure.build.empty.title": "Bouw je agent via chat",
+ "agentDetail.configure.build.inputPlaceholder": "Beschrijf wat je agent moet doen",
+ "agentDetail.configure.build.startBuild": "Build starten",
+ "agentDetail.configure.buildDraft.changes": "{{count}} wijzigingen om toe te passen",
+ "agentDetail.configure.buildDraft.discard": "Negeren",
+ "agentDetail.configure.buildDraft.modeBadge": "Buildmodus",
+ "agentDetail.configure.buildDraft.modeDescription": "Je bent in buildmodus. Werk deze configuratie bij via de chat rechts en pas daarna toe.",
+ "agentDetail.configure.buildDraft.noChanges": "Geen wijzigingen om toe te passen",
+ "agentDetail.configure.buildDraft.title": "Buildconcept",
"agentDetail.configure.chatFeatures.description": "Geef vorm aan de chatervaring voor eindgebruikers in je webapp en chatoppervlakken.",
"agentDetail.configure.chatFeatures.title": "Chatfuncties",
"agentDetail.configure.files.add": "Bestand toevoegen",
@@ -67,7 +80,8 @@
"agentDetail.configure.files.preview.failed": "Laden van voorbeeld mislukt.",
"agentDetail.configure.files.preview.unsupported": "Dit bestand ondersteunt geen voorbeeldweergave.",
"agentDetail.configure.files.remove": "{{name}} verwijderen",
- "agentDetail.configure.files.tip": "Bestanden die deze agent kan gebruiken tijdens het orkestreren van taken.",
+ "agentDetail.configure.files.tip": "Geef uw agent voorbeelden, richtlijnen of simpelweg informatie die te lang is voor de prompt. Verwijs er expliciet naar met / in de prompt.",
+ "agentDetail.configure.files.toggle": "Bestanden in/uit",
"agentDetail.configure.files.treeLabel": "Agentbestanden",
"agentDetail.configure.files.upload.action": "Uploaden",
"agentDetail.configure.files.upload.browse": "bladeren",
@@ -113,8 +127,11 @@
"agentDetail.configure.orchestrate": "Orkestreren",
"agentDetail.configure.preview.chatFeatures": "Chatfuncties",
"agentDetail.configure.preview.empty.defaultAgentName": "Agent",
- "agentDetail.configure.preview.empty.description": "Stuur een bericht om het huidige concept te testen.",
+ "agentDetail.configure.preview.empty.description": "Voer de agent uit als een afgeronde chat, precies zoals mensen die na publicatie ervaren.",
"agentDetail.configure.preview.empty.noInstructionsDescription": "Nog geen instructies, dus antwoorden komen van het kale model.",
+ "agentDetail.configure.preview.empty.title": "Voorbeeld van {{name}}",
+ "agentDetail.configure.preview.endUserAuth": "Authenticatie eindgebruiker",
+ "agentDetail.configure.preview.inputPlaceholder": "Bericht sturen naar {{name}}",
"agentDetail.configure.preview.restart": "Voorbeeld opnieuw starten",
"agentDetail.configure.preview.title": "Voorbeeld",
"agentDetail.configure.prompt.copied": "Prompt gekopieerd",
@@ -128,7 +145,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "Schrijf hier instructies,",
- "agentDetail.configure.prompt.tip": "Bepaal hoe deze agent invoer interpreteert, tools aanroept en uitvoer genereert.",
+ "agentDetail.configure.prompt.tip": "Definieer de rol van de agent en beschrijf zijn typische taak. Gebruik / om expliciet te verwijzen naar skills, bestanden, tools en kennisophalingen.",
"agentDetail.configure.publishBar.draft": "Concept",
"agentDetail.configure.publishBar.publishUpdate": "Update publiceren",
"agentDetail.configure.publishBar.published": "Gepubliceerd",
@@ -147,6 +164,14 @@
"agentDetail.configure.publishImpact.title": "{{action}} naar {{name}}",
"agentDetail.configure.publishImpact.workflowCount_one": "{{count}} workflow",
"agentDetail.configure.publishImpact.workflowCount_other": "{{count}} workflows",
+ "agentDetail.configure.rightPanel.build": "Bouwen",
+ "agentDetail.configure.rightPanel.buildTipBody": "Build stelt de agent in via chat. Beschrijf wat je wilt en de instellingen links worden ingevuld.",
+ "agentDetail.configure.rightPanel.buildTipTitle": "Bouw je agent via chat",
+ "agentDetail.configure.rightPanel.learnMore": "Meer informatie",
+ "agentDetail.configure.rightPanel.modeLabel": "Agentconfiguratiemodus",
+ "agentDetail.configure.rightPanel.preview": "Voorbeeld",
+ "agentDetail.configure.rightPanel.previewTipBody": "Preview voert de voltooide agent uit zoals je gebruikers die zien, met duidelijke antwoorden en chatfuncties.",
+ "agentDetail.configure.rightPanel.previewTipTitle": "Voorbeeld van je agent",
"agentDetail.configure.skills.add": "Skill toevoegen",
"agentDetail.configure.skills.detail.contentRegion": "Skill-detailinhoud",
"agentDetail.configure.skills.detail.fileCount": "{{count}} BESTANDEN",
@@ -156,7 +181,9 @@
"agentDetail.configure.skills.itemType": "Skill",
"agentDetail.configure.skills.label": "Skills",
"agentDetail.configure.skills.remove": "{{name}} verwijderen",
- "agentDetail.configure.skills.tip": "Skills die deze agent kan gebruiken tijdens het orkestreren van taken.",
+ "agentDetail.configure.skills.richTip": "Voorzie uw agent van modulaire mogelijkheden. Zie <docLink>documentatie</docLink>. Verwijs er expliciet naar met / in de prompt.",
+ "agentDetail.configure.skills.tip": "Voorzie uw agent van modulaire mogelijkheden. Zie documentatie. Verwijs er expliciet naar met / in de prompt.",
+ "agentDetail.configure.skills.toggle": "Skills in/uit",
"agentDetail.configure.skills.upload.action": "Uploaden",
"agentDetail.configure.skills.upload.browse": "bladeren",
"agentDetail.configure.skills.upload.description": "Upload een .zip- of .skill-pakket voor deze agent.",
@@ -166,6 +193,7 @@
"agentDetail.configure.skills.upload.invalidFile": "Upload een .zip- of .skill-bestand.",
"agentDetail.configure.skills.upload.success": "Skill geüpload.",
"agentDetail.configure.skills.upload.title": "Skill uploaden",
+ "agentDetail.configure.title": "Configureren",
"agentDetail.configure.tools.add": "Tool toevoegen",
"agentDetail.configure.tools.addMenu.cliTool.badge": "Voor ontwikkelaars",
"agentDetail.configure.tools.addMenu.cliTool.description": "Installeer een commandoregelprogramma dat de agent in zijn sandbox uitvoert. Vereist installatie en meestal API-keys.",
@@ -179,7 +207,7 @@
"agentDetail.configure.tools.cliDialog.env.optional": "(optioneel)",
"agentDetail.configure.tools.cliDialog.installCommand.description": "Sandboxed · wordt eenmaal uitgevoerd bij de eerste aanroep",
"agentDetail.configure.tools.cliDialog.installCommand.label": "Installatiecommando",
- "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "Plak hier je installatiecommando, bv. npm install -g @lark/cli · brew install jq",
+ "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "Plak hier je installatiecommando, bv. npx -y @playwright/mcp@latest · uv tool install httpie",
"agentDetail.configure.tools.cliDialog.installCommand.required": "Installatiecommando is verplicht.",
"agentDetail.configure.tools.cliDialog.learnMore": "Meer over CLI-tool",
"agentDetail.configure.tools.cliDialog.name.label": "Naam van CLI-tool",
@@ -196,13 +224,19 @@
"agentDetail.configure.tools.moreActions": "Meer acties voor {{name}}",
"agentDetail.configure.tools.removeAction": "{{name}} verwijderen",
"agentDetail.configure.tools.removeProvider": "Alle tools verwijderen",
- "agentDetail.configure.tools.tip": "Tools die deze agent kan aanroepen tijdens het orkestreren van taken.",
+ "agentDetail.configure.tools.richTip": "Voorzie uw agent van Dify-plugins. Zie <pluginDocLink>documentatie</pluginDocLink>. Verwijs er expliciet naar met / in de prompt.\nU kunt de agent ook altijd via een Build-chat vragen andere tools (bijv. MCPs en CLI-tools) te installeren en te authenticeren. Let op: tools die via Build-chats zijn geconfigureerd, verschijnen hier NIET, hoewel ze voortaan nog steeds beschikbaar zijn voor uw agent. Zie <buildDocLink>documentatie</buildDocLink>.",
+ "agentDetail.configure.tools.tip": "Voorzie uw agent van Dify-plugins. Zie documentatie. Verwijs er expliciet naar met / in de prompt. U kunt de agent ook altijd via een Build-chat vragen andere tools (bijv. MCPs en CLI-tools) te installeren en te authenticeren. Let op: tools die via Build-chats zijn geconfigureerd, verschijnen hier NIET, hoewel ze voortaan nog steeds beschikbaar zijn voor uw agent. Zie documentatie.",
+ "agentDetail.configure.tools.toggle": "Tools in/uit",
"agentDetail.configure.tools.toolTabs.all": "Alle",
"agentDetail.configure.tools.toolTabs.cli": "CLI",
"agentDetail.configure.tools.toolTabs.custom": "Aangepast",
"agentDetail.configure.tools.toolTabs.mcp": "MCP",
"agentDetail.configure.tools.toolTabs.plugins": "Plugins",
"agentDetail.configure.tools.toolTabs.workflow": "Workflow",
+ "agentDetail.configure.workingDirectory.description": "Bestanden die de agent leest en schrijft tijdens het uitvoeren. Alles wat hij genereert, zoals qna_report.pdf, verschijnt hier.",
+ "agentDetail.configure.workingDirectory.open": "Werkmap openen",
+ "agentDetail.configure.workingDirectory.title": "Werkmap",
+ "agentDetail.configure.workingDirectory.treeLabel": "Bestanden in de werkmap",
"agentDetail.documentTitle": "Agent",
"agentDetail.logs.description": "Volledige logs registreren de status van de applicatie tijdens het uitvoeren, inclusief gebruikersinvoer, antwoorden van de agent, planning en gebruik van tools.",
"agentDetail.logs.empty": "Geen logs gevonden",
@@ -279,7 +313,7 @@
"agentDetail.navigationLabel": "Agentnavigatie",
"agentDetail.publish": "Publiceren",
"agentDetail.sections.access": "Toegangspunt",
- "agentDetail.sections.configure": "Orkestreren",
+ "agentDetail.sections.configure": "Configure",
"agentDetail.sections.logs": "Logs",
"agentDetail.sections.monitoring": "Monitoring",
"agentDetail.title": "Agent",
@@ -334,6 +368,11 @@
"roster.nodeSelector.startFromScratch": "Vanaf nul beginnen",
"roster.references.label": "Workflows die {{name}} gebruiken",
"roster.references.trigger": "Workflows die {{name}} gebruiken",
+ "roster.saveToRoster": "Save to Agent Console",
+ "roster.saveToRosterDialog.description": "Save this inline setup as a reusable roster agent.",
+ "roster.saveToRosterDialog.title": "Save to Agent Console",
+ "roster.saveToRosterForm.changeIcon": "Change roster agent icon",
+ "roster.saveToRosterSuccess": "Agent saved to roster.",
"roster.searchLabel": "Agents zoeken",
"roster.searchPlaceholder": "Agents op naam zoeken…",
"roster.tabs.agent": "Agent",
diff --git a/web/i18n/nl-NL/common.json b/web/i18n/nl-NL/common.json
index b988beaf492..f9145e7b0e1 100644
--- a/web/i18n/nl-NL/common.json
+++ b/web/i18n/nl-NL/common.json
@@ -288,6 +288,7 @@
"menus.exploreMarketplace": "Explore Marketplace",
"menus.plugins": "Integraties",
"menus.roster": "Agentenoverzicht",
+ "menus.status": "beta",
"menus.tools": "Tools",
"model.capabilities": "MultiModal Capabilities",
"model.params.stop_sequencesPlaceholder": "Enter sequence and press Tab",
diff --git a/web/i18n/nl-NL/workflow.json b/web/i18n/nl-NL/workflow.json
index 5e747ccf943..4893ba732a1 100644
--- a/web/i18n/nl-NL/workflow.json
+++ b/web/i18n/nl-NL/workflow.json
@@ -464,7 +464,7 @@
"nodes.agent.task.label": "Agenttaak",
"nodes.agent.task.mention": "Vermelden",
"nodes.agent.task.placeholder": "Beschrijf wat deze agent moet doen...",
- "nodes.agent.task.tooltip": "Bepaal de taakinstructies die deze agent in deze workflow moet volgen.",
+ "nodes.agent.task.tooltip": "Aanvullende prompt om de agent te helpen deze specifieke node af te handelen. Gebruik / om expliciet naar variabelen te verwijzen.\nAls dit goed is geconfigureerd, kun je erop vertrouwen dat je agent zelf uitzoekt wat nodig is.",
"nodes.agent.toolNotAuthorizedTooltip": "{{tool}} Not Authorized",
"nodes.agent.toolNotInstallTooltip": "{{tool}} is not installed",
"nodes.agent.toolbox": "toolbox",
diff --git a/web/i18n/pl-PL/agent-v-2.json b/web/i18n/pl-PL/agent-v-2.json
index 547fae932af..07514243ee9 100644
--- a/web/i18n/pl-PL/agent-v-2.json
+++ b/web/i18n/pl-PL/agent-v-2.json
@@ -49,14 +49,27 @@
"agentDetail.configure.advancedSettings.envEditor.keyPlaceholder": "Key",
"agentDetail.configure.advancedSettings.envEditor.label": "Env Editor",
"agentDetail.configure.advancedSettings.envEditor.revealValue": "Pokaż wartość {{key}}",
+ "agentDetail.configure.advancedSettings.envEditor.richTip": "Twój agent działa w środowisku Linux. Możesz wstępnie ustawić konfiguracje lub sekrety, definiując tutaj zmienne środowiskowe.\n\nAlternatywnie zawsze możesz skonfigurować je przez czat Build. Zobacz <docLink>dokumentację</docLink>.",
"agentDetail.configure.advancedSettings.envEditor.scopeColumn": "Scope",
"agentDetail.configure.advancedSettings.envEditor.scopePlain": "Plain",
"agentDetail.configure.advancedSettings.envEditor.scopeSecret": "Secret",
"agentDetail.configure.advancedSettings.envEditor.scopeSelector": "Wybierz zakres zmiennej środowiskowej",
- "agentDetail.configure.advancedSettings.envEditor.tip": "Zmienne środowiskowe dostępne dla tego agenta w czasie wykonywania.",
+ "agentDetail.configure.advancedSettings.envEditor.tip": "Twój agent działa w środowisku Linux. Możesz wstępnie ustawić konfiguracje lub sekrety, definiując tutaj zmienne środowiskowe. Alternatywnie zawsze możesz skonfigurować je przez czat Build. Zobacz dokumentację.",
+ "agentDetail.configure.advancedSettings.envEditor.toggle": "Przełącz Env Editor",
"agentDetail.configure.advancedSettings.envEditor.valueColumn": "Value",
"agentDetail.configure.advancedSettings.envEditor.valuePlaceholder": "Value",
"agentDetail.configure.advancedSettings.label": "Ustawienia zaawansowane",
+ "agentDetail.configure.advancedSettings.toggle": "Przełącz ustawienia zaawansowane",
+ "agentDetail.configure.build.empty.description": "Opisz, czego chcesz, a formularz po lewej będzie wypełniany w trakcie rozmowy.",
+ "agentDetail.configure.build.empty.title": "Buduj agenta przez czat",
+ "agentDetail.configure.build.inputPlaceholder": "Opisz, co agent ma robić",
+ "agentDetail.configure.build.startBuild": "Rozpocznij budowanie",
+ "agentDetail.configure.buildDraft.changes": "{{count}} zmian do zastosowania",
+ "agentDetail.configure.buildDraft.discard": "Odrzuć",
+ "agentDetail.configure.buildDraft.modeBadge": "Tryb budowania",
+ "agentDetail.configure.buildDraft.modeDescription": "Jesteś w trybie budowania. Dostosuj tę konfigurację przez czat po prawej, a następnie zastosuj.",
+ "agentDetail.configure.buildDraft.noChanges": "Brak zmian do zastosowania",
+ "agentDetail.configure.buildDraft.title": "Szkic budowania",
"agentDetail.configure.chatFeatures.description": "Ukształtuj doświadczenie czatu użytkownika końcowego w aplikacji webowej i powierzchniach czatu.",
"agentDetail.configure.chatFeatures.title": "Funkcje czatu",
"agentDetail.configure.files.add": "Dodaj plik",
@@ -67,7 +80,8 @@
"agentDetail.configure.files.preview.failed": "Nie udało się załadować podglądu.",
"agentDetail.configure.files.preview.unsupported": "Ten plik nie obsługuje podglądu.",
"agentDetail.configure.files.remove": "Usuń {{name}}",
- "agentDetail.configure.files.tip": "Pliki, których ten agent może używać podczas wykonywania zadań.",
+ "agentDetail.configure.files.tip": "Przekaż agentowi dowolny przykład, wytyczne lub po prostu nośnik informacji, który jest zbyt długi dla promptu. Odwołaj się do niego jawnie za pomocą / w prompcie.",
+ "agentDetail.configure.files.toggle": "Przełącz pliki",
"agentDetail.configure.files.treeLabel": "Pliki agenta",
"agentDetail.configure.files.upload.action": "Prześlij",
"agentDetail.configure.files.upload.browse": "przeglądaj",
@@ -113,8 +127,11 @@
"agentDetail.configure.orchestrate": "Orkiestracja",
"agentDetail.configure.preview.chatFeatures": "Funkcje czatu",
"agentDetail.configure.preview.empty.defaultAgentName": "Agent",
- "agentDetail.configure.preview.empty.description": "Wyślij wiadomość, aby przetestować bieżącą wersję roboczą.",
+ "agentDetail.configure.preview.empty.description": "Uruchom agenta jako gotowy czat, dokładnie tak, jak zobaczą go użytkownicy po publikacji.",
"agentDetail.configure.preview.empty.noInstructionsDescription": "Brak instrukcji, więc odpowiedzi pochodzą z podstawowego modelu.",
+ "agentDetail.configure.preview.empty.title": "Podgląd {{name}}",
+ "agentDetail.configure.preview.endUserAuth": "Uwierzytelnianie użytkownika końcowego",
+ "agentDetail.configure.preview.inputPlaceholder": "Wyślij wiadomość do {{name}}",
"agentDetail.configure.preview.restart": "Uruchom podgląd ponownie",
"agentDetail.configure.preview.title": "Podgląd",
"agentDetail.configure.prompt.copied": "Prompt skopiowany",
@@ -128,7 +145,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "Napisz tutaj instrukcje,",
- "agentDetail.configure.prompt.tip": "Określ, jak ten agent ma interpretować dane wejściowe, wywoływać narzędzia i tworzyć dane wyjściowe.",
+ "agentDetail.configure.prompt.tip": "Zdefiniuj rolę agenta i opisz jego typowe zadanie. Użyj /, aby jawnie odwołać się do umiejętności, plików, narzędzi i pobierania wiedzy.",
"agentDetail.configure.publishBar.draft": "Wersja robocza",
"agentDetail.configure.publishBar.publishUpdate": "Opublikuj aktualizację",
"agentDetail.configure.publishBar.published": "Opublikowane",
@@ -147,6 +164,14 @@
"agentDetail.configure.publishImpact.title": "{{action}} do {{name}}",
"agentDetail.configure.publishImpact.workflowCount_one": "{{count}} workflow",
"agentDetail.configure.publishImpact.workflowCount_other": "{{count}} workflow",
+ "agentDetail.configure.rightPanel.build": "Buduj",
+ "agentDetail.configure.rightPanel.buildTipBody": "Build konfiguruje agenta przez czat. Opisz, czego chcesz, a ustawienia po lewej zostaną uzupełnione.",
+ "agentDetail.configure.rightPanel.buildTipTitle": "Zbuduj agenta przez czat",
+ "agentDetail.configure.rightPanel.learnMore": "Dowiedz się więcej",
+ "agentDetail.configure.rightPanel.modeLabel": "Tryb konfiguracji agenta",
+ "agentDetail.configure.rightPanel.preview": "Podgląd",
+ "agentDetail.configure.rightPanel.previewTipBody": "Preview uruchamia gotowego agenta tak, jak zobaczą go użytkownicy, z przejrzystymi odpowiedziami i funkcjami czatu.",
+ "agentDetail.configure.rightPanel.previewTipTitle": "Podgląd agenta",
"agentDetail.configure.skills.add": "Dodaj umiejętność",
"agentDetail.configure.skills.detail.contentRegion": "Zawartość szczegółów umiejętności",
"agentDetail.configure.skills.detail.fileCount": "{{count}} PLIKÓW",
@@ -156,7 +181,9 @@
"agentDetail.configure.skills.itemType": "Umiejętność",
"agentDetail.configure.skills.label": "Umiejętności",
"agentDetail.configure.skills.remove": "Usuń {{name}}",
- "agentDetail.configure.skills.tip": "Umiejętności, których ten agent może używać podczas wykonywania zadań.",
+ "agentDetail.configure.skills.richTip": "Wyposaż agenta w modułowe możliwości. Zobacz <docLink>dokumentację</docLink>. Odwołaj się do nich jawnie za pomocą / w prompcie.",
+ "agentDetail.configure.skills.tip": "Wyposaż agenta w modułowe możliwości. Zobacz dokumentację. Odwołaj się do nich jawnie za pomocą / w prompcie.",
+ "agentDetail.configure.skills.toggle": "Przełącz umiejętności",
"agentDetail.configure.skills.upload.action": "Prześlij",
"agentDetail.configure.skills.upload.browse": "przeglądaj",
"agentDetail.configure.skills.upload.description": "Prześlij pakiet .zip lub .skill dla tego agenta.",
@@ -166,6 +193,7 @@
"agentDetail.configure.skills.upload.invalidFile": "Prześlij plik .zip lub .skill.",
"agentDetail.configure.skills.upload.success": "Umiejętność przesłana.",
"agentDetail.configure.skills.upload.title": "Prześlij umiejętność",
+ "agentDetail.configure.title": "Konfiguruj",
"agentDetail.configure.tools.add": "Dodaj narzędzie",
"agentDetail.configure.tools.addMenu.cliTool.badge": "Dla deweloperów",
"agentDetail.configure.tools.addMenu.cliTool.description": "Zainstaluj program wiersza poleceń, który agent uruchamia w sandboxie. Wymaga instalacji i zwykle API Key.",
@@ -179,7 +207,7 @@
"agentDetail.configure.tools.cliDialog.env.optional": "(opcjonalnie)",
"agentDetail.configure.tools.cliDialog.installCommand.description": "W sandboxie · uruchamia się raz przy pierwszym wywołaniu",
"agentDetail.configure.tools.cliDialog.installCommand.label": "Polecenie instalacji",
- "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "Wklej tutaj polecenie instalacji, np. npm install -g @lark/cli · brew install jq",
+ "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "Wklej tutaj polecenie instalacji, np. npx -y @playwright/mcp@latest · uv tool install httpie",
"agentDetail.configure.tools.cliDialog.installCommand.required": "Polecenie instalacji jest wymagane.",
"agentDetail.configure.tools.cliDialog.learnMore": "Dowiedz się więcej o narzędziu CLI",
"agentDetail.configure.tools.cliDialog.name.label": "Nazwa narzędzia CLI",
@@ -196,13 +224,19 @@
"agentDetail.configure.tools.moreActions": "Więcej akcji dla {{name}}",
"agentDetail.configure.tools.removeAction": "Usuń {{name}}",
"agentDetail.configure.tools.removeProvider": "Usuń wszystkie narzędzia",
- "agentDetail.configure.tools.tip": "Narzędzia, które ten agent może wywoływać podczas wykonywania zadań.",
+ "agentDetail.configure.tools.richTip": "Wyposaż agenta we wtyczki Dify. Zobacz <pluginDocLink>dokumentację</pluginDocLink>. Odwołaj się do nich jawnie za pomocą / w prompcie.\nAlternatywnie możesz zawsze polecić agentowi instalację i uwierzytelnienie innych narzędzi (np. MCPs i narzędzi CLI) przez czat Build. Pamiętaj, że narzędzia skonfigurowane przez czaty Build NIE pojawią się tutaj, choć nadal będą dostępne dla agenta w przyszłości. Zobacz <buildDocLink>dokumentację</buildDocLink>.",
+ "agentDetail.configure.tools.tip": "Wyposaż agenta we wtyczki Dify. Zobacz dokumentację. Odwołaj się do nich jawnie za pomocą / w prompcie. Alternatywnie możesz zawsze polecić agentowi instalację i uwierzytelnienie innych narzędzi (np. MCPs i narzędzi CLI) przez czat Build. Pamiętaj, że narzędzia skonfigurowane przez czaty Build NIE pojawią się tutaj, choć nadal będą dostępne dla agenta w przyszłości. Zobacz dokumentację.",
+ "agentDetail.configure.tools.toggle": "Przełącz narzędzia",
"agentDetail.configure.tools.toolTabs.all": "Wszystkie",
"agentDetail.configure.tools.toolTabs.cli": "CLI",
"agentDetail.configure.tools.toolTabs.custom": "Niestandardowe",
"agentDetail.configure.tools.toolTabs.mcp": "MCP",
"agentDetail.configure.tools.toolTabs.plugins": "Integracje",
"agentDetail.configure.tools.toolTabs.workflow": "Workflow",
+ "agentDetail.configure.workingDirectory.description": "Pliki, które agent odczytuje i zapisuje podczas działania. Wszystko, co wygeneruje, np. qna_report.pdf, pojawi się tutaj.",
+ "agentDetail.configure.workingDirectory.open": "Otwórz katalog roboczy",
+ "agentDetail.configure.workingDirectory.title": "Katalog roboczy",
+ "agentDetail.configure.workingDirectory.treeLabel": "Pliki katalogu roboczego",
"agentDetail.documentTitle": "Agent",
"agentDetail.logs.description": "Pełne logi rejestrują stan działania aplikacji, w tym dane wejściowe użytkownika, odpowiedzi agenta, planowanie i użycie narzędzi.",
"agentDetail.logs.empty": "Nie znaleziono logów",
@@ -279,7 +313,7 @@
"agentDetail.navigationLabel": "Nawigacja agenta",
"agentDetail.publish": "Opublikuj",
"agentDetail.sections.access": "Punkt dostępu",
- "agentDetail.sections.configure": "Orkiestracja",
+ "agentDetail.sections.configure": "Skonfiguruj",
"agentDetail.sections.logs": "Logi",
"agentDetail.sections.monitoring": "Monitorowanie",
"agentDetail.title": "Agent",
@@ -334,6 +368,11 @@
"roster.nodeSelector.startFromScratch": "Zacznij od zera",
"roster.references.label": "Workflow używające {{name}}",
"roster.references.trigger": "Workflow używające {{name}}",
+ "roster.saveToRoster": "Save to Agent Console",
+ "roster.saveToRosterDialog.description": "Save this inline setup as a reusable roster agent.",
+ "roster.saveToRosterDialog.title": "Save to Agent Console",
+ "roster.saveToRosterForm.changeIcon": "Change roster agent icon",
+ "roster.saveToRosterSuccess": "Agent saved to roster.",
"roster.searchLabel": "Szukaj agentów",
"roster.searchPlaceholder": "Wyszukaj agentów po nazwie…",
"roster.tabs.agent": "Agent",
diff --git a/web/i18n/pl-PL/common.json b/web/i18n/pl-PL/common.json
index 61af6244299..25af5d5f368 100644
--- a/web/i18n/pl-PL/common.json
+++ b/web/i18n/pl-PL/common.json
@@ -288,6 +288,7 @@
"menus.exploreMarketplace": "Zapoznaj się z Marketplace",
"menus.plugins": "Integracjay",
"menus.roster": "Lista agentów",
+ "menus.status": "beta",
"menus.tools": "Narzędzia",
"model.capabilities": "Możliwości multimodalne",
"model.params.stop_sequencesPlaceholder": "Wpisz sekwencję i naciśnij Tab",
diff --git a/web/i18n/pl-PL/workflow.json b/web/i18n/pl-PL/workflow.json
index d24c9034268..0d1d978f0d1 100644
--- a/web/i18n/pl-PL/workflow.json
+++ b/web/i18n/pl-PL/workflow.json
@@ -464,7 +464,7 @@
"nodes.agent.task.label": "Zadanie agenta",
"nodes.agent.task.mention": "Wzmianka",
"nodes.agent.task.placeholder": "Opisz, co ma robić ten agent…",
- "nodes.agent.task.tooltip": "Określ instrukcje zadania, które ten agent powinien wykonywać w tym workflow.",
+ "nodes.agent.task.tooltip": "Dodatkowy prompt, który pomaga agentowi obsłużyć dokładnie ten węzeł. Użyj /, aby jawnie odwołać się do zmiennych.\nJeśli zostanie poprawnie skonfigurowany, możesz zaufać agentowi, że sam rozwiąże problem.",
"nodes.agent.toolNotAuthorizedTooltip": "{{tool}} Nieautoryzowany",
"nodes.agent.toolNotInstallTooltip": "{{tool}} nie jest zainstalowany",
"nodes.agent.toolbox": "skrzynka z narzędziami",
diff --git a/web/i18n/pt-BR/agent-v-2.json b/web/i18n/pt-BR/agent-v-2.json
index 98b80e1f202..63f3ea7cd43 100644
--- a/web/i18n/pt-BR/agent-v-2.json
+++ b/web/i18n/pt-BR/agent-v-2.json
@@ -49,14 +49,27 @@
"agentDetail.configure.advancedSettings.envEditor.keyPlaceholder": "Key",
"agentDetail.configure.advancedSettings.envEditor.label": "Env Editor",
"agentDetail.configure.advancedSettings.envEditor.revealValue": "Revelar valor de {{key}}",
+ "agentDetail.configure.advancedSettings.envEditor.richTip": "Seu agente é executado em um ambiente Linux. Você pode predefinir configurações ou segredos definindo variáveis de ambiente aqui.\n\nComo alternativa, você sempre pode configurar tudo por meio de um chat Build. Consulte a <docLink>documentação</docLink>.",
"agentDetail.configure.advancedSettings.envEditor.scopeColumn": "Scope",
"agentDetail.configure.advancedSettings.envEditor.scopePlain": "Plain",
"agentDetail.configure.advancedSettings.envEditor.scopeSecret": "Secret",
"agentDetail.configure.advancedSettings.envEditor.scopeSelector": "Selecionar escopo da variável de ambiente",
- "agentDetail.configure.advancedSettings.envEditor.tip": "Variáveis de ambiente disponíveis para este agente em tempo de execução.",
+ "agentDetail.configure.advancedSettings.envEditor.tip": "Seu agente é executado em um ambiente Linux. Você pode predefinir configurações ou segredos definindo variáveis de ambiente aqui. Como alternativa, você sempre pode configurar tudo por meio de um chat Build. Consulte a documentação.",
+ "agentDetail.configure.advancedSettings.envEditor.toggle": "Alternar Env Editor",
"agentDetail.configure.advancedSettings.envEditor.valueColumn": "Value",
"agentDetail.configure.advancedSettings.envEditor.valuePlaceholder": "Value",
"agentDetail.configure.advancedSettings.label": "Configurações avançadas",
+ "agentDetail.configure.advancedSettings.toggle": "Alternar configurações avançadas",
+ "agentDetail.configure.build.empty.description": "Descreva o que você quer e o formulário à esquerda será preenchido conforme a conversa avança.",
+ "agentDetail.configure.build.empty.title": "Crie seu agente conversando",
+ "agentDetail.configure.build.inputPlaceholder": "Descreva o que seu agente deve fazer",
+ "agentDetail.configure.build.startBuild": "Iniciar build",
+ "agentDetail.configure.buildDraft.changes": "{{count}} alterações para aplicar",
+ "agentDetail.configure.buildDraft.discard": "Descartar",
+ "agentDetail.configure.buildDraft.modeBadge": "Modo build",
+ "agentDetail.configure.buildDraft.modeDescription": "Você está no modo build. Ajuste esta configuração pelo chat à direita e depois aplique.",
+ "agentDetail.configure.buildDraft.noChanges": "Nenhuma alteração para aplicar",
+ "agentDetail.configure.buildDraft.title": "Rascunho de build",
"agentDetail.configure.chatFeatures.description": "Modele a experiência de chat do usuário final no seu webapp e superfícies de chat.",
"agentDetail.configure.chatFeatures.title": "Recursos de chat",
"agentDetail.configure.files.add": "Adicionar arquivo",
@@ -67,7 +80,8 @@
"agentDetail.configure.files.preview.failed": "Falha ao carregar a pré-visualização.",
"agentDetail.configure.files.preview.unsupported": "Este arquivo não oferece suporte à pré-visualização.",
"agentDetail.configure.files.remove": "Remover {{name}}",
- "agentDetail.configure.files.tip": "Arquivos que este agente pode usar ao orquestrar tarefas.",
+ "agentDetail.configure.files.tip": "Forneça ao seu agente qualquer exemplo, diretriz ou simplesmente um portador de informações que seja longo demais para o prompt. Faça referência explícita com / no prompt.",
+ "agentDetail.configure.files.toggle": "Alternar arquivos",
"agentDetail.configure.files.treeLabel": "Arquivos do agente",
"agentDetail.configure.files.upload.action": "Enviar",
"agentDetail.configure.files.upload.browse": "procurar",
@@ -113,8 +127,11 @@
"agentDetail.configure.orchestrate": "Orquestrar",
"agentDetail.configure.preview.chatFeatures": "Recursos de chat",
"agentDetail.configure.preview.empty.defaultAgentName": "Agente",
- "agentDetail.configure.preview.empty.description": "Envie uma mensagem para testar o rascunho atual.",
+ "agentDetail.configure.preview.empty.description": "Execute o agente como um chat finalizado, exatamente como as pessoas verão após a publicação.",
"agentDetail.configure.preview.empty.noInstructionsDescription": "Ainda não há instruções, então as respostas virão do modelo puro.",
+ "agentDetail.configure.preview.empty.title": "Pré-visualizar {{name}}",
+ "agentDetail.configure.preview.endUserAuth": "Autenticação do usuário final",
+ "agentDetail.configure.preview.inputPlaceholder": "Enviar mensagem para {{name}}",
"agentDetail.configure.preview.restart": "Reiniciar pré-visualização",
"agentDetail.configure.preview.title": "Pré-visualização",
"agentDetail.configure.prompt.copied": "Prompt copiado",
@@ -128,7 +145,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "Escreva as instruções aqui,",
- "agentDetail.configure.prompt.tip": "Defina como este agente deve interpretar entradas, chamar ferramentas e produzir saídas.",
+ "agentDetail.configure.prompt.tip": "Defina o papel do agente e descreva sua tarefa típica. Use / para fazer referência explícita a habilidades, arquivos, ferramentas e recuperações de conhecimento.",
"agentDetail.configure.publishBar.draft": "Rascunho",
"agentDetail.configure.publishBar.publishUpdate": "Publicar atualização",
"agentDetail.configure.publishBar.published": "Publicado",
@@ -147,6 +164,14 @@
"agentDetail.configure.publishImpact.title": "{{action}} em {{name}}",
"agentDetail.configure.publishImpact.workflowCount_one": "{{count}} workflow",
"agentDetail.configure.publishImpact.workflowCount_other": "{{count}} workflows",
+ "agentDetail.configure.rightPanel.build": "Criar",
+ "agentDetail.configure.rightPanel.buildTipBody": "Build configura o agente por chat. Descreva o que você quer e ele preenche a configuração à esquerda.",
+ "agentDetail.configure.rightPanel.buildTipTitle": "Crie seu agente via chat",
+ "agentDetail.configure.rightPanel.learnMore": "Saiba mais",
+ "agentDetail.configure.rightPanel.modeLabel": "Modo de configuração do agente",
+ "agentDetail.configure.rightPanel.preview": "Pré-visualização",
+ "agentDetail.configure.rightPanel.previewTipBody": "Preview executa o agente finalizado como seus usuários o verão, com respostas claras e recursos de chat.",
+ "agentDetail.configure.rightPanel.previewTipTitle": "Pré-visualize seu agente",
"agentDetail.configure.skills.add": "Adicionar habilidade",
"agentDetail.configure.skills.detail.contentRegion": "Conteúdo dos detalhes da habilidade",
"agentDetail.configure.skills.detail.fileCount": "{{count}} ARQUIVOS",
@@ -156,7 +181,9 @@
"agentDetail.configure.skills.itemType": "Habilidade",
"agentDetail.configure.skills.label": "Habilidades",
"agentDetail.configure.skills.remove": "Remover {{name}}",
- "agentDetail.configure.skills.tip": "Habilidades que este agente pode usar ao orquestrar tarefas.",
+ "agentDetail.configure.skills.richTip": "Equipe seu agente com capacidades modulares. Consulte a <docLink>documentação</docLink>. Faça referência explícita com / no prompt.",
+ "agentDetail.configure.skills.tip": "Equipe seu agente com capacidades modulares. Consulte a documentação. Faça referência explícita com / no prompt.",
+ "agentDetail.configure.skills.toggle": "Alternar habilidades",
"agentDetail.configure.skills.upload.action": "Enviar",
"agentDetail.configure.skills.upload.browse": "procurar",
"agentDetail.configure.skills.upload.description": "Envie um pacote .zip ou .skill para este agente.",
@@ -166,6 +193,7 @@
"agentDetail.configure.skills.upload.invalidFile": "Envie um arquivo .zip ou .skill.",
"agentDetail.configure.skills.upload.success": "Habilidade enviada.",
"agentDetail.configure.skills.upload.title": "Enviar habilidade",
+ "agentDetail.configure.title": "Configurar",
"agentDetail.configure.tools.add": "Adicionar ferramenta",
"agentDetail.configure.tools.addMenu.cliTool.badge": "Para desenvolvedores",
"agentDetail.configure.tools.addMenu.cliTool.description": "Instale um programa de linha de comando que o agente executa em seu sandbox. Requer instalação e geralmente chaves de API.",
@@ -179,7 +207,7 @@
"agentDetail.configure.tools.cliDialog.env.optional": "(opcional)",
"agentDetail.configure.tools.cliDialog.installCommand.description": "Em sandbox · executado uma vez na primeira invocação",
"agentDetail.configure.tools.cliDialog.installCommand.label": "Comando de instalação",
- "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "Cole seu comando de instalação aqui, ex.: npm install -g @lark/cli · brew install jq",
+ "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "Cole seu comando de instalação aqui, ex.: npx -y @playwright/mcp@latest · uv tool install httpie",
"agentDetail.configure.tools.cliDialog.installCommand.required": "Comando de instalação é obrigatório.",
"agentDetail.configure.tools.cliDialog.learnMore": "Saiba mais sobre ferramenta CLI",
"agentDetail.configure.tools.cliDialog.name.label": "Nome da ferramenta CLI",
@@ -196,13 +224,19 @@
"agentDetail.configure.tools.moreActions": "Mais ações para {{name}}",
"agentDetail.configure.tools.removeAction": "Remover {{name}}",
"agentDetail.configure.tools.removeProvider": "Remover todas as ferramentas",
- "agentDetail.configure.tools.tip": "Ferramentas que este agente pode chamar ao orquestrar tarefas.",
+ "agentDetail.configure.tools.richTip": "Equipe seu agente com os plugins do Dify. Consulte a <pluginDocLink>documentação</pluginDocLink>. Faça referência explícita com / no prompt.\nComo alternativa, você sempre pode dizer ao agente para instalar e autenticar outras ferramentas (por exemplo, MCPs e ferramentas CLI) via um chat de Build. Observe que as ferramentas configuradas por chats de Build NÃO aparecerão aqui, embora continuem disponíveis para o seu agente daqui em diante. Consulte a <buildDocLink>documentação</buildDocLink>.",
+ "agentDetail.configure.tools.tip": "Equipe seu agente com os plugins do Dify. Consulte a documentação. Faça referência explícita com / no prompt. Como alternativa, você sempre pode dizer ao agente para instalar e autenticar outras ferramentas (por exemplo, MCPs e ferramentas CLI) via um chat de Build. Observe que as ferramentas configuradas por chats de Build NÃO aparecerão aqui, embora continuem disponíveis para o seu agente daqui em diante. Consulte a documentação.",
+ "agentDetail.configure.tools.toggle": "Alternar ferramentas",
"agentDetail.configure.tools.toolTabs.all": "Todas",
"agentDetail.configure.tools.toolTabs.cli": "CLI",
"agentDetail.configure.tools.toolTabs.custom": "Personalizado",
"agentDetail.configure.tools.toolTabs.mcp": "MCP",
"agentDetail.configure.tools.toolTabs.plugins": "Plugins",
"agentDetail.configure.tools.toolTabs.workflow": "Workflow",
+ "agentDetail.configure.workingDirectory.description": "Arquivos que o agente lê e grava enquanto executa. Tudo o que ele gera, como qna_report.pdf, aparece aqui.",
+ "agentDetail.configure.workingDirectory.open": "Abrir diretório de trabalho",
+ "agentDetail.configure.workingDirectory.title": "Diretório de trabalho",
+ "agentDetail.configure.workingDirectory.treeLabel": "Arquivos do diretório de trabalho",
"agentDetail.documentTitle": "Agente",
"agentDetail.logs.description": "Os logs completos registram o status de execução do aplicativo, incluindo entradas do usuário, respostas do agente, planejamento e uso de ferramentas.",
"agentDetail.logs.empty": "Nenhum log encontrado",
@@ -279,7 +313,7 @@
"agentDetail.navigationLabel": "Navegação do agente",
"agentDetail.publish": "Publicar",
"agentDetail.sections.access": "Ponto de acesso",
- "agentDetail.sections.configure": "Orquestrar",
+ "agentDetail.sections.configure": "Configurar",
"agentDetail.sections.logs": "Logs",
"agentDetail.sections.monitoring": "Monitoramento",
"agentDetail.title": "Agente",
@@ -334,6 +368,11 @@
"roster.nodeSelector.startFromScratch": "Começar do zero",
"roster.references.label": "Workflows que usam {{name}}",
"roster.references.trigger": "Workflows que usam {{name}}",
+ "roster.saveToRoster": "Save to Agent Console",
+ "roster.saveToRosterDialog.description": "Save this inline setup as a reusable roster agent.",
+ "roster.saveToRosterDialog.title": "Save to Agent Console",
+ "roster.saveToRosterForm.changeIcon": "Change roster agent icon",
+ "roster.saveToRosterSuccess": "Agent saved to roster.",
"roster.searchLabel": "Pesquisar agentes",
"roster.searchPlaceholder": "Pesquisar agentes pelo nome…",
"roster.tabs.agent": "Agente",
diff --git a/web/i18n/pt-BR/common.json b/web/i18n/pt-BR/common.json
index 81c230084ed..05cd08af5be 100644
--- a/web/i18n/pt-BR/common.json
+++ b/web/i18n/pt-BR/common.json
@@ -288,6 +288,7 @@
"menus.exploreMarketplace": "Explorar Mercado",
"menus.plugins": "Integrações",
"menus.roster": "Lista de agentes",
+ "menus.status": "beta",
"menus.tools": "Ferramentas",
"model.capabilities": "Recursos multimodais",
"model.params.stop_sequencesPlaceholder": "Digite a sequência e pressione Tab",
diff --git a/web/i18n/pt-BR/workflow.json b/web/i18n/pt-BR/workflow.json
index eb35b5fd28e..1c60015ce0a 100644
--- a/web/i18n/pt-BR/workflow.json
+++ b/web/i18n/pt-BR/workflow.json
@@ -464,7 +464,7 @@
"nodes.agent.task.label": "Tarefa do agente",
"nodes.agent.task.mention": "Mencionar",
"nodes.agent.task.placeholder": "Descreva o que este agente deve fazer...",
- "nodes.agent.task.tooltip": "Defina as instruções da tarefa que este agente deve seguir neste workflow.",
+ "nodes.agent.task.tooltip": "Prompt adicional para ajudar o agente a lidar com este nó específico. Use / para fazer referência explícita a variáveis.\nSe configurado corretamente, você poderá confiar que o agente descobrirá as coisas por conta própria.",
"nodes.agent.toolNotAuthorizedTooltip": "{{tool}} Não autorizado",
"nodes.agent.toolNotInstallTooltip": "{{tool}} não está instalado",
"nodes.agent.toolbox": "caixa de ferramentas",
diff --git a/web/i18n/ro-RO/agent-v-2.json b/web/i18n/ro-RO/agent-v-2.json
index 80d03949631..1c23a05436a 100644
--- a/web/i18n/ro-RO/agent-v-2.json
+++ b/web/i18n/ro-RO/agent-v-2.json
@@ -49,14 +49,27 @@
"agentDetail.configure.advancedSettings.envEditor.keyPlaceholder": "Key",
"agentDetail.configure.advancedSettings.envEditor.label": "Env Editor",
"agentDetail.configure.advancedSettings.envEditor.revealValue": "Dezvăluie valoarea {{key}}",
+ "agentDetail.configure.advancedSettings.envEditor.richTip": "Agentul tău rulează într-un mediu Linux. Poți preseta configurații sau secrete definind aici variabile de mediu.\n\nAlternativ, poți configura oricând lucrurile printr-un chat Build. Consultă <docLink>documentația</docLink>.",
"agentDetail.configure.advancedSettings.envEditor.scopeColumn": "Scope",
"agentDetail.configure.advancedSettings.envEditor.scopePlain": "Plain",
"agentDetail.configure.advancedSettings.envEditor.scopeSecret": "Secret",
"agentDetail.configure.advancedSettings.envEditor.scopeSelector": "Selectați domeniul variabilei de mediu",
- "agentDetail.configure.advancedSettings.envEditor.tip": "Variabile de mediu disponibile pentru acest agent în timpul execuției.",
+ "agentDetail.configure.advancedSettings.envEditor.tip": "Agentul tău rulează într-un mediu Linux. Poți preseta configurații sau secrete definind aici variabile de mediu. Alternativ, poți configura oricând lucrurile printr-un chat Build. Consultă documentația.",
+ "agentDetail.configure.advancedSettings.envEditor.toggle": "Comută Env Editor",
"agentDetail.configure.advancedSettings.envEditor.valueColumn": "Value",
"agentDetail.configure.advancedSettings.envEditor.valuePlaceholder": "Value",
"agentDetail.configure.advancedSettings.label": "Setări avansate",
+ "agentDetail.configure.advancedSettings.toggle": "Comută setările avansate",
+ "agentDetail.configure.build.empty.description": "Descrie ce dorești, iar formularul din stânga se completează pe măsură ce avansezi.",
+ "agentDetail.configure.build.empty.title": "Construiește agentul prin chat",
+ "agentDetail.configure.build.inputPlaceholder": "Descrie ce ar trebui să facă agentul tău",
+ "agentDetail.configure.build.startBuild": "Pornește build-ul",
+ "agentDetail.configure.buildDraft.changes": "{{count}} modificări de aplicat",
+ "agentDetail.configure.buildDraft.discard": "Renunță",
+ "agentDetail.configure.buildDraft.modeBadge": "Mod build",
+ "agentDetail.configure.buildDraft.modeDescription": "Ești în modul build. Ajustează această configurare prin chatul din dreapta, apoi aplică.",
+ "agentDetail.configure.buildDraft.noChanges": "Nu există modificări de aplicat",
+ "agentDetail.configure.buildDraft.title": "Schiță de build",
"agentDetail.configure.chatFeatures.description": "Modelează experiența de chat a utilizatorului final pe webapp-ul tău și pe suprafețele de chat.",
"agentDetail.configure.chatFeatures.title": "Funcții de chat",
"agentDetail.configure.files.add": "Adaugă fișier",
@@ -67,7 +80,8 @@
"agentDetail.configure.files.preview.failed": "Încărcarea previzualizării a eșuat.",
"agentDetail.configure.files.preview.unsupported": "Acest fișier nu acceptă previzualizarea.",
"agentDetail.configure.files.remove": "Elimină {{name}}",
- "agentDetail.configure.files.tip": "Fișiere pe care acest agent le poate folosi în timpul orchestrării sarcinilor.",
+ "agentDetail.configure.files.tip": "Oferiți agentului orice exemplu, ghid sau pur și simplu un suport de informații prea lung pentru prompt. Faceți referire explicită cu / în prompt.",
+ "agentDetail.configure.files.toggle": "Comută fișierele",
"agentDetail.configure.files.treeLabel": "Fișierele agentului",
"agentDetail.configure.files.upload.action": "Încarcă",
"agentDetail.configure.files.upload.browse": "răsfoiește",
@@ -113,8 +127,11 @@
"agentDetail.configure.orchestrate": "Orchestrare",
"agentDetail.configure.preview.chatFeatures": "Funcții de chat",
"agentDetail.configure.preview.empty.defaultAgentName": "Agent",
- "agentDetail.configure.preview.empty.description": "Trimiteți un mesaj pentru a testa ciorna curentă.",
+ "agentDetail.configure.preview.empty.description": "Rulează agentul ca un chat finalizat, exact cum îl vor experimenta utilizatorii după publicare.",
"agentDetail.configure.preview.empty.noInstructionsDescription": "Nu există încă instrucțiuni, așa că răspunsurile vin de la modelul de bază.",
+ "agentDetail.configure.preview.empty.title": "Previzualizează {{name}}",
+ "agentDetail.configure.preview.endUserAuth": "Autentificare utilizator final",
+ "agentDetail.configure.preview.inputPlaceholder": "Trimite mesaj către {{name}}",
"agentDetail.configure.preview.restart": "Reporniți previzualizarea",
"agentDetail.configure.preview.title": "Previzualizare",
"agentDetail.configure.prompt.copied": "Prompt copiat",
@@ -128,7 +145,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "Scrieți instrucțiunile aici,",
- "agentDetail.configure.prompt.tip": "Definiți modul în care acest agent ar trebui să interpreteze intrările, să apeleze instrumentele și să producă ieșirile.",
+ "agentDetail.configure.prompt.tip": "Definiți rolul agentului și descrieți sarcina sa tipică. Folosiți / pentru a face referire explicită la abilități, fișiere, instrumente și recuperări de cunoștințe.",
"agentDetail.configure.publishBar.draft": "Ciornă",
"agentDetail.configure.publishBar.publishUpdate": "Publică actualizarea",
"agentDetail.configure.publishBar.published": "Publicat",
@@ -147,6 +164,14 @@
"agentDetail.configure.publishImpact.title": "{{action}} pentru {{name}}",
"agentDetail.configure.publishImpact.workflowCount_one": "{{count}} workflow",
"agentDetail.configure.publishImpact.workflowCount_other": "{{count}} workflow-uri",
+ "agentDetail.configure.rightPanel.build": "Construire",
+ "agentDetail.configure.rightPanel.buildTipBody": "Build configurează agentul prin chat. Descrie ce dorești, iar configurarea din stânga va fi completată.",
+ "agentDetail.configure.rightPanel.buildTipTitle": "Construiește agentul prin chat",
+ "agentDetail.configure.rightPanel.learnMore": "Află mai multe",
+ "agentDetail.configure.rightPanel.modeLabel": "Mod de configurare agent",
+ "agentDetail.configure.rightPanel.preview": "Previzualizare",
+ "agentDetail.configure.rightPanel.previewTipBody": "Preview rulează agentul finalizat așa cum îl vor vedea utilizatorii, cu răspunsuri clare și funcții de chat.",
+ "agentDetail.configure.rightPanel.previewTipTitle": "Previzualizează agentul",
"agentDetail.configure.skills.add": "Adaugă abilitate",
"agentDetail.configure.skills.detail.contentRegion": "Conținutul detaliilor abilității",
"agentDetail.configure.skills.detail.fileCount": "{{count}} FIȘIERE",
@@ -156,7 +181,9 @@
"agentDetail.configure.skills.itemType": "Abilitate",
"agentDetail.configure.skills.label": "Abilități",
"agentDetail.configure.skills.remove": "Elimină {{name}}",
- "agentDetail.configure.skills.tip": "Abilități pe care acest agent le poate folosi în timpul orchestrării sarcinilor.",
+ "agentDetail.configure.skills.richTip": "Echipați agentul cu capabilități modulare. Consultați <docLink>documentația</docLink>. Faceți referire explicită cu / în prompt.",
+ "agentDetail.configure.skills.tip": "Echipați agentul cu capabilități modulare. Consultați documentația. Faceți referire explicită cu / în prompt.",
+ "agentDetail.configure.skills.toggle": "Comută abilitățile",
"agentDetail.configure.skills.upload.action": "Încarcă",
"agentDetail.configure.skills.upload.browse": "răsfoiește",
"agentDetail.configure.skills.upload.description": "Încarcă un pachet .zip sau .skill pentru acest agent.",
@@ -166,6 +193,7 @@
"agentDetail.configure.skills.upload.invalidFile": "Încărcați un fișier .zip sau .skill.",
"agentDetail.configure.skills.upload.success": "Abilitate încărcată.",
"agentDetail.configure.skills.upload.title": "Încarcă abilitate",
+ "agentDetail.configure.title": "Configurare",
"agentDetail.configure.tools.add": "Adaugă instrument",
"agentDetail.configure.tools.addMenu.cliTool.badge": "Pentru dezvoltatori",
"agentDetail.configure.tools.addMenu.cliTool.description": "Instalați un program de linie de comandă pe care agentul îl rulează în sandbox-ul său. Necesită instalare și, de obicei, chei API.",
@@ -179,7 +207,7 @@
"agentDetail.configure.tools.cliDialog.env.optional": "(opțional)",
"agentDetail.configure.tools.cliDialog.installCommand.description": "În sandbox · rulat o singură dată la prima invocare",
"agentDetail.configure.tools.cliDialog.installCommand.label": "Comandă de instalare",
- "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "Lipiți comanda de instalare aici, de ex. npm install -g @lark/cli · brew install jq",
+ "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "Lipiți comanda de instalare aici, de ex. npx -y @playwright/mcp@latest · uv tool install httpie",
"agentDetail.configure.tools.cliDialog.installCommand.required": "Comanda de instalare este obligatorie.",
"agentDetail.configure.tools.cliDialog.learnMore": "Aflați mai multe despre instrumentul CLI",
"agentDetail.configure.tools.cliDialog.name.label": "Numele instrumentului CLI",
@@ -196,13 +224,19 @@
"agentDetail.configure.tools.moreActions": "Mai multe acțiuni pentru {{name}}",
"agentDetail.configure.tools.removeAction": "Eliminați {{name}}",
"agentDetail.configure.tools.removeProvider": "Eliminați toate instrumentele",
- "agentDetail.configure.tools.tip": "Instrumente pe care acest agent le poate apela în timpul orchestrării sarcinilor.",
+ "agentDetail.configure.tools.richTip": "Echipați agentul cu pluginurile Dify. Consultați <pluginDocLink>documentația</pluginDocLink>. Faceți referire explicită cu / în prompt.\nAlternativ, puteți oricând să îi spuneți agentului să instaleze și să autentifice alte instrumente (de ex. MCPs și instrumente CLI) printr-un chat Build. Rețineți că instrumentele configurate prin chat-uri Build NU vor apărea aici, deși vor rămâne disponibile pentru agentul dvs. în continuare. Consultați <buildDocLink>documentația</buildDocLink>.",
+ "agentDetail.configure.tools.tip": "Echipați agentul cu pluginurile Dify. Consultați documentația. Faceți referire explicită cu / în prompt. Alternativ, puteți oricând să îi spuneți agentului să instaleze și să autentifice alte instrumente (de ex. MCPs și instrumente CLI) printr-un chat Build. Rețineți că instrumentele configurate prin chat-uri Build NU vor apărea aici, deși vor rămâne disponibile pentru agentul dvs. în continuare. Consultați documentația.",
+ "agentDetail.configure.tools.toggle": "Comută instrumentele",
"agentDetail.configure.tools.toolTabs.all": "Toate",
"agentDetail.configure.tools.toolTabs.cli": "CLI",
"agentDetail.configure.tools.toolTabs.custom": "Personalizat",
"agentDetail.configure.tools.toolTabs.mcp": "MCP",
"agentDetail.configure.tools.toolTabs.plugins": "Plugin-uri",
"agentDetail.configure.tools.toolTabs.workflow": "Workflow",
+ "agentDetail.configure.workingDirectory.description": "Fișierele pe care agentul le citește și le scrie în timpul rulării. Tot ce generează, precum qna_report.pdf, apare aici.",
+ "agentDetail.configure.workingDirectory.open": "Deschide directorul de lucru",
+ "agentDetail.configure.workingDirectory.title": "Director de lucru",
+ "agentDetail.configure.workingDirectory.treeLabel": "Fișiere din directorul de lucru",
"agentDetail.documentTitle": "Agent",
"agentDetail.logs.description": "Jurnalele complete înregistrează starea de execuție a aplicației, inclusiv intrările utilizatorilor, răspunsurile agentului, planificarea și utilizarea instrumentelor.",
"agentDetail.logs.empty": "Niciun jurnal găsit",
@@ -279,7 +313,7 @@
"agentDetail.navigationLabel": "Navigarea agentului",
"agentDetail.publish": "Publică",
"agentDetail.sections.access": "Punct de acces",
- "agentDetail.sections.configure": "Orchestrare",
+ "agentDetail.sections.configure": "Configurează",
"agentDetail.sections.logs": "Jurnale",
"agentDetail.sections.monitoring": "Monitorizare",
"agentDetail.title": "Agent",
@@ -334,6 +368,11 @@
"roster.nodeSelector.startFromScratch": "Începeți de la zero",
"roster.references.label": "Workflow-uri care folosesc {{name}}",
"roster.references.trigger": "Workflow-uri care folosesc {{name}}",
+ "roster.saveToRoster": "Save to Agent Console",
+ "roster.saveToRosterDialog.description": "Save this inline setup as a reusable roster agent.",
+ "roster.saveToRosterDialog.title": "Save to Agent Console",
+ "roster.saveToRosterForm.changeIcon": "Change roster agent icon",
+ "roster.saveToRosterSuccess": "Agent saved to roster.",
"roster.searchLabel": "Căutați agenți",
"roster.searchPlaceholder": "Căutați agenți după nume…",
"roster.tabs.agent": "Agent",
diff --git a/web/i18n/ro-RO/common.json b/web/i18n/ro-RO/common.json
index 76205d7809e..b36af8851f0 100644
--- a/web/i18n/ro-RO/common.json
+++ b/web/i18n/ro-RO/common.json
@@ -288,6 +288,7 @@
"menus.exploreMarketplace": "Explorați Marketplace",
"menus.plugins": "Integrare-uri",
"menus.roster": "Listă agenți",
+ "menus.status": "beta",
"menus.tools": "Instrumente",
"model.capabilities": "Capacități multimodale",
"model.params.stop_sequencesPlaceholder": "Introduceți secvența și apăsați Tab",
diff --git a/web/i18n/ro-RO/workflow.json b/web/i18n/ro-RO/workflow.json
index 506d99765af..b03a7296d53 100644
--- a/web/i18n/ro-RO/workflow.json
+++ b/web/i18n/ro-RO/workflow.json
@@ -464,7 +464,7 @@
"nodes.agent.task.label": "Sarcina agentului",
"nodes.agent.task.mention": "Menționează",
"nodes.agent.task.placeholder": "Descrieți ce ar trebui să facă acest agent...",
- "nodes.agent.task.tooltip": "Definiți instrucțiunile sarcinii pe care acest agent trebuie să le urmeze în acest workflow.",
+ "nodes.agent.task.tooltip": "Prompt suplimentar pentru a ajuta agentul să gestioneze exact acest nod. Folosește / pentru a face referire explicită la variabile.\nDacă este configurat corect, ai putea avea încredere că agentul își va da seama singur ce are de făcut.",
"nodes.agent.toolNotAuthorizedTooltip": "{{tool}} Neautorizat",
"nodes.agent.toolNotInstallTooltip": "{{tool}} nu este instalat",
"nodes.agent.toolbox": "cutie de scule",
diff --git a/web/i18n/ru-RU/agent-v-2.json b/web/i18n/ru-RU/agent-v-2.json
index bb34e5b854c..108763b8202 100644
--- a/web/i18n/ru-RU/agent-v-2.json
+++ b/web/i18n/ru-RU/agent-v-2.json
@@ -49,14 +49,27 @@
"agentDetail.configure.advancedSettings.envEditor.keyPlaceholder": "Key",
"agentDetail.configure.advancedSettings.envEditor.label": "Env Editor",
"agentDetail.configure.advancedSettings.envEditor.revealValue": "Показать значение {{key}}",
+ "agentDetail.configure.advancedSettings.envEditor.richTip": "Ваш агент работает в среде Linux. Вы можете заранее задать конфигурации или секреты, определив здесь переменные окружения.\n\nТакже вы всегда можете настроить всё через чат Build. См. <docLink>документацию</docLink>.",
"agentDetail.configure.advancedSettings.envEditor.scopeColumn": "Scope",
"agentDetail.configure.advancedSettings.envEditor.scopePlain": "Plain",
"agentDetail.configure.advancedSettings.envEditor.scopeSecret": "Secret",
"agentDetail.configure.advancedSettings.envEditor.scopeSelector": "Выберите область переменной окружения",
- "agentDetail.configure.advancedSettings.envEditor.tip": "Переменные окружения, доступные этому агенту во время выполнения.",
+ "agentDetail.configure.advancedSettings.envEditor.tip": "Ваш агент работает в среде Linux. Вы можете заранее задать конфигурации или секреты, определив здесь переменные окружения. Также вы всегда можете настроить всё через чат Build. См. документацию.",
+ "agentDetail.configure.advancedSettings.envEditor.toggle": "Переключить Env Editor",
"agentDetail.configure.advancedSettings.envEditor.valueColumn": "Value",
"agentDetail.configure.advancedSettings.envEditor.valuePlaceholder": "Value",
"agentDetail.configure.advancedSettings.label": "Расширенные настройки",
+ "agentDetail.configure.advancedSettings.toggle": "Переключить расширенные настройки",
+ "agentDetail.configure.build.empty.description": "Опишите, что вам нужно, и форма слева будет заполняться по ходу диалога.",
+ "agentDetail.configure.build.empty.title": "Создайте агента в чате",
+ "agentDetail.configure.build.inputPlaceholder": "Опишите, что должен делать агент",
+ "agentDetail.configure.build.startBuild": "Начать сборку",
+ "agentDetail.configure.buildDraft.changes": "{{count}} изменений для применения",
+ "agentDetail.configure.buildDraft.discard": "Отменить",
+ "agentDetail.configure.buildDraft.modeBadge": "Режим сборки",
+ "agentDetail.configure.buildDraft.modeDescription": "Вы в режиме сборки. Настройте эту конфигурацию через чат справа, затем примените изменения.",
+ "agentDetail.configure.buildDraft.noChanges": "Нет изменений для применения",
+ "agentDetail.configure.buildDraft.title": "Черновик сборки",
"agentDetail.configure.chatFeatures.description": "Настройте чат-опыт конечного пользователя в вашем веб-приложении и чат-поверхностях.",
"agentDetail.configure.chatFeatures.title": "Функции чата",
"agentDetail.configure.files.add": "Добавить файл",
@@ -67,7 +80,8 @@
"agentDetail.configure.files.preview.failed": "Не удалось загрузить предпросмотр.",
"agentDetail.configure.files.preview.unsupported": "Этот файл не поддерживает предварительный просмотр.",
"agentDetail.configure.files.remove": "Удалить {{name}}",
- "agentDetail.configure.files.tip": "Файлы, которые этот агент может использовать при выполнении задач.",
+ "agentDetail.configure.files.tip": "Предоставьте агенту любой пример, инструкцию или просто носитель информации, который слишком длинный для промпта. Явно ссылайтесь на него через / в промпте.",
+ "agentDetail.configure.files.toggle": "Переключить файлы",
"agentDetail.configure.files.treeLabel": "Файлы агента",
"agentDetail.configure.files.upload.action": "Загрузить",
"agentDetail.configure.files.upload.browse": "обзор",
@@ -113,8 +127,11 @@
"agentDetail.configure.orchestrate": "Оркестрация",
"agentDetail.configure.preview.chatFeatures": "Функции чата",
"agentDetail.configure.preview.empty.defaultAgentName": "Агент",
- "agentDetail.configure.preview.empty.description": "Отправьте сообщение, чтобы протестировать текущий черновик.",
+ "agentDetail.configure.preview.empty.description": "Запустите агента как готовый чат, именно так, как его увидят пользователи после публикации.",
"agentDetail.configure.preview.empty.noInstructionsDescription": "Инструкций пока нет, поэтому ответы приходят от базовой модели.",
+ "agentDetail.configure.preview.empty.title": "Предпросмотр {{name}}",
+ "agentDetail.configure.preview.endUserAuth": "Аутентификация конечного пользователя",
+ "agentDetail.configure.preview.inputPlaceholder": "Написать {{name}}",
"agentDetail.configure.preview.restart": "Перезапустить предпросмотр",
"agentDetail.configure.preview.title": "Предпросмотр",
"agentDetail.configure.prompt.copied": "Промпт скопирован",
@@ -128,7 +145,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "Напишите инструкции здесь,",
- "agentDetail.configure.prompt.tip": "Определите, как этот агент должен интерпретировать входные данные, вызывать инструменты и формировать выходные данные.",
+ "agentDetail.configure.prompt.tip": "Определите роль агента и опишите его типичную задачу. Используйте /, чтобы явно ссылаться на навыки, файлы, инструменты и извлечение знаний.",
"agentDetail.configure.publishBar.draft": "Черновик",
"agentDetail.configure.publishBar.publishUpdate": "Опубликовать обновление",
"agentDetail.configure.publishBar.published": "Опубликовано",
@@ -147,6 +164,14 @@
"agentDetail.configure.publishImpact.title": "{{action}} в {{name}}",
"agentDetail.configure.publishImpact.workflowCount_one": "{{count}} рабочий процесс",
"agentDetail.configure.publishImpact.workflowCount_other": "{{count}} рабочих процессов",
+ "agentDetail.configure.rightPanel.build": "Сборка",
+ "agentDetail.configure.rightPanel.buildTipBody": "Build настраивает агента через чат. Опишите, что вам нужно, и он заполнит настройки слева.",
+ "agentDetail.configure.rightPanel.buildTipTitle": "Создайте агента через чат",
+ "agentDetail.configure.rightPanel.learnMore": "Подробнее",
+ "agentDetail.configure.rightPanel.modeLabel": "Режим настройки агента",
+ "agentDetail.configure.rightPanel.preview": "Предпросмотр",
+ "agentDetail.configure.rightPanel.previewTipBody": "Preview запускает готового агента так, как его увидят пользователи, с чистыми ответами и функциями чата.",
+ "agentDetail.configure.rightPanel.previewTipTitle": "Предпросмотр агента",
"agentDetail.configure.skills.add": "Добавить навык",
"agentDetail.configure.skills.detail.contentRegion": "Содержимое деталей навыка",
"agentDetail.configure.skills.detail.fileCount": "{{count}} ФАЙЛОВ",
@@ -156,7 +181,9 @@
"agentDetail.configure.skills.itemType": "Навык",
"agentDetail.configure.skills.label": "Навыки",
"agentDetail.configure.skills.remove": "Удалить {{name}}",
- "agentDetail.configure.skills.tip": "Навыки, которые этот агент может использовать при выполнении задач.",
+ "agentDetail.configure.skills.richTip": "Оснастите агента модульными возможностями. См. <docLink>документацию</docLink>. Явно ссылайтесь на них через / в промпте.",
+ "agentDetail.configure.skills.tip": "Оснастите агента модульными возможностями. См. документацию. Явно ссылайтесь на них через / в промпте.",
+ "agentDetail.configure.skills.toggle": "Переключить навыки",
"agentDetail.configure.skills.upload.action": "Загрузить",
"agentDetail.configure.skills.upload.browse": "обзор",
"agentDetail.configure.skills.upload.description": "Загрузите пакет .zip или .skill для этого агента.",
@@ -166,6 +193,7 @@
"agentDetail.configure.skills.upload.invalidFile": "Загрузите файл .zip или .skill.",
"agentDetail.configure.skills.upload.success": "Навык загружен.",
"agentDetail.configure.skills.upload.title": "Загрузить навык",
+ "agentDetail.configure.title": "Настроить",
"agentDetail.configure.tools.add": "Добавить инструмент",
"agentDetail.configure.tools.addMenu.cliTool.badge": "Для разработчиков",
"agentDetail.configure.tools.addMenu.cliTool.description": "Установите программу командной строки, которую агент запускает в песочнице. Требуется установка, обычно также API Key.",
@@ -179,7 +207,7 @@
"agentDetail.configure.tools.cliDialog.env.optional": "(необязательно)",
"agentDetail.configure.tools.cliDialog.installCommand.description": "В песочнице · запускается один раз при первом вызове",
"agentDetail.configure.tools.cliDialog.installCommand.label": "Команда установки",
- "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "Вставьте команду установки здесь, например npm install -g @lark/cli · brew install jq",
+ "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "Вставьте команду установки здесь, например npx -y @playwright/mcp@latest · uv tool install httpie",
"agentDetail.configure.tools.cliDialog.installCommand.required": "Команда установки обязательна.",
"agentDetail.configure.tools.cliDialog.learnMore": "Подробнее о CLI-инструменте",
"agentDetail.configure.tools.cliDialog.name.label": "Имя CLI-инструмента",
@@ -196,13 +224,19 @@
"agentDetail.configure.tools.moreActions": "Дополнительные действия для {{name}}",
"agentDetail.configure.tools.removeAction": "Удалить {{name}}",
"agentDetail.configure.tools.removeProvider": "Удалить все инструменты",
- "agentDetail.configure.tools.tip": "Инструменты, которые этот агент может вызывать при выполнении задач.",
+ "agentDetail.configure.tools.richTip": "Оснастите агента плагинами Dify. См. <pluginDocLink>документацию</pluginDocLink>. Явно ссылайтесь на них через / в промпте.\nТакже вы всегда можете попросить агента установить и аутентифицировать другие инструменты (например, MCPs и CLI-инструменты) через Build-чат. Обратите внимание: инструменты, настроенные через Build-чаты, НЕ будут отображаться здесь, хотя и останутся доступны вашему агенту в дальнейшем. См. <buildDocLink>документацию</buildDocLink>.",
+ "agentDetail.configure.tools.tip": "Оснастите агента плагинами Dify. См. документацию. Явно ссылайтесь на них через / в промпте. Также вы всегда можете попросить агента установить и аутентифицировать другие инструменты (например, MCPs и CLI-инструменты) через Build-чат. Обратите внимание: инструменты, настроенные через Build-чаты, НЕ будут отображаться здесь, хотя и останутся доступны вашему агенту в дальнейшем. См. документацию.",
+ "agentDetail.configure.tools.toggle": "Переключить инструменты",
"agentDetail.configure.tools.toolTabs.all": "Все",
"agentDetail.configure.tools.toolTabs.cli": "CLI",
"agentDetail.configure.tools.toolTabs.custom": "Пользовательские",
"agentDetail.configure.tools.toolTabs.mcp": "MCP",
"agentDetail.configure.tools.toolTabs.plugins": "Интеграции",
"agentDetail.configure.tools.toolTabs.workflow": "Рабочий процесс",
+ "agentDetail.configure.workingDirectory.description": "Файлы, которые агент читает и записывает во время работы. Все, что он создает, например qna_report.pdf, появится здесь.",
+ "agentDetail.configure.workingDirectory.open": "Открыть рабочий каталог",
+ "agentDetail.configure.workingDirectory.title": "Рабочий каталог",
+ "agentDetail.configure.workingDirectory.treeLabel": "Файлы рабочего каталога",
"agentDetail.documentTitle": "Агент",
"agentDetail.logs.description": "Полные журналы записывают статус работы приложения, включая ввод пользователя, ответы агента, планирование и использование инструментов.",
"agentDetail.logs.empty": "Журналы не найдены",
@@ -279,7 +313,7 @@
"agentDetail.navigationLabel": "Навигация агента",
"agentDetail.publish": "Опубликовать",
"agentDetail.sections.access": "Точка доступа",
- "agentDetail.sections.configure": "Оркестрация",
+ "agentDetail.sections.configure": "Настроить",
"agentDetail.sections.logs": "Журналы",
"agentDetail.sections.monitoring": "Мониторинг",
"agentDetail.title": "Агент",
@@ -334,6 +368,11 @@
"roster.nodeSelector.startFromScratch": "Начать с нуля",
"roster.references.label": "Рабочие процессы, использующие {{name}}",
"roster.references.trigger": "Рабочие процессы, использующие {{name}}",
+ "roster.saveToRoster": "Save to Agent Console",
+ "roster.saveToRosterDialog.description": "Save this inline setup as a reusable roster agent.",
+ "roster.saveToRosterDialog.title": "Save to Agent Console",
+ "roster.saveToRosterForm.changeIcon": "Change roster agent icon",
+ "roster.saveToRosterSuccess": "Agent saved to roster.",
"roster.searchLabel": "Поиск агентов",
"roster.searchPlaceholder": "Поиск агентов по имени…",
"roster.tabs.agent": "Агент",
diff --git a/web/i18n/ru-RU/common.json b/web/i18n/ru-RU/common.json
index 98801747f16..8ee073dbf2e 100644
--- a/web/i18n/ru-RU/common.json
+++ b/web/i18n/ru-RU/common.json
@@ -288,6 +288,7 @@
"menus.exploreMarketplace": "Подробнее о Marketplace",
"menus.plugins": "Интеграции",
"menus.roster": "Список агентов",
+ "menus.status": "бета",
"menus.tools": "Инструменты",
"model.capabilities": "Мультимодальные возможности",
"model.params.stop_sequencesPlaceholder": "Введите последовательность и нажмите Tab",
diff --git a/web/i18n/ru-RU/workflow.json b/web/i18n/ru-RU/workflow.json
index 3551d1f21ff..e2ed173998e 100644
--- a/web/i18n/ru-RU/workflow.json
+++ b/web/i18n/ru-RU/workflow.json
@@ -464,7 +464,7 @@
"nodes.agent.task.label": "Задача агента",
"nodes.agent.task.mention": "Упомянуть",
"nodes.agent.task.placeholder": "Опишите, что должен делать этот агент…",
- "nodes.agent.task.tooltip": "Определите инструкции задачи, которые этот агент должен выполнять в этом рабочем процессе.",
+ "nodes.agent.task.tooltip": "Дополнительный промпт, который помогает агенту обработать именно этот узел. Используйте /, чтобы явно ссылаться на переменные.\nПри правильной настройке вы сможете доверить агенту самостоятельно разбираться с задачей.",
"nodes.agent.toolNotAuthorizedTooltip": "{{tool}} Не авторизован",
"nodes.agent.toolNotInstallTooltip": "{{tool}} не установлен",
"nodes.agent.toolbox": "ящик для инструментов",
diff --git a/web/i18n/sl-SI/agent-v-2.json b/web/i18n/sl-SI/agent-v-2.json
index 7f04929e3c0..cf777db6c0c 100644
--- a/web/i18n/sl-SI/agent-v-2.json
+++ b/web/i18n/sl-SI/agent-v-2.json
@@ -49,14 +49,27 @@
"agentDetail.configure.advancedSettings.envEditor.keyPlaceholder": "Key",
"agentDetail.configure.advancedSettings.envEditor.label": "Env Editor",
"agentDetail.configure.advancedSettings.envEditor.revealValue": "Razkrij vrednost {{key}}",
+ "agentDetail.configure.advancedSettings.envEditor.richTip": "Vaš agent se izvaja v okolju Linux. Konfiguracije ali skrivnosti lahko vnaprej nastavite tako, da tukaj določite okoljske spremenljivke.\n\nDruga možnost je, da nastavitev vedno izvedete prek klepeta Build. Glejte <docLink>dokumentacijo</docLink>.",
"agentDetail.configure.advancedSettings.envEditor.scopeColumn": "Scope",
"agentDetail.configure.advancedSettings.envEditor.scopePlain": "Plain",
"agentDetail.configure.advancedSettings.envEditor.scopeSecret": "Secret",
"agentDetail.configure.advancedSettings.envEditor.scopeSelector": "Izberite obseg okoljske spremenljivke",
- "agentDetail.configure.advancedSettings.envEditor.tip": "Okoljske spremenljivke, ki so na voljo temu agentu med izvajanjem.",
+ "agentDetail.configure.advancedSettings.envEditor.tip": "Vaš agent se izvaja v okolju Linux. Konfiguracije ali skrivnosti lahko vnaprej nastavite tako, da tukaj določite okoljske spremenljivke. Druga možnost je, da nastavitev vedno izvedete prek klepeta Build. Glejte dokumentacijo.",
+ "agentDetail.configure.advancedSettings.envEditor.toggle": "Preklopi Env Editor",
"agentDetail.configure.advancedSettings.envEditor.valueColumn": "Value",
"agentDetail.configure.advancedSettings.envEditor.valuePlaceholder": "Value",
"agentDetail.configure.advancedSettings.label": "Napredne nastavitve",
+ "agentDetail.configure.advancedSettings.toggle": "Preklopi napredne nastavitve",
+ "agentDetail.configure.build.empty.description": "Opišite, kaj želite, in obrazec na levi se bo sproti izpolnjeval.",
+ "agentDetail.configure.build.empty.title": "Izdelajte agenta s klepetom",
+ "agentDetail.configure.build.inputPlaceholder": "Opišite, kaj naj vaš agent počne",
+ "agentDetail.configure.build.startBuild": "Začni gradnjo",
+ "agentDetail.configure.buildDraft.changes": "{{count}} sprememb za uporabo",
+ "agentDetail.configure.buildDraft.discard": "Zavrzi",
+ "agentDetail.configure.buildDraft.modeBadge": "Način gradnje",
+ "agentDetail.configure.buildDraft.modeDescription": "Ste v načinu gradnje. Nastavitev oblikujte s klepetom na desni, nato jo uporabite.",
+ "agentDetail.configure.buildDraft.noChanges": "Ni sprememb za uporabo",
+ "agentDetail.configure.buildDraft.title": "Osnutek gradnje",
"agentDetail.configure.chatFeatures.description": "Oblikujte uporabniško izkušnjo klepeta v vaši spletni aplikaciji in klepetalnih površinah.",
"agentDetail.configure.chatFeatures.title": "Funkcije klepeta",
"agentDetail.configure.files.add": "Dodaj datoteko",
@@ -67,7 +80,8 @@
"agentDetail.configure.files.preview.failed": "Predogleda ni bilo mogoče naložiti.",
"agentDetail.configure.files.preview.unsupported": "Ta datoteka ne podpira predogleda.",
"agentDetail.configure.files.remove": "Odstrani {{name}}",
- "agentDetail.configure.files.tip": "Datoteke, ki jih ta agent lahko uporablja pri izvajanju opravil.",
+ "agentDetail.configure.files.tip": "Agentu zagotovite primer, smernice ali preprosto nosilec informacij, ki je predolg za poziv. V pozivu ga izrecno navedite z /.",
+ "agentDetail.configure.files.toggle": "Preklopi datoteke",
"agentDetail.configure.files.treeLabel": "Datoteke agenta",
"agentDetail.configure.files.upload.action": "Naloži",
"agentDetail.configure.files.upload.browse": "prebrskaj",
@@ -113,8 +127,11 @@
"agentDetail.configure.orchestrate": "Orkestracija",
"agentDetail.configure.preview.chatFeatures": "Funkcije klepeta",
"agentDetail.configure.preview.empty.defaultAgentName": "Agent",
- "agentDetail.configure.preview.empty.description": "Pošljite sporočilo, da preizkusite trenutni osnutek.",
+ "agentDetail.configure.preview.empty.description": "Zaženite agenta kot dokončan klepet, natanko tako, kot ga bodo uporabniki doživeli po objavi.",
"agentDetail.configure.preview.empty.noInstructionsDescription": "Ni še navodil, zato odgovori prihajajo iz osnovnega modela.",
+ "agentDetail.configure.preview.empty.title": "Predogled {{name}}",
+ "agentDetail.configure.preview.endUserAuth": "Preverjanje pristnosti končnega uporabnika",
+ "agentDetail.configure.preview.inputPlaceholder": "Pošlji sporočilo za {{name}}",
"agentDetail.configure.preview.restart": "Znova zaženi predogled",
"agentDetail.configure.preview.title": "Predogled",
"agentDetail.configure.prompt.copied": "Poziv kopiran",
@@ -128,7 +145,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "Tukaj napišite navodila,",
- "agentDetail.configure.prompt.tip": "Določite, kako naj ta agent razume vhodne podatke, kliče orodja in ustvarja izhode.",
+ "agentDetail.configure.prompt.tip": "Določite vlogo agenta in opišite njegovo tipično opravilo. Uporabite / za izrecno sklicevanje na veščine, datoteke, orodja in pridobivanje znanja.",
"agentDetail.configure.publishBar.draft": "Osnutek",
"agentDetail.configure.publishBar.publishUpdate": "Objavi posodobitev",
"agentDetail.configure.publishBar.published": "Objavljeno",
@@ -147,6 +164,14 @@
"agentDetail.configure.publishImpact.title": "{{action}} v {{name}}",
"agentDetail.configure.publishImpact.workflowCount_one": "{{count}} potek dela",
"agentDetail.configure.publishImpact.workflowCount_other": "{{count}} potekov dela",
+ "agentDetail.configure.rightPanel.build": "Izdelaj",
+ "agentDetail.configure.rightPanel.buildTipBody": "Build nastavi agenta prek klepeta. Opišite, kaj želite, in izpolnil bo nastavitev na levi.",
+ "agentDetail.configure.rightPanel.buildTipTitle": "Zgradite agenta prek klepeta",
+ "agentDetail.configure.rightPanel.learnMore": "Več o tem",
+ "agentDetail.configure.rightPanel.modeLabel": "Način konfiguracije agenta",
+ "agentDetail.configure.rightPanel.preview": "Predogled",
+ "agentDetail.configure.rightPanel.previewTipBody": "Preview zažene dokončanega agenta tako, kot ga bodo videli uporabniki, z jasnimi odgovori in funkcijami klepeta.",
+ "agentDetail.configure.rightPanel.previewTipTitle": "Predogled agenta",
"agentDetail.configure.skills.add": "Dodaj veščino",
"agentDetail.configure.skills.detail.contentRegion": "Vsebina podrobnosti veščine",
"agentDetail.configure.skills.detail.fileCount": "{{count}} DATOTEK",
@@ -156,7 +181,9 @@
"agentDetail.configure.skills.itemType": "Veščina",
"agentDetail.configure.skills.label": "Veščine",
"agentDetail.configure.skills.remove": "Odstrani {{name}}",
- "agentDetail.configure.skills.tip": "Veščine, ki jih ta agent lahko uporablja pri izvajanju opravil.",
+ "agentDetail.configure.skills.richTip": "Opremite agenta z modularnimi zmožnostmi. Glejte <docLink>dokumentacijo</docLink>. V pozivu jih izrecno navedite z /.",
+ "agentDetail.configure.skills.tip": "Opremite agenta z modularnimi zmožnostmi. Glejte dokumentacijo. V pozivu jih izrecno navedite z /.",
+ "agentDetail.configure.skills.toggle": "Preklopi veščine",
"agentDetail.configure.skills.upload.action": "Naloži",
"agentDetail.configure.skills.upload.browse": "prebrskaj",
"agentDetail.configure.skills.upload.description": "Naložite paket .zip ali .skill za tega agenta.",
@@ -166,6 +193,7 @@
"agentDetail.configure.skills.upload.invalidFile": "Naložite datoteko .zip ali .skill.",
"agentDetail.configure.skills.upload.success": "Veščina naložena.",
"agentDetail.configure.skills.upload.title": "Naloži veščino",
+ "agentDetail.configure.title": "Konfiguriraj",
"agentDetail.configure.tools.add": "Dodaj orodje",
"agentDetail.configure.tools.addMenu.cliTool.badge": "Za razvijalce",
"agentDetail.configure.tools.addMenu.cliTool.description": "Namestite program ukazne vrstice, ki ga agent zaganja v svojem sandboxu. Potrebuje namestitev in običajno tudi API Key.",
@@ -179,7 +207,7 @@
"agentDetail.configure.tools.cliDialog.env.optional": "(neobvezno)",
"agentDetail.configure.tools.cliDialog.installCommand.description": "V sandboxu · zažene se enkrat ob prvi uporabi",
"agentDetail.configure.tools.cliDialog.installCommand.label": "Namestitveni ukaz",
- "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "Sem prilepite namestitveni ukaz, npr. npm install -g @lark/cli · brew install jq",
+ "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "Sem prilepite namestitveni ukaz, npr. npx -y @playwright/mcp@latest · uv tool install httpie",
"agentDetail.configure.tools.cliDialog.installCommand.required": "Namestitveni ukaz je obvezen.",
"agentDetail.configure.tools.cliDialog.learnMore": "Več o orodju CLI",
"agentDetail.configure.tools.cliDialog.name.label": "Ime orodja CLI",
@@ -196,13 +224,19 @@
"agentDetail.configure.tools.moreActions": "Več dejanj za {{name}}",
"agentDetail.configure.tools.removeAction": "Odstrani {{name}}",
"agentDetail.configure.tools.removeProvider": "Odstrani vsa orodja",
- "agentDetail.configure.tools.tip": "Orodja, ki jih ta agent lahko kliče pri izvajanju opravil.",
+ "agentDetail.configure.tools.richTip": "Opremite agenta z vtičniki Dify. Glejte <pluginDocLink>dokumentacijo</pluginDocLink>. V pozivu jih izrecno navedite z /.\nLahko pa agentu prek klepeta Build vedno naročite, naj namesti in overi druga orodja (npr. MCPs in orodja CLI). Orodja, konfigurirana prek klepetov Build, se tukaj NE bodo prikazala, vendar bodo agentu še naprej na voljo. Glejte <buildDocLink>dokumentacijo</buildDocLink>.",
+ "agentDetail.configure.tools.tip": "Opremite agenta z vtičniki Dify. Glejte dokumentacijo. V pozivu jih izrecno navedite z /. Lahko pa agentu prek klepeta Build vedno naročite, naj namesti in overi druga orodja (npr. MCPs in orodja CLI). Orodja, konfigurirana prek klepetov Build, se tukaj NE bodo prikazala, vendar bodo agentu še naprej na voljo. Glejte dokumentacijo.",
+ "agentDetail.configure.tools.toggle": "Preklopi orodja",
"agentDetail.configure.tools.toolTabs.all": "Vse",
"agentDetail.configure.tools.toolTabs.cli": "CLI",
"agentDetail.configure.tools.toolTabs.custom": "Po meri",
"agentDetail.configure.tools.toolTabs.mcp": "MCP",
"agentDetail.configure.tools.toolTabs.plugins": "Integracije",
"agentDetail.configure.tools.toolTabs.workflow": "Potek dela",
+ "agentDetail.configure.workingDirectory.description": "Datoteke, ki jih agent bere in zapisuje med izvajanjem. Vse, kar ustvari, na primer qna_report.pdf, se prikaže tukaj.",
+ "agentDetail.configure.workingDirectory.open": "Odpri delovni imenik",
+ "agentDetail.configure.workingDirectory.title": "Delovni imenik",
+ "agentDetail.configure.workingDirectory.treeLabel": "Datoteke delovnega imenika",
"agentDetail.documentTitle": "Agent",
"agentDetail.logs.description": "Polni dnevniki beležijo stanje izvajanja aplikacije, vključno z uporabniškimi vnosi, odgovori agenta, načrtovanjem in uporabo orodij.",
"agentDetail.logs.empty": "Dnevnikov ni",
@@ -279,7 +313,7 @@
"agentDetail.navigationLabel": "Navigacija agenta",
"agentDetail.publish": "Objavi",
"agentDetail.sections.access": "Dostopna točka",
- "agentDetail.sections.configure": "Orkestracija",
+ "agentDetail.sections.configure": "Konfiguriraj",
"agentDetail.sections.logs": "Dnevniki",
"agentDetail.sections.monitoring": "Spremljanje",
"agentDetail.title": "Agent",
@@ -334,6 +368,11 @@
"roster.nodeSelector.startFromScratch": "Začni iz nič",
"roster.references.label": "Poteki dela, ki uporabljajo {{name}}",
"roster.references.trigger": "Poteki dela, ki uporabljajo {{name}}",
+ "roster.saveToRoster": "Save to Agent Console",
+ "roster.saveToRosterDialog.description": "Save this inline setup as a reusable roster agent.",
+ "roster.saveToRosterDialog.title": "Save to Agent Console",
+ "roster.saveToRosterForm.changeIcon": "Change roster agent icon",
+ "roster.saveToRosterSuccess": "Agent saved to roster.",
"roster.searchLabel": "Iskanje agentov",
"roster.searchPlaceholder": "Iskanje agentov po imenu…",
"roster.tabs.agent": "Agent",
diff --git a/web/i18n/sl-SI/common.json b/web/i18n/sl-SI/common.json
index 95290ceee8b..ab5c23a62e2 100644
--- a/web/i18n/sl-SI/common.json
+++ b/web/i18n/sl-SI/common.json
@@ -288,6 +288,7 @@
"menus.exploreMarketplace": "Raziščite Marketplace",
"menus.plugins": "Integracije",
"menus.roster": "Seznam agentov",
+ "menus.status": "beta",
"menus.tools": "Orodja",
"model.capabilities": "Multimodalne zmogljivosti",
"model.params.stop_sequencesPlaceholder": "Vnesite zaporedje in pritisnite Tab",
diff --git a/web/i18n/sl-SI/workflow.json b/web/i18n/sl-SI/workflow.json
index 27b73ada29b..824462716f5 100644
--- a/web/i18n/sl-SI/workflow.json
+++ b/web/i18n/sl-SI/workflow.json
@@ -464,7 +464,7 @@
"nodes.agent.task.label": "Opravilo agenta",
"nodes.agent.task.mention": "Omemba",
"nodes.agent.task.placeholder": "Opišite, kaj naj ta agent počne…",
- "nodes.agent.task.tooltip": "Določite navodila opravila, ki naj jih ta agent upošteva v tem poteku dela.",
+ "nodes.agent.task.tooltip": "Dodatni poziv, ki agentu pomaga obravnavati prav to vozlišče. Uporabite / za izrecno sklicevanje na spremenljivke.\nČe je pravilno konfiguriran, lahko agentu zaupate, da bo stvari ugotovil sam.",
"nodes.agent.toolNotAuthorizedTooltip": "{{tool}} Ni pooblaščen",
"nodes.agent.toolNotInstallTooltip": "{{tool}} ni nameščen",
"nodes.agent.toolbox": "delovna orodja",
diff --git a/web/i18n/th-TH/agent-v-2.json b/web/i18n/th-TH/agent-v-2.json
index d313b28cb2c..ae7ddf198c1 100644
--- a/web/i18n/th-TH/agent-v-2.json
+++ b/web/i18n/th-TH/agent-v-2.json
@@ -49,14 +49,27 @@
"agentDetail.configure.advancedSettings.envEditor.keyPlaceholder": "Key",
"agentDetail.configure.advancedSettings.envEditor.label": "Env Editor",
"agentDetail.configure.advancedSettings.envEditor.revealValue": "แสดงค่า {{key}}",
+ "agentDetail.configure.advancedSettings.envEditor.richTip": "เอเจนต์ของคุณทำงานในสภาพแวดล้อม Linux คุณสามารถตั้งค่าคอนฟิกหรือความลับไว้ล่วงหน้าได้โดยกำหนดตัวแปรสภาพแวดล้อมที่นี่\n\nหรือจะให้ตั้งค่าผ่านแชท Build ก็ได้ ดู<docLink>เอกสารประกอบ</docLink>",
"agentDetail.configure.advancedSettings.envEditor.scopeColumn": "Scope",
"agentDetail.configure.advancedSettings.envEditor.scopePlain": "Plain",
"agentDetail.configure.advancedSettings.envEditor.scopeSecret": "Secret",
"agentDetail.configure.advancedSettings.envEditor.scopeSelector": "เลือกขอบเขตตัวแปรสภาพแวดล้อม",
- "agentDetail.configure.advancedSettings.envEditor.tip": "ตัวแปรสภาพแวดล้อมที่ตัวแทนนี้สามารถใช้ได้ขณะรันไทม์",
+ "agentDetail.configure.advancedSettings.envEditor.tip": "เอเจนต์ของคุณทำงานในสภาพแวดล้อม Linux คุณสามารถตั้งค่าคอนฟิกหรือความลับไว้ล่วงหน้าได้โดยกำหนดตัวแปรสภาพแวดล้อมที่นี่ หรือจะให้ตั้งค่าผ่านแชท Build ก็ได้ ดูเอกสารประกอบ",
+ "agentDetail.configure.advancedSettings.envEditor.toggle": "สลับ Env Editor",
"agentDetail.configure.advancedSettings.envEditor.valueColumn": "Value",
"agentDetail.configure.advancedSettings.envEditor.valuePlaceholder": "Value",
"agentDetail.configure.advancedSettings.label": "การตั้งค่าขั้นสูง",
+ "agentDetail.configure.advancedSettings.toggle": "สลับการตั้งค่าขั้นสูง",
+ "agentDetail.configure.build.empty.description": "อธิบายสิ่งที่คุณต้องการ แล้วแบบฟอร์มด้านซ้ายจะถูกกรอกไปพร้อมกับการสนทนา",
+ "agentDetail.configure.build.empty.title": "สร้างเอเจนต์ของคุณด้วยการแชท",
+ "agentDetail.configure.build.inputPlaceholder": "อธิบายว่าเอเจนต์ของคุณควรทำอะไร",
+ "agentDetail.configure.build.startBuild": "เริ่มสร้าง",
+ "agentDetail.configure.buildDraft.changes": "{{count}} รายการเปลี่ยนแปลงที่ต้องใช้",
+ "agentDetail.configure.buildDraft.discard": "ทิ้ง",
+ "agentDetail.configure.buildDraft.modeBadge": "โหมด Build",
+ "agentDetail.configure.buildDraft.modeDescription": "คุณอยู่ในโหมด Build ปรับแต่งการตั้งค่านี้ผ่านแชททางขวา แล้วกดนำไปใช้",
+ "agentDetail.configure.buildDraft.noChanges": "ไม่มีการเปลี่ยนแปลงที่ต้องใช้",
+ "agentDetail.configure.buildDraft.title": "ฉบับร่าง Build",
"agentDetail.configure.chatFeatures.description": "กำหนดประสบการณ์การแชทของผู้ใช้ปลายทางบน Web app และหน้าจอแชท",
"agentDetail.configure.chatFeatures.title": "ฟีเจอร์แชท",
"agentDetail.configure.files.add": "เพิ่มไฟล์",
@@ -67,7 +80,8 @@
"agentDetail.configure.files.preview.failed": "โหลดตัวอย่างไม่สำเร็จ",
"agentDetail.configure.files.preview.unsupported": "ไฟล์นี้ไม่รองรับการแสดงตัวอย่าง",
"agentDetail.configure.files.remove": "ลบ {{name}}",
- "agentDetail.configure.files.tip": "ไฟล์ที่ตัวแทนนี้สามารถใช้ได้ขณะจัดการงาน",
+ "agentDetail.configure.files.tip": "มอบตัวอย่าง แนวทาง หรือข้อมูลที่ยาวเกินกว่าจะใส่ในพรอมป์ให้ตัวแทนของคุณ อ้างอิงอย่างชัดเจนด้วย / ในพรอมป์",
+ "agentDetail.configure.files.toggle": "สลับไฟล์",
"agentDetail.configure.files.treeLabel": "ไฟล์ตัวแทน",
"agentDetail.configure.files.upload.action": "อัปโหลด",
"agentDetail.configure.files.upload.browse": "เรียกดู",
@@ -113,8 +127,11 @@
"agentDetail.configure.orchestrate": "การจัดการ",
"agentDetail.configure.preview.chatFeatures": "ฟีเจอร์แชท",
"agentDetail.configure.preview.empty.defaultAgentName": "ตัวแทน",
- "agentDetail.configure.preview.empty.description": "ส่งข้อความเพื่อทดสอบฉบับร่างปัจจุบัน",
+ "agentDetail.configure.preview.empty.description": "เรียกใช้เอเจนต์เป็นแชทที่เสร็จสมบูรณ์ เหมือนที่ผู้ใช้จะได้รับหลังเผยแพร่",
"agentDetail.configure.preview.empty.noInstructionsDescription": "ยังไม่มีคำสั่ง ดังนั้นการตอบกลับจะมาจากโมเดลพื้นฐาน",
+ "agentDetail.configure.preview.empty.title": "แสดงตัวอย่าง {{name}}",
+ "agentDetail.configure.preview.endUserAuth": "การยืนยันตัวตนของผู้ใช้ปลายทาง",
+ "agentDetail.configure.preview.inputPlaceholder": "ส่งข้อความถึง {{name}}",
"agentDetail.configure.preview.restart": "เริ่มการแสดงตัวอย่างใหม่",
"agentDetail.configure.preview.title": "แสดงตัวอย่าง",
"agentDetail.configure.prompt.copied": "คัดลอกพรอมต์แล้ว",
@@ -128,7 +145,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "เขียนคำสั่งที่นี่,",
- "agentDetail.configure.prompt.tip": "กำหนดวิธีที่ตัวแทนนี้ตีความอินพุต เรียกใช้เครื่องมือ และสร้างเอาต์พุต",
+ "agentDetail.configure.prompt.tip": "กำหนดบทบาทของตัวแทนและอธิบายงานทั่วไป ใช้ / เพื่ออ้างอิง Skills, Files, Tools และ Knowledge Retrievals อย่างชัดเจน",
"agentDetail.configure.publishBar.draft": "ฉบับร่าง",
"agentDetail.configure.publishBar.publishUpdate": "เผยแพร่อัปเดต",
"agentDetail.configure.publishBar.published": "เผยแพร่แล้ว",
@@ -147,6 +164,14 @@
"agentDetail.configure.publishImpact.title": "{{action}}ไปยัง {{name}}",
"agentDetail.configure.publishImpact.workflowCount_one": "เวิร์กโฟลว์ {{count}} รายการ",
"agentDetail.configure.publishImpact.workflowCount_other": "เวิร์กโฟลว์ {{count}} รายการ",
+ "agentDetail.configure.rightPanel.build": "สร้าง",
+ "agentDetail.configure.rightPanel.buildTipBody": "Build ตั้งค่าเอเจนต์ผ่านการแชท อธิบายสิ่งที่คุณต้องการ แล้วระบบจะเติมการตั้งค่าทางซ้ายให้",
+ "agentDetail.configure.rightPanel.buildTipTitle": "สร้างเอเจนต์ผ่านแชท",
+ "agentDetail.configure.rightPanel.learnMore": "เรียนรู้เพิ่มเติม",
+ "agentDetail.configure.rightPanel.modeLabel": "โหมดการกำหนดค่าเอเจนต์",
+ "agentDetail.configure.rightPanel.preview": "แสดงตัวอย่าง",
+ "agentDetail.configure.rightPanel.previewTipBody": "Preview เรียกใช้เอเจนต์ที่เสร็จแล้วในแบบที่ผู้ใช้จะเห็น พร้อมคำตอบที่ชัดเจนและฟีเจอร์แชท",
+ "agentDetail.configure.rightPanel.previewTipTitle": "ดูตัวอย่างเอเจนต์",
"agentDetail.configure.skills.add": "เพิ่มทักษะ",
"agentDetail.configure.skills.detail.contentRegion": "เนื้อหารายละเอียดทักษะ",
"agentDetail.configure.skills.detail.fileCount": "{{count}} ไฟล์",
@@ -156,7 +181,9 @@
"agentDetail.configure.skills.itemType": "ทักษะ",
"agentDetail.configure.skills.label": "ทักษะ",
"agentDetail.configure.skills.remove": "ลบ {{name}}",
- "agentDetail.configure.skills.tip": "ทักษะที่ตัวแทนนี้สามารถใช้ได้ขณะจัดการงาน",
+ "agentDetail.configure.skills.richTip": "เพิ่มความสามารถแบบโมดูลาร์ให้ตัวแทนของคุณ ดู<docLink>เอกสาร</docLink> อ้างอิงอย่างชัดเจนด้วย / ในพรอมป์",
+ "agentDetail.configure.skills.tip": "เพิ่มความสามารถแบบโมดูลาร์ให้ตัวแทนของคุณ ดูเอกสาร อ้างอิงอย่างชัดเจนด้วย / ในพรอมป์",
+ "agentDetail.configure.skills.toggle": "สลับทักษะ",
"agentDetail.configure.skills.upload.action": "อัปโหลด",
"agentDetail.configure.skills.upload.browse": "เรียกดู",
"agentDetail.configure.skills.upload.description": "อัปโหลดแพ็กเกจ .zip หรือ .skill สำหรับตัวแทนนี้",
@@ -166,6 +193,7 @@
"agentDetail.configure.skills.upload.invalidFile": "อัปโหลดไฟล์ .zip หรือ .skill",
"agentDetail.configure.skills.upload.success": "อัปโหลดทักษะแล้ว",
"agentDetail.configure.skills.upload.title": "อัปโหลดทักษะ",
+ "agentDetail.configure.title": "กำหนดค่า",
"agentDetail.configure.tools.add": "เพิ่มเครื่องมือ",
"agentDetail.configure.tools.addMenu.cliTool.badge": "สำหรับนักพัฒนา",
"agentDetail.configure.tools.addMenu.cliTool.description": "ติดตั้งโปรแกรมคำสั่งบรรทัดที่ตัวแทนรันในแซนด์บ็อกซ์ ต้องติดตั้งและมักต้องการ API Key",
@@ -179,7 +207,7 @@
"agentDetail.configure.tools.cliDialog.env.optional": "(ตัวเลือก)",
"agentDetail.configure.tools.cliDialog.installCommand.description": "รันในแซนด์บ็อกซ์ · รันหนึ่งครั้งเมื่อเรียกใช้ครั้งแรก",
"agentDetail.configure.tools.cliDialog.installCommand.label": "คำสั่งติดตั้ง",
- "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "วางคำสั่งติดตั้งของคุณที่นี่ เช่น npm install -g @lark/cli · brew install jq",
+ "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "วางคำสั่งติดตั้งของคุณที่นี่ เช่น npx -y @playwright/mcp@latest · uv tool install httpie",
"agentDetail.configure.tools.cliDialog.installCommand.required": "ต้องระบุคำสั่งติดตั้ง",
"agentDetail.configure.tools.cliDialog.learnMore": "เรียนรู้เพิ่มเติมเกี่ยวกับเครื่องมือ CLI",
"agentDetail.configure.tools.cliDialog.name.label": "ชื่อเครื่องมือ CLI",
@@ -196,13 +224,19 @@
"agentDetail.configure.tools.moreActions": "การกระทำเพิ่มเติมสำหรับ {{name}}",
"agentDetail.configure.tools.removeAction": "ลบ {{name}}",
"agentDetail.configure.tools.removeProvider": "ลบเครื่องมือทั้งหมด",
- "agentDetail.configure.tools.tip": "เครื่องมือที่ตัวแทนนี้สามารถเรียกใช้ได้ขณะจัดการงาน",
+ "agentDetail.configure.tools.richTip": "เพิ่มปลั๊กอินของ Dify ให้ตัวแทนของคุณ ดู<pluginDocLink>เอกสาร</pluginDocLink> อ้างอิงอย่างชัดเจนด้วย / ในพรอมป์\nอีกทางหนึ่ง คุณสามารถบอกให้ตัวแทนติดตั้งและยืนยันตัวตนเครื่องมืออื่น ๆ (เช่น MCPs และเครื่องมือ CLI) ผ่านแชต Build ได้เสมอ โปรดทราบว่าเครื่องมือที่กำหนดค่าผ่านแชต Build จะไม่แสดงที่นี่ แม้ว่าจะยังพร้อมใช้งานสำหรับตัวแทนของคุณต่อไป ดู<buildDocLink>เอกสาร</buildDocLink>",
+ "agentDetail.configure.tools.tip": "เพิ่มปลั๊กอินของ Dify ให้ตัวแทนของคุณ ดูเอกสาร อ้างอิงอย่างชัดเจนด้วย / ในพรอมป์ อีกทางหนึ่ง คุณสามารถบอกให้ตัวแทนติดตั้งและยืนยันตัวตนเครื่องมืออื่น ๆ (เช่น MCPs และเครื่องมือ CLI) ผ่านแชต Build ได้เสมอ โปรดทราบว่าเครื่องมือที่กำหนดค่าผ่านแชต Build จะไม่แสดงที่นี่ แม้ว่าจะยังพร้อมใช้งานสำหรับตัวแทนของคุณต่อไป ดูเอกสาร",
+ "agentDetail.configure.tools.toggle": "สลับเครื่องมือ",
"agentDetail.configure.tools.toolTabs.all": "ทั้งหมด",
"agentDetail.configure.tools.toolTabs.cli": "CLI",
"agentDetail.configure.tools.toolTabs.custom": "กำหนดเอง",
"agentDetail.configure.tools.toolTabs.mcp": "MCP",
"agentDetail.configure.tools.toolTabs.plugins": "ปลั๊กอิน",
"agentDetail.configure.tools.toolTabs.workflow": "Workflow",
+ "agentDetail.configure.workingDirectory.description": "ไฟล์ที่ Agent อ่านและเขียนระหว่างทำงาน สิ่งที่สร้างขึ้น เช่น qna_report.pdf จะแสดงที่นี่",
+ "agentDetail.configure.workingDirectory.open": "เปิดไดเรกทอรีทำงาน",
+ "agentDetail.configure.workingDirectory.title": "ไดเรกทอรีทำงาน",
+ "agentDetail.configure.workingDirectory.treeLabel": "ไฟล์ในไดเรกทอรีทำงาน",
"agentDetail.documentTitle": "ตัวแทน",
"agentDetail.logs.description": "บันทึกแบบเต็มจะบันทึกสถานะการทำงานของแอปพลิเคชัน รวมถึงอินพุตของผู้ใช้ การตอบกลับของตัวแทน การวางแผน และการใช้เครื่องมือ",
"agentDetail.logs.empty": "ไม่พบบันทึก",
@@ -279,7 +313,7 @@
"agentDetail.navigationLabel": "การนำทางตัวแทน",
"agentDetail.publish": "เผยแพร่",
"agentDetail.sections.access": "จุดเข้าถึง",
- "agentDetail.sections.configure": "การจัดการ",
+ "agentDetail.sections.configure": "กําหนดค่า",
"agentDetail.sections.logs": "บันทึก",
"agentDetail.sections.monitoring": "การมอนิเตอร์",
"agentDetail.title": "ตัวแทน",
@@ -334,6 +368,11 @@
"roster.nodeSelector.startFromScratch": "เริ่มต้นจากศูนย์",
"roster.references.label": "เวิร์กโฟลว์ที่ใช้ {{name}}",
"roster.references.trigger": "เวิร์กโฟลว์ที่ใช้ {{name}}",
+ "roster.saveToRoster": "Save to Agent Console",
+ "roster.saveToRosterDialog.description": "Save this inline setup as a reusable roster agent.",
+ "roster.saveToRosterDialog.title": "Save to Agent Console",
+ "roster.saveToRosterForm.changeIcon": "Change roster agent icon",
+ "roster.saveToRosterSuccess": "Agent saved to roster.",
"roster.searchLabel": "ค้นหาตัวแทน",
"roster.searchPlaceholder": "ค้นหาตัวแทนตามชื่อ…",
"roster.tabs.agent": "ตัวแทน",
diff --git a/web/i18n/th-TH/common.json b/web/i18n/th-TH/common.json
index 55586e5dd4f..74c67abb94f 100644
--- a/web/i18n/th-TH/common.json
+++ b/web/i18n/th-TH/common.json
@@ -288,6 +288,7 @@
"menus.exploreMarketplace": "สํารวจ Marketplace",
"menus.plugins": "การผสานรวม",
"menus.roster": "รายชื่อตัวแทน",
+ "menus.status": "Beta",
"menus.tools": "เครื่อง มือ",
"model.capabilities": "ความสามารถหลายรูปแบบ",
"model.params.stop_sequencesPlaceholder": "ป้อนลําดับแล้วกด Tab",
diff --git a/web/i18n/th-TH/workflow.json b/web/i18n/th-TH/workflow.json
index 5fc865471dc..52359f3d004 100644
--- a/web/i18n/th-TH/workflow.json
+++ b/web/i18n/th-TH/workflow.json
@@ -464,7 +464,7 @@
"nodes.agent.task.label": "งาน Agent",
"nodes.agent.task.mention": "กล่าวถึง",
"nodes.agent.task.placeholder": "อธิบายสิ่งที่ Agent นี้ควรทำ...",
- "nodes.agent.task.tooltip": "กำหนดคำสั่งงานที่ Agent นี้ควรปฏิบัติตามในเวิร์กโฟลว์นี้",
+ "nodes.agent.task.tooltip": "พรอมป์เพิ่มเติมเพื่อช่วยให้เอเจนต์จัดการโหนดนี้โดยเฉพาะ ใช้ / เพื่ออ้างอิงตัวแปรอย่างชัดเจน\nหากตั้งค่าอย่างเหมาะสม คุณอาจไว้วางใจให้เอเจนต์หาทางจัดการสิ่งต่าง ๆ ได้เอง",
"nodes.agent.toolNotAuthorizedTooltip": "{{tool}} ไม่ได้รับอนุญาต",
"nodes.agent.toolNotInstallTooltip": "{{tool}} ไม่ได้ติดตั้ง",
"nodes.agent.toolbox": "เครื่อง มือ",
diff --git a/web/i18n/tr-TR/agent-v-2.json b/web/i18n/tr-TR/agent-v-2.json
index 672d70d5597..9200789bd95 100644
--- a/web/i18n/tr-TR/agent-v-2.json
+++ b/web/i18n/tr-TR/agent-v-2.json
@@ -49,14 +49,27 @@
"agentDetail.configure.advancedSettings.envEditor.keyPlaceholder": "Key",
"agentDetail.configure.advancedSettings.envEditor.label": "Env Editor",
"agentDetail.configure.advancedSettings.envEditor.revealValue": "{{key}} değerini göster",
+ "agentDetail.configure.advancedSettings.envEditor.richTip": "Ajanınız bir Linux ortamında çalışır. Burada ortam değişkenleri tanımlayarak yapılandırmaları veya gizli değerleri önceden ayarlayabilirsiniz.\n\nAlternatif olarak, kurulumları her zaman bir Build sohbeti üzerinden yaptırabilirsiniz. <docLink>Dokümanlara</docLink> bakın.",
"agentDetail.configure.advancedSettings.envEditor.scopeColumn": "Scope",
"agentDetail.configure.advancedSettings.envEditor.scopePlain": "Plain",
"agentDetail.configure.advancedSettings.envEditor.scopeSecret": "Secret",
"agentDetail.configure.advancedSettings.envEditor.scopeSelector": "Çevre değişkeni kapsamını seç",
- "agentDetail.configure.advancedSettings.envEditor.tip": "Bu ajan için çalışma zamanında kullanılabilen çevre değişkenleri.",
+ "agentDetail.configure.advancedSettings.envEditor.tip": "Ajanınız bir Linux ortamında çalışır. Burada ortam değişkenleri tanımlayarak yapılandırmaları veya gizli değerleri önceden ayarlayabilirsiniz. Alternatif olarak, kurulumları her zaman bir Build sohbeti üzerinden yaptırabilirsiniz. Dokümanlara bakın.",
+ "agentDetail.configure.advancedSettings.envEditor.toggle": "Env Editor'ü değiştir",
"agentDetail.configure.advancedSettings.envEditor.valueColumn": "Value",
"agentDetail.configure.advancedSettings.envEditor.valuePlaceholder": "Value",
"agentDetail.configure.advancedSettings.label": "Gelişmiş Ayarlar",
+ "agentDetail.configure.advancedSettings.toggle": "Gelişmiş ayarları değiştir",
+ "agentDetail.configure.build.empty.description": "Ne istediğinizi açıklayın; soldaki form ilerledikçe doldurulur.",
+ "agentDetail.configure.build.empty.title": "Aracınızı sohbet ederek oluşturun",
+ "agentDetail.configure.build.inputPlaceholder": "Aracınızın ne yapması gerektiğini açıklayın",
+ "agentDetail.configure.build.startBuild": "Build’i başlat",
+ "agentDetail.configure.buildDraft.changes": "Uygulanacak {{count}} değişiklik",
+ "agentDetail.configure.buildDraft.discard": "Vazgeç",
+ "agentDetail.configure.buildDraft.modeBadge": "Build modu",
+ "agentDetail.configure.buildDraft.modeDescription": "Build modundasınız. Bu kurulumu sağdaki sohbetle şekillendirin, ardından uygulayın.",
+ "agentDetail.configure.buildDraft.noChanges": "Uygulanacak değişiklik yok",
+ "agentDetail.configure.buildDraft.title": "Build taslağı",
"agentDetail.configure.chatFeatures.description": "Web app ve sohbet yüzeylerinizde son kullanıcı sohbet deneyimini şekillendirin.",
"agentDetail.configure.chatFeatures.title": "Sohbet Özellikleri",
"agentDetail.configure.files.add": "Dosya ekle",
@@ -67,7 +80,8 @@
"agentDetail.configure.files.preview.failed": "Önizleme yüklenemedi.",
"agentDetail.configure.files.preview.unsupported": "Bu dosya önizlemeyi desteklemiyor.",
"agentDetail.configure.files.remove": "{{name}} kaldır",
- "agentDetail.configure.files.tip": "Bu ajanın görevleri koordine ederken kullanabileceği dosyalar.",
+ "agentDetail.configure.files.tip": "Aracıya, istem için çok uzun olan herhangi bir örnek, yönerge veya bilgi taşıyıcısı sağlayın. İstemde / ile açıkça referans verin.",
+ "agentDetail.configure.files.toggle": "Dosyaları değiştir",
"agentDetail.configure.files.treeLabel": "Ajan dosyaları",
"agentDetail.configure.files.upload.action": "Yükle",
"agentDetail.configure.files.upload.browse": "göz at",
@@ -113,8 +127,11 @@
"agentDetail.configure.orchestrate": "Koordine Et",
"agentDetail.configure.preview.chatFeatures": "Sohbet Özellikleri",
"agentDetail.configure.preview.empty.defaultAgentName": "Ajan",
- "agentDetail.configure.preview.empty.description": "Mevcut taslağı test etmek için bir mesaj gönderin.",
+ "agentDetail.configure.preview.empty.description": "Aracıyı yayınlandıktan sonra kullanıcıların deneyimleyeceği tamamlanmış sohbet olarak çalıştırın.",
"agentDetail.configure.preview.empty.noInstructionsDescription": "Henüz talimat yok, bu yüzden yanıtlar düz modelden geliyor.",
+ "agentDetail.configure.preview.empty.title": "{{name}} önizlemesi",
+ "agentDetail.configure.preview.endUserAuth": "Son kullanıcı kimlik doğrulaması",
+ "agentDetail.configure.preview.inputPlaceholder": "{{name}} ile mesajlaş",
"agentDetail.configure.preview.restart": "Önizlemeyi yeniden başlat",
"agentDetail.configure.preview.title": "Önizleme",
"agentDetail.configure.prompt.copied": "İstem kopyalandı",
@@ -128,7 +145,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "Talimatları buraya yazın,",
- "agentDetail.configure.prompt.tip": "Bu ajanın girdileri nasıl yorumlayacağını, araçları nasıl çağıracağını ve çıktıları nasıl üreteceğini tanımlayın.",
+ "agentDetail.configure.prompt.tip": "Aracının rolünü tanımlayın ve tipik görevini açıklayın. Skills, Files, Tools ve Knowledge Retrievals için açık referans vermek üzere / kullanın.",
"agentDetail.configure.publishBar.draft": "Taslak",
"agentDetail.configure.publishBar.publishUpdate": "Güncellemeyi yayınla",
"agentDetail.configure.publishBar.published": "Yayınlandı",
@@ -147,6 +164,14 @@
"agentDetail.configure.publishImpact.title": "{{name}} için {{action}}",
"agentDetail.configure.publishImpact.workflowCount_one": "{{count}} iş akışı",
"agentDetail.configure.publishImpact.workflowCount_other": "{{count}} iş akışı",
+ "agentDetail.configure.rightPanel.build": "Oluştur",
+ "agentDetail.configure.rightPanel.buildTipBody": "Build, ajanı sohbet yoluyla ayarlar. Ne istediğinizi açıklayın; soldaki kurulum alanlarını doldurur.",
+ "agentDetail.configure.rightPanel.buildTipTitle": "Ajanınızı sohbetle oluşturun",
+ "agentDetail.configure.rightPanel.learnMore": "Daha fazla bilgi",
+ "agentDetail.configure.rightPanel.modeLabel": "Aracı yapılandırma modu",
+ "agentDetail.configure.rightPanel.preview": "Önizleme",
+ "agentDetail.configure.rightPanel.previewTipBody": "Preview, tamamlanan ajanı kullanıcılarınızın göreceği şekilde, temiz yanıtlar ve sohbet özellikleriyle çalıştırır.",
+ "agentDetail.configure.rightPanel.previewTipTitle": "Ajanınızı önizleyin",
"agentDetail.configure.skills.add": "Beceri ekle",
"agentDetail.configure.skills.detail.contentRegion": "Beceri detay içeriği",
"agentDetail.configure.skills.detail.fileCount": "{{count}} DOSYA",
@@ -156,7 +181,9 @@
"agentDetail.configure.skills.itemType": "Beceri",
"agentDetail.configure.skills.label": "Beceriler",
"agentDetail.configure.skills.remove": "{{name}} kaldır",
- "agentDetail.configure.skills.tip": "Bu ajanın görevleri koordine ederken kullanabileceği beceriler.",
+ "agentDetail.configure.skills.richTip": "Aracınızı modüler yeteneklerle donatın. <docLink>Belgelere</docLink> bakın. İstemde / ile açıkça referans verin.",
+ "agentDetail.configure.skills.tip": "Aracınızı modüler yeteneklerle donatın. Belgelere bakın. İstemde / ile açıkça referans verin.",
+ "agentDetail.configure.skills.toggle": "Becerileri değiştir",
"agentDetail.configure.skills.upload.action": "Yükle",
"agentDetail.configure.skills.upload.browse": "göz at",
"agentDetail.configure.skills.upload.description": "Bu ajan için bir .zip veya .skill paketi yükleyin.",
@@ -166,6 +193,7 @@
"agentDetail.configure.skills.upload.invalidFile": "Bir .zip veya .skill dosyası yükleyin.",
"agentDetail.configure.skills.upload.success": "Beceri yüklendi.",
"agentDetail.configure.skills.upload.title": "Beceri yükle",
+ "agentDetail.configure.title": "Yapılandır",
"agentDetail.configure.tools.add": "Araç ekle",
"agentDetail.configure.tools.addMenu.cliTool.badge": "Geliştiriciler için",
"agentDetail.configure.tools.addMenu.cliTool.description": "Ajanın sandbox'ında çalıştırdığı bir komut satırı programı yükleyin. Kurulum ve genellikle API Key gerektirir.",
@@ -179,7 +207,7 @@
"agentDetail.configure.tools.cliDialog.env.optional": "(isteğe bağlı)",
"agentDetail.configure.tools.cliDialog.installCommand.description": "Sandbox · ilk çağrıda bir kez çalışır",
"agentDetail.configure.tools.cliDialog.installCommand.label": "Kurulum Komutu",
- "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "Kurulum komutunuzu buraya yapıştırın, örneğin npm install -g @lark/cli · brew install jq",
+ "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "Kurulum komutunuzu buraya yapıştırın, örneğin npx -y @playwright/mcp@latest · uv tool install httpie",
"agentDetail.configure.tools.cliDialog.installCommand.required": "Kurulum komutu gerekli.",
"agentDetail.configure.tools.cliDialog.learnMore": "CLI Aracı hakkında daha fazla bilgi",
"agentDetail.configure.tools.cliDialog.name.label": "CLI Aracı Adı",
@@ -196,13 +224,19 @@
"agentDetail.configure.tools.moreActions": "{{name}} için daha fazla eylem",
"agentDetail.configure.tools.removeAction": "{{name}} kaldır",
"agentDetail.configure.tools.removeProvider": "Tüm araçları kaldır",
- "agentDetail.configure.tools.tip": "Bu ajanın görevleri koordine ederken çağırabileceği araçlar.",
+ "agentDetail.configure.tools.richTip": "Aracınızı Dify eklentileriyle donatın. <pluginDocLink>Belgelere</pluginDocLink> bakın. İstemde / ile açıkça referans verin.\nAlternatif olarak, aracınıza bir Build sohbeti üzerinden başka araçları (örn. MCPs ve CLI araçları) yüklemesini ve kimlik doğrulamasını yapmasını her zaman söyleyebilirsiniz. Build sohbetleriyle yapılandırılan araçların burada görünmeyeceğini, ancak ileride aracınız için kullanılabilir olmaya devam edeceğini unutmayın. <buildDocLink>Belgelere</buildDocLink> bakın.",
+ "agentDetail.configure.tools.tip": "Aracınızı Dify eklentileriyle donatın. Belgelere bakın. İstemde / ile açıkça referans verin. Alternatif olarak, aracınıza bir Build sohbeti üzerinden başka araçları (örn. MCPs ve CLI araçları) yüklemesini ve kimlik doğrulamasını yapmasını her zaman söyleyebilirsiniz. Build sohbetleriyle yapılandırılan araçların burada görünmeyeceğini, ancak ileride aracınız için kullanılabilir olmaya devam edeceğini unutmayın. Belgelere bakın.",
+ "agentDetail.configure.tools.toggle": "Araçları değiştir",
"agentDetail.configure.tools.toolTabs.all": "Tümü",
"agentDetail.configure.tools.toolTabs.cli": "CLI",
"agentDetail.configure.tools.toolTabs.custom": "Özel",
"agentDetail.configure.tools.toolTabs.mcp": "MCP",
"agentDetail.configure.tools.toolTabs.plugins": "Eklentiler",
"agentDetail.configure.tools.toolTabs.workflow": "Workflow",
+ "agentDetail.configure.workingDirectory.description": "Agent çalışırken okuduğu ve yazdığı dosyalar. qna_report.pdf gibi ürettiği her şey burada görünür.",
+ "agentDetail.configure.workingDirectory.open": "Çalışma dizinini aç",
+ "agentDetail.configure.workingDirectory.title": "Çalışma dizini",
+ "agentDetail.configure.workingDirectory.treeLabel": "Çalışma dizini dosyaları",
"agentDetail.documentTitle": "Ajan",
"agentDetail.logs.description": "Tam günlükler, kullanıcı girişleri, ajan yanıtları, planlama ve araç kullanımları dahil olmak üzere uygulamanın çalışma durumunu kaydeder.",
"agentDetail.logs.empty": "Günlük bulunamadı",
@@ -279,7 +313,7 @@
"agentDetail.navigationLabel": "Ajan gezinmesi",
"agentDetail.publish": "Yayınla",
"agentDetail.sections.access": "Erişim Noktası",
- "agentDetail.sections.configure": "Koordine Et",
+ "agentDetail.sections.configure": "Yapılandır",
"agentDetail.sections.logs": "Günlükler",
"agentDetail.sections.monitoring": "İzleme",
"agentDetail.title": "Ajan",
@@ -334,6 +368,11 @@
"roster.nodeSelector.startFromScratch": "Sıfırdan Başla",
"roster.references.label": "{{name}} kullanan iş akışları",
"roster.references.trigger": "{{name}} kullanan iş akışları",
+ "roster.saveToRoster": "Save to Agent Console",
+ "roster.saveToRosterDialog.description": "Save this inline setup as a reusable roster agent.",
+ "roster.saveToRosterDialog.title": "Save to Agent Console",
+ "roster.saveToRosterForm.changeIcon": "Change roster agent icon",
+ "roster.saveToRosterSuccess": "Agent saved to roster.",
"roster.searchLabel": "Ajanları ara",
"roster.searchPlaceholder": "Ajanları ada göre ara…",
"roster.tabs.agent": "Ajan",
diff --git a/web/i18n/tr-TR/common.json b/web/i18n/tr-TR/common.json
index 0d797a0c83d..32b6c8a1a2c 100644
--- a/web/i18n/tr-TR/common.json
+++ b/web/i18n/tr-TR/common.json
@@ -288,6 +288,7 @@
"menus.exploreMarketplace": "Pazar Yeri'ni Keşfedin",
"menus.plugins": "Entegrasyonlar",
"menus.roster": "Ajan listesi",
+ "menus.status": "beta",
"menus.tools": "Araçlar",
"model.capabilities": "MultiModal Yetenekler",
"model.params.stop_sequencesPlaceholder": "Sıra girin ve Tab tuşuna basın",
diff --git a/web/i18n/tr-TR/workflow.json b/web/i18n/tr-TR/workflow.json
index c1f21cb59bf..433d2a1a973 100644
--- a/web/i18n/tr-TR/workflow.json
+++ b/web/i18n/tr-TR/workflow.json
@@ -464,7 +464,7 @@
"nodes.agent.task.label": "Ajan görevi",
"nodes.agent.task.mention": "Bahset",
"nodes.agent.task.placeholder": "Bu ajanın ne yapması gerektiğini açıklayın...",
- "nodes.agent.task.tooltip": "Bu ajanın bu iş akışında izlemesi gereken görev talimatlarını tanımlayın.",
+ "nodes.agent.task.tooltip": "Ajanın tam olarak bu düğümü ele almasına yardımcı olacak ek prompt. Değişkenlere açıkça referans vermek için / kullanın.\nDoğru yapılandırılırsa, ajanın işleri kendi başına çözmesine güvenebilirsiniz.",
"nodes.agent.toolNotAuthorizedTooltip": "{{tool}} Yetkili Değil",
"nodes.agent.toolNotInstallTooltip": "{{tool}} yüklü değil",
"nodes.agent.toolbox": "Araç",
diff --git a/web/i18n/uk-UA/agent-v-2.json b/web/i18n/uk-UA/agent-v-2.json
index 7d5d63b62e4..a3709b67e30 100644
--- a/web/i18n/uk-UA/agent-v-2.json
+++ b/web/i18n/uk-UA/agent-v-2.json
@@ -49,14 +49,27 @@
"agentDetail.configure.advancedSettings.envEditor.keyPlaceholder": "Key",
"agentDetail.configure.advancedSettings.envEditor.label": "Env Editor",
"agentDetail.configure.advancedSettings.envEditor.revealValue": "Показати значення {{key}}",
+ "agentDetail.configure.advancedSettings.envEditor.richTip": "Ваш агент працює в середовищі Linux. Ви можете попередньо задати конфігурації або секрети, визначивши тут змінні середовища.\n\nТакож ви завжди можете налаштувати все через чат Build. Див. <docLink>документацію</docLink>.",
"agentDetail.configure.advancedSettings.envEditor.scopeColumn": "Scope",
"agentDetail.configure.advancedSettings.envEditor.scopePlain": "Plain",
"agentDetail.configure.advancedSettings.envEditor.scopeSecret": "Secret",
"agentDetail.configure.advancedSettings.envEditor.scopeSelector": "Виберіть область змінної середовища",
- "agentDetail.configure.advancedSettings.envEditor.tip": "Змінні середовища, доступні цьому агенту під час виконання.",
+ "agentDetail.configure.advancedSettings.envEditor.tip": "Ваш агент працює в середовищі Linux. Ви можете попередньо задати конфігурації або секрети, визначивши тут змінні середовища. Також ви завжди можете налаштувати все через чат Build. Див. документацію.",
+ "agentDetail.configure.advancedSettings.envEditor.toggle": "Перемкнути Env Editor",
"agentDetail.configure.advancedSettings.envEditor.valueColumn": "Value",
"agentDetail.configure.advancedSettings.envEditor.valuePlaceholder": "Value",
"agentDetail.configure.advancedSettings.label": "Розширені налаштування",
+ "agentDetail.configure.advancedSettings.toggle": "Перемкнути розширені налаштування",
+ "agentDetail.configure.build.empty.description": "Опишіть, що вам потрібно, і форма ліворуч заповнюватиметься під час розмови.",
+ "agentDetail.configure.build.empty.title": "Створіть агента через чат",
+ "agentDetail.configure.build.inputPlaceholder": "Опишіть, що має робити ваш агент",
+ "agentDetail.configure.build.startBuild": "Почати збірку",
+ "agentDetail.configure.buildDraft.changes": "{{count}} змін для застосування",
+ "agentDetail.configure.buildDraft.discard": "Відхилити",
+ "agentDetail.configure.buildDraft.modeBadge": "Режим збірки",
+ "agentDetail.configure.buildDraft.modeDescription": "Ви в режимі збірки. Налаштуйте цю конфігурацію через чат праворуч, а потім застосуйте.",
+ "agentDetail.configure.buildDraft.noChanges": "Немає змін для застосування",
+ "agentDetail.configure.buildDraft.title": "Чернетка збірки",
"agentDetail.configure.chatFeatures.description": "Налаштуйте чат-досвід кінцевого користувача у вашому веб-застосунку та чат-поверхнях.",
"agentDetail.configure.chatFeatures.title": "Функції чату",
"agentDetail.configure.files.add": "Додати файл",
@@ -67,7 +80,8 @@
"agentDetail.configure.files.preview.failed": "Не вдалося завантажити перегляд.",
"agentDetail.configure.files.preview.unsupported": "Попередній перегляд цього файлу не підтримується.",
"agentDetail.configure.files.remove": "Видалити {{name}}",
- "agentDetail.configure.files.tip": "Файли, які цей агент може використовувати під час оркестрації задач.",
+ "agentDetail.configure.files.tip": "Надайте агенту будь-який приклад, інструкцію або просто носій інформації, який занадто довгий для промпта. Явно посилайтеся на нього через / у промпті.",
+ "agentDetail.configure.files.toggle": "Перемкнути файли",
"agentDetail.configure.files.treeLabel": "Файли агента",
"agentDetail.configure.files.upload.action": "Завантажити",
"agentDetail.configure.files.upload.browse": "огляд",
@@ -113,8 +127,11 @@
"agentDetail.configure.orchestrate": "Оркестрація",
"agentDetail.configure.preview.chatFeatures": "Функції чату",
"agentDetail.configure.preview.empty.defaultAgentName": "Агент",
- "agentDetail.configure.preview.empty.description": "Надішліть повідомлення, щоб протестувати поточний чернетку.",
+ "agentDetail.configure.preview.empty.description": "Запустіть агента як готовий чат, саме так, як його побачать користувачі після публікації.",
"agentDetail.configure.preview.empty.noInstructionsDescription": "Інструкцій ще немає, тому відповіді надходять від базової моделі.",
+ "agentDetail.configure.preview.empty.title": "Перегляд {{name}}",
+ "agentDetail.configure.preview.endUserAuth": "Автентифікація кінцевого користувача",
+ "agentDetail.configure.preview.inputPlaceholder": "Надіслати повідомлення {{name}}",
"agentDetail.configure.preview.restart": "Перезапустити перегляд",
"agentDetail.configure.preview.title": "Перегляд",
"agentDetail.configure.prompt.copied": "Промпт скопійовано",
@@ -128,7 +145,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "Напишіть інструкції тут,",
- "agentDetail.configure.prompt.tip": "Визначте, як цей агент має інтерпретувати вхідні дані, викликати інструменти та формувати вихідні дані.",
+ "agentDetail.configure.prompt.tip": "Визначте роль агента й опишіть його типове завдання. Використовуйте /, щоб явно посилатися на навички, файли, інструменти та пошук знань.",
"agentDetail.configure.publishBar.draft": "Чернетка",
"agentDetail.configure.publishBar.publishUpdate": "Опублікувати оновлення",
"agentDetail.configure.publishBar.published": "Опубліковано",
@@ -147,6 +164,14 @@
"agentDetail.configure.publishImpact.title": "{{action}} до {{name}}",
"agentDetail.configure.publishImpact.workflowCount_one": "{{count}} робочий процес",
"agentDetail.configure.publishImpact.workflowCount_other": "{{count}} робочих процесів",
+ "agentDetail.configure.rightPanel.build": "Створення",
+ "agentDetail.configure.rightPanel.buildTipBody": "Build налаштовує агента через чат. Опишіть, що потрібно, і він заповнить налаштування ліворуч.",
+ "agentDetail.configure.rightPanel.buildTipTitle": "Створіть агента через чат",
+ "agentDetail.configure.rightPanel.learnMore": "Дізнатися більше",
+ "agentDetail.configure.rightPanel.modeLabel": "Режим налаштування агента",
+ "agentDetail.configure.rightPanel.preview": "Перегляд",
+ "agentDetail.configure.rightPanel.previewTipBody": "Preview запускає готового агента так, як його побачать користувачі, з чистими відповідями та функціями чату.",
+ "agentDetail.configure.rightPanel.previewTipTitle": "Попередній перегляд агента",
"agentDetail.configure.skills.add": "Додати навичку",
"agentDetail.configure.skills.detail.contentRegion": "Вміст деталей навички",
"agentDetail.configure.skills.detail.fileCount": "{{count}} ФАЙЛІВ",
@@ -156,7 +181,9 @@
"agentDetail.configure.skills.itemType": "Навичка",
"agentDetail.configure.skills.label": "Навички",
"agentDetail.configure.skills.remove": "Видалити {{name}}",
- "agentDetail.configure.skills.tip": "Навички, які цей агент може використовувати під час оркестрації задач.",
+ "agentDetail.configure.skills.richTip": "Оснастіть агента модульними можливостями. Див. <docLink>документацію</docLink>. Явно посилайтеся на них через / у промпті.",
+ "agentDetail.configure.skills.tip": "Оснастіть агента модульними можливостями. Див. документацію. Явно посилайтеся на них через / у промпті.",
+ "agentDetail.configure.skills.toggle": "Перемкнути навички",
"agentDetail.configure.skills.upload.action": "Завантажити",
"agentDetail.configure.skills.upload.browse": "огляд",
"agentDetail.configure.skills.upload.description": "Завантажте пакет .zip або .skill для цього агента.",
@@ -166,6 +193,7 @@
"agentDetail.configure.skills.upload.invalidFile": "Завантажте файл .zip або .skill.",
"agentDetail.configure.skills.upload.success": "Навичку завантажено.",
"agentDetail.configure.skills.upload.title": "Завантажити навичку",
+ "agentDetail.configure.title": "Налаштувати",
"agentDetail.configure.tools.add": "Додати інструмент",
"agentDetail.configure.tools.addMenu.cliTool.badge": "Для розробників",
"agentDetail.configure.tools.addMenu.cliTool.description": "Встановіть програму командного рядка, яку агент запускає в пісочниці. Потрібне встановлення, зазвичай також API Key.",
@@ -179,7 +207,7 @@
"agentDetail.configure.tools.cliDialog.env.optional": "(необов'язково)",
"agentDetail.configure.tools.cliDialog.installCommand.description": "У пісочниці · виконується один раз при першому виклику",
"agentDetail.configure.tools.cliDialog.installCommand.label": "Команда встановлення",
- "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "Вставте сюди команду встановлення, напр. npm install -g @lark/cli · brew install jq",
+ "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "Вставте сюди команду встановлення, напр. npx -y @playwright/mcp@latest · uv tool install httpie",
"agentDetail.configure.tools.cliDialog.installCommand.required": "Команда встановлення обов'язкова.",
"agentDetail.configure.tools.cliDialog.learnMore": "Докладніше про CLI-інструмент",
"agentDetail.configure.tools.cliDialog.name.label": "Назва CLI-інструмента",
@@ -196,13 +224,19 @@
"agentDetail.configure.tools.moreActions": "Більше дій для {{name}}",
"agentDetail.configure.tools.removeAction": "Видалити {{name}}",
"agentDetail.configure.tools.removeProvider": "Видалити всі інструменти",
- "agentDetail.configure.tools.tip": "Інструменти, які цей агент може викликати під час оркестрації задач.",
+ "agentDetail.configure.tools.richTip": "Оснастіть агента плагінами Dify. Див. <pluginDocLink>документацію</pluginDocLink>. Явно посилайтеся на них через / у промпті.\nКрім того, ви завжди можете сказати агенту встановити й автентифікувати інші інструменти (наприклад, MCPs та CLI-інструменти) через Build-чат. Зверніть увагу: інструменти, налаштовані через Build-чати, НЕ відображатимуться тут, хоча й надалі будуть доступні вашому агенту. Див. <buildDocLink>документацію</buildDocLink>.",
+ "agentDetail.configure.tools.tip": "Оснастіть агента плагінами Dify. Див. документацію. Явно посилайтеся на них через / у промпті. Крім того, ви завжди можете сказати агенту встановити й автентифікувати інші інструменти (наприклад, MCPs та CLI-інструменти) через Build-чат. Зверніть увагу: інструменти, налаштовані через Build-чати, НЕ відображатимуться тут, хоча й надалі будуть доступні вашому агенту. Див. документацію.",
+ "agentDetail.configure.tools.toggle": "Перемкнути інструменти",
"agentDetail.configure.tools.toolTabs.all": "Усі",
"agentDetail.configure.tools.toolTabs.cli": "CLI",
"agentDetail.configure.tools.toolTabs.custom": "Користувацькі",
"agentDetail.configure.tools.toolTabs.mcp": "MCP",
"agentDetail.configure.tools.toolTabs.plugins": "Інтеграції",
"agentDetail.configure.tools.toolTabs.workflow": "Робочий процес",
+ "agentDetail.configure.workingDirectory.description": "Файли, які агент читає і записує під час роботи. Усе, що він створює, наприклад qna_report.pdf, з’являється тут.",
+ "agentDetail.configure.workingDirectory.open": "Відкрити робочий каталог",
+ "agentDetail.configure.workingDirectory.title": "Робочий каталог",
+ "agentDetail.configure.workingDirectory.treeLabel": "Файли робочого каталогу",
"agentDetail.documentTitle": "Агент",
"agentDetail.logs.description": "Повні журнали записують стан роботи застосунка, включаючи введення користувача, відповіді агента, планування та використання інструментів.",
"agentDetail.logs.empty": "Журнали не знайдено",
@@ -279,7 +313,7 @@
"agentDetail.navigationLabel": "Навігація агента",
"agentDetail.publish": "Опублікувати",
"agentDetail.sections.access": "Точка доступу",
- "agentDetail.sections.configure": "Оркестрація",
+ "agentDetail.sections.configure": "Налаштувати",
"agentDetail.sections.logs": "Журнали",
"agentDetail.sections.monitoring": "Моніторинг",
"agentDetail.title": "Агент",
@@ -334,6 +368,11 @@
"roster.nodeSelector.startFromScratch": "Почати з нуля",
"roster.references.label": "Робочі процеси, що використовують {{name}}",
"roster.references.trigger": "Робочі процеси, що використовують {{name}}",
+ "roster.saveToRoster": "Save to Agent Console",
+ "roster.saveToRosterDialog.description": "Save this inline setup as a reusable roster agent.",
+ "roster.saveToRosterDialog.title": "Save to Agent Console",
+ "roster.saveToRosterForm.changeIcon": "Change roster agent icon",
+ "roster.saveToRosterSuccess": "Agent saved to roster.",
"roster.searchLabel": "Пошук агентів",
"roster.searchPlaceholder": "Пошук агентів за ім'ям…",
"roster.tabs.agent": "Агент",
diff --git a/web/i18n/uk-UA/common.json b/web/i18n/uk-UA/common.json
index c57418dde38..c3ce66f7d06 100644
--- a/web/i18n/uk-UA/common.json
+++ b/web/i18n/uk-UA/common.json
@@ -288,6 +288,7 @@
"menus.exploreMarketplace": "Дізнайтеся більше про Marketplace",
"menus.plugins": "Інтеграції",
"menus.roster": "Список агентів",
+ "menus.status": "бета",
"menus.tools": "Інструменти",
"model.capabilities": "Можливості MultiModal",
"model.params.stop_sequencesPlaceholder": "Введіть послідовність і натисніть Tab",
diff --git a/web/i18n/uk-UA/workflow.json b/web/i18n/uk-UA/workflow.json
index c2d245d32e9..495e233eab6 100644
--- a/web/i18n/uk-UA/workflow.json
+++ b/web/i18n/uk-UA/workflow.json
@@ -464,7 +464,7 @@
"nodes.agent.task.label": "Задача агента",
"nodes.agent.task.mention": "Згадати",
"nodes.agent.task.placeholder": "Опишіть, що має робити цей агент…",
- "nodes.agent.task.tooltip": "Визначте інструкції задачі, які цей агент має виконувати в цьому робочому процесі.",
+ "nodes.agent.task.tooltip": "Додатковий промпт, який допомагає агенту обробити саме цей вузол. Використовуйте /, щоб явно посилатися на змінні.\nЯкщо налаштовано правильно, ви зможете довірити агенту самостійно розібратися із завданням.",
"nodes.agent.toolNotAuthorizedTooltip": "{{tool}} Не авторизовано",
"nodes.agent.toolNotInstallTooltip": "{{tool}} не встановлено",
"nodes.agent.toolbox": "ящик для інструментів",
diff --git a/web/i18n/vi-VN/agent-v-2.json b/web/i18n/vi-VN/agent-v-2.json
index 626d68efd69..f9088d18b43 100644
--- a/web/i18n/vi-VN/agent-v-2.json
+++ b/web/i18n/vi-VN/agent-v-2.json
@@ -49,14 +49,27 @@
"agentDetail.configure.advancedSettings.envEditor.keyPlaceholder": "Key",
"agentDetail.configure.advancedSettings.envEditor.label": "Env Editor",
"agentDetail.configure.advancedSettings.envEditor.revealValue": "Hiện giá trị của {{key}}",
+ "agentDetail.configure.advancedSettings.envEditor.richTip": "Agent của bạn chạy trong môi trường Linux. Bạn có thể thiết lập sẵn cấu hình hoặc bí mật bằng cách định nghĩa biến môi trường tại đây.\n\nNgoài ra, bạn luôn có thể thiết lập thông qua chat Build. Xem <docLink>tài liệu</docLink>.",
"agentDetail.configure.advancedSettings.envEditor.scopeColumn": "Scope",
"agentDetail.configure.advancedSettings.envEditor.scopePlain": "Plain",
"agentDetail.configure.advancedSettings.envEditor.scopeSecret": "Secret",
"agentDetail.configure.advancedSettings.envEditor.scopeSelector": "Chọn phạm vi biến môi trường",
- "agentDetail.configure.advancedSettings.envEditor.tip": "Các biến môi trường khả dụng cho tác nhân này khi chạy.",
+ "agentDetail.configure.advancedSettings.envEditor.tip": "Agent của bạn chạy trong môi trường Linux. Bạn có thể thiết lập sẵn cấu hình hoặc bí mật bằng cách định nghĩa biến môi trường tại đây. Ngoài ra, bạn luôn có thể thiết lập thông qua chat Build. Xem tài liệu.",
+ "agentDetail.configure.advancedSettings.envEditor.toggle": "Bật/tắt Env Editor",
"agentDetail.configure.advancedSettings.envEditor.valueColumn": "Value",
"agentDetail.configure.advancedSettings.envEditor.valuePlaceholder": "Value",
"agentDetail.configure.advancedSettings.label": "Cài đặt nâng cao",
+ "agentDetail.configure.advancedSettings.toggle": "Bật/tắt cài đặt nâng cao",
+ "agentDetail.configure.build.empty.description": "Mô tả điều bạn muốn và biểu mẫu bên trái sẽ được điền dần khi trò chuyện.",
+ "agentDetail.configure.build.empty.title": "Xây dựng tác nhân bằng trò chuyện",
+ "agentDetail.configure.build.inputPlaceholder": "Mô tả tác nhân của bạn nên làm gì",
+ "agentDetail.configure.build.startBuild": "Bắt đầu build",
+ "agentDetail.configure.buildDraft.changes": "{{count}} thay đổi cần áp dụng",
+ "agentDetail.configure.buildDraft.discard": "Hủy bỏ",
+ "agentDetail.configure.buildDraft.modeBadge": "Chế độ build",
+ "agentDetail.configure.buildDraft.modeDescription": "Bạn đang ở chế độ build. Điều chỉnh thiết lập này qua khung chat bên phải, rồi Áp dụng.",
+ "agentDetail.configure.buildDraft.noChanges": "Không có thay đổi cần áp dụng",
+ "agentDetail.configure.buildDraft.title": "Bản nháp build",
"agentDetail.configure.chatFeatures.description": "Định hình trải nghiệm trò chuyện cho người dùng cuối trên Web app và các bề mặt trò chuyện.",
"agentDetail.configure.chatFeatures.title": "Tính năng trò chuyện",
"agentDetail.configure.files.add": "Thêm tệp",
@@ -67,7 +80,8 @@
"agentDetail.configure.files.preview.failed": "Tải xem trước thất bại.",
"agentDetail.configure.files.preview.unsupported": "Tệp này không hỗ trợ xem trước.",
"agentDetail.configure.files.remove": "Xóa {{name}}",
- "agentDetail.configure.files.tip": "Các tệp mà tác nhân này có thể sử dụng khi điều phối tác vụ.",
+ "agentDetail.configure.files.tip": "Cung cấp cho tác nhân của bạn bất kỳ ví dụ, hướng dẫn hoặc đơn giản là một nguồn thông tin quá dài để đưa vào prompt. Tham chiếu rõ ràng bằng / trong Prompt.",
+ "agentDetail.configure.files.toggle": "Bật/tắt tệp",
"agentDetail.configure.files.treeLabel": "Tệp tác nhân",
"agentDetail.configure.files.upload.action": "Tải lên",
"agentDetail.configure.files.upload.browse": "duyệt",
@@ -113,8 +127,11 @@
"agentDetail.configure.orchestrate": "Điều phối",
"agentDetail.configure.preview.chatFeatures": "Tính năng trò chuyện",
"agentDetail.configure.preview.empty.defaultAgentName": "Tác nhân",
- "agentDetail.configure.preview.empty.description": "Gửi một tin nhắn để thử nghiệm bản nháp hiện tại.",
+ "agentDetail.configure.preview.empty.description": "Chạy tác nhân như một cuộc trò chuyện hoàn chỉnh, đúng như người dùng sẽ trải nghiệm sau khi xuất bản.",
"agentDetail.configure.preview.empty.noInstructionsDescription": "Chưa có hướng dẫn, vì vậy câu trả lời đến từ mô hình thuần.",
+ "agentDetail.configure.preview.empty.title": "Xem trước {{name}}",
+ "agentDetail.configure.preview.endUserAuth": "Xác thực người dùng cuối",
+ "agentDetail.configure.preview.inputPlaceholder": "Nhắn cho {{name}}",
"agentDetail.configure.preview.restart": "Khởi động lại bản xem trước",
"agentDetail.configure.preview.title": "Xem trước",
"agentDetail.configure.prompt.copied": "Đã sao chép lời nhắc",
@@ -128,7 +145,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "Viết hướng dẫn tại đây,",
- "agentDetail.configure.prompt.tip": "Xác định cách tác nhân này nên hiểu đầu vào, gọi công cụ và tạo đầu ra.",
+ "agentDetail.configure.prompt.tip": "Xác định vai trò của tác nhân và mô tả nhiệm vụ điển hình của nó. Dùng / để tham chiếu rõ ràng đến Skills, Files, Tools và Knowledge Retrievals.",
"agentDetail.configure.publishBar.draft": "Bản nháp",
"agentDetail.configure.publishBar.publishUpdate": "Xuất bản cập nhật",
"agentDetail.configure.publishBar.published": "Đã xuất bản",
@@ -147,6 +164,14 @@
"agentDetail.configure.publishImpact.title": "{{action}} đến {{name}}",
"agentDetail.configure.publishImpact.workflowCount_one": "{{count}} quy trình làm việc",
"agentDetail.configure.publishImpact.workflowCount_other": "{{count}} quy trình làm việc",
+ "agentDetail.configure.rightPanel.build": "Xây dựng",
+ "agentDetail.configure.rightPanel.buildTipBody": "Build thiết lập agent bằng cách trò chuyện. Mô tả điều bạn muốn và phần thiết lập bên trái sẽ được điền.",
+ "agentDetail.configure.rightPanel.buildTipTitle": "Xây dựng agent qua chat",
+ "agentDetail.configure.rightPanel.learnMore": "Tìm hiểu thêm",
+ "agentDetail.configure.rightPanel.modeLabel": "Chế độ cấu hình tác nhân",
+ "agentDetail.configure.rightPanel.preview": "Xem trước",
+ "agentDetail.configure.rightPanel.previewTipBody": "Preview chạy agent hoàn chỉnh theo cách người dùng sẽ thấy, với câu trả lời rõ ràng và các tính năng chat.",
+ "agentDetail.configure.rightPanel.previewTipTitle": "Xem trước agent",
"agentDetail.configure.skills.add": "Thêm kỹ năng",
"agentDetail.configure.skills.detail.contentRegion": "Nội dung chi tiết kỹ năng",
"agentDetail.configure.skills.detail.fileCount": "{{count}} TỆP",
@@ -156,7 +181,9 @@
"agentDetail.configure.skills.itemType": "Kỹ năng",
"agentDetail.configure.skills.label": "Kỹ năng",
"agentDetail.configure.skills.remove": "Xóa {{name}}",
- "agentDetail.configure.skills.tip": "Các kỹ năng mà tác nhân này có thể sử dụng khi điều phối tác vụ.",
+ "agentDetail.configure.skills.richTip": "Trang bị cho tác nhân các năng lực dạng mô-đun. Tham khảo <docLink>tài liệu</docLink>. Tham chiếu rõ ràng bằng / trong Prompt.",
+ "agentDetail.configure.skills.tip": "Trang bị cho tác nhân các năng lực dạng mô-đun. Tham khảo tài liệu. Tham chiếu rõ ràng bằng / trong Prompt.",
+ "agentDetail.configure.skills.toggle": "Bật/tắt kỹ năng",
"agentDetail.configure.skills.upload.action": "Tải lên",
"agentDetail.configure.skills.upload.browse": "duyệt",
"agentDetail.configure.skills.upload.description": "Tải lên gói .zip hoặc .skill cho tác nhân này.",
@@ -166,6 +193,7 @@
"agentDetail.configure.skills.upload.invalidFile": "Tải lên một tệp .zip hoặc .skill.",
"agentDetail.configure.skills.upload.success": "Đã tải lên kỹ năng.",
"agentDetail.configure.skills.upload.title": "Tải lên kỹ năng",
+ "agentDetail.configure.title": "Cấu hình",
"agentDetail.configure.tools.add": "Thêm công cụ",
"agentDetail.configure.tools.addMenu.cliTool.badge": "Dành cho nhà phát triển",
"agentDetail.configure.tools.addMenu.cliTool.description": "Cài đặt một chương trình dòng lệnh mà tác nhân chạy trong sandbox của nó. Cần cài đặt và thường cần API Key.",
@@ -179,7 +207,7 @@
"agentDetail.configure.tools.cliDialog.env.optional": "(tùy chọn)",
"agentDetail.configure.tools.cliDialog.installCommand.description": "Sandbox · chạy một lần khi gọi lần đầu",
"agentDetail.configure.tools.cliDialog.installCommand.label": "Lệnh cài đặt",
- "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "Dán lệnh cài đặt của bạn vào đây, ví dụ npm install -g @lark/cli · brew install jq",
+ "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "Dán lệnh cài đặt của bạn vào đây, ví dụ npx -y @playwright/mcp@latest · uv tool install httpie",
"agentDetail.configure.tools.cliDialog.installCommand.required": "Cần lệnh cài đặt.",
"agentDetail.configure.tools.cliDialog.learnMore": "Tìm hiểu thêm về công cụ CLI",
"agentDetail.configure.tools.cliDialog.name.label": "Tên công cụ CLI",
@@ -196,13 +224,19 @@
"agentDetail.configure.tools.moreActions": "Thêm hành động cho {{name}}",
"agentDetail.configure.tools.removeAction": "Xóa {{name}}",
"agentDetail.configure.tools.removeProvider": "Xóa tất cả công cụ",
- "agentDetail.configure.tools.tip": "Các công cụ mà tác nhân này có thể gọi khi điều phối tác vụ.",
+ "agentDetail.configure.tools.richTip": "Trang bị cho tác nhân các plugin của Dify. Tham khảo <pluginDocLink>tài liệu</pluginDocLink>. Tham chiếu rõ ràng bằng / trong Prompt.\nNgoài ra, bạn luôn có thể yêu cầu tác nhân cài đặt và xác thực các công cụ khác (ví dụ: MCPs và công cụ CLI) thông qua Build chat. Lưu ý rằng các công cụ được cấu hình qua Build chats sẽ KHÔNG hiển thị ở đây, mặc dù chúng vẫn sẽ khả dụng cho tác nhân của bạn về sau. Tham khảo <buildDocLink>tài liệu</buildDocLink>.",
+ "agentDetail.configure.tools.tip": "Trang bị cho tác nhân các plugin của Dify. Tham khảo tài liệu. Tham chiếu rõ ràng bằng / trong Prompt. Ngoài ra, bạn luôn có thể yêu cầu tác nhân cài đặt và xác thực các công cụ khác (ví dụ: MCPs và công cụ CLI) thông qua Build chat. Lưu ý rằng các công cụ được cấu hình qua Build chats sẽ KHÔNG hiển thị ở đây, mặc dù chúng vẫn sẽ khả dụng cho tác nhân của bạn về sau. Tham khảo tài liệu.",
+ "agentDetail.configure.tools.toggle": "Bật/tắt công cụ",
"agentDetail.configure.tools.toolTabs.all": "Tất cả",
"agentDetail.configure.tools.toolTabs.cli": "CLI",
"agentDetail.configure.tools.toolTabs.custom": "Tùy chỉnh",
"agentDetail.configure.tools.toolTabs.mcp": "MCP",
"agentDetail.configure.tools.toolTabs.plugins": "Plugin",
"agentDetail.configure.tools.toolTabs.workflow": "Workflow",
+ "agentDetail.configure.workingDirectory.description": "Các tệp mà agent đọc và ghi khi chạy. Mọi thứ nó tạo ra, như qna_report.pdf, sẽ xuất hiện ở đây.",
+ "agentDetail.configure.workingDirectory.open": "Mở thư mục làm việc",
+ "agentDetail.configure.workingDirectory.title": "Thư mục làm việc",
+ "agentDetail.configure.workingDirectory.treeLabel": "Tệp trong thư mục làm việc",
"agentDetail.documentTitle": "Tác nhân",
"agentDetail.logs.description": "Nhật ký đầy đủ ghi lại trạng thái chạy của ứng dụng, bao gồm đầu vào của người dùng, phản hồi của tác nhân, lập kế hoạch và sử dụng công cụ.",
"agentDetail.logs.empty": "Không tìm thấy nhật ký",
@@ -279,7 +313,7 @@
"agentDetail.navigationLabel": "Điều hướng tác nhân",
"agentDetail.publish": "Xuất bản",
"agentDetail.sections.access": "Điểm truy cập",
- "agentDetail.sections.configure": "Điều phối",
+ "agentDetail.sections.configure": "Cấu hình",
"agentDetail.sections.logs": "Nhật ký",
"agentDetail.sections.monitoring": "Giám sát",
"agentDetail.title": "Tác nhân",
@@ -334,6 +368,11 @@
"roster.nodeSelector.startFromScratch": "Bắt đầu từ đầu",
"roster.references.label": "Quy trình làm việc đang dùng {{name}}",
"roster.references.trigger": "Quy trình làm việc đang dùng {{name}}",
+ "roster.saveToRoster": "Save to Agent Console",
+ "roster.saveToRosterDialog.description": "Save this inline setup as a reusable roster agent.",
+ "roster.saveToRosterDialog.title": "Save to Agent Console",
+ "roster.saveToRosterForm.changeIcon": "Change roster agent icon",
+ "roster.saveToRosterSuccess": "Agent saved to roster.",
"roster.searchLabel": "Tìm kiếm tác nhân",
"roster.searchPlaceholder": "Tìm kiếm tác nhân theo tên…",
"roster.tabs.agent": "Tác nhân",
diff --git a/web/i18n/vi-VN/common.json b/web/i18n/vi-VN/common.json
index 8a12640b872..81838ca6844 100644
--- a/web/i18n/vi-VN/common.json
+++ b/web/i18n/vi-VN/common.json
@@ -288,6 +288,7 @@
"menus.exploreMarketplace": "Khám phá Marketplace",
"menus.plugins": "Tích hợp",
"menus.roster": "Danh sách tác nhân",
+ "menus.status": "beta",
"menus.tools": "Công cụ",
"model.capabilities": "Khả năng đa phương thức",
"model.params.stop_sequencesPlaceholder": "Nhập chuỗi và nhấn Tab",
diff --git a/web/i18n/vi-VN/workflow.json b/web/i18n/vi-VN/workflow.json
index d87cb85560b..5ad996f9c1a 100644
--- a/web/i18n/vi-VN/workflow.json
+++ b/web/i18n/vi-VN/workflow.json
@@ -464,7 +464,7 @@
"nodes.agent.task.label": "Tác vụ tác nhân",
"nodes.agent.task.mention": "Đề cập",
"nodes.agent.task.placeholder": "Mô tả tác nhân này nên làm gì...",
- "nodes.agent.task.tooltip": "Xác định các hướng dẫn tác vụ mà tác nhân này nên tuân theo trong quy trình làm việc này.",
+ "nodes.agent.task.tooltip": "Prompt bổ sung để giúp agent xử lý đúng node này. Dùng / để tham chiếu rõ ràng đến các biến.\nNếu được cấu hình đúng, bạn có thể tin agent tự tìm ra cách xử lý.",
"nodes.agent.toolNotAuthorizedTooltip": "{{tool}} Không được ủy quyền",
"nodes.agent.toolNotInstallTooltip": "{{tool}} không được cài đặt",
"nodes.agent.toolbox": "hộp công cụ",
diff --git a/web/i18n/zh-Hans/agent-v-2.json b/web/i18n/zh-Hans/agent-v-2.json
index 7885c5ac247..a2416bdcaac 100644
--- a/web/i18n/zh-Hans/agent-v-2.json
+++ b/web/i18n/zh-Hans/agent-v-2.json
@@ -3,7 +3,7 @@
"agentDetail.access.copyAccessUrl": "复制访问 URL",
"agentDetail.access.copyFailed": "引用复制失败。",
"agentDetail.access.copyServiceEndpoint": "复制服务 API 端点",
- "agentDetail.access.description": "此智能体可被触达的所有入口。",
+ "agentDetail.access.description": "此 Agent 可被触达的所有入口。",
"agentDetail.access.learnMore": "了解更多",
"agentDetail.access.serviceApi.actions.apiKey": "API Key",
"agentDetail.access.serviceApi.actions.apiReference": "API Reference",
@@ -49,29 +49,43 @@
"agentDetail.configure.advancedSettings.envEditor.keyPlaceholder": "Key",
"agentDetail.configure.advancedSettings.envEditor.label": "Env Editor",
"agentDetail.configure.advancedSettings.envEditor.revealValue": "显示 {{key}} 的值",
+ "agentDetail.configure.advancedSettings.envEditor.richTip": "你的 Agent 运行在 Linux 环境中。你可以在这里通过定义环境变量预设配置或密钥。\n\n或者,也可以随时通过 Build 对话完成设置。参考 <docLink>文档</docLink>。",
"agentDetail.configure.advancedSettings.envEditor.scopeColumn": "Scope",
"agentDetail.configure.advancedSettings.envEditor.scopePlain": "Plain",
"agentDetail.configure.advancedSettings.envEditor.scopeSecret": "Secret",
"agentDetail.configure.advancedSettings.envEditor.scopeSelector": "选择环境变量作用域",
- "agentDetail.configure.advancedSettings.envEditor.tip": "此智能体运行时可使用的环境变量。",
+ "agentDetail.configure.advancedSettings.envEditor.tip": "你的 Agent 运行在 Linux 环境中。你可以在这里通过定义环境变量预设配置或密钥。或者,也可以随时通过 Build 对话完成设置。参考文档。",
+ "agentDetail.configure.advancedSettings.envEditor.toggle": "展开或收起 Env Editor",
"agentDetail.configure.advancedSettings.envEditor.valueColumn": "Value",
"agentDetail.configure.advancedSettings.envEditor.valuePlaceholder": "Value",
"agentDetail.configure.advancedSettings.label": "高级设置",
+ "agentDetail.configure.advancedSettings.toggle": "展开或收起高级设置",
+ "agentDetail.configure.build.empty.description": "描述你的需求,它会随着对话填写左侧表单。",
+ "agentDetail.configure.build.empty.title": "通过对话构建 Agent",
+ "agentDetail.configure.build.inputPlaceholder": "描述你的 Agent 应该做什么",
+ "agentDetail.configure.build.startBuild": "开始构建",
+ "agentDetail.configure.buildDraft.changes": "{{count}} 项待应用更改",
+ "agentDetail.configure.buildDraft.discard": "放弃",
+ "agentDetail.configure.buildDraft.modeBadge": "构建模式",
+ "agentDetail.configure.buildDraft.modeDescription": "你正在使用构建模式。通过右侧聊天调整此配置,然后应用。",
+ "agentDetail.configure.buildDraft.noChanges": "没有待应用的更改",
+ "agentDetail.configure.buildDraft.title": "Build 草稿",
"agentDetail.configure.chatFeatures.description": "配置 Web app 和聊天界面的终端用户聊天体验。",
"agentDetail.configure.chatFeatures.title": "Chat 功能",
"agentDetail.configure.files.add": "添加文件",
- "agentDetail.configure.files.empty.description": "上传智能体可读取的文档,例如规格、模板或指南",
+ "agentDetail.configure.files.empty.description": "上传 Agent 可读取的文档,例如规格、模板或指南",
"agentDetail.configure.files.empty.title": "暂无文件",
"agentDetail.configure.files.label": "文件",
"agentDetail.configure.files.preview.empty": "暂无预览内容。",
"agentDetail.configure.files.preview.failed": "预览加载失败。",
"agentDetail.configure.files.preview.unsupported": "该文件不支持预览。",
"agentDetail.configure.files.remove": "移除 {{name}}",
- "agentDetail.configure.files.tip": "此智能体在编排任务时可使用的文件。",
- "agentDetail.configure.files.treeLabel": "智能体文件",
+ "agentDetail.configure.files.tip": "为 Agent 提供示例、指南,或任何过长而不适合放入提示词的信息载体。请在提示词中使用 / 显式引用。",
+ "agentDetail.configure.files.toggle": "展开或收起文件",
+ "agentDetail.configure.files.treeLabel": "Agent 文件",
"agentDetail.configure.files.upload.action": "上传",
"agentDetail.configure.files.upload.browse": "选择",
- "agentDetail.configure.files.upload.description": "为此智能体上传文件。",
+ "agentDetail.configure.files.upload.description": "为此 Agent 上传文件。",
"agentDetail.configure.files.upload.dropzone": "拖入文件,或",
"agentDetail.configure.files.upload.failed": "文件上传失败。",
"agentDetail.configure.files.upload.fileType": "文件",
@@ -92,29 +106,32 @@
"agentDetail.configure.knowledgeRetrieval.dialog.metadata.manual": "手动",
"agentDetail.configure.knowledgeRetrieval.dialog.metadata.modeLabel": "选择元数据过滤模式",
"agentDetail.configure.knowledgeRetrieval.dialog.nameLabel": "知识检索名称",
- "agentDetail.configure.knowledgeRetrieval.dialog.query.agent": "智能体决定",
- "agentDetail.configure.knowledgeRetrieval.dialog.query.agentDescription": "智能体会根据提示词和可用上下文自行编写查询。无需在此设置。",
+ "agentDetail.configure.knowledgeRetrieval.dialog.query.agent": "Agent 决定",
+ "agentDetail.configure.knowledgeRetrieval.dialog.query.agentDescription": "Agent 会根据提示词和可用上下文自行编写查询。无需在此设置。",
"agentDetail.configure.knowledgeRetrieval.dialog.query.custom": "自定义查询",
"agentDetail.configure.knowledgeRetrieval.dialog.query.customDescription": "为此检索来源编写固定查询。",
"agentDetail.configure.knowledgeRetrieval.dialog.query.customInputLabel": "自定义查询文本",
"agentDetail.configure.knowledgeRetrieval.dialog.query.customPlaceholder": "输入搜索查询",
"agentDetail.configure.knowledgeRetrieval.dialog.query.label": "查询",
- "agentDetail.configure.knowledgeRetrieval.dialog.title": "知识检索 · 智能体决定",
+ "agentDetail.configure.knowledgeRetrieval.dialog.title": "知识检索 · Agent 决定",
"agentDetail.configure.knowledgeRetrieval.edit": "编辑 {{name}}",
- "agentDetail.configure.knowledgeRetrieval.empty.description": "连接智能体回答时可搜索的知识库",
+ "agentDetail.configure.knowledgeRetrieval.empty.description": "连接 Agent 回答时可搜索的知识库",
"agentDetail.configure.knowledgeRetrieval.empty.title": "暂无知识",
"agentDetail.configure.knowledgeRetrieval.label": "知识检索",
"agentDetail.configure.knowledgeRetrieval.remove": "删除 {{name}}",
"agentDetail.configure.knowledgeRetrieval.retrievalOne": "Retrieval 1",
"agentDetail.configure.knowledgeRetrieval.retrievalTwo": "Retrieval 2",
- "agentDetail.configure.knowledgeRetrieval.tip": "此智能体在编排任务时可使用的知识检索来源。",
+ "agentDetail.configure.knowledgeRetrieval.tip": "此 Agent 在编排任务时可使用的知识检索来源。",
"agentDetail.configure.knowledgeRetrieval.toggle": "展开或收起知识检索",
"agentDetail.configure.model.label": "模型",
"agentDetail.configure.orchestrate": "编排",
"agentDetail.configure.preview.chatFeatures": "Chat 功能",
- "agentDetail.configure.preview.empty.defaultAgentName": "智能体",
- "agentDetail.configure.preview.empty.description": "发送一条消息来测试当前草稿。",
+ "agentDetail.configure.preview.empty.defaultAgentName": "Agent",
+ "agentDetail.configure.preview.empty.description": "像已发布后用户体验到的那样运行 Agent。",
"agentDetail.configure.preview.empty.noInstructionsDescription": "尚未设置指令,回复将来自基础模型。",
+ "agentDetail.configure.preview.empty.title": "预览 {{name}}",
+ "agentDetail.configure.preview.endUserAuth": "终端用户认证",
+ "agentDetail.configure.preview.inputPlaceholder": "向 {{name}} 发送消息",
"agentDetail.configure.preview.restart": "重新开始预览",
"agentDetail.configure.preview.title": "预览",
"agentDetail.configure.prompt.copied": "提示词已复制",
@@ -128,7 +145,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "在此编写指令,",
- "agentDetail.configure.prompt.tip": "定义这个智能体如何理解输入、调用工具并生成输出。",
+ "agentDetail.configure.prompt.tip": "定义 Agent 的角色,并描述它的典型任务。使用 / 显式引用 Skill、文件、工具和知识检索。",
"agentDetail.configure.publishBar.draft": "草稿",
"agentDetail.configure.publishBar.publishUpdate": "发布更新",
"agentDetail.configure.publishBar.published": "已发布",
@@ -141,70 +158,87 @@
"agentDetail.configure.publishBar.versionHistory": "打开版本历史",
"agentDetail.configure.publishImpact.affectedWorkflows": "受影响的工作流",
"agentDetail.configure.publishImpact.cancel": "取消",
- "agentDetail.configure.publishImpact.descriptionPrefix": "你的智能体出现在",
+ "agentDetail.configure.publishImpact.descriptionPrefix": "你的 Agent 出现在",
"agentDetail.configure.publishImpact.descriptionSuffix": "中。更改会影响它们。",
- "agentDetail.configure.publishImpact.fallbackAgentName": "此智能体",
+ "agentDetail.configure.publishImpact.fallbackAgentName": "此 Agent",
"agentDetail.configure.publishImpact.title": "{{action}}到 {{name}}",
"agentDetail.configure.publishImpact.workflowCount_one": "{{count}} 个工作流",
"agentDetail.configure.publishImpact.workflowCount_other": "{{count}} 个工作流",
- "agentDetail.configure.skills.add": "添加技能",
- "agentDetail.configure.skills.detail.contentRegion": "技能详情内容",
+ "agentDetail.configure.rightPanel.build": "构建",
+ "agentDetail.configure.rightPanel.buildTipBody": "描述你的目标,指示 Agent 安装并认证工具,或带它完成一个完整示例。保存后,你的指令将被固化到 Agent 中。",
+ "agentDetail.configure.rightPanel.buildTipTitle": "通过对话构建你的 Agent",
+ "agentDetail.configure.rightPanel.learnMore": "了解更多",
+ "agentDetail.configure.rightPanel.modeLabel": "Agent 配置模式",
+ "agentDetail.configure.rightPanel.preview": "预览",
+ "agentDetail.configure.rightPanel.previewTipBody": "像用户一样测试它。你的交互不会影响 Agent 后续的行为。",
+ "agentDetail.configure.rightPanel.previewTipTitle": "预览你的 Agent",
+ "agentDetail.configure.skills.add": "添加 Skill",
+ "agentDetail.configure.skills.detail.contentRegion": "Skill 详情内容",
"agentDetail.configure.skills.detail.fileCount": "{{count}} 个文件",
"agentDetail.configure.skills.detail.files": "文件",
- "agentDetail.configure.skills.empty.description": "技能为智能体提供工作时可调用的可复用专业能力",
- "agentDetail.configure.skills.empty.title": "暂无技能",
- "agentDetail.configure.skills.itemType": "技能",
- "agentDetail.configure.skills.label": "技能",
+ "agentDetail.configure.skills.empty.description": "Skill 为 Agent 提供工作时可调用的可复用专业能力",
+ "agentDetail.configure.skills.empty.title": "暂无 Skill",
+ "agentDetail.configure.skills.itemType": "Skill",
+ "agentDetail.configure.skills.label": "Skill",
"agentDetail.configure.skills.remove": "移除 {{name}}",
- "agentDetail.configure.skills.tip": "此智能体在编排任务时可使用的技能。",
+ "agentDetail.configure.skills.richTip": "为 Agent 配备模块化能力。请参考<docLink>文档</docLink>。请在提示词中使用 / 显式引用。",
+ "agentDetail.configure.skills.tip": "为 Agent 配备模块化能力。请参考文档。请在提示词中使用 / 显式引用。",
+ "agentDetail.configure.skills.toggle": "展开或收起 Skill",
"agentDetail.configure.skills.upload.action": "上传",
"agentDetail.configure.skills.upload.browse": "选择",
- "agentDetail.configure.skills.upload.description": "为此智能体上传 .zip 或 .skill 技能包。",
- "agentDetail.configure.skills.upload.dropzone": "拖入技能包,或",
- "agentDetail.configure.skills.upload.failed": "技能上传失败。",
+ "agentDetail.configure.skills.upload.description": "为此 Agent 上传 .zip 或 .skill 格式的 Skill 包。",
+ "agentDetail.configure.skills.upload.dropzone": "拖入 Skill 包,或",
+ "agentDetail.configure.skills.upload.failed": "Skill 上传失败。",
"agentDetail.configure.skills.upload.fileType": "ZIP / SKILL",
"agentDetail.configure.skills.upload.invalidFile": "请上传 .zip 或 .skill 文件。",
- "agentDetail.configure.skills.upload.success": "技能已上传。",
- "agentDetail.configure.skills.upload.title": "上传技能",
+ "agentDetail.configure.skills.upload.success": "Skill 已上传。",
+ "agentDetail.configure.skills.upload.title": "上传 Skill",
+ "agentDetail.configure.title": "配置",
"agentDetail.configure.tools.add": "添加工具",
"agentDetail.configure.tools.addMenu.cliTool.badge": "开发者适用",
- "agentDetail.configure.tools.addMenu.cliTool.description": "安装智能体可在沙箱中运行的命令行程序。需要安装命令,通常还需要 API Key。",
+ "agentDetail.configure.tools.addMenu.cliTool.description": "安装 Agent 可在沙箱中运行的命令行程序。需要安装命令,通常还需要 API Key。",
"agentDetail.configure.tools.addMenu.cliTool.label": "CLI 工具",
"agentDetail.configure.tools.addMenu.tool.description": "选择工作区中已有的工具,例如 Web 搜索或集成。",
"agentDetail.configure.tools.addMenu.tool.label": "工具",
- "agentDetail.configure.tools.cliDialog.description": "从任意包注册表安装 CLI 工具。智能体会获得运行该二进制文件的 shell 访问能力。",
+ "agentDetail.configure.tools.cliDialog.description": "从任意包注册表安装 CLI 工具。Agent 会获得运行该二进制文件的 shell 访问能力。",
"agentDetail.configure.tools.cliDialog.editTitle": "编辑 CLI 工具",
- "agentDetail.configure.tools.cliDialog.env.description": "存储此 CLI 工具所需的 API Key、Token 或密钥。值会静态加密,并在智能体调用工具时作为环境变量注入。",
+ "agentDetail.configure.tools.cliDialog.env.description": "存储此 CLI 工具所需的 API Key、Token 或密钥。值会静态加密,并在 Agent 调用工具时作为环境变量注入。",
"agentDetail.configure.tools.cliDialog.env.label": "环境变量",
"agentDetail.configure.tools.cliDialog.env.optional": "(可选)",
"agentDetail.configure.tools.cliDialog.installCommand.description": "沙箱中执行 · 首次调用时运行一次",
"agentDetail.configure.tools.cliDialog.installCommand.label": "安装命令",
- "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "粘贴安装命令,例如 npm install -g @lark/cli · brew install jq",
+ "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "粘贴安装命令,例如 npx -y @playwright/mcp@latest · uv tool install httpie",
"agentDetail.configure.tools.cliDialog.installCommand.required": "请输入安装命令。",
"agentDetail.configure.tools.cliDialog.learnMore": "了解 CLI 工具",
"agentDetail.configure.tools.cliDialog.name.label": "CLI 工具名称",
"agentDetail.configure.tools.cliDialog.name.placeholder": "为 CLI 工具命名",
"agentDetail.configure.tools.cliDialog.name.required": "请输入 CLI 工具名称。",
- "agentDetail.configure.tools.cliDialog.securityTip": "不会出现在智能体提示词中;仅在运行时作为 $VAR 注入",
+ "agentDetail.configure.tools.cliDialog.securityTip": "不会出现在 Agent 提示词中;仅在运行时作为 $VAR 注入",
"agentDetail.configure.tools.cliDialog.title": "添加 CLI 工具",
"agentDetail.configure.tools.cliTool": "CLI 工具",
"agentDetail.configure.tools.credential.authOne": "Auth 1",
"agentDetail.configure.tools.editAction": "编辑 {{name}}",
- "agentDetail.configure.tools.empty.description": "工具让智能体可以执行操作,例如搜索网页或调用你的应用",
+ "agentDetail.configure.tools.empty.description": "工具让 Agent 可以执行操作,例如搜索网页或调用你的应用",
"agentDetail.configure.tools.empty.title": "暂无工具",
"agentDetail.configure.tools.label": "工具",
"agentDetail.configure.tools.moreActions": "{{name}} 的更多操作",
"agentDetail.configure.tools.removeAction": "移除 {{name}}",
"agentDetail.configure.tools.removeProvider": "移除所有工具",
- "agentDetail.configure.tools.tip": "此智能体在编排任务时可调用的工具。",
+ "agentDetail.configure.tools.richTip": "为 Agent 配备 Dify 插件。请参考<pluginDocLink>文档</pluginDocLink>。请在提示词中使用 / 显式引用。\n或者,你也可以随时通过 Build 对话让 Agent 安装并认证其他工具(例如 MCP 和 CLI 工具)。注意,通过 Build 对话配置的工具不会显示在这里,但后续仍可供你的 Agent 使用。请参考<buildDocLink>文档</buildDocLink>。",
+ "agentDetail.configure.tools.tip": "为 Agent 配备 Dify 插件。请参考文档。请在提示词中使用 / 显式引用。或者,你也可以随时通过 Build 对话让 Agent 安装并认证其他工具(例如 MCP 和 CLI 工具)。注意,通过 Build 对话配置的工具不会显示在这里,但后续仍可供你的 Agent 使用。请参考文档。",
+ "agentDetail.configure.tools.toggle": "展开或收起工具",
"agentDetail.configure.tools.toolTabs.all": "全部",
"agentDetail.configure.tools.toolTabs.cli": "CLI",
"agentDetail.configure.tools.toolTabs.custom": "自定义",
"agentDetail.configure.tools.toolTabs.mcp": "MCP",
"agentDetail.configure.tools.toolTabs.plugins": "插件",
"agentDetail.configure.tools.toolTabs.workflow": "Workflow",
- "agentDetail.documentTitle": "智能体",
- "agentDetail.logs.description": "完整日志记录应用运行状态,包括用户输入、智能体回复、规划和工具使用。",
+ "agentDetail.configure.workingDirectory.description": "Agent 运行时读取和写入的文件。它生成的任何内容,例如 qna_report.pdf,都会显示在这里。",
+ "agentDetail.configure.workingDirectory.open": "打开工作目录",
+ "agentDetail.configure.workingDirectory.title": "工作目录",
+ "agentDetail.configure.workingDirectory.treeLabel": "工作目录文件",
+ "agentDetail.documentTitle": "Agent",
+ "agentDetail.logs.description": "完整日志记录应用运行状态,包括用户输入、Agent 回复、规划和工具使用。",
"agentDetail.logs.empty": "暂无日志",
"agentDetail.logs.filters.period.allTime": "全部时间",
"agentDetail.logs.filters.period.last30days": "最近 30 天",
@@ -247,20 +281,20 @@
"agentDetail.metadata.sourceLabel": "来源",
"agentDetail.monitoring.change": "较上一周期 {{value}}",
"agentDetail.monitoring.dateRangeLabel": "日期范围",
- "agentDetail.monitoring.description": "跟踪可复用智能体在工作流中的活跃度、成本和交互质量。",
+ "agentDetail.monitoring.description": "跟踪可复用 Agent 在工作流中的活跃度、成本和交互质量。",
"agentDetail.monitoring.learnMore": "了解更多",
"agentDetail.monitoring.loadFailed": "监控数据加载失败",
- "agentDetail.monitoring.metrics.activeUsers.explanation": "触发过使用此智能体的工作流的独立终端用户数。",
+ "agentDetail.monitoring.metrics.activeUsers.explanation": "触发过使用此 Agent 的工作流的独立终端用户数。",
"agentDetail.monitoring.metrics.activeUsers.title": "活跃用户",
- "agentDetail.monitoring.metrics.avgSessionInteractions.explanation": "此访问入口下用户与智能体的连续沟通次数。",
+ "agentDetail.monitoring.metrics.avgSessionInteractions.explanation": "此访问入口下用户与 Agent 的连续沟通次数。",
"agentDetail.monitoring.metrics.avgSessionInteractions.title": "平均会话互动数",
"agentDetail.monitoring.metrics.tokenOutputSpeed.explanation": "从请求开始到输出完成期间的平均输出速度。",
"agentDetail.monitoring.metrics.tokenOutputSpeed.title": "Token 输出速度",
- "agentDetail.monitoring.metrics.tokenUsage.explanation": "此智能体在工作流运行中产生的预估 token 成本。",
+ "agentDetail.monitoring.metrics.tokenUsage.explanation": "此 Agent 在工作流运行中产生的预估 token 成本。",
"agentDetail.monitoring.metrics.tokenUsage.title": "Token 用量",
- "agentDetail.monitoring.metrics.totalConversations.explanation": "通过所选访问入口触达此智能体的每日 AI 会话数。",
+ "agentDetail.monitoring.metrics.totalConversations.explanation": "通过所选访问入口触达此 Agent 的每日 AI 会话数。",
"agentDetail.monitoring.metrics.totalConversations.title": "全部会话数",
- "agentDetail.monitoring.metrics.totalMessages.explanation": "每日智能体互动总次数。",
+ "agentDetail.monitoring.metrics.totalMessages.explanation": "每日 Agent 互动总次数。",
"agentDetail.monitoring.metrics.totalMessages.title": "全部消息数",
"agentDetail.monitoring.metrics.userSatisfactionRate.explanation": "每 1000 条消息的点赞数,反映用户满意度。",
"agentDetail.monitoring.metrics.userSatisfactionRate.title": "用户满意度",
@@ -276,24 +310,24 @@
"agentDetail.monitoring.title": "监控",
"agentDetail.monitoring.tokenUsageConsumed": "耗费 Tokens",
"agentDetail.monitoring.units.tokenPerSecond": "Token/秒",
- "agentDetail.navigationLabel": "智能体导航",
+ "agentDetail.navigationLabel": "Agent 导航",
"agentDetail.publish": "发布",
"agentDetail.sections.access": "访问点",
- "agentDetail.sections.configure": "编排",
+ "agentDetail.sections.configure": "配置",
"agentDetail.sections.logs": "日志",
"agentDetail.sections.monitoring": "监控",
- "agentDetail.title": "智能体",
- "agentDetail.type": "智能体",
+ "agentDetail.title": "Agent",
+ "agentDetail.type": "Agent",
"agentDetail.versionHistory.empty": "暂无版本",
"agentDetail.versionHistory.exitVersions": "退出版本",
"agentDetail.versionHistory.filter": "筛选版本",
"agentDetail.versionHistory.restore": "还原",
"agentDetail.versionHistory.versionName": "版本 {{version}}",
"agentDetail.versionHistory.viewOnly": "只读",
- "roster.createAgent": "创建智能体",
- "roster.createDialog.description": "在当前工作区 Roster 中创建一个可复用智能体。",
- "roster.createDialog.title": "创建智能体",
- "roster.createForm.changeIcon": "更换智能体图标",
+ "roster.createAgent": "创建 Agent",
+ "roster.createDialog.description": "在当前工作区 Roster 中创建一个可复用 Agent。",
+ "roster.createDialog.title": "创建 Agent",
+ "roster.createForm.changeIcon": "更换 Agent 图标",
"roster.createForm.descriptionLabel": "描述",
"roster.createForm.descriptionPlaceholder": "例如:收集某个主题的来源资料并总结关键发现",
"roster.createForm.nameLabel": "名称",
@@ -302,43 +336,48 @@
"roster.createForm.roleLabel": "角色",
"roster.createForm.rolePlaceholder": "例如:研究助理",
"roster.createForm.roleRequired": "请输入角色。",
- "roster.createSuccess": "智能体已创建。",
+ "roster.createSuccess": "Agent 已创建。",
"roster.dateTimeFormat": "YYYY-MM-DD HH:mm:ss",
- "roster.deleteDialog.description": "此智能体将从当前活跃 Roster 列表中移除。",
+ "roster.deleteDialog.description": "此 Agent 将从当前活跃 Roster 列表中移除。",
"roster.deleteDialog.title": "删除 {{name}}?",
- "roster.deleteFailed": "智能体删除失败。",
- "roster.deleteSuccess": "智能体已删除。",
+ "roster.deleteFailed": "Agent 删除失败。",
+ "roster.deleteSuccess": "Agent 已删除。",
"roster.duplicateDialog.description": "创建 {{name}} 的副本,并自定义它在 Roster 中的身份信息。",
- "roster.duplicateDialog.title": "复制智能体",
+ "roster.duplicateDialog.title": "复制 Agent",
"roster.duplicateForm.changeIcon": "更换 {{name}} 副本的图标",
- "roster.duplicateSuccess": "智能体已复制。",
+ "roster.duplicateSuccess": "Agent 已复制。",
"roster.editAgent": "编辑 {{name}}",
- "roster.editDialog.description": "更新此智能体在 Roster 中的名称、描述和角色。",
- "roster.editDialog.title": "编辑智能体",
+ "roster.editDialog.description": "更新此 Agent 在 Roster 中的名称、描述和角色。",
+ "roster.editDialog.title": "编辑 Agent",
"roster.editInfo": "编辑信息",
- "roster.empty": "暂无智能体",
- "roster.emptySearch": "没有匹配的智能体",
+ "roster.empty": "暂无 Agent",
+ "roster.emptySearch": "没有匹配的 Agent",
"roster.filters.all": "全部",
"roster.filters.drafts": "草稿",
- "roster.filters.label": "智能体筛选",
+ "roster.filters.label": "Agent 筛选",
"roster.filters.published": "已发布",
- "roster.learnMore": "了解 Agent Roster",
- "roster.listLabel": "智能体 Roster 列表",
+ "roster.learnMore": "了解 Agent 名册",
+ "roster.listLabel": "Agent 名册列表",
"roster.loadMore": "加载更多",
- "roster.loadingError": "智能体加载失败。请刷新后重试。",
+ "roster.loadingError": "Agent 加载失败。请刷新后重试。",
"roster.moreActions": "{{name}} 的更多操作",
- "roster.nodeSelector.createInlineFailed": "Inline 智能体创建失败。请刷新后重试。",
- "roster.nodeSelector.dialogLabel": "选择智能体",
- "roster.nodeSelector.manageInAgentConsole": "在智能体控制台管理",
+ "roster.nodeSelector.createInlineFailed": "Inline Agent 创建失败。请刷新后重试。",
+ "roster.nodeSelector.dialogLabel": "选择 Agent",
+ "roster.nodeSelector.manageInAgentConsole": "在 Agent Console 管理",
"roster.nodeSelector.searchPlaceholder": "搜索…",
"roster.nodeSelector.startFromScratch": "从空白开始",
"roster.references.label": "使用 {{name}} 的工作流",
"roster.references.trigger": "使用 {{name}} 的工作流",
- "roster.searchLabel": "搜索智能体",
- "roster.searchPlaceholder": "按名称搜索智能体…",
- "roster.tabs.agent": "智能体",
+ "roster.saveToRoster": "保存到 Agent Console",
+ "roster.saveToRosterDialog.description": "将此内联配置保存为可复用的 Roster Agent。",
+ "roster.saveToRosterDialog.title": "保存到 Agent Console",
+ "roster.saveToRosterForm.changeIcon": "更换 Roster Agent 图标",
+ "roster.saveToRosterSuccess": "Agent 已保存到 Roster。",
+ "roster.searchLabel": "搜索 Agent",
+ "roster.searchPlaceholder": "按名称搜索 Agent…",
+ "roster.tabs.agent": "Agent",
"roster.tabs.human": "人工成员",
"roster.tabsLabel": "Roster 类型",
- "roster.updateSuccess": "智能体已更新。",
+ "roster.updateSuccess": "Agent 已更新。",
"roster.usageStatus.draft": "草稿"
}
diff --git a/web/i18n/zh-Hans/common.json b/web/i18n/zh-Hans/common.json
index eeb8fa321d4..47f93a80e1d 100644
--- a/web/i18n/zh-Hans/common.json
+++ b/web/i18n/zh-Hans/common.json
@@ -73,7 +73,7 @@
"actionMsg.noModification": "暂无修改",
"actionMsg.payCancelled": "已取消支付",
"actionMsg.paySucceeded": "已支付成功",
- "agentStrategyPage.description": "定义 AI 智能体的推理与决策方式——包括它如何选择工具、处理结果、自主解决问题。",
+ "agentStrategyPage.description": "定义 AI Agent 的推理与决策方式——包括它如何选择工具、处理结果、自主解决问题。",
"api.actionFailed": "操作失败",
"api.actionSuccess": "操作成功",
"api.remove": "已移除",
@@ -287,7 +287,8 @@
"menus.explore": "探索",
"menus.exploreMarketplace": "探索 Marketplace",
"menus.plugins": "集成",
- "menus.roster": "智能体名册",
+ "menus.roster": "Agent 名册",
+ "menus.status": "beta",
"menus.tools": "工具",
"model.capabilities": "多模态能力",
"model.params.stop_sequencesPlaceholder": "输入序列并按 Tab 键",
diff --git a/web/i18n/zh-Hans/workflow.json b/web/i18n/zh-Hans/workflow.json
index cbec4fcc526..0135c42722d 100644
--- a/web/i18n/zh-Hans/workflow.json
+++ b/web/i18n/zh-Hans/workflow.json
@@ -464,7 +464,7 @@
"nodes.agent.task.label": "Agent 任务",
"nodes.agent.task.mention": "提及",
"nodes.agent.task.placeholder": "描述这个 Agent 要完成的任务...",
- "nodes.agent.task.tooltip": "定义该 Agent 在当前工作流中需要遵循的任务指令。",
+ "nodes.agent.task.tooltip": "帮助 Agent 处理当前节点的附加提示词。使用 / 显式引用变量。\n如果配置得当,你可以信任 Agent 自行判断如何完成任务。",
"nodes.agent.toolNotAuthorizedTooltip": "{{tool}} 未授权",
"nodes.agent.toolNotInstallTooltip": "{{tool}} 未安装",
"nodes.agent.toolbox": "工具箱",
diff --git a/web/i18n/zh-Hant/agent-v-2.json b/web/i18n/zh-Hant/agent-v-2.json
index 7b57933cec6..8eb424b4041 100644
--- a/web/i18n/zh-Hant/agent-v-2.json
+++ b/web/i18n/zh-Hant/agent-v-2.json
@@ -3,7 +3,7 @@
"agentDetail.access.copyAccessUrl": "複製存取 URL",
"agentDetail.access.copyFailed": "引用複製失敗。",
"agentDetail.access.copyServiceEndpoint": "複製服務 API 端點",
- "agentDetail.access.description": "此智能體可被觸達的所有入口。",
+ "agentDetail.access.description": "此 Agent 可被觸達的所有入口。",
"agentDetail.access.learnMore": "了解更多",
"agentDetail.access.serviceApi.actions.apiKey": "API Key",
"agentDetail.access.serviceApi.actions.apiReference": "API Reference",
@@ -49,29 +49,43 @@
"agentDetail.configure.advancedSettings.envEditor.keyPlaceholder": "Key",
"agentDetail.configure.advancedSettings.envEditor.label": "Env Editor",
"agentDetail.configure.advancedSettings.envEditor.revealValue": "顯示 {{key}} 的值",
+ "agentDetail.configure.advancedSettings.envEditor.richTip": "你的 Agent 執行於 Linux 環境中。你可以在這裡透過定義環境變數預設設定或密鑰。\n\n或者,也可以隨時透過 Build 對話完成設定。參考 <docLink>文件</docLink>。",
"agentDetail.configure.advancedSettings.envEditor.scopeColumn": "Scope",
"agentDetail.configure.advancedSettings.envEditor.scopePlain": "Plain",
"agentDetail.configure.advancedSettings.envEditor.scopeSecret": "Secret",
"agentDetail.configure.advancedSettings.envEditor.scopeSelector": "選擇環境變數作用域",
- "agentDetail.configure.advancedSettings.envEditor.tip": "此智能體在執行時可用的環境變數。",
+ "agentDetail.configure.advancedSettings.envEditor.tip": "你的 Agent 執行於 Linux 環境中。你可以在這裡透過定義環境變數預設設定或密鑰。或者,也可以隨時透過 Build 對話完成設定。參考文件。",
+ "agentDetail.configure.advancedSettings.envEditor.toggle": "展開或收合 Env Editor",
"agentDetail.configure.advancedSettings.envEditor.valueColumn": "Value",
"agentDetail.configure.advancedSettings.envEditor.valuePlaceholder": "Value",
"agentDetail.configure.advancedSettings.label": "進階設定",
+ "agentDetail.configure.advancedSettings.toggle": "展開或收合進階設定",
+ "agentDetail.configure.build.empty.description": "描述你的需求,它會隨著對話填寫左側表單。",
+ "agentDetail.configure.build.empty.title": "透過對話建置 Agent",
+ "agentDetail.configure.build.inputPlaceholder": "描述你的 Agent 應該做什麼",
+ "agentDetail.configure.build.startBuild": "開始構建",
+ "agentDetail.configure.buildDraft.changes": "{{count}} 項待套用變更",
+ "agentDetail.configure.buildDraft.discard": "放棄",
+ "agentDetail.configure.buildDraft.modeBadge": "建置模式",
+ "agentDetail.configure.buildDraft.modeDescription": "你正在使用建置模式。透過右側聊天調整此設定,然後套用。",
+ "agentDetail.configure.buildDraft.noChanges": "沒有待套用的變更",
+ "agentDetail.configure.buildDraft.title": "Build 草稿",
"agentDetail.configure.chatFeatures.description": "配置 Web app 和聊天介面的終端使用者聊天體驗。",
"agentDetail.configure.chatFeatures.title": "Chat 功能",
"agentDetail.configure.files.add": "新增檔案",
- "agentDetail.configure.files.empty.description": "上傳智能體可讀取的文件,例如規格、範本或指南",
+ "agentDetail.configure.files.empty.description": "上傳 Agent 可讀取的文件,例如規格、範本或指南",
"agentDetail.configure.files.empty.title": "暫無檔案",
"agentDetail.configure.files.label": "檔案",
"agentDetail.configure.files.preview.empty": "暫無預覽內容。",
"agentDetail.configure.files.preview.failed": "預覽載入失敗。",
"agentDetail.configure.files.preview.unsupported": "此檔案不支援預覽。",
"agentDetail.configure.files.remove": "移除 {{name}}",
- "agentDetail.configure.files.tip": "此智能體在編排任務時可使用的檔案。",
- "agentDetail.configure.files.treeLabel": "智能體檔案",
+ "agentDetail.configure.files.tip": "為 Agent 提供範例、指南,或任何過長而不適合放入提示詞的資訊載體。請在提示詞中使用 / 明確引用。",
+ "agentDetail.configure.files.toggle": "展開或收合檔案",
+ "agentDetail.configure.files.treeLabel": "Agent 檔案",
"agentDetail.configure.files.upload.action": "上傳",
"agentDetail.configure.files.upload.browse": "選擇",
- "agentDetail.configure.files.upload.description": "為此智能體上傳檔案。",
+ "agentDetail.configure.files.upload.description": "為此 Agent 上傳檔案。",
"agentDetail.configure.files.upload.dropzone": "拖入檔案,或",
"agentDetail.configure.files.upload.failed": "檔案上傳失敗。",
"agentDetail.configure.files.upload.fileType": "檔案",
@@ -92,29 +106,32 @@
"agentDetail.configure.knowledgeRetrieval.dialog.metadata.manual": "手動",
"agentDetail.configure.knowledgeRetrieval.dialog.metadata.modeLabel": "選擇中繼資料過濾模式",
"agentDetail.configure.knowledgeRetrieval.dialog.nameLabel": "知識檢索名稱",
- "agentDetail.configure.knowledgeRetrieval.dialog.query.agent": "智能體決定",
- "agentDetail.configure.knowledgeRetrieval.dialog.query.agentDescription": "智能體會根據提示詞和可用上下文自行編寫查詢。無需在此設定。",
+ "agentDetail.configure.knowledgeRetrieval.dialog.query.agent": "Agent 決定",
+ "agentDetail.configure.knowledgeRetrieval.dialog.query.agentDescription": "Agent 會根據提示詞和可用上下文自行編寫查詢。無需在此設定。",
"agentDetail.configure.knowledgeRetrieval.dialog.query.custom": "自訂查詢",
"agentDetail.configure.knowledgeRetrieval.dialog.query.customDescription": "為此檢索來源編寫固定查詢。",
"agentDetail.configure.knowledgeRetrieval.dialog.query.customInputLabel": "自訂查詢文字",
"agentDetail.configure.knowledgeRetrieval.dialog.query.customPlaceholder": "輸入搜尋查詢",
"agentDetail.configure.knowledgeRetrieval.dialog.query.label": "查詢",
- "agentDetail.configure.knowledgeRetrieval.dialog.title": "知識檢索 · 智能體決定",
+ "agentDetail.configure.knowledgeRetrieval.dialog.title": "知識檢索 · Agent 決定",
"agentDetail.configure.knowledgeRetrieval.edit": "編輯 {{name}}",
- "agentDetail.configure.knowledgeRetrieval.empty.description": "連接智能體回答時可搜尋的知識庫",
+ "agentDetail.configure.knowledgeRetrieval.empty.description": "連接 Agent 回答時可搜尋的知識庫",
"agentDetail.configure.knowledgeRetrieval.empty.title": "暫無知識",
"agentDetail.configure.knowledgeRetrieval.label": "知識檢索",
"agentDetail.configure.knowledgeRetrieval.remove": "刪除 {{name}}",
"agentDetail.configure.knowledgeRetrieval.retrievalOne": "Retrieval 1",
"agentDetail.configure.knowledgeRetrieval.retrievalTwo": "Retrieval 2",
- "agentDetail.configure.knowledgeRetrieval.tip": "此智能體在編排任務時可使用的知識檢索來源。",
+ "agentDetail.configure.knowledgeRetrieval.tip": "此 Agent 在編排任務時可使用的知識檢索來源。",
"agentDetail.configure.knowledgeRetrieval.toggle": "展開或收合知識檢索",
"agentDetail.configure.model.label": "模型",
"agentDetail.configure.orchestrate": "編排",
"agentDetail.configure.preview.chatFeatures": "Chat 功能",
- "agentDetail.configure.preview.empty.defaultAgentName": "智能體",
- "agentDetail.configure.preview.empty.description": "傳送一則訊息以測試目前草稿。",
+ "agentDetail.configure.preview.empty.defaultAgentName": "Agent",
+ "agentDetail.configure.preview.empty.description": "像發布後使用者體驗到的那樣執行 Agent。",
"agentDetail.configure.preview.empty.noInstructionsDescription": "尚未設定指令,回覆將來自基礎模型。",
+ "agentDetail.configure.preview.empty.title": "預覽 {{name}}",
+ "agentDetail.configure.preview.endUserAuth": "終端使用者驗證",
+ "agentDetail.configure.preview.inputPlaceholder": "傳訊息給 {{name}}",
"agentDetail.configure.preview.restart": "重新開始預覽",
"agentDetail.configure.preview.title": "預覽",
"agentDetail.configure.prompt.copied": "提示詞已複製",
@@ -128,7 +145,7 @@
"agentDetail.configure.prompt.mention.davidHayes": "David Hayes",
"agentDetail.configure.prompt.mention.priyaRamanathan": "Priya Ramanathan",
"agentDetail.configure.prompt.placeholder": "在此編寫指令,",
- "agentDetail.configure.prompt.tip": "定義此智能體如何理解輸入、呼叫工具並產生輸出。",
+ "agentDetail.configure.prompt.tip": "定義 Agent 的角色,並描述它的典型任務。使用 / 明確引用 Skill、檔案、工具和知識檢索。",
"agentDetail.configure.publishBar.draft": "草稿",
"agentDetail.configure.publishBar.publishUpdate": "發佈更新",
"agentDetail.configure.publishBar.published": "已發佈",
@@ -141,70 +158,87 @@
"agentDetail.configure.publishBar.versionHistory": "開啟版本歷史",
"agentDetail.configure.publishImpact.affectedWorkflows": "受影響的工作流程",
"agentDetail.configure.publishImpact.cancel": "取消",
- "agentDetail.configure.publishImpact.descriptionPrefix": "你的智能體出現在",
+ "agentDetail.configure.publishImpact.descriptionPrefix": "你的 Agent 出現在",
"agentDetail.configure.publishImpact.descriptionSuffix": "中。變更會影響它們。",
- "agentDetail.configure.publishImpact.fallbackAgentName": "此智能體",
+ "agentDetail.configure.publishImpact.fallbackAgentName": "此 Agent",
"agentDetail.configure.publishImpact.title": "{{action}}到 {{name}}",
"agentDetail.configure.publishImpact.workflowCount_one": "{{count}} 個工作流程",
"agentDetail.configure.publishImpact.workflowCount_other": "{{count}} 個工作流程",
- "agentDetail.configure.skills.add": "新增技能",
- "agentDetail.configure.skills.detail.contentRegion": "技能詳情內容",
+ "agentDetail.configure.rightPanel.build": "建置",
+ "agentDetail.configure.rightPanel.buildTipBody": "描述你的目標,指示 Agent 安裝並認證工具,或帶它完成一個完整範例。儲存後,你的指令將被固定到 Agent 中。",
+ "agentDetail.configure.rightPanel.buildTipTitle": "透過對話建立你的 Agent",
+ "agentDetail.configure.rightPanel.learnMore": "了解更多",
+ "agentDetail.configure.rightPanel.modeLabel": "Agent 配置模式",
+ "agentDetail.configure.rightPanel.preview": "預覽",
+ "agentDetail.configure.rightPanel.previewTipBody": "像使用者一樣測試它。你的互動不會影響 Agent 後續的行為。",
+ "agentDetail.configure.rightPanel.previewTipTitle": "預覽你的 Agent",
+ "agentDetail.configure.skills.add": "新增 Skill",
+ "agentDetail.configure.skills.detail.contentRegion": "Skill 詳情內容",
"agentDetail.configure.skills.detail.fileCount": "{{count}} 個檔案",
"agentDetail.configure.skills.detail.files": "檔案",
- "agentDetail.configure.skills.empty.description": "技能為智能體提供工作時可呼叫的可複用專業能力",
- "agentDetail.configure.skills.empty.title": "暫無技能",
- "agentDetail.configure.skills.itemType": "技能",
- "agentDetail.configure.skills.label": "技能",
+ "agentDetail.configure.skills.empty.description": "Skill 為 Agent 提供工作時可呼叫的可複用專業能力",
+ "agentDetail.configure.skills.empty.title": "暫無 Skill",
+ "agentDetail.configure.skills.itemType": "Skill",
+ "agentDetail.configure.skills.label": "Skill",
"agentDetail.configure.skills.remove": "移除 {{name}}",
- "agentDetail.configure.skills.tip": "此智能體在編排任務時可使用的技能。",
+ "agentDetail.configure.skills.richTip": "為 Agent 配備模組化能力。請參考<docLink>文件</docLink>。請在提示詞中使用 / 明確引用。",
+ "agentDetail.configure.skills.tip": "為 Agent 配備模組化能力。請參考文件。請在提示詞中使用 / 明確引用。",
+ "agentDetail.configure.skills.toggle": "展開或收合 Skill",
"agentDetail.configure.skills.upload.action": "上傳",
"agentDetail.configure.skills.upload.browse": "選擇",
- "agentDetail.configure.skills.upload.description": "為此智能體上傳 .zip 或 .skill 技能包。",
- "agentDetail.configure.skills.upload.dropzone": "拖入技能包,或",
- "agentDetail.configure.skills.upload.failed": "技能上傳失敗。",
+ "agentDetail.configure.skills.upload.description": "為此 Agent 上傳 .zip 或 .skill 格式的 Skill 包。",
+ "agentDetail.configure.skills.upload.dropzone": "拖入 Skill 包,或",
+ "agentDetail.configure.skills.upload.failed": "Skill 上傳失敗。",
"agentDetail.configure.skills.upload.fileType": "ZIP / SKILL",
"agentDetail.configure.skills.upload.invalidFile": "請上傳 .zip 或 .skill 檔案。",
- "agentDetail.configure.skills.upload.success": "技能已上傳。",
- "agentDetail.configure.skills.upload.title": "上傳技能",
+ "agentDetail.configure.skills.upload.success": "Skill 已上傳。",
+ "agentDetail.configure.skills.upload.title": "上傳 Skill",
+ "agentDetail.configure.title": "設定",
"agentDetail.configure.tools.add": "新增工具",
"agentDetail.configure.tools.addMenu.cliTool.badge": "開發者適用",
- "agentDetail.configure.tools.addMenu.cliTool.description": "安裝智能體可在沙箱中執行的命令列程式。需要安裝命令,通常還需要 API Key。",
+ "agentDetail.configure.tools.addMenu.cliTool.description": "安裝 Agent 可在沙箱中執行的命令列程式。需要安裝命令,通常還需要 API Key。",
"agentDetail.configure.tools.addMenu.cliTool.label": "CLI 工具",
"agentDetail.configure.tools.addMenu.tool.description": "選擇工作區中已有的工具,例如 Web 搜尋或整合。",
"agentDetail.configure.tools.addMenu.tool.label": "工具",
- "agentDetail.configure.tools.cliDialog.description": "從任意套件登錄安裝 CLI 工具。智能體會獲得執行該二進位檔案的 shell 存取能力。",
+ "agentDetail.configure.tools.cliDialog.description": "從任意套件登錄安裝 CLI 工具。Agent 會獲得執行該二進位檔案的 shell 存取能力。",
"agentDetail.configure.tools.cliDialog.editTitle": "編輯 CLI 工具",
- "agentDetail.configure.tools.cliDialog.env.description": "儲存此 CLI 工具所需的 API Key、Token 或密鑰。值會靜態加密,並在智能體呼叫工具時作為環境變數注入。",
+ "agentDetail.configure.tools.cliDialog.env.description": "儲存此 CLI 工具所需的 API Key、Token 或密鑰。值會靜態加密,並在 Agent 呼叫工具時作為環境變數注入。",
"agentDetail.configure.tools.cliDialog.env.label": "環境變數",
"agentDetail.configure.tools.cliDialog.env.optional": "(選用)",
"agentDetail.configure.tools.cliDialog.installCommand.description": "沙箱中執行 · 首次呼叫時執行一次",
"agentDetail.configure.tools.cliDialog.installCommand.label": "安裝命令",
- "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "貼上安裝命令,例如 npm install -g @lark/cli · brew install jq",
+ "agentDetail.configure.tools.cliDialog.installCommand.placeholder": "貼上安裝命令,例如 npx -y @playwright/mcp@latest · uv tool install httpie",
"agentDetail.configure.tools.cliDialog.installCommand.required": "請輸入安裝命令。",
"agentDetail.configure.tools.cliDialog.learnMore": "了解 CLI 工具",
"agentDetail.configure.tools.cliDialog.name.label": "CLI 工具名稱",
"agentDetail.configure.tools.cliDialog.name.placeholder": "為 CLI 工具命名",
"agentDetail.configure.tools.cliDialog.name.required": "請輸入 CLI 工具名稱。",
- "agentDetail.configure.tools.cliDialog.securityTip": "不會出現在智能體提示詞中;僅在執行時作為 $VAR 注入",
+ "agentDetail.configure.tools.cliDialog.securityTip": "不會出現在 Agent 提示詞中;僅在執行時作為 $VAR 注入",
"agentDetail.configure.tools.cliDialog.title": "新增 CLI 工具",
"agentDetail.configure.tools.cliTool": "CLI 工具",
"agentDetail.configure.tools.credential.authOne": "Auth 1",
"agentDetail.configure.tools.editAction": "編輯 {{name}}",
- "agentDetail.configure.tools.empty.description": "工具讓智能體可以執行操作,例如搜尋網頁或呼叫你的應用程式",
+ "agentDetail.configure.tools.empty.description": "工具讓 Agent 可以執行操作,例如搜尋網頁或呼叫你的應用程式",
"agentDetail.configure.tools.empty.title": "暫無工具",
"agentDetail.configure.tools.label": "工具",
"agentDetail.configure.tools.moreActions": "{{name}} 的更多操作",
"agentDetail.configure.tools.removeAction": "移除 {{name}}",
"agentDetail.configure.tools.removeProvider": "移除所有工具",
- "agentDetail.configure.tools.tip": "此智能體在編排任務時可呼叫的工具。",
+ "agentDetail.configure.tools.richTip": "為 Agent 配備 Dify 外掛。請參考<pluginDocLink>文件</pluginDocLink>。請在提示詞中使用 / 明確引用。\n或者,你也可以隨時透過 Build 對話讓 Agent 安裝並驗證其他工具(例如 MCP 和 CLI 工具)。注意,透過 Build 對話設定的工具不會顯示在這裡,但後續仍可供你的 Agent 使用。請參考<buildDocLink>文件</buildDocLink>。",
+ "agentDetail.configure.tools.tip": "為 Agent 配備 Dify 外掛。請參考文件。請在提示詞中使用 / 明確引用。或者,你也可以隨時透過 Build 對話讓 Agent 安裝並驗證其他工具(例如 MCP 和 CLI 工具)。注意,透過 Build 對話設定的工具不會顯示在這裡,但後續仍可供你的 Agent 使用。請參考文件。",
+ "agentDetail.configure.tools.toggle": "展開或收合工具",
"agentDetail.configure.tools.toolTabs.all": "全部",
"agentDetail.configure.tools.toolTabs.cli": "CLI",
"agentDetail.configure.tools.toolTabs.custom": "自訂",
"agentDetail.configure.tools.toolTabs.mcp": "MCP",
"agentDetail.configure.tools.toolTabs.plugins": "外掛",
"agentDetail.configure.tools.toolTabs.workflow": "Workflow",
- "agentDetail.documentTitle": "智能體",
- "agentDetail.logs.description": "完整日誌記錄應用程式執行狀態,包括使用者輸入、智能體回覆、規劃和工具使用。",
+ "agentDetail.configure.workingDirectory.description": "Agent 執行時讀取和寫入的檔案。它產生的任何內容,例如 qna_report.pdf,都會顯示在這裡。",
+ "agentDetail.configure.workingDirectory.open": "開啟工作目錄",
+ "agentDetail.configure.workingDirectory.title": "工作目錄",
+ "agentDetail.configure.workingDirectory.treeLabel": "工作目錄檔案",
+ "agentDetail.documentTitle": "Agent",
+ "agentDetail.logs.description": "完整日誌記錄應用程式執行狀態,包括使用者輸入、Agent 回覆、規劃和工具使用。",
"agentDetail.logs.empty": "暫無日誌",
"agentDetail.logs.filters.period.allTime": "全部時間",
"agentDetail.logs.filters.period.last30days": "最近 30 天",
@@ -247,20 +281,20 @@
"agentDetail.metadata.sourceLabel": "來源",
"agentDetail.monitoring.change": "較上一週期 {{value}}",
"agentDetail.monitoring.dateRangeLabel": "日期範圍",
- "agentDetail.monitoring.description": "追蹤可複用智能體在工作流程中的活躍度、成本和互動品質。",
+ "agentDetail.monitoring.description": "追蹤可複用 Agent 在工作流程中的活躍度、成本和互動品質。",
"agentDetail.monitoring.learnMore": "了解更多",
"agentDetail.monitoring.loadFailed": "監控資料載入失敗",
- "agentDetail.monitoring.metrics.activeUsers.explanation": "觸發過使用此智能體的工作流程的獨立終端使用者數。",
+ "agentDetail.monitoring.metrics.activeUsers.explanation": "觸發過使用此 Agent 的工作流程的獨立終端使用者數。",
"agentDetail.monitoring.metrics.activeUsers.title": "活躍使用者",
- "agentDetail.monitoring.metrics.avgSessionInteractions.explanation": "此存取入口下使用者與智能體的連續溝通次數。",
+ "agentDetail.monitoring.metrics.avgSessionInteractions.explanation": "此存取入口下使用者與 Agent 的連續溝通次數。",
"agentDetail.monitoring.metrics.avgSessionInteractions.title": "平均工作階段互動數",
"agentDetail.monitoring.metrics.tokenOutputSpeed.explanation": "從請求開始到輸出完成期間的平均輸出速度。",
"agentDetail.monitoring.metrics.tokenOutputSpeed.title": "Token 輸出速度",
- "agentDetail.monitoring.metrics.tokenUsage.explanation": "此智能體在工作流程執行中產生的預估 token 成本。",
+ "agentDetail.monitoring.metrics.tokenUsage.explanation": "此 Agent 在工作流程執行中產生的預估 token 成本。",
"agentDetail.monitoring.metrics.tokenUsage.title": "Token 用量",
- "agentDetail.monitoring.metrics.totalConversations.explanation": "透過所選存取入口觸達此智能體的每日 AI 會話數。",
+ "agentDetail.monitoring.metrics.totalConversations.explanation": "透過所選存取入口觸達此 Agent 的每日 AI 會話數。",
"agentDetail.monitoring.metrics.totalConversations.title": "全部會話數",
- "agentDetail.monitoring.metrics.totalMessages.explanation": "每日智能體互動總次數。",
+ "agentDetail.monitoring.metrics.totalMessages.explanation": "每日 Agent 互動總次數。",
"agentDetail.monitoring.metrics.totalMessages.title": "全部訊息數",
"agentDetail.monitoring.metrics.userSatisfactionRate.explanation": "每 1,000 條訊息的按讚數,反映使用者滿意度。",
"agentDetail.monitoring.metrics.userSatisfactionRate.title": "使用者滿意度",
@@ -276,24 +310,24 @@
"agentDetail.monitoring.title": "監控",
"agentDetail.monitoring.tokenUsageConsumed": "消耗 Tokens",
"agentDetail.monitoring.units.tokenPerSecond": "Token/秒",
- "agentDetail.navigationLabel": "智能體導覽",
+ "agentDetail.navigationLabel": "Agent 導覽",
"agentDetail.publish": "發佈",
"agentDetail.sections.access": "存取點",
- "agentDetail.sections.configure": "編排",
+ "agentDetail.sections.configure": "配置",
"agentDetail.sections.logs": "日誌",
"agentDetail.sections.monitoring": "監控",
- "agentDetail.title": "智能體",
- "agentDetail.type": "智能體",
+ "agentDetail.title": "Agent",
+ "agentDetail.type": "Agent",
"agentDetail.versionHistory.empty": "暫無版本",
"agentDetail.versionHistory.exitVersions": "退出版本",
"agentDetail.versionHistory.filter": "篩選版本",
"agentDetail.versionHistory.restore": "還原",
"agentDetail.versionHistory.versionName": "版本 {{version}}",
"agentDetail.versionHistory.viewOnly": "唯讀",
- "roster.createAgent": "建立智能體",
- "roster.createDialog.description": "在目前工作區 Roster 中建立一個可複用智能體。",
- "roster.createDialog.title": "建立智能體",
- "roster.createForm.changeIcon": "更換智能體圖示",
+ "roster.createAgent": "建立 Agent",
+ "roster.createDialog.description": "在目前工作區 Roster 中建立一個可複用 Agent。",
+ "roster.createDialog.title": "建立 Agent",
+ "roster.createForm.changeIcon": "更換 Agent 圖示",
"roster.createForm.descriptionLabel": "描述",
"roster.createForm.descriptionPlaceholder": "例如:收集某個主題的來源資料並總結關鍵發現",
"roster.createForm.nameLabel": "名稱",
@@ -302,43 +336,48 @@
"roster.createForm.roleLabel": "角色",
"roster.createForm.rolePlaceholder": "例如:研究助理",
"roster.createForm.roleRequired": "請輸入角色。",
- "roster.createSuccess": "智能體已建立。",
+ "roster.createSuccess": "Agent 已建立。",
"roster.dateTimeFormat": "YYYY-MM-DD HH:mm:ss",
- "roster.deleteDialog.description": "此智能體將從目前活躍 Roster 清單中移除。",
+ "roster.deleteDialog.description": "此 Agent 將從目前活躍 Roster 清單中移除。",
"roster.deleteDialog.title": "刪除 {{name}}?",
- "roster.deleteFailed": "智能體刪除失敗。",
- "roster.deleteSuccess": "智能體已刪除。",
+ "roster.deleteFailed": "Agent 刪除失敗。",
+ "roster.deleteSuccess": "Agent 已刪除。",
"roster.duplicateDialog.description": "建立 {{name}} 的副本,並自訂它在 Roster 中的身份資訊。",
- "roster.duplicateDialog.title": "複製智能體",
+ "roster.duplicateDialog.title": "複製 Agent",
"roster.duplicateForm.changeIcon": "更換 {{name}} 副本的圖示",
- "roster.duplicateSuccess": "智能體已複製。",
+ "roster.duplicateSuccess": "Agent 已複製。",
"roster.editAgent": "編輯 {{name}}",
- "roster.editDialog.description": "更新此智能體在 Roster 中的名稱、描述和角色。",
- "roster.editDialog.title": "編輯智能體",
+ "roster.editDialog.description": "更新此 Agent 在 Roster 中的名稱、描述和角色。",
+ "roster.editDialog.title": "編輯 Agent",
"roster.editInfo": "編輯資訊",
- "roster.empty": "暫無智能體",
- "roster.emptySearch": "沒有符合的智能體",
+ "roster.empty": "暫無 Agent",
+ "roster.emptySearch": "沒有符合的 Agent",
"roster.filters.all": "全部",
"roster.filters.drafts": "草稿",
- "roster.filters.label": "智能體篩選",
+ "roster.filters.label": "Agent 篩選",
"roster.filters.published": "已發佈",
- "roster.learnMore": "了解 Agent Roster",
- "roster.listLabel": "智能體 Roster 清單",
+ "roster.learnMore": "了解 Agent 名冊",
+ "roster.listLabel": "Agent 名冊清單",
"roster.loadMore": "載入更多",
- "roster.loadingError": "智能體載入失敗。請重新整理後再試。",
+ "roster.loadingError": "Agent 載入失敗。請重新整理後再試。",
"roster.moreActions": "{{name}} 的更多操作",
- "roster.nodeSelector.createInlineFailed": "Inline 智能體建立失敗。請重新整理後再試。",
- "roster.nodeSelector.dialogLabel": "選擇智能體",
- "roster.nodeSelector.manageInAgentConsole": "在智能體控制台管理",
+ "roster.nodeSelector.createInlineFailed": "Inline Agent 建立失敗。請重新整理後再試。",
+ "roster.nodeSelector.dialogLabel": "選擇 Agent",
+ "roster.nodeSelector.manageInAgentConsole": "在 Agent Console 管理",
"roster.nodeSelector.searchPlaceholder": "搜尋…",
"roster.nodeSelector.startFromScratch": "從空白開始",
"roster.references.label": "使用 {{name}} 的工作流程",
"roster.references.trigger": "使用 {{name}} 的工作流程",
- "roster.searchLabel": "搜尋智能體",
- "roster.searchPlaceholder": "依名稱搜尋智能體…",
- "roster.tabs.agent": "智能體",
+ "roster.saveToRoster": "儲存到 Agent Console",
+ "roster.saveToRosterDialog.description": "將此內聯設定儲存為可重用的 Roster Agent。",
+ "roster.saveToRosterDialog.title": "儲存到 Agent Console",
+ "roster.saveToRosterForm.changeIcon": "更換 Roster Agent 圖示",
+ "roster.saveToRosterSuccess": "Agent 已儲存到 Roster。",
+ "roster.searchLabel": "搜尋 Agent",
+ "roster.searchPlaceholder": "依名稱搜尋 Agent…",
+ "roster.tabs.agent": "Agent",
"roster.tabs.human": "人工成員",
"roster.tabsLabel": "Roster 類型",
- "roster.updateSuccess": "智能體已更新。",
+ "roster.updateSuccess": "Agent 已更新。",
"roster.usageStatus.draft": "草稿"
}
diff --git a/web/i18n/zh-Hant/common.json b/web/i18n/zh-Hant/common.json
index 90138628ea5..a708dafa564 100644
--- a/web/i18n/zh-Hant/common.json
+++ b/web/i18n/zh-Hant/common.json
@@ -287,7 +287,8 @@
"menus.explore": "探索",
"menus.exploreMarketplace": "探索 Marketplace",
"menus.plugins": "集成",
- "menus.roster": "智能體名冊",
+ "menus.roster": "Agent 名冊",
+ "menus.status": "beta",
"menus.tools": "工具",
"model.capabilities": "多模式功能",
"model.params.stop_sequencesPlaceholder": "輸入序列並按 Tab 鍵",
diff --git a/web/i18n/zh-Hant/workflow.json b/web/i18n/zh-Hant/workflow.json
index 8f1c29fd432..42263ab9252 100644
--- a/web/i18n/zh-Hant/workflow.json
+++ b/web/i18n/zh-Hant/workflow.json
@@ -444,7 +444,7 @@
"nodes.agent.roster.inlineSetup.name": "內聯設定",
"nodes.agent.roster.inlineSetup.title": "Agent 設定",
"nodes.agent.roster.inlineSetup.type": "僅在此節點中",
- "nodes.agent.roster.label": "智能體",
+ "nodes.agent.roster.label": "Agent",
"nodes.agent.roster.makeCopy": "建立副本",
"nodes.agent.roster.more": "更多 Agent 操作",
"nodes.agent.roster.openPanel": "開啟 {{name}} 詳情",
@@ -464,7 +464,7 @@
"nodes.agent.task.label": "Agent 任務",
"nodes.agent.task.mention": "提及",
"nodes.agent.task.placeholder": "描述這個 Agent 要完成的任務...",
- "nodes.agent.task.tooltip": "定義該 Agent 在目前工作流程中需要遵循的任務指令。",
+ "nodes.agent.task.tooltip": "幫助 Agent 處理目前節點的附加提示詞。使用 / 明確引用變數。\n如果設定得當,你可以信任 Agent 自行判斷如何完成任務。",
"nodes.agent.toolNotAuthorizedTooltip": "{{tool}} 未授權",
"nodes.agent.toolNotInstallTooltip": "{{tool}} 未安裝",
"nodes.agent.toolbox": "工具箱",
diff --git a/web/proxy.ts b/web/proxy.ts
index 354f8306192..8288bea5f23 100644
--- a/web/proxy.ts
+++ b/web/proxy.ts
@@ -8,11 +8,17 @@ import { env } from '@/env'
const NECESSARY_DOMAIN = '*.sentry.io http://localhost:* http://127.0.0.1:* https://analytics.google.com googletagmanager.com *.googletagmanager.com https://www.google-analytics.com https://ungh.cc https://api2.amplitude.com *.amplitude.com'
const CURRENT_PATHNAME_HEADER = 'x-dify-pathname'
const CURRENT_SEARCH_HEADER = 'x-dify-search'
+const EMBEDDABLE_PATH_PREFIXES = ['/chat', '/workflow', '/completion', '/webapp-signin']
+const EMBEDDABLE_PATH_SEGMENTS = ['/agent']
+
+export const canEmbedPath = (pathname: string) =>
+ EMBEDDABLE_PATH_PREFIXES.some(prefix => pathname.startsWith(prefix))
+ || EMBEDDABLE_PATH_SEGMENTS.some(segment => pathname === segment || pathname.startsWith(`${segment}/`))
const wrapResponseWithXFrameOptions = (response: NextResponse, pathname: string) => {
// prevent clickjacking: https://owasp.org/www-community/attacks/Clickjacking
// Chatbot page should be allowed to be embedded in iframe. It's a feature
- if (env.NEXT_PUBLIC_ALLOW_EMBED !== true && !pathname.startsWith('/chat') && !pathname.startsWith('/workflow') && !pathname.startsWith('/completion') && !pathname.startsWith('/webapp-signin'))
+ if (env.NEXT_PUBLIC_ALLOW_EMBED !== true && !canEmbedPath(pathname))
response.headers.set('X-Frame-Options', 'DENY')
return response
diff --git a/web/public/embed.js b/web/public/embed.js
index f7c6fdaf4a8..945058e975a 100644
--- a/web/public/embed.js
+++ b/web/public/embed.js
@@ -133,6 +133,7 @@
const baseUrl =
config.baseUrl || `https://${config.isDev ? "dev." : ""}udify.app`;
+ const routeSegment = (config.routeSegment || "chatbot").replace(/^\/+|\/+$/g, "") || "chatbot";
const targetOrigin = new URL(baseUrl).origin;
// Pass sendOnEnter config as URL parameter
@@ -141,7 +142,7 @@
}
// pre-check the length of the URL
- const iframeUrl = `${baseUrl}/chatbot/${config.token}?${params}`;
+ const iframeUrl = `${baseUrl}/${routeSegment}/${config.token}?${params}`;
// 1) CREATE the iframe immediately, so it can load in the background:
const preloadedIframe = createIframe();
// 2) HIDE it by default:
diff --git a/web/public/embed.min.js b/web/public/embed.min.js
index 7c366f8f2eb..afbd1d24fed 100644
--- a/web/public/embed.min.js
+++ b/web/public/embed.min.js
@@ -1,17 +1,11 @@
-(function(){const configKey="difyChatbotConfig";const buttonId="dify-chatbot-bubble-button";const iframeId="dify-chatbot-bubble-window";const config=window[configKey];let isExpanded=false;const svgIcons=`<svg id="openIcon" width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
- <path fill-rule="evenodd" clip-rule="evenodd" d="M7.7586 2L16.2412 2C17.0462 1.99999 17.7105 1.99998 18.2517 2.04419C18.8138 2.09012 19.3305 2.18868 19.8159 2.43598C20.5685 2.81947 21.1804 3.43139 21.5639 4.18404C21.8112 4.66937 21.9098 5.18608 21.9557 5.74818C21.9999 6.28937 21.9999 6.95373 21.9999 7.7587L22 14.1376C22.0004 14.933 22.0007 15.5236 21.8636 16.0353C21.4937 17.4156 20.4155 18.4938 19.0352 18.8637C18.7277 18.9461 18.3917 18.9789 17.9999 18.9918L17.9999 20.371C18 20.6062 18 20.846 17.9822 21.0425C17.9651 21.2305 17.9199 21.5852 17.6722 21.8955C17.3872 22.2525 16.9551 22.4602 16.4983 22.4597C16.1013 22.4593 15.7961 22.273 15.6386 22.1689C15.474 22.06 15.2868 21.9102 15.1031 21.7632L12.69 19.8327C12.1714 19.4178 12.0174 19.3007 11.8575 19.219C11.697 19.137 11.5262 19.0771 11.3496 19.0408C11.1737 19.0047 10.9803 19 10.3162 19H7.75858C6.95362 19 6.28927 19 5.74808 18.9558C5.18598 18.9099 4.66928 18.8113 4.18394 18.564C3.43129 18.1805 2.81937 17.5686 2.43588 16.816C2.18859 16.3306 2.09002 15.8139 2.0441 15.2518C1.99988 14.7106 1.99989 14.0463 1.9999 13.2413V7.75868C1.99989 6.95372 1.99988 6.28936 2.0441 5.74818C2.09002 5.18608 2.18859 4.66937 2.43588 4.18404C2.81937 3.43139 3.43129 2.81947 4.18394 2.43598C4.66928 2.18868 5.18598 2.09012 5.74808 2.04419C6.28927 1.99998 6.95364 1.99999 7.7586 2ZM10.5073 7.5C10.5073 6.67157 9.83575 6 9.00732 6C8.1789 6 7.50732 6.67157 7.50732 7.5C7.50732 8.32843 8.1789 9 9.00732 9C9.83575 9 10.5073 8.32843 10.5073 7.5ZM16.6073 11.7001C16.1669 11.3697 15.5426 11.4577 15.2105 11.8959C15.1488 11.9746 15.081 12.0486 15.0119 12.1207C14.8646 12.2744 14.6432 12.4829 14.3566 12.6913C13.7796 13.111 12.9818 13.5001 12.0073 13.5001C11.0328 13.5001 10.235 13.111 9.65799 12.6913C9.37138 12.4829 9.15004 12.2744 9.00274 12.1207C8.93366 12.0486 8.86581 11.9745 8.80418 11.8959C8.472 11.4577 7.84775 11.3697 7.40732 11.7001C6.96549 12.0314 6.87595 12.6582 7.20732 13.1001C7.20479 13.0968 7.21072 13.1043 7.22094 13.1171C7.24532 13.1478 7.29407 13.2091 7.31068 13.2289C7.36932 13.2987 7.45232 13.3934 7.55877 13.5045C7.77084 13.7258 8.08075 14.0172 8.48165 14.3088C9.27958 14.8891 10.4818 15.5001 12.0073 15.5001C13.5328 15.5001 14.735 14.8891 15.533 14.3088C15.9339 14.0172 16.2438 13.7258 16.4559 13.5045C16.5623 13.3934 16.6453 13.2987 16.704 13.2289C16.7333 13.1939 16.7567 13.165 16.7739 13.1432C17.1193 12.6969 17.0729 12.0493 16.6073 11.7001ZM15.0073 6C15.8358 6 16.5073 6.67157 16.5073 7.5C16.5073 8.32843 15.8358 9 15.0073 9C14.1789 9 13.5073 8.32843 13.5073 7.5C13.5073 6.67157 14.1789 6 15.0073 6Z" fill="white"/>
- </svg>
- <svg id="closeIcon" style="display:none" width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
- <path d="M18 18L6 6M6 18L18 6" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
- </svg>
- `;const originalIframeStyleText=`
+(()=>{let t="difyChatbotConfig",m="dify-chatbot-bubble-button",h="dify-chatbot-bubble-window",y=window[t],l=!1,c=`
position: absolute;
display: flex;
flex-direction: column;
justify-content: space-between;
top: unset;
- right: var(--${buttonId}-right, 1rem); /* Align with dify-chatbot-bubble-button. */
- bottom: var(--${buttonId}-bottom, 1rem); /* Align with dify-chatbot-bubble-button. */
+ right: var(--${m}-right, 1rem); /* Align with dify-chatbot-bubble-button. */
+ bottom: var(--${m}-bottom, 1rem); /* Align with dify-chatbot-bubble-button. */
left: unset;
width: 24rem;
max-width: calc(100vw - 2rem);
@@ -25,42 +19,25 @@
transition-property: width, height;
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
transition-duration: 150ms;
- `;const expandedIframeStyleText=`
- position: absolute;
- display: flex;
- flex-direction: column;
- justify-content: space-between;
- top: unset;
- right: var(--${buttonId}-right, 1rem); /* Align with dify-chatbot-bubble-button. */
- bottom: var(--${buttonId}-bottom, 1rem); /* Align with dify-chatbot-bubble-button. */
- left: unset;
- min-width: 24rem;
- width: 48%;
- max-width: 40rem; /* Match mobile breakpoint*/
- min-height: 43.75rem;
- height: 88%;
- max-height: calc(100vh - 6rem);
- border: none;
- border-radius: 1rem;
- z-index: 2147483640;
- overflow: hidden;
- user-select: none;
- transition-property: width, height;
- transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
- transition-duration: 150ms;
- `;async function embedChatbot(){let isDragging=false;if(!config||!config.token){console.error(`${configKey} is empty or token is not provided`);return}async function compressAndEncodeBase64(input){const uint8Array=(new TextEncoder).encode(input);const compressedStream=new Response(new Blob([uint8Array]).stream().pipeThrough(new CompressionStream("gzip"))).arrayBuffer();const compressedUint8Array=new Uint8Array(await compressedStream);return btoa(String.fromCharCode(...compressedUint8Array))}async function getCompressedInputsFromConfig(){const inputs=config?.inputs||{};const compressedInputs={};await Promise.all(Object.entries(inputs).map(async([key,value])=>{compressedInputs[key]=await compressAndEncodeBase64(value)}));return compressedInputs}async function getCompressedSystemVariablesFromConfig(){const systemVariables=config?.systemVariables||{};const compressedSystemVariables={};await Promise.all(Object.entries(systemVariables).map(async([key,value])=>{compressedSystemVariables[`sys.${key}`]=await compressAndEncodeBase64(value)}));return compressedSystemVariables}async function getCompressedUserVariablesFromConfig(){const userVariables=config?.userVariables||{};const compressedUserVariables={};await Promise.all(Object.entries(userVariables).map(async([key,value])=>{compressedUserVariables[`user.${key}`]=await compressAndEncodeBase64(value)}));return compressedUserVariables}const params=new URLSearchParams({...await getCompressedInputsFromConfig(),...await getCompressedSystemVariablesFromConfig(),...await getCompressedUserVariablesFromConfig()});const baseUrl=config.baseUrl||`https://${config.isDev?"dev.":""}udify.app`;const targetOrigin=new URL(baseUrl).origin;if(config.sendOnEnter===false){params.set("sendOnEnter","false")}const iframeUrl=`${baseUrl}/chatbot/${config.token}?${params}`;const preloadedIframe=createIframe();preloadedIframe.style.display="none";document.body.appendChild(preloadedIframe);if(iframeUrl.length>2048){console.error("The URL is too long, please reduce the number of inputs to prevent the bot from failing to load")}function createIframe(){const iframe=document.createElement("iframe");iframe.allow="fullscreen;microphone";iframe.title="dify chatbot bubble window";iframe.id=iframeId;iframe.src=iframeUrl;iframe.style.cssText=originalIframeStyleText;return iframe}function resetIframePosition(){if(window.innerWidth<=640)return;const targetIframe=document.getElementById(iframeId);const targetButton=document.getElementById(buttonId);if(targetIframe&&targetButton){const buttonRect=targetButton.getBoundingClientRect();const viewportCenterY=window.innerHeight/2;const buttonCenterY=buttonRect.top+buttonRect.height/2;if(buttonCenterY<viewportCenterY){targetIframe.style.top=`var(--${buttonId}-bottom, 1rem)`;targetIframe.style.bottom="unset"}else{targetIframe.style.bottom=`var(--${buttonId}-bottom, 1rem)`;targetIframe.style.top="unset"}const viewportCenterX=window.innerWidth/2;const buttonCenterX=buttonRect.left+buttonRect.width/2;if(buttonCenterX<viewportCenterX){targetIframe.style.left=`var(--${buttonId}-right, 1rem)`;targetIframe.style.right="unset"}else{targetIframe.style.right=`var(--${buttonId}-right, 1rem)`;targetIframe.style.left="unset"}}}function toggleExpand(){isExpanded=!isExpanded;const targetIframe=document.getElementById(iframeId);if(!targetIframe)return;if(isExpanded){targetIframe.style.cssText=expandedIframeStyleText}else{targetIframe.style.cssText=originalIframeStyleText}resetIframePosition()}window.addEventListener("message",event=>{if(event.origin!==targetOrigin)return;const targetIframe=document.getElementById(iframeId);if(!targetIframe||event.source!==targetIframe.contentWindow)return;if(event.data.type==="dify-chatbot-iframe-ready"){targetIframe.contentWindow?.postMessage({type:"dify-chatbot-config",payload:{isToggledByButton:true,isDraggable:!!config.draggable}},targetOrigin)}if(event.data.type==="dify-chatbot-expand-change"){toggleExpand()}});function createButton(){const containerDiv=document.createElement("div");Object.entries(config.containerProps||{}).forEach(([key,value])=>{if(key==="className"){containerDiv.classList.add(...value.split(" "))}else if(key==="style"){if(typeof value==="object"){Object.assign(containerDiv.style,value)}else{containerDiv.style.cssText=value}}else if(typeof value==="function"){containerDiv.addEventListener(key.replace(/^on/,"").toLowerCase(),value)}else{containerDiv[key]=value}});containerDiv.id=buttonId;const styleSheet=document.createElement("style");document.head.appendChild(styleSheet);styleSheet.sheet.insertRule(`
- #${containerDiv.id} {
+ `;async function e(){let u=!1;if(y&&y.token){var e=new URLSearchParams({...await(async()=>{var e=y?.inputs||{};let n={};return await Promise.all(Object.entries(e).map(async([e,t])=>{n[e]=await r(t)})),n})(),...await(async()=>{var e=y?.systemVariables||{};let n={};return await Promise.all(Object.entries(e).map(async([e,t])=>{n["sys."+e]=await r(t)})),n})(),...await(async()=>{var e=y?.userVariables||{};let n={};return await Promise.all(Object.entries(e).map(async([e,t])=>{n["user."+e]=await r(t)})),n})()}),n=y.baseUrl||`https://${y.isDev?"dev.":""}udify.app`,i=(y.routeSegment||"chatbot").replace(/^\/+|\/+$/g,"")||"chatbot";let o=new URL(n).origin,t=(!1===y.sendOnEnter&&e.set("sendOnEnter","false"),`${n}/${i}/${y.token}?`+e);n=s();async function r(e){e=(new TextEncoder).encode(e),e=new Response(new Blob([e]).stream().pipeThrough(new CompressionStream("gzip"))).arrayBuffer(),e=new Uint8Array(await e);return btoa(String.fromCharCode(...e))}function s(){var e=document.createElement("iframe");return e.allow="fullscreen;microphone",e.title="dify chatbot bubble window",e.id=h,e.src=t,e.style.cssText=c,e}function d(){var e,t,n;window.innerWidth<=640||(e=document.getElementById(h),t=document.getElementById(m),e&&t&&(t=t.getBoundingClientRect(),n=window.innerHeight/2,t.top+t.height/2<n?(e.style.top=`var(--${m}-bottom, 1rem)`,e.style.bottom="unset"):(e.style.bottom=`var(--${m}-bottom, 1rem)`,e.style.top="unset"),t.left+t.width/2<window.innerWidth/2?(e.style.left=`var(--${m}-right, 1rem)`,e.style.right="unset"):(e.style.right=`var(--${m}-right, 1rem)`,e.style.left="unset")))}function a(){let n=document.createElement("div");Object.entries(y.containerProps||{}).forEach(([e,t])=>{"className"===e?n.classList.add(...t.split(" ")):"style"===e?"object"==typeof t?Object.assign(n.style,t):n.style.cssText=t:"function"==typeof t?n.addEventListener(e.replace(/^on/,"").toLowerCase(),t):n[e]=t}),n.id=m;var e=document.createElement("style"),e=(document.head.appendChild(e),e.sheet.insertRule(`
+ #${n.id} {
position: fixed;
- bottom: var(--${containerDiv.id}-bottom, 1rem);
- right: var(--${containerDiv.id}-right, 1rem);
- left: var(--${containerDiv.id}-left, unset);
- top: var(--${containerDiv.id}-top, unset);
- width: var(--${containerDiv.id}-width, 48px);
- height: var(--${containerDiv.id}-height, 48px);
- border-radius: var(--${containerDiv.id}-border-radius, 25px);
- background-color: var(--${containerDiv.id}-bg-color, #155EEF);
- box-shadow: var(--${containerDiv.id}-box-shadow, rgba(0, 0, 0, 0.2) 0px 4px 8px 0px);
+ bottom: var(--${n.id}-bottom, 1rem);
+ right: var(--${n.id}-right, 1rem);
+ left: var(--${n.id}-left, unset);
+ top: var(--${n.id}-top, unset);
+ width: var(--${n.id}-width, 48px);
+ height: var(--${n.id}-height, 48px);
+ border-radius: var(--${n.id}-border-radius, 25px);
+ background-color: var(--${n.id}-bg-color, #155EEF);
+ box-shadow: var(--${n.id}-box-shadow, rgba(0, 0, 0, 0.2) 0px 4px 8px 0px);
cursor: pointer;
z-index: 2147483647;
}
- `);const displayDiv=document.createElement("div");displayDiv.style.cssText="position: relative; display: flex; align-items: center; justify-content: center; width: 100%; height: 100%; z-index: 2147483647;";displayDiv.innerHTML=svgIcons;containerDiv.appendChild(displayDiv);document.body.appendChild(containerDiv);containerDiv.addEventListener("click",handleClick);containerDiv.addEventListener("touchend",event=>{event.preventDefault();handleClick()},{passive:false});function handleClick(){if(isDragging)return;const targetIframe=document.getElementById(iframeId);if(!targetIframe){containerDiv.appendChild(createIframe());resetIframePosition();this.title="Exit (ESC)";setSvgIcon("close");document.addEventListener("keydown",handleEscKey);return}targetIframe.style.display=targetIframe.style.display==="none"?"block":"none";targetIframe.style.display==="none"?setSvgIcon("open"):setSvgIcon("close");if(targetIframe.style.display==="none"){document.removeEventListener("keydown",handleEscKey)}else{document.addEventListener("keydown",handleEscKey)}resetIframePosition()}if(config.draggable){enableDragging(containerDiv,config.dragAxis||"both")}}function enableDragging(element,axis){let startX,startY,startClientX,startClientY;element.addEventListener("mousedown",startDragging);element.addEventListener("touchstart",startDragging);function startDragging(e){isDragging=false;if(e.type==="touchstart"){startX=e.touches[0].clientX-element.offsetLeft;startY=e.touches[0].clientY-element.offsetTop;startClientX=e.touches[0].clientX;startClientY=e.touches[0].clientY}else{startX=e.clientX-element.offsetLeft;startY=e.clientY-element.offsetTop;startClientX=e.clientX;startClientY=e.clientY}document.addEventListener("mousemove",drag);document.addEventListener("touchmove",drag,{passive:false});document.addEventListener("mouseup",stopDragging);document.addEventListener("touchend",stopDragging);e.preventDefault()}function drag(e){const touch=e.type==="touchmove"?e.touches[0]:e;const deltaX=touch.clientX-startClientX;const deltaY=touch.clientY-startClientY;if(Math.abs(deltaX)>8||Math.abs(deltaY)>8){isDragging=true}if(!isDragging)return;element.style.transition="none";element.style.cursor="grabbing";const targetIframe=document.getElementById(iframeId);if(targetIframe){targetIframe.style.display="none";setSvgIcon("open")}let newLeft,newBottom;if(e.type==="touchmove"){newLeft=e.touches[0].clientX-startX;newBottom=window.innerHeight-e.touches[0].clientY-startY}else{newLeft=e.clientX-startX;newBottom=window.innerHeight-e.clientY-startY}const elementRect=element.getBoundingClientRect();const maxX=window.innerWidth-elementRect.width;const maxY=window.innerHeight-elementRect.height;if(axis==="x"||axis==="both"){element.style.setProperty(`--${buttonId}-left`,`${Math.max(0,Math.min(newLeft,maxX))}px`)}if(axis==="y"||axis==="both"){element.style.setProperty(`--${buttonId}-bottom`,`${Math.max(0,Math.min(newBottom,maxY))}px`)}}function stopDragging(){setTimeout(()=>{isDragging=false},0);element.style.transition="";element.style.cursor="pointer";document.removeEventListener("mousemove",drag);document.removeEventListener("touchmove",drag);document.removeEventListener("mouseup",stopDragging);document.removeEventListener("touchend",stopDragging)}}if(!document.getElementById(buttonId)){createButton()}}function setSvgIcon(type="open"){if(type==="open"){document.getElementById("openIcon").style.display="block";document.getElementById("closeIcon").style.display="none"}else{document.getElementById("openIcon").style.display="none";document.getElementById("closeIcon").style.display="block"}}function handleEscKey(event){if(event.key==="Escape"){const targetIframe=document.getElementById(iframeId);if(targetIframe&&targetIframe.style.display!=="none"){targetIframe.style.display="none";setSvgIcon("open")}}}document.addEventListener("keydown",handleEscKey);if(config?.dynamicScript){embedChatbot()}else{document.body.onload=embedChatbot}})();
\ No newline at end of file
+ `),document.createElement("div"));function t(){var e;u||((e=document.getElementById(h))?(e.style.display="none"===e.style.display?"block":"none","none"===e.style.display?p("open"):p("close"),"none"===e.style.display?document.removeEventListener("keydown",b):document.addEventListener("keydown",b),d()):(n.appendChild(s()),d(),this.title="Exit (ESC)",p("close"),document.addEventListener("keydown",b)))}if(e.style.cssText="position: relative; display: flex; align-items: center; justify-content: center; width: 100%; height: 100%; z-index: 2147483647;",e.innerHTML=`<svg id="openIcon" width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path fill-rule="evenodd" clip-rule="evenodd" d="M7.7586 2L16.2412 2C17.0462 1.99999 17.7105 1.99998 18.2517 2.04419C18.8138 2.09012 19.3305 2.18868 19.8159 2.43598C20.5685 2.81947 21.1804 3.43139 21.5639 4.18404C21.8112 4.66937 21.9098 5.18608 21.9557 5.74818C21.9999 6.28937 21.9999 6.95373 21.9999 7.7587L22 14.1376C22.0004 14.933 22.0007 15.5236 21.8636 16.0353C21.4937 17.4156 20.4155 18.4938 19.0352 18.8637C18.7277 18.9461 18.3917 18.9789 17.9999 18.9918L17.9999 20.371C18 20.6062 18 20.846 17.9822 21.0425C17.9651 21.2305 17.9199 21.5852 17.6722 21.8955C17.3872 22.2525 16.9551 22.4602 16.4983 22.4597C16.1013 22.4593 15.7961 22.273 15.6386 22.1689C15.474 22.06 15.2868 21.9102 15.1031 21.7632L12.69 19.8327C12.1714 19.4178 12.0174 19.3007 11.8575 19.219C11.697 19.137 11.5262 19.0771 11.3496 19.0408C11.1737 19.0047 10.9803 19 10.3162 19H7.75858C6.95362 19 6.28927 19 5.74808 18.9558C5.18598 18.9099 4.66928 18.8113 4.18394 18.564C3.43129 18.1805 2.81937 17.5686 2.43588 16.816C2.18859 16.3306 2.09002 15.8139 2.0441 15.2518C1.99988 14.7106 1.99989 14.0463 1.9999 13.2413V7.75868C1.99989 6.95372 1.99988 6.28936 2.0441 5.74818C2.09002 5.18608 2.18859 4.66937 2.43588 4.18404C2.81937 3.43139 3.43129 2.81947 4.18394 2.43598C4.66928 2.18868 5.18598 2.09012 5.74808 2.04419C6.28927 1.99998 6.95364 1.99999 7.7586 2ZM10.5073 7.5C10.5073 6.67157 9.83575 6 9.00732 6C8.1789 6 7.50732 6.67157 7.50732 7.5C7.50732 8.32843 8.1789 9 9.00732 9C9.83575 9 10.5073 8.32843 10.5073 7.5ZM16.6073 11.7001C16.1669 11.3697 15.5426 11.4577 15.2105 11.8959C15.1488 11.9746 15.081 12.0486 15.0119 12.1207C14.8646 12.2744 14.6432 12.4829 14.3566 12.6913C13.7796 13.111 12.9818 13.5001 12.0073 13.5001C11.0328 13.5001 10.235 13.111 9.65799 12.6913C9.37138 12.4829 9.15004 12.2744 9.00274 12.1207C8.93366 12.0486 8.86581 11.9745 8.80418 11.8959C8.472 11.4577 7.84775 11.3697 7.40732 11.7001C6.96549 12.0314 6.87595 12.6582 7.20732 13.1001C7.20479 13.0968 7.21072 13.1043 7.22094 13.1171C7.24532 13.1478 7.29407 13.2091 7.31068 13.2289C7.36932 13.2987 7.45232 13.3934 7.55877 13.5045C7.77084 13.7258 8.08075 14.0172 8.48165 14.3088C9.27958 14.8891 10.4818 15.5001 12.0073 15.5001C13.5328 15.5001 14.735 14.8891 15.533 14.3088C15.9339 14.0172 16.2438 13.7258 16.4559 13.5045C16.5623 13.3934 16.6453 13.2987 16.704 13.2289C16.7333 13.1939 16.7567 13.165 16.7739 13.1432C17.1193 12.6969 17.0729 12.0493 16.6073 11.7001ZM15.0073 6C15.8358 6 16.5073 6.67157 16.5073 7.5C16.5073 8.32843 15.8358 9 15.0073 9C14.1789 9 13.5073 8.32843 13.5073 7.5C13.5073 6.67157 14.1789 6 15.0073 6Z" fill="white"/>
+ </svg>
+ <svg id="closeIcon" style="display:none" width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M18 18L6 6M6 18L18 6" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
+ </svg>
+ `,n.appendChild(e),document.body.appendChild(n),n.addEventListener("click",t),n.addEventListener("touchend",e=>{e.preventDefault(),t()},{passive:!1}),y.draggable){var a=n;var l=y.dragAxis||"both";let r,s,t,d;function o(e){u=!1,d=("touchstart"===e.type?(r=e.touches[0].clientX-a.offsetLeft,s=e.touches[0].clientY-a.offsetTop,t=e.touches[0].clientX,e.touches[0]):(r=e.clientX-a.offsetLeft,s=e.clientY-a.offsetTop,t=e.clientX,e)).clientY,document.addEventListener("mousemove",i),document.addEventListener("touchmove",i,{passive:!1}),document.addEventListener("mouseup",c),document.addEventListener("touchend",c),e.preventDefault()}function i(n){var o="touchmove"===n.type?n.touches[0]:n,i=o.clientX-t,o=o.clientY-d;if(u=8<Math.abs(i)||8<Math.abs(o)?!0:u){a.style.transition="none",a.style.cursor="grabbing";i=document.getElementById(h);i&&(i.style.display="none",p("open"));let e,t;t="touchmove"===n.type?(e=n.touches[0].clientX-r,window.innerHeight-n.touches[0].clientY-s):(e=n.clientX-r,window.innerHeight-n.clientY-s);o=a.getBoundingClientRect(),i=window.innerWidth-o.width,n=window.innerHeight-o.height;"x"!==l&&"both"!==l||a.style.setProperty(`--${m}-left`,Math.max(0,Math.min(e,i))+"px"),"y"!==l&&"both"!==l||a.style.setProperty(`--${m}-bottom`,Math.max(0,Math.min(t,n))+"px")}}function c(){setTimeout(()=>{u=!1},0),a.style.transition="",a.style.cursor="pointer",document.removeEventListener("mousemove",i),document.removeEventListener("touchmove",i),document.removeEventListener("mouseup",c),document.removeEventListener("touchend",c)}a.addEventListener("mousedown",o),a.addEventListener("touchstart",o)}}n.style.display="none",document.body.appendChild(n),2048<t.length&&console.error("The URL is too long, please reduce the number of inputs to prevent the bot from failing to load"),window.addEventListener("message",e=>{var t,n;e.origin===o&&(t=document.getElementById(h))&&e.source===t.contentWindow&&("dify-chatbot-iframe-ready"===e.data.type&&t.contentWindow?.postMessage({type:"dify-chatbot-config",payload:{isToggledByButton:!0,isDraggable:!!y.draggable}},o),"dify-chatbot-expand-change"===e.data.type)&&(l=!l,n=document.getElementById(h))&&(l?n.style.cssText="\n position: absolute;\n display: flex;\n flex-direction: column;\n justify-content: space-between;\n top: unset;\n right: var(--dify-chatbot-bubble-button-right, 1rem); /* Align with dify-chatbot-bubble-button. */\n bottom: var(--dify-chatbot-bubble-button-bottom, 1rem); /* Align with dify-chatbot-bubble-button. */\n left: unset;\n min-width: 24rem;\n width: 48%;\n max-width: 40rem; /* Match mobile breakpoint*/\n min-height: 43.75rem;\n height: 88%;\n max-height: calc(100vh - 6rem);\n border: none;\n border-radius: 1rem;\n z-index: 2147483640;\n overflow: hidden;\n user-select: none;\n transition-property: width, height;\n transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);\n transition-duration: 150ms;\n ":n.style.cssText=c,d())}),document.getElementById(m)||a()}else console.error(t+" is empty or token is not provided")}function p(e="open"){"open"===e?(document.getElementById("openIcon").style.display="block",document.getElementById("closeIcon").style.display="none"):(document.getElementById("openIcon").style.display="none",document.getElementById("closeIcon").style.display="block")}function b(e){"Escape"===e.key&&(e=document.getElementById(h))&&"none"!==e.style.display&&(e.style.display="none",p("open"))}m,m,document.addEventListener("keydown",b),y?.dynamicScript?e():document.body.onload=e})();
\ No newline at end of file
diff --git a/web/service/client.spec.ts b/web/service/client.spec.ts
index 414cf37d325..d1c9eab682a 100644
--- a/web/service/client.spec.ts
+++ b/web/service/client.spec.ts
@@ -46,6 +46,8 @@ const createApiBasedExtension = (overrides: Partial<ApiBasedExtensionResponse> =
type AgentMutationResponse = Parameters<NonNullable<ReturnType<typeof ConsoleQuery.agent.post.mutationOptions>['onSuccess']>>[0]
type AgentComposerMutationResponse = Parameters<NonNullable<ReturnType<typeof ConsoleQuery.agent.byAgentId.composer.put.mutationOptions>['onSuccess']>>[0]
+type AgentPublishMutationResponse = Parameters<NonNullable<ReturnType<typeof ConsoleQuery.agent.byAgentId.publish.post.mutationOptions>['onSuccess']>>[0]
+type WorkflowAgentComposerMutationResponse = Parameters<NonNullable<ReturnType<typeof ConsoleQuery.apps.byAppId.workflows.draft.nodes.byNodeId.agentComposer.saveToRoster.post.mutationOptions>['onSuccess']>>[0]
const createAgent = (overrides: Partial<AgentMutationResponse> = {}): AgentMutationResponse => ({
...overrides,
@@ -53,6 +55,7 @@ const createAgent = (overrides: Partial<AgentMutationResponse> = {}): AgentMutat
enable_api: overrides.enable_api ?? true,
enable_site: overrides.enable_site ?? true,
description: overrides.description ?? 'Agent description',
+ hidden_app_backed: overrides.hidden_app_backed ?? false,
id: overrides.id ?? 'agent-1',
icon_url: overrides.icon_url ?? null,
mode: overrides.mode ?? 'agent',
@@ -68,6 +71,7 @@ const createComposerState = (overrides: Partial<AgentComposerMutationResponse> =
agent: {
active_config_snapshot_id: 'snapshot-1',
description: 'Agent description',
+ hidden_app_backed: false,
id: 'agent-1',
name: 'Agent',
scope: 'roster',
@@ -76,11 +80,58 @@ const createComposerState = (overrides: Partial<AgentComposerMutationResponse> =
agent_soul: {
schema_version: 1,
},
+ hidden_app_backed: false,
save_options: ['save_to_current_version', 'save_as_new_version'],
variant: 'agent_app',
...overrides,
})
+const createAgentPublishResponse = (overrides: Partial<AgentPublishMutationResponse> = {}): AgentPublishMutationResponse => ({
+ active_config_snapshot: {
+ id: 'snapshot-1',
+ version: 1,
+ },
+ active_config_snapshot_id: 'snapshot-1',
+ result: 'success',
+ ...overrides,
+})
+
+const createWorkflowComposerState = (overrides: Partial<WorkflowAgentComposerMutationResponse> = {}): WorkflowAgentComposerMutationResponse => ({
+ agent: {
+ active_config_snapshot_id: 'snapshot-1',
+ description: 'Agent description',
+ hidden_app_backed: false,
+ id: 'agent-1',
+ name: 'Agent',
+ scope: 'roster',
+ status: 'active',
+ },
+ agent_soul: {
+ schema_version: 1,
+ },
+ hidden_app_backed: false,
+ binding: {
+ agent_id: 'agent-1',
+ binding_type: 'roster_agent',
+ current_snapshot_id: 'snapshot-1',
+ id: 'binding-1',
+ node_id: 'node-1',
+ workflow_id: 'workflow-1',
+ },
+ node_job: {
+ mode: 'tell_agent_what_to_do',
+ schema_version: 1,
+ workflow_prompt: '',
+ },
+ save_options: ['node_job_only', 'save_as_new_agent'],
+ soul_lock: {
+ can_unlock: false,
+ locked: true,
+ },
+ variant: 'workflow',
+ ...overrides,
+})
+
// Scenario: base URL selection and warnings.
describe('getBaseURL', () => {
beforeEach(() => {
@@ -222,6 +273,145 @@ describe('consoleQuery agent mutation defaults', () => {
})
})
+ it('should cache workflow composer state after copying a roster agent into an inline agent', async () => {
+ const consoleQuery = await loadConsoleQuery()
+ const queryClient = new QueryClient()
+ const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')
+ const composerState = createWorkflowComposerState({
+ binding: {
+ agent_id: 'inline-agent-1',
+ binding_type: 'inline_agent',
+ current_snapshot_id: 'inline-snapshot-1',
+ id: 'binding-1',
+ node_id: 'node-1',
+ workflow_id: 'workflow-1',
+ },
+ })
+
+ const mutationOptions = consoleQuery.apps.byAppId.workflows.draft.nodes.byNodeId.agentComposer.copyFromRoster.post.mutationOptions()
+ await mutationOptions.onSuccess?.(
+ composerState,
+ {
+ params: {
+ app_id: 'app-1',
+ node_id: 'node-1',
+ },
+ body: {
+ source_agent_id: 'roster-agent-1',
+ },
+ },
+ undefined,
+ createMutationContext(queryClient),
+ )
+
+ expect(queryClient.getQueryData(consoleQuery.apps.byAppId.workflows.draft.nodes.byNodeId.agentComposer.get.queryKey({
+ input: {
+ params: {
+ app_id: 'app-1',
+ node_id: 'node-1',
+ },
+ },
+ }))).toEqual(composerState)
+ expect(invalidateQueries).not.toHaveBeenCalledWith({
+ queryKey: consoleQuery.agent.get.key(),
+ })
+ expect(invalidateQueries).not.toHaveBeenCalledWith({
+ queryKey: consoleQuery.agent.inviteOptions.get.key(),
+ })
+ })
+
+ it('should cache workflow composer state after saving workflow node composer', async () => {
+ const consoleQuery = await loadConsoleQuery()
+ const queryClient = new QueryClient()
+ const composerState = createWorkflowComposerState({
+ binding: {
+ agent_id: 'inline-agent-1',
+ binding_type: 'inline_agent',
+ current_snapshot_id: 'inline-snapshot-1',
+ id: 'binding-1',
+ node_id: 'node-1',
+ workflow_id: 'workflow-1',
+ },
+ })
+
+ const mutationOptions = consoleQuery.apps.byAppId.workflows.draft.nodes.byNodeId.agentComposer.put.mutationOptions()
+ await mutationOptions.onSuccess?.(
+ composerState,
+ {
+ params: {
+ app_id: 'app-1',
+ node_id: 'node-1',
+ },
+ body: {
+ variant: 'workflow',
+ save_strategy: 'node_job_only',
+ },
+ },
+ undefined,
+ createMutationContext(queryClient),
+ )
+
+ expect(queryClient.getQueryData(consoleQuery.apps.byAppId.workflows.draft.nodes.byNodeId.agentComposer.get.queryKey({
+ input: {
+ params: {
+ app_id: 'app-1',
+ node_id: 'node-1',
+ },
+ },
+ }))).toEqual(composerState)
+ })
+
+ it('should cache workflow composer state and invalidate roster lists after saving inline agent to roster', async () => {
+ const consoleQuery = await loadConsoleQuery()
+ const queryClient = new QueryClient()
+ const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')
+ const composerState = createWorkflowComposerState()
+
+ const mutationOptions = consoleQuery.apps.byAppId.workflows.draft.nodes.byNodeId.agentComposer.saveToRoster.post.mutationOptions()
+ await mutationOptions.onSuccess?.(
+ composerState,
+ {
+ params: {
+ app_id: 'app-1',
+ node_id: 'node-1',
+ },
+ body: {
+ variant: 'workflow',
+ save_strategy: 'save_to_roster',
+ new_agent_name: 'Saved Agent',
+ description: 'Agent description',
+ role: 'Assistant',
+ },
+ },
+ undefined,
+ createMutationContext(queryClient),
+ )
+
+ expect(queryClient.getQueryData(consoleQuery.apps.byAppId.workflows.draft.nodes.byNodeId.agentComposer.get.queryKey({
+ input: {
+ params: {
+ app_id: 'app-1',
+ node_id: 'node-1',
+ },
+ },
+ }))).toEqual(composerState)
+ expect(invalidateQueries).toHaveBeenCalledWith({
+ queryKey: consoleQuery.agent.get.key(),
+ })
+ expect(invalidateQueries).toHaveBeenCalledWith({
+ queryKey: consoleQuery.agent.inviteOptions.get.key(),
+ })
+ expect(invalidateQueries).toHaveBeenCalledWith({
+ queryKey: consoleQuery.agent.byAgentId.get.queryKey({
+ input: {
+ params: {
+ agent_id: 'agent-1',
+ },
+ },
+ }),
+ })
+ })
+
it('should invalidate invite option lists after updating an agent', async () => {
const consoleQuery = await loadConsoleQuery()
const queryClient = new QueryClient()
@@ -277,6 +467,7 @@ describe('consoleQuery agent mutation defaults', () => {
created_by: null,
description: 'Agent description',
existing_node_ids: [],
+ hidden_app_backed: false,
icon: null,
icon_background: null,
icon_type: null,
@@ -303,20 +494,14 @@ describe('consoleQuery agent mutation defaults', () => {
total: 1,
})
- const mutationOptions = consoleQuery.agent.byAgentId.composer.put.mutationOptions()
+ const mutationOptions = consoleQuery.agent.byAgentId.publish.post.mutationOptions()
await mutationOptions.onSuccess?.(
- createComposerState(),
+ createAgentPublishResponse(),
{
params: {
agent_id: 'agent-1',
},
- body: {
- variant: 'agent_app',
- save_strategy: 'save_as_new_version',
- agent_soul: {
- schema_version: 1,
- },
- },
+ body: {},
},
undefined,
createMutationContext(queryClient),
diff --git a/web/service/client.ts b/web/service/client.ts
index 73c23f60da8..e5c1abc7edf 100644
--- a/web/service/client.ts
+++ b/web/service/client.ts
@@ -347,6 +347,87 @@ export const consoleClient: JsonifiedClient<ContractRouterClient<typeof consoleR
export const consoleQuery: RouterUtils<typeof consoleClient> = createTanstackQueryUtils(consoleClient, {
path: ['console'],
experimental_defaults: {
+ apps: {
+ byAppId: {
+ workflows: {
+ draft: {
+ nodes: {
+ byNodeId: {
+ agentComposer: {
+ put: {
+ mutationOptions: {
+ onSuccess: (composerState, variables, _onMutateResult, context) => {
+ context.client.setQueryData(
+ consoleQuery.apps.byAppId.workflows.draft.nodes.byNodeId.agentComposer.get.queryKey({
+ input: {
+ params: variables.params,
+ },
+ }),
+ composerState,
+ )
+ },
+ },
+ },
+ copyFromRoster: {
+ post: {
+ mutationOptions: {
+ onSuccess: (composerState, variables, _onMutateResult, context) => {
+ context.client.setQueryData(
+ consoleQuery.apps.byAppId.workflows.draft.nodes.byNodeId.agentComposer.get.queryKey({
+ input: {
+ params: variables.params,
+ },
+ }),
+ composerState,
+ )
+ },
+ },
+ },
+ },
+ saveToRoster: {
+ post: {
+ mutationOptions: {
+ onSuccess: (composerState, variables, _onMutateResult, context) => {
+ context.client.setQueryData(
+ consoleQuery.apps.byAppId.workflows.draft.nodes.byNodeId.agentComposer.get.queryKey({
+ input: {
+ params: variables.params,
+ },
+ }),
+ composerState,
+ )
+ context.client.invalidateQueries({
+ queryKey: consoleQuery.agent.get.key(),
+ })
+ context.client.invalidateQueries({
+ queryKey: consoleQuery.agent.inviteOptions.get.key(),
+ })
+
+ const agentId = composerState.binding?.binding_type === 'roster_agent'
+ ? composerState.binding.agent_id
+ : undefined
+ if (agentId) {
+ context.client.invalidateQueries({
+ queryKey: consoleQuery.agent.byAgentId.get.queryKey({
+ input: {
+ params: {
+ agent_id: agentId,
+ },
+ },
+ }),
+ })
+ }
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
+ },
agent: {
post: {
mutationOptions: {
@@ -455,6 +536,23 @@ export const consoleQuery: RouterUtils<typeof consoleClient> = createTanstackQue
},
},
},
+ publish: {
+ post: {
+ mutationOptions: {
+ onSuccess: (_publishResult, _variables, _onMutateResult, context) => {
+ context.client.invalidateQueries({
+ queryKey: consoleQuery.agent.get.key(),
+ })
+ context.client.invalidateQueries({
+ queryKey: consoleQuery.agent.inviteOptions.get.key(),
+ })
+ context.client.removeQueries({
+ queryKey: consoleQuery.agent.inviteOptions.get.key(),
+ })
+ },
+ },
+ },
+ },
delete: {
mutationOptions: {
onSuccess: (_data, variables, _onMutateResult, context) => {