From f6dfedeec00a949c974818325c3732bc9d89f9bc Mon Sep 17 00:00:00 2001 From: Yunlu Wen Date: Fri, 13 Nov 2026 08:30:30 +0000 Subject: [PATCH] feat(chatflow): stream Agent v2 tool activity in chat (#46220) Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- api/core/app/apps/workflow_app_runner.py | 2 +- .../agent/events.py => agent_log_events.py} | 36 + api/core/workflow/nodes/agent/agent_node.py | 15 +- .../nodes/agent/message_transformer.py | 2 +- .../workflow/nodes/agent_v2/agent_node.py | 110 ++- .../workflow/nodes/agent_v2/output_adapter.py | 5 +- .../workflow/nodes/agent_v2/tool_activity.py | 319 +++++++++ .../core/app/apps/test_workflow_app_runner.py | 2 +- .../workflow/nodes/agent/test_agent_node.py | 2 +- .../nodes/agent_v2/test_agent_node.py | 449 +++++++++++- .../nodes/agent_v2/test_tool_activity.py | 657 ++++++++++++++++++ oxlint-suppressions.json | 8 - .../workflow-agent-tool-activity.spec.ts | 161 +++++ .../chat/chat/__tests__/chat-owner-preset.tsx | 2 + .../base/chat/chat/__tests__/hooks.spec.tsx | 266 ++++++- .../workflow-tool-activity.browser.spec.tsx | 293 ++++++++ .../answer/agent-roster-response-content.tsx | 90 +-- .../base/chat/chat/answer/index.tsx | 168 +++-- .../chat/chat/answer/tool-activity-item.tsx | 139 ++++ .../answer/workflow-tool-activity.stories.tsx | 309 ++++++++ .../chat/answer/workflow-tool-activity.tsx | 64 ++ web/app/components/base/chat/chat/hooks.ts | 17 + web/app/components/base/chat/types.ts | 24 + .../base/chat/workflow-agent-tool-activity.ts | 63 ++ .../__tests__/use-workflow-agent-log.spec.ts | 59 +- .../use-workflow-agent-log.ts | 42 +- .../__tests__/hooks/sse-callbacks.spec.ts | 44 +- .../workflow/panel/debug-and-preview/hooks.ts | 74 +- web/i18n/locales/ar-TN/agent-v-2.json | 1 + web/i18n/locales/az-AZ/agent-v-2.json | 1 + web/i18n/locales/de-DE/agent-v-2.json | 1 + web/i18n/locales/en-US/agent-v-2.json | 1 + web/i18n/locales/es-ES/agent-v-2.json | 1 + web/i18n/locales/fa-IR/agent-v-2.json | 1 + web/i18n/locales/fr-FR/agent-v-2.json | 1 + web/i18n/locales/hi-IN/agent-v-2.json | 1 + web/i18n/locales/id-ID/agent-v-2.json | 1 + web/i18n/locales/it-IT/agent-v-2.json | 1 + web/i18n/locales/ja-JP/agent-v-2.json | 1 + web/i18n/locales/ko-KR/agent-v-2.json | 1 + web/i18n/locales/lo-LA/agent-v-2.json | 1 + web/i18n/locales/nl-NL/agent-v-2.json | 1 + web/i18n/locales/pl-PL/agent-v-2.json | 1 + web/i18n/locales/pt-BR/agent-v-2.json | 1 + web/i18n/locales/ro-RO/agent-v-2.json | 1 + web/i18n/locales/ru-RU/agent-v-2.json | 1 + web/i18n/locales/sl-SI/agent-v-2.json | 1 + web/i18n/locales/th-TH/agent-v-2.json | 1 + web/i18n/locales/tr-TR/agent-v-2.json | 1 + web/i18n/locales/uk-UA/agent-v-2.json | 1 + web/i18n/locales/vi-VN/agent-v-2.json | 1 + web/i18n/locales/zh-Hans/agent-v-2.json | 1 + web/i18n/locales/zh-Hant/agent-v-2.json | 1 + web/i18n/resources.generated.d.ts | 1 + web/types/workflow.ts | 14 +- 55 files changed, 3205 insertions(+), 257 deletions(-) rename api/core/workflow/{nodes/agent/events.py => agent_log_events.py} (53%) create mode 100644 api/core/workflow/nodes/agent_v2/tool_activity.py create mode 100644 api/tests/unit_tests/core/workflow/nodes/agent_v2/test_tool_activity.py create mode 100644 web/app/components/base/chat/__tests__/workflow-agent-tool-activity.spec.ts create mode 100644 web/app/components/base/chat/chat/answer/__tests__/workflow-tool-activity.browser.spec.tsx create mode 100644 web/app/components/base/chat/chat/answer/tool-activity-item.tsx create mode 100644 web/app/components/base/chat/chat/answer/workflow-tool-activity.stories.tsx create mode 100644 web/app/components/base/chat/chat/answer/workflow-tool-activity.tsx create mode 100644 web/app/components/base/chat/workflow-agent-tool-activity.ts diff --git a/api/core/app/apps/workflow_app_runner.py b/api/core/app/apps/workflow_app_runner.py index 3df06d4b0df..3268744245d 100644 --- a/api/core/app/apps/workflow_app_runner.py +++ b/api/core/app/apps/workflow_app_runner.py @@ -47,13 +47,13 @@ from core.credit_usage import CreditUsageAppType from core.rag.entities import RetrievalSourceMetadata from core.repositories.factory import WorkflowExecutionRepository, WorkflowNodeExecutionRepository from core.repositories.human_input_repository import HumanInputFormRecord +from core.workflow.agent_log_events import NodeRunAgentLogEvent from core.workflow.node_factory import ( DifyGraphInitContext, DifyNodeFactory, get_default_root_node_id, resolve_workflow_node_class, ) -from core.workflow.nodes.agent.events import NodeRunAgentLogEvent from core.workflow.nodes.human_input.boundary import resolve_human_input_node_id from core.workflow.nodes.human_input.callback import DifyHITLCallback from core.workflow.nodes.human_input.enums import HumanInputFormStatus diff --git a/api/core/workflow/nodes/agent/events.py b/api/core/workflow/agent_log_events.py similarity index 53% rename from api/core/workflow/nodes/agent/events.py rename to api/core/workflow/agent_log_events.py index 24820fdbe40..3222958da55 100644 --- a/api/core/workflow/nodes/agent/events.py +++ b/api/core/workflow/agent_log_events.py @@ -1,9 +1,17 @@ +"""Shared agent-log event contract for Agent v1 and v2 nodes. + +``AgentLogEvent`` is the payload projected by agent node executions and +``NodeRunAgentLogEvent`` is its node-run envelope; ``workflow_app_runner`` +maps the latter to ``QueueAgentLogEvent`` for SSE delivery. +""" + from collections.abc import Mapping from typing import Any from pydantic import Field from graphon.engine_events import NodeEvent +from graphon.enums import NodeType from graphon.node_events import NodeEventPayload @@ -28,3 +36,31 @@ class NodeRunAgentLogEvent(NodeEvent): status: str = Field(..., description="status") data: Mapping[str, object] = Field(..., description="data") metadata: Mapping[str, object] = Field(default_factory=dict) + + +def node_run_agent_log_event( + event: AgentLogEvent, + *, + execution_id: str, + node_id: str, + node_type: NodeType, +) -> NodeRunAgentLogEvent: + """Build the node-run ``agent_log`` event for one projected payload. + + Precondition: ``event`` was emitted by the node's own execution. The + returned event is stamped with the node's execution id, node id, and + node type; every payload field passes through unchanged. + """ + return NodeRunAgentLogEvent( + id=execution_id, + node_id=node_id, + node_type=node_type, + message_id=event.message_id, + label=event.label, + node_execution_id=event.node_execution_id, + parent_id=event.parent_id, + error=event.error, + status=event.status, + data=event.data, + metadata=event.metadata, + ) diff --git a/api/core/workflow/nodes/agent/agent_node.py b/api/core/workflow/nodes/agent/agent_node.py index d5036f09f4c..69cb79a8ecd 100644 --- a/api/core/workflow/nodes/agent/agent_node.py +++ b/api/core/workflow/nodes/agent/agent_node.py @@ -5,6 +5,7 @@ from functools import singledispatchmethod from typing import TYPE_CHECKING, Any, override from core.app.entities.app_invoke_entities import DIFY_RUN_CONTEXT_KEY, DifyRunContext +from core.workflow.agent_log_events import AgentLogEvent, NodeRunAgentLogEvent, node_run_agent_log_event from core.workflow.system_variables import SystemVariableKey, get_system_text from graphon.engine_events import NodeEvent from graphon.enums import BuiltinNodeTypes, WorkflowNodeExecutionStatus @@ -13,7 +14,6 @@ from graphon.nodes.base.node import Node from graphon.nodes.base.variable_template_parser import VariableTemplateParser from .entities import AgentNodeData -from .events import AgentLogEvent, NodeRunAgentLogEvent from .exceptions import ( AgentInvocationError, AgentMessageTransformError, @@ -82,18 +82,11 @@ class AgentNode(Node[AgentNodeData]): @_dispatch.register def _dispatch_agent_log(self, event: AgentLogEvent) -> NodeRunAgentLogEvent: - return NodeRunAgentLogEvent( - id=self.execution_id, + return node_run_agent_log_event( + event, + execution_id=self.execution_id, node_id=self._node_id, node_type=self.node_type, - message_id=event.message_id, - label=event.label, - node_execution_id=event.node_execution_id, - parent_id=event.parent_id, - error=event.error, - status=event.status, - data=event.data, - metadata=event.metadata, ) @override diff --git a/api/core/workflow/nodes/agent/message_transformer.py b/api/core/workflow/nodes/agent/message_transformer.py index de64593159f..432f017ce4f 100644 --- a/api/core/workflow/nodes/agent/message_transformer.py +++ b/api/core/workflow/nodes/agent/message_transformer.py @@ -9,6 +9,7 @@ from sqlalchemy.orm import Session from core.app.file_access import DatabaseFileAccessController from core.tools.entities.tool_entities import ToolInvokeMessage from core.tools.utils.message_transformer import ToolFileMessageTransformer +from core.workflow.agent_log_events import AgentLogEvent from extensions.ext_database import db from factories import file_factory from graphon.enums import BuiltinNodeTypes, NodeType, WorkflowNodeExecutionMetadataKey, WorkflowNodeExecutionStatus @@ -25,7 +26,6 @@ from graphon.variables.segments import ArrayFileSegment from models import ToolFile from services.tools.builtin_tools_manage_service import BuiltinToolManageService -from .events import AgentLogEvent from .exceptions import AgentNodeError, AgentVariableTypeError, ToolFileNotFoundError from .think_tags import ThinkStreamState diff --git a/api/core/workflow/nodes/agent_v2/agent_node.py b/api/core/workflow/nodes/agent_v2/agent_node.py index 650cf7d0b57..0b92a8bc098 100644 --- a/api/core/workflow/nodes/agent_v2/agent_node.py +++ b/api/core/workflow/nodes/agent_v2/agent_node.py @@ -2,6 +2,7 @@ from __future__ import annotations import logging from collections.abc import Generator, Mapping, Sequence +from functools import singledispatchmethod from typing import TYPE_CHECKING, Any, override from dify_agent.protocol import CancelRunRequest @@ -23,9 +24,14 @@ from clients.agent_backend import ( AgentBackendValidationError, ) from core.app.entities.app_invoke_entities import DIFY_RUN_CONTEXT_KEY, DifyRunContext +from core.workflow.agent_log_events import ( + AgentLogEvent, + NodeRunAgentLogEvent, + node_run_agent_log_event, +) from core.workflow.node_execution_process_data import WORKFLOW_TOOL_INVOCATION_ID_KEY from core.workflow.system_variables import SystemVariableKey, get_system_text -from graphon.engine_events import NodeRunPauseRequestedEvent +from graphon.engine_events import NodeEvent, NodeRunPauseRequestedEvent from graphon.enums import ( BuiltinNodeTypes, ErrorStrategy, @@ -49,7 +55,7 @@ from services.agent.workspace_service import AgentWorkspaceNotFoundError from .binding_resolver import WorkflowAgentBindingError, WorkflowAgentBindingResolver from .entities import DifyAgentNodeData -from .output_adapter import WorkflowAgentOutputAdapter +from .output_adapter import STREAM_EXHAUSTED_ERROR, WorkflowAgentOutputAdapter from .output_failure_orchestrator import ( FailedOutput, OutputFailureDecision, @@ -63,6 +69,11 @@ from .runtime_request_builder import ( WorkflowAgentRuntimeRequestBuildError, ) from .session_store import WorkflowAgentSessionScope, WorkflowAgentWorkspaceStore +from .tool_activity import ( + FinishStatus, + WorkflowAgentToolActivity, + WorkflowAgentToolActivityProjector, +) if TYPE_CHECKING: from graphon.runtime import InitParams, RuntimeState @@ -134,6 +145,22 @@ class DifyAgentNode(Node[DifyAgentNodeData]): def populate_start_event(self, event) -> None: event.extras["agent_node"] = {"version": "2", "agent_node_kind": self.node_data.agent_node_kind} + @override + @singledispatchmethod + def _dispatch( # pyrefly: ignore[missing-override-decorator] + self, event: NodeEventPayload + ) -> NodeEvent: + return super()._dispatch(event) + + @_dispatch.register + def _dispatch_agent_log(self, event: AgentLogEvent) -> NodeRunAgentLogEvent: + return node_run_agent_log_event( + event, + execution_id=self.execution_id, + node_id=self._node_id, + node_type=self.node_type, + ) + @override def _run(self) -> Generator[NodeEventPayload | NodeRunPauseRequestedEvent]: inputs: dict[str, Any] = {} @@ -454,7 +481,7 @@ class DifyAgentNode(Node[DifyAgentNodeData]): metadata: dict[str, Any], stream_text: bool, ) -> Generator[ - StreamChunkEvent, + StreamChunkEvent | AgentLogEvent, None, tuple[_TerminalAgentBackendEvent | None, StreamCompletedEvent | None], ]: @@ -471,6 +498,13 @@ class DifyAgentNode(Node[DifyAgentNodeData]): the variable pool, so a configured fallback ``text`` would be dropped after a partial stream. + Tool lifecycle stream events are projected into ``AgentLogEvent`` + payloads so chat UIs can render live tool activity, but only when + ``stream_text`` is set: structured-output, output-route, and + default-value runs stay fully buffered and do not project logs. + ``finish`` closes any still-started calls before this generator + returns. + Returns a 2-tuple ``(terminal_event, transport_failure)``: - ``terminal_event``: the first non-stream/non-started internal event, or ``None`` if the stream ended without one. @@ -479,16 +513,33 @@ class DifyAgentNode(Node[DifyAgentNodeData]): terminal may accompany it so the caller can persist the final session snapshot while preserving the original transport failure. """ - result = yield from self._read_event_stream( + projector = ( + WorkflowAgentToolActivityProjector( + node_id=self._node_id, + node_execution_id=self.execution_id, + node_title=self.title, + ) + if stream_text + else None + ) + terminal_event, transport_failure = yield from self._read_event_stream( run_id, inputs=inputs, process_data=process_data, metadata=metadata, stream_text=stream_text, + projector=projector, ) + if projector is not None: + finish_status, finish_error = self._tool_activity_finish( + terminal_event=terminal_event, + transport_failure=transport_failure, + ) + for activity in projector.finish(finish_status, error=finish_error): + yield self._agent_log_event(activity) if stream_text and (metadata.get("agent_backend") or {}).get("agent_message_delta_count"): yield StreamChunkEvent(selector=[self._node_id, "text"], chunk="", is_final=True) - return result # noqa: B901 # StopIteration.value is the generator completion result. + return terminal_event, transport_failure # noqa: B901 # StopIteration.value is the generator completion result. def _read_event_stream( self, @@ -498,11 +549,17 @@ class DifyAgentNode(Node[DifyAgentNodeData]): process_data: dict[str, Any], metadata: dict[str, Any], stream_text: bool, + projector: WorkflowAgentToolActivityProjector | None, ) -> Generator[ - StreamChunkEvent, + StreamChunkEvent | AgentLogEvent, None, tuple[_TerminalAgentBackendEvent | None, StreamCompletedEvent | None], ]: + """Read one Agent backend SSE stream into workflow events. + + ``projector=None`` disables tool-activity projection; raw backend + event consumption and stream metadata recording remain active. + """ stream_event_count = 0 last_event_id: str | None = None try: @@ -519,6 +576,9 @@ class DifyAgentNode(Node[DifyAgentNodeData]): if internal_event.type == AgentBackendInternalEventType.STREAM_EVENT: if isinstance(internal_event, AgentBackendStreamInternalEvent): self._record_stream_metadata(metadata, internal_event) + if projector is not None: + for activity in projector.handle(internal_event): + yield self._agent_log_event(activity) continue if internal_event.type == AgentBackendInternalEventType.AGENT_MESSAGE_DELTA: if isinstance(internal_event, AgentBackendAgentMessageDeltaInternalEvent): @@ -716,6 +776,44 @@ class DifyAgentNode(Node[DifyAgentNodeData]): return "agent_backend_transport_error" return "agent_backend_error" + @staticmethod + def _tool_activity_finish( + *, + terminal_event: _TerminalAgentBackendEvent | None, + transport_failure: StreamCompletedEvent | None, + ) -> tuple[FinishStatus, str | None]: + """Map the stream outcome to the projector's terminal status and error. + + A transport failure wins over any accompanying cancellation terminal + because it carries the real stream error; a cancellation terminal + closes activity as ``cancelled``. A ``None`` terminal with no + transport failure mirrors the ``_run_inner`` stream-exhausted path, + which fails the node, so unfinished calls close as ``failed``. + """ + if transport_failure is not None: + return "failed", transport_failure.node_run_result.error + if isinstance(terminal_event, AgentBackendRunSucceededInternalEvent): + return "succeeded", None + if isinstance(terminal_event, AgentBackendRunFailedInternalEvent): + return "failed", terminal_event.error + if isinstance(terminal_event, AgentBackendRunCancelledInternalEvent): + return "cancelled", terminal_event.message or terminal_event.reason + return "failed", STREAM_EXHAUSTED_ERROR + + @staticmethod + def _agent_log_event(activity: WorkflowAgentToolActivity) -> AgentLogEvent: + return AgentLogEvent( + message_id=activity.id, + label=activity.label, + node_execution_id=activity.node_execution_id, + parent_id=None, + error=activity.error, + status=activity.status, + data=activity.data.model_dump(mode="json"), + metadata=dict(activity.metadata), + node_id=activity.node_id, + ) + @staticmethod def _record_stream_metadata(metadata: dict[str, Any], event: AgentBackendStreamInternalEvent) -> None: agent_backend = dict(metadata.get("agent_backend") or {}) diff --git a/api/core/workflow/nodes/agent_v2/output_adapter.py b/api/core/workflow/nodes/agent_v2/output_adapter.py index 051f2670857..c8f037eb482 100644 --- a/api/core/workflow/nodes/agent_v2/output_adapter.py +++ b/api/core/workflow/nodes/agent_v2/output_adapter.py @@ -25,6 +25,9 @@ class ToolFileRebacker(Protocol): def __call__(self, *, tenant_id: str, tool_file_id: str) -> File | None: ... +STREAM_EXHAUSTED_ERROR = "Agent backend stream ended before a terminal event." + + class WorkflowAgentOutputAdapter: """Convert terminal Agent backend events into workflow node run results. @@ -134,7 +137,7 @@ class WorkflowAgentOutputAdapter: process_data=process_data, metadata=self._build_node_metadata(metadata=metadata, usage=usage), llm_usage=usage or LLMUsage.empty_usage(), - error="Agent backend stream ended before a terminal event.", + error=STREAM_EXHAUSTED_ERROR, error_type="agent_backend_stream_error", ) diff --git a/api/core/workflow/nodes/agent_v2/tool_activity.py b/api/core/workflow/nodes/agent_v2/tool_activity.py new file mode 100644 index 00000000000..a4e2a0e1ef8 --- /dev/null +++ b/api/core/workflow/nodes/agent_v2/tool_activity.py @@ -0,0 +1,319 @@ +"""Project Agent v2 backend stream events into ephemeral tool activity snapshots. + +Pure and in-memory: never persists state and reads only allowlisted tool +fields. ``output_tool_*`` events are structured output, not tool activity. +""" + +from __future__ import annotations + +import json +from collections.abc import Mapping +from dataclasses import dataclass +from typing import Literal + +from pydantic import BaseModel, ConfigDict, Field, JsonValue, ValidationError + +from clients.agent_backend import AgentBackendStreamInternalEvent + +_TOOL_FIELD_LIMIT = 16 * 1024 + +_UNFINISHED_TOOL_ERROR = "Tool call did not return a result." + +ActivityStatus = Literal["started", "running", "succeeded", "failed", "cancelled"] +FinishStatus = Literal["succeeded", "failed", "cancelled"] + +_EARLY_TOOL_NAMES = frozenset({"shell_run", "shell_wait", "shell_input", "shell_interrupt"}) + + +class WorkflowAgentToolActivityData(BaseModel): + """Allowlisted tool fields carried inside the ``agent_log`` data payload.""" + + model_config = ConfigDict(frozen=True) + + tool_call_id: str + tool_name: str + tool_input: str + tool_output: str + node_title: str + + +class WorkflowAgentToolActivity(BaseModel): + """One immutable tool-activity snapshot for the chat UI. + + ``id`` is ``:`` so parallel same-named calls + and retry attempts never collapse into one entry. + """ + + model_config = ConfigDict(frozen=True) + + id: str + node_id: str + node_execution_id: str + label: str + status: ActivityStatus + error: str | None = None + data: WorkflowAgentToolActivityData + metadata: dict[str, str] = Field( + default_factory=lambda: {"agent_node_version": "2", "kind": "tool"}, + ) + + +class _ToolStreamPart(BaseModel): + """Allowlisted boundary view of one pydantic-ai tool stream part.""" + + model_config = ConfigDict(extra="ignore") + + part_kind: str | None = None + tool_call_id: str | None = None + tool_name: str | None = None + args: JsonValue = None + content: JsonValue = None + outcome: str | None = None + + +@dataclass +class _ToolCallState: + """Mutable per-call state; snapshots are emitted as new models.""" + + tool_call_id: str + tool_name: str + tool_input: str + tool_output: str = "" + status: ActivityStatus = "started" + error: str | None = None + + +def _bounded_text(value: JsonValue | None) -> str: + """Return a bounded display string for one JSON-safe tool field. + + Strings pass through; structured values are compactly JSON-serialized. + The result never exceeds ``_TOOL_FIELD_LIMIT`` characters. + """ + if value is None: + return "" + if isinstance(value, str): + return value[:_TOOL_FIELD_LIMIT] + try: + serialized = json.dumps(value, ensure_ascii=False, default=str) + except (TypeError, ValueError): + serialized = str(value) + return serialized[:_TOOL_FIELD_LIMIT] + + +def _first_stream_part(candidates: list[Mapping[str, JsonValue]]) -> _ToolStreamPart | None: + """Return the first candidate mapping that validates as a tool stream part.""" + for candidate in candidates: + try: + return _ToolStreamPart.model_validate(candidate) + except ValidationError: + pass + return None + + +class WorkflowAgentToolActivityProjector: + """Project one Agent v2 backend run's tool lifecycle into activity snapshots. + + Precondition: ``handle`` receives only ``STREAM_EVENT`` internal events + adapted from public ``dify-agent`` run events for a single backend run. + Postcondition: every returned snapshot is JSON-safe, carries the + ``agent_node_version=2``/``kind=tool`` metadata marker, and preserves the + invariant that a tool call emits at most one ``started`` preview and one + ``running`` transition before reaching a terminal status at most once. + ``finish`` closes calls still in ``started`` or ``running`` state; + terminal calls are never regressed. + """ + + def __init__(self, *, node_id: str, node_execution_id: str, node_title: str) -> None: + self._node_id = node_id + self._node_execution_id = node_execution_id + self._node_title = node_title + self._calls: dict[tuple[str, str], _ToolCallState] = {} + + def handle(self, event: AgentBackendStreamInternalEvent) -> list[WorkflowAgentToolActivity]: + """Return activity snapshots produced by one stream event. + + Unrelated kinds, malformed payloads, missing ids, and duplicate + terminal transitions return an empty list. + """ + if event.event_kind not in {"function_tool_call", "function_tool_result", "part_start"}: + return [] + part = self._stream_part(event.data, result_event=event.event_kind == "function_tool_result") + if part is None: + return [] + if event.event_kind == "function_tool_call" and part.part_kind == "tool-call": + return self._run_call(event.run_id, part) + if event.event_kind == "part_start" and part.part_kind == "builtin-tool-call": + return self._run_call(event.run_id, part) + if event.event_kind == "part_start" and part.part_kind == "tool-call": + return self._start_call(event.run_id, part) + if event.event_kind == "function_tool_result": + return self._finish_call(event.run_id, part, retry_is_failure=True) + if event.event_kind == "part_start" and part.part_kind == "builtin-tool-return": + return self._finish_call(event.run_id, part, retry_is_failure=False) + return [] + + def finish( + self, + status: FinishStatus, + error: str | None = None, + ) -> list[WorkflowAgentToolActivity]: + """Close every still-active call when the backend run terminates. + + ``cancelled`` closes calls as ``cancelled``; any other status closes + them as ``failed`` so an unfinished tool is never shown as successful. + Snapshots preserve start order. + """ + bounded_error = _bounded_text(error) or None + activities: list[WorkflowAgentToolActivity] = [] + for (run_id, _tool_call_id), state in self._calls.items(): + if state.status in {"started", "running"}: + if status == "cancelled": + state.status = "cancelled" + state.error = bounded_error + else: + state.status = "failed" + state.error = bounded_error or _UNFINISHED_TOOL_ERROR + activities.append(self._snapshot(run_id, state)) + return activities + + @staticmethod + def _stream_part(data: JsonValue, *, result_event: bool) -> _ToolStreamPart | None: + """Validate allowlisted part fields from the supported payload shapes. + + Call/start events accept only ``data.part``; result events also accept + ``data.result`` and top-level fields. A result without ``part_kind`` is + inferred as ``tool-return``; unknown declared kinds are rejected later. + """ + if not isinstance(data, Mapping): + return None + candidates: list[Mapping[str, JsonValue]] = [] + part = data.get("part") + if isinstance(part, Mapping): + candidates.append(part) + if result_event: + result = data.get("result") + if isinstance(result, Mapping): + candidates.append(result) + if any(key in data for key in ("tool_call_id", "tool_name", "content")): + candidates.append(data) + parsed = _first_stream_part(candidates) + if parsed is not None and result_event and not parsed.part_kind: + parsed.part_kind = "tool-return" + return parsed + + def _start_call(self, run_id: str, part: _ToolStreamPart) -> list[WorkflowAgentToolActivity]: + """Emit an early ``started`` preview for known shell tool calls only. + + Part starts fire for every tool (including structured-output + preambles) with partial arguments, so other tools first appear as + ``running``. A repeated start for a known call is ignored so state + never regresses. + """ + if not part.tool_call_id or not part.tool_name: + return [] + if part.tool_name not in _EARLY_TOOL_NAMES: + return [] + key = (run_id, part.tool_call_id) + if key in self._calls: + return [] + state = _ToolCallState( + tool_call_id=part.tool_call_id, + tool_name=part.tool_name, + tool_input=_bounded_text(part.args), + ) + self._calls[key] = state + return [self._snapshot(run_id, state)] + + def _run_call(self, run_id: str, part: _ToolStreamPart) -> list[WorkflowAgentToolActivity]: + """Mark a tool call ``running`` with its complete arguments. + + A ``started`` preview is promoted and its partial arguments replaced; + a new call is created as ``running``. Repeats and calls already + terminal return no snapshot. + """ + if not part.tool_call_id or not part.tool_name: + return [] + key = (run_id, part.tool_call_id) + state = self._calls.get(key) + if state is None: + state = _ToolCallState( + tool_call_id=part.tool_call_id, + tool_name=part.tool_name, + tool_input=_bounded_text(part.args), + status="running", + ) + self._calls[key] = state + return [self._snapshot(run_id, state)] + if state.status != "started": + return [] + state.tool_name = part.tool_name + state.tool_input = _bounded_text(part.args) + state.status = "running" + return [self._snapshot(run_id, state)] + + def _finish_call( + self, + run_id: str, + part: _ToolStreamPart, + *, + retry_is_failure: bool, + ) -> list[WorkflowAgentToolActivity]: + """Complete an active call, or emit one completed snapshot when unmatched. + + ``retry-prompt`` -> ``failed``; ``tool-return`` -> ``failed`` when + ``outcome == "failure"``, else ``succeeded``. An unmatched result with + a ``tool_name`` still yields one terminal snapshot; duplicates are + ignored. + """ + if not part.tool_call_id: + return [] + is_retry = part.part_kind == "retry-prompt" + is_return = part.part_kind in {"tool-return", "builtin-tool-return"} + if not is_retry and not is_return: + return [] + if is_retry and not retry_is_failure: + return [] + key = (run_id, part.tool_call_id) + state = self._calls.get(key) + if state is None: + if not part.tool_name: + return [] + state = _ToolCallState( + tool_call_id=part.tool_call_id, + tool_name=part.tool_name, + tool_input="", + ) + self._calls[key] = state + if state.status not in {"started", "running"}: + return [] + if state.tool_name == "" and part.tool_name: + state.tool_name = part.tool_name + if is_retry: + state.status = "failed" + state.error = _bounded_text(part.content) or None + else: + output = _bounded_text(part.content) + state.tool_output = output + if part.outcome == "failure": + state.status = "failed" + state.error = output or None + else: + state.status = "succeeded" + return [self._snapshot(run_id, state)] + + def _snapshot(self, run_id: str, state: _ToolCallState) -> WorkflowAgentToolActivity: + return WorkflowAgentToolActivity( + id=f"{run_id}:{state.tool_call_id}", + node_id=self._node_id, + node_execution_id=self._node_execution_id, + label=state.tool_name, + status=state.status, + error=state.error, + data=WorkflowAgentToolActivityData( + tool_call_id=state.tool_call_id, + tool_name=state.tool_name, + tool_input=state.tool_input, + tool_output=state.tool_output, + node_title=self._node_title, + ), + ) diff --git a/api/tests/unit_tests/core/app/apps/test_workflow_app_runner.py b/api/tests/unit_tests/core/app/apps/test_workflow_app_runner.py index 4ffc0bde565..e661a87bb4e 100644 --- a/api/tests/unit_tests/core/app/apps/test_workflow_app_runner.py +++ b/api/tests/unit_tests/core/app/apps/test_workflow_app_runner.py @@ -51,8 +51,8 @@ from core.db.session_factory import session_factory from core.repositories.human_input_repository import HumanInputFormRepositoryImpl, HumanInputFormSubmissionRepository from core.repositories.sqlalchemy_workflow_execution_repository import SQLAlchemyWorkflowExecutionRepository from core.repositories.sqlalchemy_workflow_node_execution_repository import SQLAlchemyWorkflowNodeExecutionRepository +from core.workflow.agent_log_events import NodeRunAgentLogEvent from core.workflow.node_runtime import DifyFileReferenceFactory -from core.workflow.nodes.agent.events import NodeRunAgentLogEvent from core.workflow.nodes.human_input.boundary import human_input_container_selector from core.workflow.nodes.human_input.callback import DifyHITLCallback from core.workflow.nodes.human_input.entities import ( diff --git a/api/tests/unit_tests/core/workflow/nodes/agent/test_agent_node.py b/api/tests/unit_tests/core/workflow/nodes/agent/test_agent_node.py index 2ed54e5fadc..c9d96f11783 100644 --- a/api/tests/unit_tests/core/workflow/nodes/agent/test_agent_node.py +++ b/api/tests/unit_tests/core/workflow/nodes/agent/test_agent_node.py @@ -1,8 +1,8 @@ from unittest.mock import MagicMock +from core.workflow.agent_log_events import AgentLogEvent, NodeRunAgentLogEvent from core.workflow.nodes.agent.agent_node import AgentNode from core.workflow.nodes.agent.entities import AgentNodeData -from core.workflow.nodes.agent.events import AgentLogEvent, NodeRunAgentLogEvent from graphon.engine_events import NodeRunStreamChunkEvent from graphon.enums import BuiltinNodeTypes from graphon.node_events import StreamChunkEvent 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 7a8f8c9ffc4..a5cd6f3dc9a 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 @@ -1,7 +1,8 @@ +import json from collections.abc import Callable, Iterator from datetime import UTC, datetime from types import SimpleNamespace -from typing import cast +from typing import cast, override from unittest.mock import MagicMock, patch from uuid import UUID, uuid4 @@ -21,7 +22,16 @@ from dify_agent.protocol import ( RunSucceededEventData, ) from dify_agent.protocol.snapshot import SessionSnapshot -from pydantic_ai.messages import PartDeltaEvent, TextPartDelta +from pydantic import JsonValue +from pydantic_ai.messages import ( + FunctionToolCallEvent, + FunctionToolResultEvent, + PartDeltaEvent, + PartStartEvent, + TextPartDelta, + ToolCallPart, + ToolReturnPart, +) from sqlalchemy.orm import Session from clients.agent_backend import ( @@ -34,11 +44,12 @@ from clients.agent_backend import ( FakeAgentBackendScenario, ) from core.app.entities.app_invoke_entities import DIFY_RUN_CONTEXT_KEY, DifyRunContext, InvokeFrom, UserFrom +from core.workflow.agent_log_events import AgentLogEvent, NodeRunAgentLogEvent from core.workflow.file_reference import build_file_reference from core.workflow.nodes.agent_v2 import DifyAgentNode from core.workflow.nodes.agent_v2.binding_resolver import WorkflowAgentBindingBundle, WorkflowAgentBindingResolver from core.workflow.nodes.agent_v2.entities import DifyAgentNodeData -from core.workflow.nodes.agent_v2.output_adapter import WorkflowAgentOutputAdapter +from core.workflow.nodes.agent_v2.output_adapter import STREAM_EXHAUSTED_ERROR, WorkflowAgentOutputAdapter from core.workflow.nodes.agent_v2.runtime_request_builder import ( WorkflowAgentRuntimeBuildContext, WorkflowAgentRuntimeRequestBuilder, @@ -298,6 +309,181 @@ class AgentMessageDeltaBackendClient(FakeAgentBackendRunClient): ) +class ToolActivityBackendClient(FakeAgentBackendRunClient): + def __init__( + self, + *, + output: JsonValue = "hello agent", + include_delta: bool = True, + early_start: bool = False, + ) -> None: + super().__init__(scenario=FakeAgentBackendScenario.SUCCESS) + self._output = output + self._include_delta = include_delta + self._early_start = early_start + + @override + def _events(self, run_id: str): + created_at = datetime(2026, 1, 1, tzinfo=UTC) + call_args = {"script": "ls -la", "timeout": 30} if self._early_start else {"command": "ls"} + events: list[RunEvent] = [ + RunStartedEvent(id="1-0", run_id=run_id, created_at=created_at), + ] + if self._early_start: + events.append( + PydanticAIStreamRunEvent( + id="1-5", + run_id=run_id, + created_at=created_at, + data=PartStartEvent( + index=0, + part=ToolCallPart( + tool_name="shell_run", + args={"script": "ls"}, + tool_call_id="call-1", + ), + ), + ) + ) + events.extend( + [ + PydanticAIStreamRunEvent( + id="2-0", + run_id=run_id, + created_at=created_at, + data=FunctionToolCallEvent( + part=ToolCallPart( + tool_name="shell_run", + args=call_args, + tool_call_id="call-1", + ) + ), + ), + PydanticAIStreamRunEvent( + id="3-0", + run_id=run_id, + created_at=created_at, + data=FunctionToolResultEvent( + part=ToolReturnPart( + tool_name="shell_run", + content="a.txt", + tool_call_id="call-1", + outcome="success", + ) + ), + ), + ] + ) + if self._include_delta: + events.append( + PydanticAIStreamRunEvent( + id="4-0", + run_id=run_id, + created_at=created_at, + data=PartDeltaEvent(index=0, delta=TextPartDelta(content_delta="hello agent")), + agent_message_delta="hello agent", + ) + ) + events.append( + RunSucceededEvent( + id="5-0", + run_id=run_id, + created_at=created_at, + data=RunSucceededEventData( + output=self._output, + session_snapshot=SessionSnapshot(layers={}), + ), + ) + ) + return tuple(events) + + +class ToolCallThenCancelledBackendClient(FakeAgentBackendRunClient): + @override + def _events(self, run_id: str): + created_at = datetime(2026, 1, 1, tzinfo=UTC) + return ( + RunStartedEvent(id="1-0", run_id=run_id, created_at=created_at), + PydanticAIStreamRunEvent( + id="2-0", + run_id=run_id, + created_at=created_at, + data=FunctionToolCallEvent( + part=ToolCallPart( + tool_name="shell_run", + args={"command": "ls"}, + tool_call_id="call-1", + ) + ), + ), + RunCancelledEvent( + id="3-0", + run_id=run_id, + created_at=created_at, + data=RunCancelledEventData(reason="user_stop"), + ), + ) + + +class ToolCallThenFailingStreamBackendClient(FakeAgentBackendRunClient): + @override + def stream_events( + self, + run_id: str, + *, + after: str | None = None, + should_stop: Callable[[], bool] | None = None, + ) -> Iterator[RunEvent]: + del after, should_stop + created_at = datetime(2026, 1, 1, tzinfo=UTC) + yield RunStartedEvent(id="1-0", run_id=run_id, created_at=created_at) + yield PydanticAIStreamRunEvent( + id="2-0", + run_id=run_id, + created_at=created_at, + data=FunctionToolCallEvent( + part=ToolCallPart( + tool_name="shell_run", + args={"command": "ls"}, + tool_call_id="call-1", + ) + ), + ) + raise AgentBackendStreamError("stream failed mid-tool") + + +class ToolCallThenUncancellableStreamEndBackendClient(FakeAgentBackendRunClient): + @override + def _events(self, run_id: str): + created_at = datetime(2026, 1, 1, tzinfo=UTC) + return ( + RunStartedEvent(id="1-0", run_id=run_id, created_at=created_at), + PydanticAIStreamRunEvent( + id="2-0", + run_id=run_id, + created_at=created_at, + data=FunctionToolCallEvent( + part=ToolCallPart( + tool_name="shell_run", + args={"command": "ls"}, + tool_call_id="call-1", + ) + ), + ), + ) + + @override + def cancel_run_and_wait( + self, + run_id: str, + request: CancelRunRequest | None = None, + *, + after: str | None = None, + ) -> RunCancelledEvent: + del run_id, request, after + raise RuntimeError("cancel request failed") + + class FailingStreamBackendClient(FakeAgentBackendRunClient): def __init__(self) -> None: super().__init__() @@ -396,13 +582,13 @@ class CancelFailingStreamBackendClient(FailingStreamBackendClient): raise RuntimeError(f"failed to cancel {run_id}") -def _drain_event_stream(node: DifyAgentNode): +def _drain_event_stream(node: DifyAgentNode, *, stream_text: bool): stream = node._consume_event_stream( "run-1", inputs={}, process_data={"workflow_agent_binding_id": "binding-1"}, metadata={"agent_backend": {}}, - stream_text=False, + stream_text=stream_text, ) while True: try: @@ -411,6 +597,22 @@ def _drain_event_stream(node: DifyAgentNode): return stop.value +def _collect_event_stream(node: DifyAgentNode, *, stream_text: bool): + stream = node._consume_event_stream( + "run-1", + inputs={}, + process_data={"workflow_agent_binding_id": "binding-1"}, + metadata={"agent_backend": {}}, + stream_text=stream_text, + ) + events = [] + while True: + try: + events.append(next(stream)) + except StopIteration as stop: + return events, stop.value + + def _node( *, scenario: FakeAgentBackendScenario = FakeAgentBackendScenario.SUCCESS, @@ -945,7 +1147,7 @@ def test_agent_node_cancels_backend_run_when_stream_fails(): client = FailingStreamBackendClient() node = _node(agent_backend_client=client) - terminal, failure = _drain_event_stream(node) + terminal, failure = _drain_event_stream(node, stream_text=True) assert isinstance(terminal, AgentBackendRunCancelledInternalEvent) assert failure is not None @@ -959,7 +1161,7 @@ def test_agent_node_forwards_last_stream_cursor_when_cancelling_after_failure() client = FailingAfterStartedStreamBackendClient() node = _node(agent_backend_client=client) - terminal, failure = _drain_event_stream(node) + terminal, failure = _drain_event_stream(node, stream_text=True) assert isinstance(terminal, AgentBackendRunCancelledInternalEvent) assert failure is not None @@ -971,7 +1173,7 @@ def test_agent_node_cancels_backend_run_when_stream_ends_without_terminal_event( client = EmptyStreamBackendClient() node = _node(agent_backend_client=client) - terminal, failure = _drain_event_stream(node) + terminal, failure = _drain_event_stream(node, stream_text=True) assert isinstance(terminal, AgentBackendRunCancelledInternalEvent) assert failure is None @@ -983,7 +1185,7 @@ def test_agent_node_cancels_backend_run_when_stream_raises_unexpected_error(): client = GenericFailingStreamBackendClient() node = _node(agent_backend_client=client) - terminal, failure = _drain_event_stream(node) + terminal, failure = _drain_event_stream(node, stream_text=True) assert isinstance(terminal, AgentBackendRunCancelledInternalEvent) assert failure is not None @@ -998,7 +1200,7 @@ def test_agent_node_uses_graph_abort_reason_when_cancel_request_fails(caplog): node = _node(agent_backend_client=client) node.runtime_state.graph_execution = SimpleNamespace(aborted=True) - terminal, failure = _drain_event_stream(node) + terminal, failure = _drain_event_stream(node, stream_text=True) assert terminal is None assert failure is not None @@ -1019,7 +1221,7 @@ def test_agent_node_cancels_backend_run_for_unexpected_internal_event(): return_value=[SimpleNamespace(type=AgentBackendInternalEventType.RUN_FAILED)] ) - terminal, failure = _drain_event_stream(node) + terminal, failure = _drain_event_stream(node, stream_text=True) assert terminal is None assert failure is not None @@ -1080,6 +1282,231 @@ def test_agent_node_records_only_trusted_knowledge_sources_and_deduplicates(): assert sources[0]["knowledge_fs_citation"]["id"] == citation["id"] +def test_agent_node_projects_tool_activity_into_agent_log_events(): + node = _node(agent_backend_client=ToolActivityBackendClient()) + events = list(node._run()) + + agent_logs = [event for event in events if isinstance(event, AgentLogEvent)] + assert [log.status for log in agent_logs] == ["running", "succeeded"] + running, finished = agent_logs + assert running.message_id == finished.message_id == "fake-run-1:call-1" + assert running.node_id == "agent-node" + assert running.node_execution_id == finished.node_execution_id == node.execution_id + assert running.parent_id is None + assert running.label == "shell_run" + assert running.metadata == {"agent_node_version": "2", "kind": "tool"} + assert running.data["tool_call_id"] == "call-1" + assert running.data["tool_name"] == "shell_run" + assert json.loads(running.data["tool_input"]) == {"command": "ls"} + assert running.data["tool_output"] == "" + assert isinstance(running.data["node_title"], str) + assert finished.error is None + assert finished.data["tool_output"] == "a.txt" + + chunks = [event for event in events if isinstance(event, StreamChunkEvent)] + assert chunks == [ + StreamChunkEvent(selector=["agent-node", "text"], chunk="hello agent", is_final=False), + StreamChunkEvent(selector=["agent-node", "text"], chunk="", is_final=True), + ] + completed = events[-1] + assert isinstance(completed, StreamCompletedEvent) + result = completed.node_run_result + assert result.status == WorkflowNodeExecutionStatus.SUCCEEDED + assert result.outputs == {"text": "hello agent"} + + +def test_agent_node_projects_early_started_running_and_succeeded_tool_activity(): + events = list(_node(agent_backend_client=ToolActivityBackendClient(early_start=True))._run()) + + agent_logs = [event for event in events if isinstance(event, AgentLogEvent)] + assert [log.status for log in agent_logs] == ["started", "running", "succeeded"] + previewed, running, finished = agent_logs + assert previewed.message_id == running.message_id == finished.message_id == "fake-run-1:call-1" + assert json.loads(previewed.data["tool_input"]) == {"script": "ls"} + assert json.loads(running.data["tool_input"]) == {"script": "ls -la", "timeout": 30} + assert finished.data["tool_output"] == "a.txt" + + final_chunk_index = next( + index for index, event in enumerate(events) if isinstance(event, StreamChunkEvent) and event.is_final + ) + assert all(events.index(log) < final_chunk_index for log in agent_logs) + + +def test_agent_node_dispatch_maps_agent_log_to_legacy_node_run_event(): + node = _node() + payload = AgentLogEvent( + message_id="fake-run-1:call-1", + label="shell_run", + node_execution_id=node.execution_id, + parent_id=None, + error=None, + status="started", + data={"tool_call_id": "call-1", "tool_name": "shell_run"}, + metadata={"agent_node_version": "2", "kind": "tool"}, + node_id="agent-node", + ) + + dispatched = node._dispatch(payload) + + assert type(dispatched) is NodeRunAgentLogEvent + assert dispatched.message_id == "fake-run-1:call-1" + assert dispatched.node_execution_id == node.execution_id + assert dispatched.node_id == "agent-node" + assert dispatched.status == "started" + assert dispatched.data == {"tool_call_id": "call-1", "tool_name": "shell_run"} + assert dispatched.metadata == {"agent_node_version": "2", "kind": "tool"} + + +def test_agent_node_structured_run_suppresses_tool_activity_and_stream_chunks(): + events = list( + _node( + declared_outputs=[{"name": "summary", "type": DeclaredOutputType.STRING}], + agent_backend_client=ToolActivityBackendClient( + output={"text": "hello agent", "summary": "Short summary"}, + include_delta=True, + early_start=True, + ), + )._run() + ) + + assert not any(isinstance(event, AgentLogEvent) for event in events) + assert not any(isinstance(event, StreamChunkEvent) for event in events) + completed = events[-1] + assert isinstance(completed, StreamCompletedEvent) + result = completed.node_run_result + assert result.status == WorkflowNodeExecutionStatus.SUCCEEDED + assert result.outputs == {"text": "hello agent", "summary": "Short summary"} + agent_backend = result.metadata[WorkflowNodeExecutionMetadataKey.AGENT_LOG]["agent_backend"] + assert agent_backend["run_id"] == "fake-run-1" + assert agent_backend["status"] == "succeeded" + + +def test_agent_node_default_value_strategy_suppresses_tool_activity_and_stream_chunks(): + events = list( + _node( + error_strategy=ErrorStrategy.DEFAULT_VALUE, + agent_backend_client=ToolActivityBackendClient(early_start=True), + )._run() + ) + + assert not any(isinstance(event, AgentLogEvent) for event in events) + assert not any(isinstance(event, StreamChunkEvent) for event in events) + completed = events[-1] + assert isinstance(completed, StreamCompletedEvent) + result = completed.node_run_result + assert result.status == WorkflowNodeExecutionStatus.SUCCEEDED + assert result.outputs == {"text": "hello agent"} + + +def test_agent_node_output_routes_suppress_tool_activity_and_stream_chunks(): + resolver = FakeBindingResolver() + resolver.binding.node_job_config = WorkflowNodeJobConfig.model_validate( + { + "output_routes": { + "enabled": True, + "routes": [{"id": "route-0", "name": "Zero"}, {"id": "route-1", "name": "One"}], + } + } + ) + events = list( + _node( + binding_resolver=resolver, + agent_backend_client=ToolActivityBackendClient( + output={"text": "hello agent", "switch": "route-1"}, + early_start=True, + ), + )._run() + ) + + assert not any(isinstance(event, AgentLogEvent) for event in events) + assert not any(isinstance(event, StreamChunkEvent) for event in events) + completed = events[-1] + assert isinstance(completed, StreamCompletedEvent) + result = completed.node_run_result + assert result.status == WorkflowNodeExecutionStatus.SUCCEEDED + assert result.edge_source_handle == "route-1" + assert result.outputs == {"text": "hello agent", "switch": "route-1"} + + +def test_agent_node_non_stream_run_consumes_tool_events_without_logs(): + events, (terminal, failure) = _collect_event_stream( + _node(agent_backend_client=ToolActivityBackendClient(early_start=True)), + stream_text=False, + ) + + assert not any(isinstance(event, AgentLogEvent) for event in events) + assert not any(isinstance(event, StreamChunkEvent) for event in events) + assert failure is None + assert terminal is not None + + +@pytest.mark.parametrize("stream_text", [True, False]) +def test_agent_node_transport_failure_closes_unfinished_tool_calls(stream_text: bool): + events, (terminal, failure) = _collect_event_stream( + _node(agent_backend_client=ToolCallThenFailingStreamBackendClient()), + stream_text=stream_text, + ) + + agent_logs = [event for event in events if isinstance(event, AgentLogEvent)] + if stream_text: + assert [log.status for log in agent_logs] == ["running", "failed"] + assert agent_logs[1].error == "stream failed mid-tool" + assert agent_logs[1].data["tool_call_id"] == "call-1" + else: + assert agent_logs == [] + assert isinstance(terminal, AgentBackendRunCancelledInternalEvent) + assert failure is not None + assert failure.node_run_result.error == "stream failed mid-tool" + + +@pytest.mark.parametrize("stream_text", [True, False]) +def test_agent_node_cancelled_run_closes_unfinished_tool_calls(stream_text: bool): + events, (terminal, failure) = _collect_event_stream( + _node(agent_backend_client=ToolCallThenCancelledBackendClient()), + stream_text=stream_text, + ) + + agent_logs = [event for event in events if isinstance(event, AgentLogEvent)] + if stream_text: + assert [log.status for log in agent_logs] == ["running", "cancelled"] + assert agent_logs[1].error == "user_stop" + else: + assert agent_logs == [] + assert isinstance(terminal, AgentBackendRunCancelledInternalEvent) + assert failure is None + + +@pytest.mark.parametrize("stream_text", [True, False]) +def test_agent_node_stream_end_without_terminal_fails_unfinished_tool_calls(stream_text: bool): + events, (terminal, failure) = _collect_event_stream( + _node(agent_backend_client=ToolCallThenUncancellableStreamEndBackendClient()), + stream_text=stream_text, + ) + + agent_logs = [event for event in events if isinstance(event, AgentLogEvent)] + if stream_text: + assert [log.status for log in agent_logs] == ["running", "failed"] + assert agent_logs[1].error == STREAM_EXHAUSTED_ERROR + else: + assert agent_logs == [] + assert terminal is None + assert failure is None + + +def test_agent_node_stream_end_without_terminal_run_fails_with_stream_exhausted_error(): + events = list(_node(agent_backend_client=ToolCallThenUncancellableStreamEndBackendClient())._run()) + + agent_logs = [event for event in events if isinstance(event, AgentLogEvent)] + assert [log.status for log in agent_logs] == ["running", "failed"] + assert agent_logs[-1].error == STREAM_EXHAUSTED_ERROR + completed = events[-1] + assert isinstance(completed, StreamCompletedEvent) + result = completed.node_run_result + assert result.status == WorkflowNodeExecutionStatus.FAILED + assert result.error == STREAM_EXHAUSTED_ERROR + assert result.error_type == "agent_backend_stream_error" + + @pytest.mark.parametrize( ("enabled", "count", "output", "expected_handle"), [ diff --git a/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_tool_activity.py b/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_tool_activity.py new file mode 100644 index 00000000000..3bff730af2f --- /dev/null +++ b/api/tests/unit_tests/core/workflow/nodes/agent_v2/test_tool_activity.py @@ -0,0 +1,657 @@ +from __future__ import annotations + +import json +from datetime import UTC, datetime + +from dify_agent.protocol import PydanticAIStreamRunEvent +from pydantic_ai.messages import ( + FunctionToolCallEvent, + FunctionToolResultEvent, + OutputToolCallEvent, + PartDeltaEvent, + PartStartEvent, + RetryPromptPart, + TextPartDelta, + ToolCallPart, + ToolReturnPart, +) + +from clients.agent_backend import AgentBackendRunEventAdapter, AgentBackendStreamInternalEvent +from core.workflow.nodes.agent_v2.tool_activity import ( + _TOOL_FIELD_LIMIT, + WorkflowAgentToolActivityProjector, +) + +_CREATED_AT = datetime(2026, 1, 1, tzinfo=UTC) + + +def _projector() -> WorkflowAgentToolActivityProjector: + return WorkflowAgentToolActivityProjector( + node_id="agent-node", + node_execution_id="exec-1", + node_title="Research agent", + ) + + +def _internal(event_kind: str, data: dict[str, object], *, run_id: str = "run-1") -> AgentBackendStreamInternalEvent: + return AgentBackendStreamInternalEvent(run_id=run_id, event_kind=event_kind, data=data) + + +def _part_start( + tool_call_id: str, + *, + tool_name: str = "shell_run", + part_kind: str = "tool-call", + args: dict[str, object] | None = None, + run_id: str = "run-1", +) -> AgentBackendStreamInternalEvent: + return _internal( + "part_start", + { + "part": { + "part_kind": part_kind, + "tool_call_id": tool_call_id, + "tool_name": tool_name, + "args": args if args is not None else {"script": "ls"}, + } + }, + run_id=run_id, + ) + + +def _tool_call( + tool_call_id: str, + *, + tool_name: str = "shell_run", + args: dict[str, object] | None = None, + run_id: str = "run-1", +) -> AgentBackendStreamInternalEvent: + return _internal( + "function_tool_call", + { + "part": { + "part_kind": "tool-call", + "tool_call_id": tool_call_id, + "tool_name": tool_name, + "args": args if args is not None else {"command": "ls"}, + } + }, + run_id=run_id, + ) + + +def _tool_result( + tool_call_id: str, + *, + tool_name: str = "shell_run", + content: object = "file.txt", + outcome: str = "success", + run_id: str = "run-1", +) -> AgentBackendStreamInternalEvent: + return _internal( + "function_tool_result", + { + "part": { + "part_kind": "tool-return", + "tool_call_id": tool_call_id, + "tool_name": tool_name, + "content": content, + "outcome": outcome, + } + }, + run_id=run_id, + ) + + +def _retry_result( + tool_call_id: str, *, content: str = "invalid arguments", run_id: str = "run-1" +) -> AgentBackendStreamInternalEvent: + return _internal( + "function_tool_result", + { + "part": { + "part_kind": "retry-prompt", + "tool_call_id": tool_call_id, + "tool_name": "shell_run", + "content": content, + } + }, + run_id=run_id, + ) + + +def test_start_then_result_emits_matching_snapshots_with_full_fields() -> None: + projector = _projector() + + running = projector.handle(_tool_call("call-1", args={"command": "ls -la"})) + assert len(running) == 1 + activity = running[0] + assert activity.id == "run-1:call-1" + assert activity.node_id == "agent-node" + assert activity.node_execution_id == "exec-1" + assert activity.label == "shell_run" + assert activity.status == "running" + assert activity.error is None + assert activity.data.tool_call_id == "call-1" + assert activity.data.tool_name == "shell_run" + assert json.loads(activity.data.tool_input) == {"command": "ls -la"} + assert activity.data.tool_output == "" + assert activity.data.node_title == "Research agent" + assert activity.metadata == {"agent_node_version": "2", "kind": "tool"} + + finished = projector.handle(_tool_result("call-1", content="a.txt\nb.txt")) + assert len(finished) == 1 + assert finished[0].id == activity.id + assert finished[0].status == "succeeded" + assert finished[0].data.tool_input == activity.data.tool_input + assert finished[0].data.tool_output == "a.txt\nb.txt" + + +def test_same_name_parallel_calls_correlate_by_call_id_out_of_order() -> None: + projector = _projector() + + first = projector.handle(_tool_call("call-a", args={"command": "one"}))[0] + second = projector.handle(_tool_call("call-b", args={"command": "two"}))[0] + assert first.id != second.id + assert first.status == second.status == "running" + + done_b = projector.handle(_tool_result("call-b", content="out-b"))[0] + assert done_b.id == second.id + assert done_b.status == "succeeded" + assert done_b.data.tool_output == "out-b" + + done_a = projector.handle(_tool_result("call-a", content="out-a"))[0] + assert done_a.id == first.id + assert done_a.status == "succeeded" + assert done_a.data.tool_output == "out-a" + + +def test_duplicate_start_and_terminal_events_do_not_duplicate_or_regress() -> None: + projector = _projector() + + assert len(projector.handle(_tool_call("call-1"))) == 1 + assert projector.handle(_tool_call("call-1")) == [] + assert len(projector.handle(_tool_result("call-1"))) == 1 + assert projector.handle(_tool_result("call-1")) == [] + assert projector.handle(_tool_call("call-1")) == [] + late = projector.handle(_tool_result("call-1", outcome="failure", content="boom")) + assert late == [] + assert projector.finish("succeeded") == [] + + +def test_unrelated_text_and_output_tool_events_are_ignored() -> None: + projector = _projector() + + assert projector.handle(_internal("part_delta", {"delta": "hi"})) == [] + assert projector.handle(_internal("part_start", {"part": {"part_kind": "text", "content": "hi"}})) == [] + assert ( + projector.handle( + _internal( + "output_tool_call", + {"part": {"part_kind": "tool-call", "tool_call_id": "out-1", "tool_name": "final", "args": {}}}, + ) + ) + == [] + ) + assert ( + projector.handle( + _internal( + "output_tool_result", + { + "part": { + "part_kind": "tool-return", + "tool_call_id": "out-1", + "tool_name": "final", + "content": "done", + "outcome": "success", + } + }, + ) + ) + == [] + ) + assert projector.finish("succeeded") == [] + + +def test_retry_prompt_result_marks_call_failed() -> None: + projector = _projector() + + projector.handle(_tool_call("call-1", args={"bad": True})) + retried = projector.handle(_retry_result("call-1", content="arguments failed validation")) + + assert len(retried) == 1 + assert retried[0].status == "failed" + assert retried[0].error == "arguments failed validation" + assert retried[0].data.tool_output == "" + + +def test_tool_return_failure_outcome_marks_call_failed_with_output_as_error() -> None: + projector = _projector() + + projector.handle(_tool_call("call-1")) + failed = projector.handle(_tool_result("call-1", outcome="failure", content="command not found")) + + assert len(failed) == 1 + assert failed[0].status == "failed" + assert failed[0].error == "command not found" + assert failed[0].data.tool_output == "command not found" + + +def test_early_shell_part_start_then_call_then_result_emits_three_phases() -> None: + projector = _projector() + + previewed = projector.handle(_part_start("call-1", args={"script": "ls"})) + assert len(previewed) == 1 + assert previewed[0].status == "started" + assert previewed[0].id == "run-1:call-1" + assert json.loads(previewed[0].data.tool_input) == {"script": "ls"} + + running = projector.handle(_tool_call("call-1", args={"script": "ls -la", "timeout": 30})) + assert len(running) == 1 + assert running[0].id == previewed[0].id + assert running[0].status == "running" + assert json.loads(running[0].data.tool_input) == {"script": "ls -la", "timeout": 30} + + finished = projector.handle(_tool_result("call-1", content="a.txt")) + assert len(finished) == 1 + assert finished[0].id == previewed[0].id + assert finished[0].status == "succeeded" + assert finished[0].data.tool_input == running[0].data.tool_input + + +def test_generic_tool_call_has_no_early_started_phase() -> None: + projector = _projector() + + assert projector.handle(_part_start("call-1", tool_name="web_search", args={"q": "dify"})) == [] + + running = projector.handle(_tool_call("call-1", tool_name="web_search", args={"q": "dify docs"})) + assert len(running) == 1 + assert running[0].status == "running" + assert running[0].data.tool_name == "web_search" + + finished = projector.handle(_tool_result("call-1", tool_name="web_search", content="docs")) + assert finished[0].status == "succeeded" + + +def test_early_part_start_rejects_non_shell_and_incomplete_payloads() -> None: + projector = _projector() + + assert projector.handle(_part_start("call-1", tool_name="web_search")) == [] + assert projector.handle(_part_start("call-2", part_kind="text")) == [] + assert ( + projector.handle( + _internal( + "part_start", + {"part": {"part_kind": "tool-call", "tool_name": "shell_run", "args": {}}}, + ) + ) + == [] + ) + assert ( + projector.handle( + _internal( + "part_start", + {"part": {"part_kind": "tool-call", "tool_call_id": "call-3", "args": {}}}, + ) + ) + == [] + ) + assert projector.finish("succeeded") == [] + + +def test_late_early_start_does_not_regress_running_or_terminal() -> None: + projector = _projector() + + projector.handle(_tool_call("call-1", args={"script": "ls -la"})) + assert projector.handle(_part_start("call-1", args={"script": "ls"})) == [] + + projector.handle(_tool_result("call-1", content="a.txt")) + assert projector.handle(_part_start("call-1", args={"script": "ls"})) == [] + assert projector.finish("succeeded") == [] + + +def test_duplicate_running_start_does_not_duplicate_or_regress() -> None: + projector = _projector() + + first = projector.handle(_tool_call("call-1", args={"script": "ls"})) + assert len(first) == 1 + assert first[0].status == "running" + assert projector.handle(_tool_call("call-1", args={"script": "pwd"})) == [] + assert projector.handle(_part_start("call-1", args={"script": "ls"})) == [] + + +def test_unmatched_result_still_emits_one_completed_snapshot() -> None: + projector = _projector() + + finished = projector.handle(_tool_result("orphan-1", tool_name="web_search", content="results")) + assert len(finished) == 1 + assert finished[0].status == "succeeded" + assert finished[0].data.tool_input == "" + assert projector.handle(_tool_result("orphan-1")) == [] + + +def test_result_event_accepts_result_and_top_level_payload_shapes() -> None: + projector = _projector() + projector.handle(_tool_call("call-1")) + projector.handle(_tool_call("call-2")) + projector.handle(_tool_call("call-3")) + + via_result = projector.handle( + _internal( + "function_tool_result", + { + "result": { + "tool_call_id": "call-1", + "tool_name": "shell_run", + "content": "via-result", + } + }, + ) + ) + assert len(via_result) == 1 + assert via_result[0].status == "succeeded" + assert via_result[0].data.tool_output == "via-result" + + via_top_level = projector.handle( + _internal( + "function_tool_result", + { + "tool_call_id": "call-2", + "tool_name": "shell_run", + "content": "via-top-level", + }, + ) + ) + assert len(via_top_level) == 1 + assert via_top_level[0].status == "succeeded" + assert via_top_level[0].data.tool_output == "via-top-level" + + via_bare_part = projector.handle( + _internal( + "function_tool_result", + { + "part": { + "tool_call_id": "call-3", + "tool_name": "shell_run", + "content": "via-bare-part", + } + }, + ) + ) + assert len(via_bare_part) == 1 + assert via_bare_part[0].status == "succeeded" + assert via_bare_part[0].data.tool_output == "via-bare-part" + + +def test_result_event_does_not_infer_kind_for_declared_unknown_part_kind() -> None: + projector = _projector() + projector.handle(_tool_call("call-1")) + + ignored = projector.handle( + _internal( + "function_tool_result", + { + "part": { + "part_kind": "text", + "tool_call_id": "call-1", + "tool_name": "shell_run", + "content": "not a tool return", + } + }, + ) + ) + assert ignored == [] + assert projector.finish("succeeded")[0].status == "failed" + + +def test_unmatched_result_without_tool_name_is_rejected() -> None: + projector = _projector() + + assert ( + projector.handle( + _internal( + "function_tool_result", + {"tool_call_id": "orphan-1", "content": "no name"}, + ) + ) + == [] + ) + assert ( + projector.handle( + _internal( + "function_tool_result", + {"part": {"part_kind": "tool-return", "tool_call_id": "orphan-2", "content": "no name"}}, + ) + ) + == [] + ) + assert projector.finish("succeeded") == [] + + +def test_finish_error_is_bounded() -> None: + projector = _projector() + projector.handle(_tool_call("call-1")) + + closed = projector.finish("failed", error="e" * (_TOOL_FIELD_LIMIT * 2)) + assert len(closed[0].error or "") <= _TOOL_FIELD_LIMIT + + +def test_finish_closes_unfinished_started_and_running_calls() -> None: + projector = _projector() + + projector.handle(_part_start("call-preview", args={"script": "ls"})) + projector.handle(_tool_call("call-running", args={"command": "pwd"})) + projector.handle(_tool_call("call-done")) + projector.handle(_tool_result("call-done")) + + closed = projector.finish("succeeded") + assert [activity.id for activity in closed] == ["run-1:call-preview", "run-1:call-running"] + assert [activity.status for activity in closed] == ["failed", "failed"] + assert all(activity.error == "Tool call did not return a result." for activity in closed) + assert projector.finish("succeeded") == [] + + +def test_finish_failed_and_cancelled_propagate_error() -> None: + failed_projector = _projector() + failed_projector.handle(_tool_call("call-1")) + failed = failed_projector.finish("failed", error="backend exploded") + assert failed[0].status == "failed" + assert failed[0].error == "backend exploded" + + cancelled_projector = _projector() + cancelled_projector.handle(_tool_call("call-1")) + cancelled = cancelled_projector.finish("cancelled", error="user stopped") + assert cancelled[0].status == "cancelled" + assert cancelled[0].error == "user stopped" + + +def test_builtin_tool_part_start_events_project_activity() -> None: + projector = _projector() + + running = projector.handle( + _internal( + "part_start", + { + "part": { + "part_kind": "builtin-tool-call", + "tool_call_id": "builtin-1", + "tool_name": "web_search", + "args": {"query": "dify"}, + } + }, + ) + ) + assert len(running) == 1 + assert running[0].status == "running" + assert running[0].data.tool_name == "web_search" + + finished = projector.handle( + _internal( + "part_start", + { + "part": { + "part_kind": "builtin-tool-return", + "tool_call_id": "builtin-1", + "tool_name": "web_search", + "content": "search results", + "outcome": "success", + } + }, + ) + ) + assert len(finished) == 1 + assert finished[0].status == "succeeded" + assert finished[0].data.tool_output == "search results" + + +def test_malformed_payloads_and_missing_ids_are_ignored() -> None: + projector = _projector() + + assert projector.handle(_internal("function_tool_call", {"unexpected": True})) == [] + assert projector.handle(_internal("function_tool_call", {"part": "not-a-dict"})) == [] + assert ( + projector.handle( + _internal( + "function_tool_call", + {"part": {"part_kind": "tool-call", "tool_name": "shell_run", "args": {}}}, + ) + ) + == [] + ) + assert ( + projector.handle( + _internal( + "function_tool_call", + {"part": {"part_kind": "tool-call", "tool_call_id": "call-1", "args": {}}}, + ) + ) + == [] + ) + assert projector.handle(_internal("function_tool_result", {"part": {"part_kind": "unknown"}})) == [] + assert projector.finish("succeeded") == [] + + +def test_large_tool_fields_are_bounded() -> None: + projector = _projector() + + big_input: dict[str, object] = {"blob": "x" * (_TOOL_FIELD_LIMIT * 2)} + big_output = "y" * (_TOOL_FIELD_LIMIT * 2) + started = projector.handle(_tool_call("call-1", args=big_input))[0] + finished = projector.handle(_tool_result("call-1", content=big_output))[0] + + assert len(started.data.tool_input) <= _TOOL_FIELD_LIMIT + assert len(finished.data.tool_output) <= _TOOL_FIELD_LIMIT + assert started.data.tool_input.startswith('{"blob": "xxx') + assert finished.data.tool_output == "y" * _TOOL_FIELD_LIMIT + + +def test_identity_separates_runs_and_call_ids() -> None: + projector = _projector() + + a = projector.handle(_tool_call("call-1", run_id="run-1"))[0] + b = projector.handle(_tool_call("call-1", run_id="run-2"))[0] + assert a.id == "run-1:call-1" + assert b.id == "run-2:call-1" + assert a.id != b.id + + +def test_real_pydantic_ai_stream_events_through_adapter() -> None: + adapter = AgentBackendRunEventAdapter() + projector = _projector() + + public_events = [ + PydanticAIStreamRunEvent( + id="e-0", + run_id="run-1", + created_at=_CREATED_AT, + data=PartStartEvent( + index=0, + part=ToolCallPart(tool_name="shell_run", args={"script": "pwd"}, tool_call_id="call-9"), + ), + ), + PydanticAIStreamRunEvent( + id="e-1", + run_id="run-1", + created_at=_CREATED_AT, + data=FunctionToolCallEvent( + part=ToolCallPart( + tool_name="shell_run", + args={"script": "pwd", "timeout": 30}, + tool_call_id="call-9", + ) + ), + ), + PydanticAIStreamRunEvent( + id="e-2", + run_id="run-1", + created_at=_CREATED_AT, + data=FunctionToolResultEvent( + part=ToolReturnPart(tool_name="shell_run", content="/workspace", tool_call_id="call-9") + ), + ), + PydanticAIStreamRunEvent( + id="e-3", + run_id="run-1", + created_at=_CREATED_AT, + data=OutputToolCallEvent( + part=ToolCallPart(tool_name="final_result", args={"answer": "done"}, tool_call_id="out-1") + ), + ), + PydanticAIStreamRunEvent( + id="e-4", + run_id="run-1", + created_at=_CREATED_AT, + data=PartDeltaEvent( + index=0, + delta=TextPartDelta(content_delta="thinking"), + ), + ), + ] + + activities = [] + for public_event in public_events: + for internal_event in adapter.adapt(public_event): + if isinstance(internal_event, AgentBackendStreamInternalEvent): + activities.extend(projector.handle(internal_event)) + + assert [a.status for a in activities] == ["started", "running", "succeeded"] + assert activities[0].id == "run-1:call-9" + assert activities[0].data.tool_name == "shell_run" + assert json.loads(activities[0].data.tool_input) == {"script": "pwd"} + assert activities[1].status == "running" + assert json.loads(activities[1].data.tool_input) == {"script": "pwd", "timeout": 30} + assert activities[2].data.tool_output == "/workspace" + assert projector.finish("succeeded") == [] + + +def test_real_retry_prompt_event_through_adapter_fails_call() -> None: + adapter = AgentBackendRunEventAdapter() + projector = _projector() + + events = [ + PydanticAIStreamRunEvent( + id="e-1", + run_id="run-1", + created_at=_CREATED_AT, + data=FunctionToolCallEvent( + part=ToolCallPart(tool_name="shell_run", args={"command": 42}, tool_call_id="call-7") + ), + ), + PydanticAIStreamRunEvent( + id="e-2", + run_id="run-1", + created_at=_CREATED_AT, + data=FunctionToolResultEvent( + part=RetryPromptPart(content="command must be a string", tool_name="shell_run", tool_call_id="call-7") + ), + ), + ] + + activities = [] + for public_event in events: + for internal_event in adapter.adapt(public_event): + if isinstance(internal_event, AgentBackendStreamInternalEvent): + activities.extend(projector.handle(internal_event)) + + assert [a.status for a in activities] == ["running", "failed"] + assert activities[1].error == "command must be a string" diff --git a/oxlint-suppressions.json b/oxlint-suppressions.json index 1b0a318617c..81766a03b66 100644 --- a/oxlint-suppressions.json +++ b/oxlint-suppressions.json @@ -927,14 +927,6 @@ "count": 3 } }, - "web/app/components/base/chat/chat/__tests__/hooks.spec.tsx": { - "no-restricted-imports": { - "count": 1 - }, - "typescript/no-deprecated": { - "count": 91 - } - }, "web/app/components/base/chat/chat/answer/more.tsx": { "better-tailwindcss/enforce-logical-properties": { "count": 3 diff --git a/web/app/components/base/chat/__tests__/workflow-agent-tool-activity.spec.ts b/web/app/components/base/chat/__tests__/workflow-agent-tool-activity.spec.ts new file mode 100644 index 00000000000..4b8e5e67761 --- /dev/null +++ b/web/app/components/base/chat/__tests__/workflow-agent-tool-activity.spec.ts @@ -0,0 +1,161 @@ +import type { ChatItem } from '../types' +import type { AgentLogStreamData } from '@/types/workflow' +import { upsertWorkflowToolActivity } from '../workflow-agent-tool-activity' + +const toolLog = (overrides: Partial = {}): AgentLogStreamData => ({ + id: 'run-1:call-1', + node_id: 'agent-node', + node_execution_id: 'exec-1', + parent_id: null, + label: 'shell_run', + error: null, + status: 'started', + data: { + tool_call_id: 'call-1', + tool_name: 'shell_run', + tool_input: '{"command":"ls"}', + tool_output: '', + node_title: 'Research agent', + }, + metadata: { agent_node_version: '2', kind: 'tool' }, + ...overrides, +}) + +const chatItem = (): ChatItem => ({ id: 'answer-1', content: '', isAnswer: true }) + +describe('upsertWorkflowToolActivity', () => { + it('stores a started snapshot keyed by node execution and wire id', () => { + const item = chatItem() + upsertWorkflowToolActivity(item, toolLog()) + + expect(item.workflowAgentActivities).toHaveLength(1) + const activity = item.workflowAgentActivities![0]! + expect(activity.id).toBe('run-1:call-1') + expect(activity.node_execution_id).toBe('exec-1') + expect(activity.status).toBe('started') + expect(activity.data.tool_name).toBe('shell_run') + expect(activity.data.node_title).toBe('Research agent') + }) + + it('replaces the snapshot for the same call and preserves order', () => { + const item = chatItem() + upsertWorkflowToolActivity(item, toolLog()) + upsertWorkflowToolActivity( + item, + toolLog({ + id: 'run-1:call-2', + status: 'started', + data: { + tool_call_id: 'call-2', + tool_name: 'web_search', + tool_input: '{"q":"dify"}', + tool_output: '', + node_title: 'Research agent', + }, + }), + ) + upsertWorkflowToolActivity( + item, + toolLog({ + status: 'succeeded', + data: { ...toolLog().data, tool_output: 'a.txt' }, + }), + ) + + expect(item.workflowAgentActivities).toHaveLength(2) + expect(item.workflowAgentActivities!.map((a) => a.id)).toEqual(['run-1:call-1', 'run-1:call-2']) + expect(item.workflowAgentActivities![0]!.status).toBe('succeeded') + expect(item.workflowAgentActivities![0]!.data.tool_output).toBe('a.txt') + expect(item.workflowAgentActivities![1]!.status).toBe('started') + }) + + it('accepts the running phase and keeps one snapshot per call', () => { + const item = chatItem() + const data = toolLog().data + + upsertWorkflowToolActivity(item, toolLog({ status: 'started' })) + upsertWorkflowToolActivity( + item, + toolLog({ + status: 'running', + data: { ...data, tool_input: '{"script":"ls -la"}' }, + }), + ) + + expect(item.workflowAgentActivities).toHaveLength(1) + expect(item.workflowAgentActivities![0]!.status).toBe('running') + expect(item.workflowAgentActivities![0]!.data.tool_input).toBe('{"script":"ls -la"}') + + upsertWorkflowToolActivity( + item, + toolLog({ + status: 'succeeded', + data: { ...data, tool_output: 'a.txt' }, + }), + ) + + expect(item.workflowAgentActivities).toHaveLength(1) + expect(item.workflowAgentActivities![0]!.status).toBe('succeeded') + }) + + it('keeps same-name parallel calls and different executions distinct', () => { + const item = chatItem() + const base = toolLog().data + upsertWorkflowToolActivity( + item, + toolLog({ id: 'run-1:call-a', data: { ...base, tool_call_id: 'call-a' } }), + ) + upsertWorkflowToolActivity( + item, + toolLog({ id: 'run-1:call-b', data: { ...base, tool_call_id: 'call-b' } }), + ) + upsertWorkflowToolActivity( + item, + toolLog({ + id: 'run-1:call-a', + node_execution_id: 'exec-2', + data: { ...base, tool_call_id: 'call-a' }, + }), + ) + + expect(item.workflowAgentActivities).toHaveLength(3) + expect(item.workflowAgentActivities!.map((a) => `${a.node_execution_id}:${a.id}`)).toEqual([ + 'exec-1:run-1:call-a', + 'exec-1:run-1:call-b', + 'exec-2:run-1:call-a', + ]) + }) + + it('ignores legacy agent logs and unrelated metadata', () => { + const item = chatItem() + upsertWorkflowToolActivity(item, toolLog({ metadata: { provider: 'openai' } })) + upsertWorkflowToolActivity( + item, + toolLog({ metadata: { agent_node_version: '1', kind: 'tool' } }), + ) + upsertWorkflowToolActivity(item, toolLog({ metadata: { agent_node_version: '2' } })) + upsertWorkflowToolActivity(item, toolLog({ metadata: undefined })) + + expect(item.workflowAgentActivities).toBeUndefined() + }) + + it('ignores malformed payloads without tool identity', () => { + const item = chatItem() + upsertWorkflowToolActivity(item, toolLog({ data: { tool_name: 'shell_run' } })) + upsertWorkflowToolActivity(item, toolLog({ data: { tool_call_id: 'call-1' } })) + upsertWorkflowToolActivity(item, toolLog({ id: '' })) + upsertWorkflowToolActivity(item, toolLog({ status: 'weird' })) + upsertWorkflowToolActivity(item, toolLog({ node_execution_id: '' })) + + expect(item.workflowAgentActivities).toBeUndefined() + }) + + it('carries terminal failure status and error text', () => { + const item = chatItem() + upsertWorkflowToolActivity(item, toolLog({ status: 'failed', error: 'command not found' })) + + const activity = item.workflowAgentActivities![0]! + expect(activity.status).toBe('failed') + expect(activity.error).toBe('command not found') + }) +}) diff --git a/web/app/components/base/chat/chat/__tests__/chat-owner-preset.tsx b/web/app/components/base/chat/chat/__tests__/chat-owner-preset.tsx index 11012c0ab4a..b309b7fb207 100644 --- a/web/app/components/base/chat/chat/__tests__/chat-owner-preset.tsx +++ b/web/app/components/base/chat/chat/__tests__/chat-owner-preset.tsx @@ -9,6 +9,7 @@ import appDebug from '@/i18n/locales/en-US/app-debug.json' import appLog from '@/i18n/locales/en-US/app-log.json' import common from '@/i18n/locales/en-US/common.json' import share from '@/i18n/locales/en-US/share.json' +import tools from '@/i18n/locales/en-US/tools.json' import workflowHumanInput from '@/i18n/locales/en-US/workflow-human-input.json' import workflow from '@/i18n/locales/en-US/workflow.json' import { createConsoleQueryWrapper } from '@/test/console/query-data' @@ -37,6 +38,7 @@ export async function renderChatOwner(ui: ReactNode) { workflow, workflowHumanInput, share, + tools, }, }, }) 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 6e2cbc95a62..b9c94bfae4c 100644 --- a/web/app/components/base/chat/chat/__tests__/hooks.spec.tsx +++ b/web/app/components/base/chat/chat/__tests__/hooks.spec.tsx @@ -5,7 +5,6 @@ import { InputVarType, WorkflowRunningStatus } from '@/app/components/workflow/t import { toast } from '@/app/notifications' import { captureAppAccessScope, handleAppAccessError } from '@/features/app-access-error/state' import { useParams, usePathname } from '@/next/navigation' -import { sseGet, ssePost } from '@/service/base' import { renderHookWithConsoleQuery } from '@/test/console/query-data' import { createHumanInputFormFixture, @@ -13,9 +12,16 @@ import { } from '@/test/fixtures/workflow-process' import { useChat } from '../hooks' +type SseTransportCall = (url: string, fetchOptions: unknown, otherOptions: unknown) => Promise + +const { sseGet, ssePost } = vi.hoisted(() => ({ + sseGet: vi.fn(), + ssePost: vi.fn(), +})) + vi.mock('@/service/base', () => ({ - sseGet: vi.fn(), - ssePost: vi.fn(), + sseGet, + ssePost, })) const audio = vi.hoisted(() => ({ @@ -94,6 +100,7 @@ type HookCallbacks = { onLoopStart: (loopStarted: Record) => void onLoopFinish: (loopFinished: Record) => void onHumanInputRequired: (required: Record) => void + onAgentLog: (agentLog: { data: Record }) => void onHumanInputFormFilled: (filled: Record) => void onHumanInputFormTimeout: (timeout: Record) => void onWorkflowPaused: (workflowPaused: Record) => void @@ -544,6 +551,127 @@ describe('useChat', () => { expect(lastResponse!.workflowProcess?.tracing).toHaveLength(3) // node, iteration, loop }) + it('should fold workflow agent tool logs into the streamed answer on send', async () => { + let callbacks: HookCallbacks + vi.mocked(ssePost).mockImplementation(async (_url, _params, options) => { + callbacks = options as HookCallbacks + }) + + const { result } = renderHookWithConsoleQuery(() => useChat()) + + act(() => { + result.current.handleSend('test-url', { query: 'run tools' }, {}) + }) + + const toolLog = (status: string, output = '') => ({ + task_id: 't-1', + event: 'agent_log', + data: { + id: 'run-1:call-1', + node_id: 'agent-node', + node_execution_id: 'exec-1', + parent_id: null, + label: 'shell_run', + error: null, + status, + data: { + tool_call_id: 'call-1', + tool_name: 'shell_run', + tool_input: '{"command":"ls"}', + tool_output: output, + node_title: 'Agent', + }, + metadata: { agent_node_version: '2', kind: 'tool' }, + children: [], + }, + }) + + act(() => { + callbacks.onAgentLog(toolLog('started')) + }) + + let answer = result.current.chatList.at(-1)! + expect(answer.workflowAgentActivities).toHaveLength(1) + expect(answer.workflowAgentActivities![0]!.status).toBe('started') + + act(() => { + callbacks.onAgentLog(toolLog('succeeded', 'a.txt')) + callbacks.onData('final answer', true, { messageId: 'm-1' }) + callbacks.onMessageEnd({ metadata: { retriever_resources: [] } }) + callbacks.onWorkflowFinished({ data: { status: 'succeeded' } }) + callbacks.onCompleted() + }) + + answer = result.current.chatList.at(-1)! + expect(answer.workflowAgentActivities).toHaveLength(1) + expect(answer.workflowAgentActivities![0]!.status).toBe('succeeded') + expect(answer.workflowAgentActivities![0]!.data.tool_output).toBe('a.txt') + expect(answer.content).toBe('final answer') + }) + + it('should ignore agent logs from a superseded send request', async () => { + const callbacksList: HookCallbacks[] = [] + vi.mocked(ssePost).mockImplementation(async (_url, _params, options) => { + callbacksList.push(options as HookCallbacks) + }) + + const { result } = renderHookWithConsoleQuery(() => useChat()) + + vi.useFakeTimers() + try { + act(() => { + result.current.handleSend('test-url', { query: 'first request' }, {}) + }) + await act(async () => { + await callbacksList[0]!.onCompleted(true) + }) + vi.setSystemTime(Date.now() + 1000) + act(() => { + result.current.handleSend('test-url', { query: 'second request' }, {}) + }) + } finally { + vi.useRealTimers() + } + + const staleLog = { + task_id: 't-1', + event: 'agent_log', + data: { + id: 'run-1:call-1', + node_id: 'agent-node', + node_execution_id: 'exec-1', + parent_id: null, + label: 'shell_run', + error: null, + status: 'started', + data: { + tool_call_id: 'call-1', + tool_name: 'shell_run', + tool_input: '{}', + tool_output: '', + node_title: 'Agent', + }, + metadata: { agent_node_version: '2', kind: 'tool' }, + children: [], + }, + } + + act(() => { + callbacksList[0]!.onAgentLog(staleLog) + }) + + expect(result.current.chatList.every((item) => !item.workflowAgentActivities?.length)).toBe( + true, + ) + + act(() => { + callbacksList[1]!.onAgentLog(staleLog) + }) + + const answers = result.current.chatList.filter((item) => item.isAnswer) + expect(answers.at(-1)!.workflowAgentActivities).toHaveLength(1) + }) + it('should merge each parallel tool result into the thought that called the tool', async () => { let callbacks: HookCallbacks vi.mocked(ssePost).mockImplementation(async (_url, _params, options) => { @@ -1767,6 +1895,138 @@ describe('useChat', () => { expect(sseGet).toHaveBeenCalledTimes(1) }) + it('should fold workflow agent tool logs into the resumed answer', async () => { + let callbacks: HookCallbacks + vi.mocked(sseGet).mockImplementation(async (_url, _params, options) => { + callbacks = options as HookCallbacks + }) + + const prevChatTree = [ + { + id: 'q-1', + content: 'query', + isAnswer: false, + children: [ + { + id: 'm-1', + content: '', + isAnswer: true, + workflow_run_id: 'wr-1', + siblingIndex: 0, + }, + ], + }, + ] + const { result } = renderHookWithConsoleQuery(() => + useChat(undefined, undefined, prevChatTree as ChatItemInTree[]), + ) + + act(() => { + result.current.handleResume('m-1', 'wr-1', { isPublicAPI: true }) + }) + + const agentLog = { + task_id: 't-1', + event: 'agent_log', + data: { + id: 'run-1:call-1', + node_id: 'agent-node', + node_execution_id: 'exec-1', + parent_id: null, + label: 'web_search', + error: null, + status: 'started', + data: { + tool_call_id: 'call-1', + tool_name: 'web_search', + tool_input: '{"q":"dify"}', + tool_output: '', + node_title: 'Agent', + }, + metadata: { agent_node_version: '2', kind: 'tool' }, + children: [], + }, + } + + act(() => { + callbacks.onAgentLog(agentLog) + }) + + const answer = result.current.chatList.at(-1)! + expect(answer.workflowAgentActivities).toHaveLength(1) + expect(answer.workflowAgentActivities![0]!.status).toBe('started') + expect(answer.workflowAgentActivities![0]!.data.tool_name).toBe('web_search') + }) + + it('should ignore agent logs from a superseded resume subscription', async () => { + const callbacksList: HookCallbacks[] = [] + vi.mocked(sseGet).mockImplementation(async (_url, _params, options) => { + callbacksList.push(options as HookCallbacks) + }) + + const prevChatTree = [ + { + id: 'q-1', + content: 'query', + isAnswer: false, + children: [ + { + id: 'm-1', + content: '', + isAnswer: true, + workflow_run_id: 'wr-1', + siblingIndex: 0, + }, + ], + }, + ] + const { result } = renderHookWithConsoleQuery(() => + useChat(undefined, undefined, prevChatTree as ChatItemInTree[]), + ) + + act(() => { + result.current.handleResume('m-1', 'wr-1', { isPublicAPI: true }) + result.current.handleResume('m-1', 'wr-2', { isPublicAPI: true }) + }) + + const staleLog = { + task_id: 't-1', + event: 'agent_log', + data: { + id: 'run-1:call-1', + node_id: 'agent-node', + node_execution_id: 'exec-1', + parent_id: null, + label: 'web_search', + error: null, + status: 'started', + data: { + tool_call_id: 'call-1', + tool_name: 'web_search', + tool_input: '{}', + tool_output: '', + node_title: 'Agent', + }, + metadata: { agent_node_version: '2', kind: 'tool' }, + children: [], + }, + } + + act(() => { + callbacksList[0]!.onAgentLog(staleLog) + }) + + const resumedAnswer = result.current.chatList.find((item) => item.id === 'm-1')! + expect(resumedAnswer.workflowAgentActivities).toBeUndefined() + + act(() => { + callbacksList[1]!.onAgentLog(staleLog) + }) + + const updatedAnswer = result.current.chatList.find((item) => item.id === 'm-1')! + expect(updatedAnswer.workflowAgentActivities).toHaveLength(1) + }) + it('should wait for the resumed event stream before allowing a restored form submission', async () => { let callbacks: HookCallbacks vi.mocked(sseGet).mockImplementation(async (_url, _params, options) => { diff --git a/web/app/components/base/chat/chat/answer/__tests__/workflow-tool-activity.browser.spec.tsx b/web/app/components/base/chat/chat/answer/__tests__/workflow-tool-activity.browser.spec.tsx new file mode 100644 index 00000000000..b6af4d1510f --- /dev/null +++ b/web/app/components/base/chat/chat/answer/__tests__/workflow-tool-activity.browser.spec.tsx @@ -0,0 +1,293 @@ +import type { WorkflowAgentToolActivity } from '../../../types' +import { page, userEvent } from 'vite-plus/test/browser' +import { guardUnexpectedFetch } from '@/test/unexpected-fetch' +import { chatItem, renderChatOwner } from '../../__tests__/chat-owner-preset' +import Answer from '../index' + +vi.unmock('react-i18next') +// boundary: real attachment owners read params without a running Next router. +vi.mock('@/next/navigation', () => ({ useParams: () => ({}), usePathname: () => '/chat' })) + +beforeEach(async () => { + await page.viewport(1000, 800) + onTestFinished(guardUnexpectedFetch()) +}) + +const toolActivity = ( + overrides: Partial = {}, +): WorkflowAgentToolActivity => ({ + id: 'run-1:call-1', + node_id: 'agent-node', + node_execution_id: 'exec-1', + label: 'shell_run', + status: 'started', + error: null, + data: { + tool_call_id: 'call-1', + tool_name: 'shell_run', + tool_input: '{"script":"ls"}', + tool_output: '', + node_title: 'Research agent', + }, + ...overrides, +}) + +it('shows started, running, and completed phases before the final answer', async () => { + const screen = await renderChatOwner( + , + ) + + await expect.element(page.getByText('Starting commands')).toBeVisible() + await expect.element(page.getByText('Research agent')).toBeVisible() + await expect.element(page.getByText('An answer')).not.toBeInTheDocument() + + await userEvent.click(page.getByRole('button', { name: /Starting commands/ })) + await expect.element(page.getByText('Request', { exact: true })).toBeVisible() + await expect.element(page.getByText('{"script":"ls"}', { exact: true })).toBeVisible() + + await screen.rerender( + , + ) + + await expect.element(page.getByRole('button', { name: /Running commands/ })).toBeVisible() + await expect.element(page.getByText('Starting commands')).not.toBeInTheDocument() + await expect.element(page.getByText('Response', { exact: true })).not.toBeInTheDocument() + await expect.element(page.getByText('{"script":"ls -la"}', { exact: true })).toBeVisible() + + await screen.rerender( + , + ) + + await expect.element(page.getByRole('button', { name: /Ran commands/ })).toBeVisible() + await expect.element(page.getByText('Response', { exact: true })).toBeVisible() + await expect.element(page.getByText('a.txt', { exact: true })).toBeVisible() + + await screen.rerender( + , + ) + + await expect.element(page.getByText('Final answer text')).toBeVisible() + await expect.element(page.getByRole('button', { name: /Ran commands/ })).toBeVisible() +}) + +it('updates same-name parallel calls out of order and keeps per-call request/response pairs', async () => { + const searchActivity = (id: string, callId: string, status: string, output = '') => + toolActivity({ + id, + label: 'web_search', + status: status as WorkflowAgentToolActivity['status'], + data: { + tool_call_id: callId, + tool_name: 'web_search', + tool_input: `{"q":"${callId}"}`, + tool_output: output, + node_title: 'Research agent', + }, + }) + + const running = [ + searchActivity('run-1:a', 'a', 'running'), + searchActivity('run-1:b', 'b', 'running'), + ] + const screen = await renderChatOwner( + , + ) + + const buttons = page.getByRole('button', { name: /web_search/ }) + await expect.poll(() => buttons.elements().length).toBe(2) + + await screen.rerender( + , + ) + + await screen.rerender( + , + ) + + await expect.poll(() => buttons.elements().length).toBe(2) + + await userEvent.click(buttons.nth(0)) + await userEvent.click(buttons.nth(1)) + + await expect.element(page.getByText('result-a', { exact: true })).toBeVisible() + await expect.element(page.getByText('result-b', { exact: true })).toBeVisible() + + const expectedValues = ['{"q":"a"}', 'result-a', '{"q":"b"}', 'result-b'] + const values = [...page.getByTestId('workflow-tool-activity').element().querySelectorAll('div')] + .map((element) => element.textContent?.trim()) + .filter((text): text is string => expectedValues.includes(text ?? '')) + expect(values).toEqual(expectedValues) +}) + +it('shows readable failed, cancelled, and interrupted statuses with the original tool label', async () => { + const failed = toolActivity({ + status: 'failed', + error: 'command not found', + data: { + tool_call_id: 'call-1', + tool_name: 'shell_run', + tool_input: '{"command":"nope"}', + tool_output: '', + node_title: 'Research agent', + }, + }) + const cancelled = toolActivity({ + id: 'run-1:call-2', + label: 'web_search', + status: 'cancelled', + error: 'run cancelled', + data: { + tool_call_id: 'call-2', + tool_name: 'web_search', + tool_input: '{"q":"dify"}', + tool_output: '', + node_title: 'Research agent', + }, + }) + const unfinished = toolActivity({ + id: 'run-1:call-3', + label: 'web_search', + status: 'started', + data: { + tool_call_id: 'call-3', + tool_name: 'web_search', + tool_input: '{"q":"open"}', + tool_output: '', + node_title: 'Research agent', + }, + }) + const runningUnfinished = toolActivity({ + id: 'run-1:call-4', + label: 'web_search', + status: 'running', + data: { + tool_call_id: 'call-4', + tool_name: 'web_search', + tool_input: '{"q":"streaming"}', + tool_output: '', + node_title: 'Research agent', + }, + }) + + const screen = await renderChatOwner( + , + ) + + await expect.element(page.getByRole('button', { name: /shell_run/ })).toBeVisible() + await expect.element(page.getByRole('button', { name: /web_search/ }).nth(0)).toBeVisible() + await expect.element(page.getByText('Failed', { exact: true })).toBeVisible() + await expect.element(page.getByText('Stopped', { exact: true })).toBeVisible() + await expect.element(page.getByText('Ran commands')).not.toBeInTheDocument() + + await userEvent.click(page.getByRole('button', { name: /shell_run/ })) + await expect.element(page.getByText('command not found', { exact: true })).toBeVisible() + + await screen.rerender( + , + ) + + await expect.poll(() => page.getByText('Stopped', { exact: true }).elements().length).toBe(3) +}) diff --git a/web/app/components/base/chat/chat/answer/agent-roster-response-content.tsx b/web/app/components/base/chat/chat/answer/agent-roster-response-content.tsx index 6c0b42a51e9..0a6927fba9f 100644 --- a/web/app/components/base/chat/chat/answer/agent-roster-response-content.tsx +++ b/web/app/components/base/chat/chat/answer/agent-roster-response-content.tsx @@ -1,3 +1,4 @@ +import type { ToolActivity } from './tool-activity-item' import type { ThoughtItem } from '@/app/components/base/chat/chat/type' import type { ChatItem } from '@/app/components/base/chat/types' import type { Locale } from '@/i18n' @@ -9,6 +10,7 @@ import { FileList } from '@/app/components/base/file-uploader' import { Markdown } from '@/app/components/base/markdown' import { getPluginLanguage, renderI18nObject } from '@/i18n/metadata' import { resolveKnowledgeCitationLinks } from './knowledge-citation-links' +import { SHELL_TOOL_NAMES, ToolActivityItem } from './tool-activity-item' type AgentRosterResponseContentProps = { item: ChatItem @@ -17,18 +19,6 @@ type AgentRosterResponseContentProps = { showThoughts?: boolean } -const SHELL_TOOL_NAMES = new Set(['shell_run', 'shell_wait', 'shell_input', 'shell_interrupt']) - -type ToolActivity = { - kind: 'shell' | 'tool' - key: string - name: string - label: string - input: string - output: string - isFinished: boolean -} - type AgentActivityEntry = | { type: 'message' @@ -182,82 +172,6 @@ function ResponseMessage({ content }: { content: string }) { ) } -function ToolActivityItem({ tool }: { tool: ToolActivity }) { - const { t } = useTranslation(['agentV2', 'tools']) - const hasDetails = !!tool.input || !!tool.output - const label = - tool.name === 'shell_run' && tool.label === tool.name - ? tool.isFinished - ? t(($) => $['agentDetail.configure.answer.activity.ranCommands'], { ns: 'agentV2' }) - : t(($) => $['agentDetail.configure.answer.activity.runningCommands'], { - ns: 'agentV2', - }) - : tool.label - - const content = ( - <> - - - {!tool.isFinished ? ( - - ) : tool.kind === 'shell' ? ( - - ) : ( - - )} - - {label} - - {hasDetails && ( - - )} - - ) - - return ( -
- {hasDetails ? ( - - - {content} - - -
- {!!tool.input && ( -
-
- {t(($) => $['thought.requestTitle'], { ns: 'tools' })} -
-
- {tool.input} -
-
- )} - {!!tool.output && ( -
-
- {t(($) => $['thought.responseTitle'], { ns: 'tools' })} -
-
- {tool.output} -
-
- )} -
-
-
- ) : ( -
- {content} -
- )} -
- ) -} - function AgentActivityItem({ thought, responding, diff --git a/web/app/components/base/chat/chat/answer/index.tsx b/web/app/components/base/chat/chat/answer/index.tsx index 0a08120191c..edb5863bbf1 100644 --- a/web/app/components/base/chat/chat/answer/index.tsx +++ b/web/app/components/base/chat/chat/answer/index.tsx @@ -22,6 +22,7 @@ import Operation from './operation' import ReasoningPanel from './reasoning-panel' import SuggestedQuestions from './suggested-questions' import WorkflowProcessItem from './workflow-process' +import WorkflowToolActivity from './workflow-tool-activity' type AnswerProps = { footer?: ReactNode @@ -81,6 +82,7 @@ const Answer: FC = ({ const hasAgentResponseParts = !!item.agent_response_parts?.length const hasAgentContent = hasAgentThoughts || hasAgentResponseParts const hasHumanInputs = !!humanInputFormDataList?.length || !!humanInputFilledFormDataList?.length + const hasWorkflowActivities = !!item.workflowAgentActivities?.length // Truthy only when there is real reasoning text. Rehydrated messages carry an empty // `{}` (the field is always persisted), and `!!{}` would otherwise be truthy. const hasReasoning = !!item.reasoningContent && Object.values(item.reasoningContent).some(Boolean) @@ -245,75 +247,90 @@ const Answer: FC = ({ )} {/* Block 2: Response Content (when human inputs exist) */} - {hasHumanInputs && (responding || !contentIsEmpty || hasAgentContent || hasReasoning) && ( -
-
-
- {!responding && ( - - )} - {hasReasoning && ( - - )} - {responding && contentIsEmpty && !hasAgentContent && !hasReasoning && ( -
- -
- )} - {!contentIsEmpty && !hasAgentContent && } - {hasAgentContent && agentContentNode} - {!!allFiles?.length && ( - - )} - {!!message_files?.length && ( - - )} - {annotation?.id && annotation.authorName && ( - $.editBy, { ns: 'appAnnotation', author: annotation.authorName })} - /> - )} - - {!!citation?.length && !responding && ( - - )} - {typeof item.siblingCount === 'number' && item.siblingCount > 1 && ( - - )} + {hasHumanInputs && + (responding || + !contentIsEmpty || + hasAgentContent || + hasReasoning || + hasWorkflowActivities) && ( +
+
+
+ {!responding && ( + + )} + {hasReasoning && ( + + )} + {responding && + contentIsEmpty && + !hasAgentContent && + !hasReasoning && + !hasWorkflowActivities && ( +
+ +
+ )} + {hasWorkflowActivities && ( + + )} + {!contentIsEmpty && !hasAgentContent && } + {hasAgentContent && agentContentNode} + {!!allFiles?.length && ( + + )} + {!!message_files?.length && ( + + )} + {annotation?.id && annotation.authorName && ( + $.editBy, { + ns: 'appAnnotation', + author: annotation.authorName, + })} + /> + )} + + {!!citation?.length && !responding && ( + + )} + {typeof item.siblingCount === 'number' && item.siblingCount > 1 && ( + + )} +
-
- )} + )} {/* Original single block layout (when no human inputs) */} {!hasHumanInputs && ( @@ -354,10 +371,17 @@ const Answer: FC = ({ {hasReasoning && ( )} - {responding && contentIsEmpty && !hasAgentContent && !hasReasoning && ( -
- -
+ {responding && + contentIsEmpty && + !hasAgentContent && + !hasReasoning && + !hasWorkflowActivities && ( +
+ +
+ )} + {hasWorkflowActivities && ( + )} {!contentIsEmpty && !hasAgentContent && } {hasAgentContent && agentContentNode} diff --git a/web/app/components/base/chat/chat/answer/tool-activity-item.tsx b/web/app/components/base/chat/chat/answer/tool-activity-item.tsx new file mode 100644 index 00000000000..665938c028a --- /dev/null +++ b/web/app/components/base/chat/chat/answer/tool-activity-item.tsx @@ -0,0 +1,139 @@ +import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from '@langgenius/dify-ui/collapsible' +import { useTranslation } from 'react-i18next' + +export const SHELL_TOOL_NAMES = new Set([ + 'shell_run', + 'shell_wait', + 'shell_input', + 'shell_interrupt', +]) + +type ToolActivityStatus = + | 'started' + | 'running' + | 'succeeded' + | 'failed' + | 'cancelled' + | 'interrupted' + +export type ToolActivity = { + kind: 'shell' | 'tool' + key: string + name: string + label: string + input: string + output: string + isFinished: boolean + status?: ToolActivityStatus + error?: string | null +} + +export function ToolActivityItem({ tool }: { tool: ToolActivity }) { + const { t } = useTranslation(['agentV2', 'tools', 'workflow']) + const hasDetails = !!tool.input || !!tool.output || !!tool.error + const hasStatusBadge = + tool.status === 'failed' || tool.status === 'cancelled' || tool.status === 'interrupted' + const statusText = hasStatusBadge + ? tool.status === 'failed' + ? t(($) => $['tracing.status.failed'], { ns: 'workflow' }) + : t(($) => $['tracing.status.stopped'], { ns: 'workflow' }) + : '' + const resolvedPhase = + tool.status ?? (tool.isFinished ? ('succeeded' as const) : ('running' as const)) + const label = + tool.name === 'shell_run' && + tool.label === tool.name && + (resolvedPhase === 'started' || resolvedPhase === 'running' || resolvedPhase === 'succeeded') + ? resolvedPhase === 'started' + ? t(($) => $['agentDetail.configure.answer.activity.startingCommands'], { + ns: 'agentV2', + }) + : resolvedPhase === 'running' + ? t(($) => $['agentDetail.configure.answer.activity.runningCommands'], { + ns: 'agentV2', + }) + : t(($) => $['agentDetail.configure.answer.activity.ranCommands'], { ns: 'agentV2' }) + : tool.label + + const content = ( + <> + + + {!tool.isFinished ? ( + + ) : tool.status === 'failed' || tool.status === 'cancelled' ? ( + + ) : tool.status === 'interrupted' ? ( + + ) : tool.kind === 'shell' ? ( + + ) : ( + + )} + + {label} + {!!hasStatusBadge && statusText && ( + + {statusText} + + )} + + {hasDetails && ( + + )} + + ) + + return ( +
+ {hasDetails ? ( + + + {content} + + +
+ {!!tool.error && ( +
+
+ {tool.error} +
+
+ )} + {!!tool.input && ( +
+
+ {t(($) => $['thought.requestTitle'], { ns: 'tools' })} +
+
+ {tool.input} +
+
+ )} + {!!tool.output && ( +
+
+ {t(($) => $['thought.responseTitle'], { ns: 'tools' })} +
+
+ {tool.output} +
+
+ )} +
+
+
+ ) : ( +
+ {content} +
+ )} +
+ ) +} diff --git a/web/app/components/base/chat/chat/answer/workflow-tool-activity.stories.tsx b/web/app/components/base/chat/chat/answer/workflow-tool-activity.stories.tsx new file mode 100644 index 00000000000..24d58f6879a --- /dev/null +++ b/web/app/components/base/chat/chat/answer/workflow-tool-activity.stories.tsx @@ -0,0 +1,309 @@ +import type { Meta, StoryObj } from '@storybook/nextjs-vite' +import type { ChatItem } from '../../types' +import type { AgentLogResponse } from '@/types/workflow' +import { Button } from '@langgenius/dify-ui/button' +import { useEffect, useRef, useState } from 'react' +import Answer from '.' +import { upsertWorkflowToolActivity } from '../../workflow-agent-tool-activity' + +type Scenario = 'success' | 'failure' + +type ToolLogOptions = { + id: string + executionId: string + nodeTitle: string + label: string + status: 'started' | 'running' | 'succeeded' | 'failed' | 'cancelled' + error?: string | null + toolCallId: string + toolName: string + toolInput: string + toolOutput?: string +} + +const toolLog = ({ + id, + executionId, + nodeTitle, + label, + status, + error = null, + toolCallId, + toolName, + toolInput, + toolOutput = '', +}: ToolLogOptions): AgentLogResponse['data'] => ({ + id, + node_id: 'agent-node', + node_execution_id: executionId, + label, + error, + status, + data: { + tool_call_id: toolCallId, + tool_name: toolName, + tool_input: toolInput, + tool_output: toolOutput, + node_title: nodeTitle, + }, + metadata: { agent_node_version: '2', kind: 'tool' }, +}) + +const EMPTY_ITEM: ChatItem = { id: 'demo-answer', content: '', isAnswer: true } +const DEMO_QUESTION = 'Research Dify and list the files in the workspace' + +function WorkflowToolActivityDemo({ scenario }: { scenario: Scenario }) { + return +} + +function WorkflowToolActivityDemoInner({ scenario }: { scenario: Scenario }) { + const [item, setItem] = useState(EMPTY_ITEM) + const [responding, setResponding] = useState(false) + const [running, setRunning] = useState(false) + const timersRef = useRef([]) + const generationRef = useRef(0) + + const clearTimers = () => { + timersRef.current.forEach((timer) => window.clearTimeout(timer)) + timersRef.current = [] + } + + const schedule = (generation: number, delay: number, run: () => void) => { + const timer = window.setTimeout(() => { + if (generationRef.current === generation) run() + }, delay) + timersRef.current.push(timer) + } + + const emitLog = (log: AgentLogResponse['data']) => { + setItem((previous) => { + const next: ChatItem = { ...previous } + upsertWorkflowToolActivity(next, log) + return next + }) + } + + const appendText = (text: string) => { + setItem((previous) => ({ ...previous, content: previous.content + text })) + } + + const finishReplay = () => { + setResponding(false) + setRunning(false) + } + + const runDemo = () => { + clearTimers() + const generation = ++generationRef.current + setItem(EMPTY_ITEM) + setResponding(true) + setRunning(true) + + const searchA = { + executionId: 'exec-research', + nodeTitle: 'Research agent', + toolName: 'web_search', + toolInput: '{"q":"dify agent runtime"}', + } + const searchB = { + executionId: 'exec-research', + nodeTitle: 'Research agent', + toolName: 'web_search', + toolInput: '{"q":"dify workflow tools"}', + } + + if (scenario === 'failure') { + schedule(generation, 400, () => + emitLog( + toolLog({ + ...searchA, + id: 'run-demo:call-a', + label: 'web_search', + status: 'running', + toolCallId: 'call-a', + }), + ), + ) + schedule(generation, 1200, () => + emitLog( + toolLog({ + ...searchA, + id: 'run-demo:call-a', + label: 'web_search', + status: 'failed', + error: 'Search provider timed out after 30s.', + toolCallId: 'call-a', + }), + ), + ) + const failureText = 'The search tool failed, so I could not complete the research.' + failureText.split(' ').forEach((word, index) => { + schedule(generation, 1800 + index * 160, () => + appendText(`${index === 0 ? '' : ' '}${word}`), + ) + }) + schedule(generation, 1800 + failureText.split(' ').length * 160 + 300, finishReplay) + return + } + + schedule(generation, 400, () => + emitLog( + toolLog({ + ...searchA, + id: 'run-demo:call-a', + label: 'web_search', + status: 'running', + toolCallId: 'call-a', + }), + ), + ) + schedule(generation, 800, () => + emitLog( + toolLog({ + ...searchB, + id: 'run-demo:call-b', + label: 'web_search', + status: 'running', + toolCallId: 'call-b', + }), + ), + ) + schedule(generation, 1400, () => + emitLog( + toolLog({ + ...searchB, + id: 'run-demo:call-b', + label: 'web_search', + status: 'succeeded', + toolCallId: 'call-b', + toolOutput: + 'Dify Agent v2 runtime: tool calls stream as function_tool_call/result events.', + }), + ), + ) + schedule(generation, 2000, () => + emitLog( + toolLog({ + ...searchA, + id: 'run-demo:call-a', + label: 'web_search', + status: 'succeeded', + toolCallId: 'call-a', + toolOutput: 'Chatflow UI renders live tool activity above the answer text.', + }), + ), + ) + const shell = { + executionId: 'exec-shell', + nodeTitle: 'Shell agent', + toolName: 'shell_run', + id: 'run-demo:call-shell', + label: 'shell_run', + toolCallId: 'call-shell', + } + schedule(generation, 2600, () => + emitLog( + toolLog({ + ...shell, + toolInput: '{"script":"ls"}', + status: 'started', + }), + ), + ) + schedule(generation, 3200, () => + emitLog( + toolLog({ + ...shell, + toolInput: '{"script":"ls -la && wc -l notes.txt","timeout":30}', + status: 'running', + }), + ), + ) + schedule(generation, 4200, () => + emitLog( + toolLog({ + ...shell, + toolInput: '{"script":"ls -la && wc -l notes.txt","timeout":30}', + status: 'succeeded', + toolOutput: + 'total 8\ndrwxr-xr-x 2 demo staff 64 Jan 1 00:00 .\n-rw-r--r-- 1 demo staff 21 Jan 1 00:00 notes.txt\n 42 notes.txt', + }), + ), + ) + const answerText = + 'I searched the Dify documentation twice and listed the workspace files. Both tool calls completed successfully.' + answerText.split(' ').forEach((word, index) => { + schedule(generation, 4600 + index * 140, () => appendText(`${index === 0 ? '' : ' '}${word}`)) + }) + schedule(generation, 4600 + answerText.split(' ').length * 140 + 300, finishReplay) + } + + const stopReplay = () => { + clearTimers() + generationRef.current += 1 + setResponding(false) + setRunning(false) + } + + const resetDemo = () => { + stopReplay() + setItem(EMPTY_ITEM) + } + + useEffect(() => { + return () => { + generationRef.current += 1 + clearTimers() + } + }, []) + + return ( +
+
+

+ Simulated event replay — no model or tools are executed +

+
+ + + +
+
+
+
+ {DEMO_QUESTION} +
+
+ +
+ ) +} + +const meta = { + title: 'Base/Other/Chatflow Agent Tools', + component: WorkflowToolActivityDemo, + parameters: { + layout: 'fullscreen', + }, + argTypes: { + scenario: { + control: 'select', + options: ['success', 'failure'], + description: 'Which simulated tool-call sequence to replay.', + }, + }, + args: { + scenario: 'success', + }, +} satisfies Meta + +export default meta +type Story = StoryObj + +export const Default: Story = {} diff --git a/web/app/components/base/chat/chat/answer/workflow-tool-activity.tsx b/web/app/components/base/chat/chat/answer/workflow-tool-activity.tsx new file mode 100644 index 00000000000..827c5b9b9ff --- /dev/null +++ b/web/app/components/base/chat/chat/answer/workflow-tool-activity.tsx @@ -0,0 +1,64 @@ +import type { FC } from 'react' +import type { ChatItem } from '../../types' +import type { ToolActivity } from './tool-activity-item' +import { memo } from 'react' +import { SHELL_TOOL_NAMES, ToolActivityItem } from './tool-activity-item' + +type WorkflowToolActivityProps = { + item: ChatItem + responding?: boolean +} + +const WorkflowToolActivity: FC = ({ item, responding }) => { + const activities = item.workflowAgentActivities + if (!activities?.length) return null + + const groups = new Map() + for (const activity of activities) { + let group = groups.get(activity.node_execution_id) + if (!group) { + group = { + title: activity.data.node_title || activity.node_id, + tools: [], + } + groups.set(activity.node_execution_id, group) + } + const active = activity.status === 'started' || activity.status === 'running' + const finished = !active || !responding + const status = + activity.status === 'failed' || activity.status === 'cancelled' + ? activity.status + : active && !responding + ? 'interrupted' + : activity.status + group.tools.push({ + kind: SHELL_TOOL_NAMES.has(activity.data.tool_name) ? 'shell' : 'tool', + key: activity.id, + name: activity.data.tool_name, + label: activity.label || activity.data.tool_name, + input: activity.data.tool_input, + output: activity.data.tool_output, + isFinished: finished, + status, + error: activity.error, + }) + } + + return ( +
+ {[...groups.entries()].map(([executionId, group]) => ( +
+
{group.title}
+ {group.tools.map((tool) => ( + + ))} +
+ ))} +
+ ) +} + +export default memo(WorkflowToolActivity) diff --git a/web/app/components/base/chat/chat/hooks.ts b/web/app/components/base/chat/chat/hooks.ts index 30dc077cade..2156cca592d 100644 --- a/web/app/components/base/chat/chat/hooks.ts +++ b/web/app/components/base/chat/chat/hooks.ts @@ -36,6 +36,7 @@ import { useParams, usePathname } from '@/next/navigation' import { sseGet, ssePost } from '@/service/base' import { TransferMethod } from '@/types/app' import { getThreadMessages } from '../utils' +import { upsertWorkflowToolActivity } from '../workflow-agent-tool-activity' import { getProcessedInputs, processOpeningStatement } from './utils' type GetAbortController = (abortController: AbortController) => void @@ -808,6 +809,12 @@ export const useChat = ( } }) }, + onAgentLog(agentLog) { + if (requestGeneration !== workflowRequestGenerationRef.current) return + updateChatTreeNode(messageId, (responseItem) => { + upsertWorkflowToolActivity(responseItem, agentLog.data) + }) + }, onMessageEnd: (messageEnd) => { if (options.isNewAgent && messageEnd.conversation_id) conversationIdRef.current = messageEnd.conversation_id @@ -1477,6 +1484,16 @@ export const useChat = ( parentId: data.parent_message_id, }) }, + onAgentLog(agentLog) { + if (!isCurrentRequest()) return + upsertWorkflowToolActivity(responseItem, agentLog.data) + updateCurrentQAOnTree({ + placeholderQuestionId, + questionItem, + responseItem, + parentId: data.parent_message_id, + }) + }, onMessageEnd: (messageEnd) => { if (options.isNewAgent && messageEnd.conversation_id) conversationIdRef.current = messageEnd.conversation_id diff --git a/web/app/components/base/chat/types.ts b/web/app/components/base/chat/types.ts index e207da05c2f..0ed621cc044 100644 --- a/web/app/components/base/chat/types.ts +++ b/web/app/components/base/chat/types.ts @@ -43,9 +43,33 @@ export type WorkflowProcess = { humanInputFilledFormDataList?: HumanInputFilledFormData[] } +export type WorkflowAgentToolActivityStatus = + | 'started' + | 'running' + | 'succeeded' + | 'failed' + | 'cancelled' + +export type WorkflowAgentToolActivity = { + id: string + node_id: string + node_execution_id: string + label: string + status: WorkflowAgentToolActivityStatus + error: string | null + data: { + tool_call_id: string + tool_name: string + tool_input: string + tool_output: string + node_title: string + } +} + export type ChatItem = IChatItem & { isError?: boolean workflowProcess?: WorkflowProcess + workflowAgentActivities?: WorkflowAgentToolActivity[] conversationId?: string allFiles?: FileEntity[] } diff --git a/web/app/components/base/chat/workflow-agent-tool-activity.ts b/web/app/components/base/chat/workflow-agent-tool-activity.ts new file mode 100644 index 00000000000..20a4b90dfdc --- /dev/null +++ b/web/app/components/base/chat/workflow-agent-tool-activity.ts @@ -0,0 +1,63 @@ +import type { ChatItem, WorkflowAgentToolActivity, WorkflowAgentToolActivityStatus } from './types' +import type { AgentLogStreamData } from '@/types/workflow' + +const WORKFLOW_TOOL_ACTIVITY_STATUSES = new Set([ + 'started', + 'running', + 'succeeded', + 'failed', + 'cancelled', +]) + +const asRecord = (value: unknown): Record | undefined => + typeof value === 'object' && value !== null ? (value as Record) : undefined + +const asString = (value: unknown): string => (typeof value === 'string' ? value : '') + +export function isWorkflowAgentToolLog(event: AgentLogStreamData): boolean { + const metadata = asRecord(event.metadata) + return metadata?.agent_node_version === '2' && metadata?.kind === 'tool' +} + +export function upsertWorkflowToolActivity(item: ChatItem, event: AgentLogStreamData): void { + if (!isWorkflowAgentToolLog(event)) return + + const id = event.id + const nodeExecutionId = event.node_execution_id + const status = WORKFLOW_TOOL_ACTIVITY_STATUSES.has( + event.status as WorkflowAgentToolActivityStatus, + ) + ? (event.status as WorkflowAgentToolActivityStatus) + : null + if (!id || !nodeExecutionId || !status) return + + const data = asRecord(event.data) + const toolCallId = asString(data?.tool_call_id) + const toolName = asString(data?.tool_name) + if (!toolCallId || !toolName) return + + const activity: WorkflowAgentToolActivity = { + id, + node_id: asString(event.node_id), + node_execution_id: nodeExecutionId, + label: asString(event.label) || toolName, + status, + error: typeof event.error === 'string' && event.error ? event.error : null, + data: { + tool_call_id: toolCallId, + tool_name: toolName, + tool_input: asString(data?.tool_input), + tool_output: asString(data?.tool_output), + node_title: asString(data?.node_title), + }, + } + + const activities = item.workflowAgentActivities ?? [] + const index = activities.findIndex( + (existing) => existing.node_execution_id === nodeExecutionId && existing.id === id, + ) + item.workflowAgentActivities = + index > -1 + ? activities.map((existing, i) => (i === index ? activity : existing)) + : [...activities, activity] +} diff --git a/web/app/components/workflow/hooks/use-workflow-run-event/__tests__/use-workflow-agent-log.spec.ts b/web/app/components/workflow/hooks/use-workflow-run-event/__tests__/use-workflow-agent-log.spec.ts index 381b812b62c..40fa5b73681 100644 --- a/web/app/components/workflow/hooks/use-workflow-run-event/__tests__/use-workflow-agent-log.spec.ts +++ b/web/app/components/workflow/hooks/use-workflow-run-event/__tests__/use-workflow-agent-log.spec.ts @@ -1,23 +1,19 @@ -import type { AgentLogResponse } from '@/types/workflow' +import type { AgentLogResponse, AgentLogStreamData } from '@/types/workflow' import { act } from '@testing-library/react' import { createNodeTracing } from '../../../__tests__/fixtures' import { baseRunningData, renderWorkflowHook } from '../../../__tests__/workflow-test-env' import { useWorkflowAgentLog } from '../use-workflow-agent-log' -const event = ( - messageId: string, - overrides: Partial = {}, -): AgentLogResponse => ({ +const event = (id: string, overrides: Partial = {}): AgentLogResponse => ({ task_id: 'task-1', event: 'agent_log', data: { node_execution_id: 'execution-1', node_id: 'n1', - message_id: messageId, + id, label: 'Tool call', data: { result: 'initial' }, status: 'start', - children: [], ...overrides, }, }) @@ -36,7 +32,16 @@ it.each([undefined, { total_tokens: 0, total_price: 0, currency: 'USD' }])( act(() => result.current.handleWorkflowAgentLog(incoming)) expect(store.getState().workflowRunningData!.tracing![0]!.execution_metadata).toEqual({ ...execution_metadata, - agent_log: [incoming.data], + agent_log: [ + { + node_execution_id: 'execution-1', + message_id: 'm1', + node_id: 'n1', + label: 'Tool call', + data: { result: 'initial' }, + status: 'start', + }, + ], }) }, ) @@ -60,8 +65,42 @@ it('appends messages and merges repeated message updates only into their matchin act(() => result.current.handleWorkflowAgentLog(updated)) const traces = store.getState().workflowRunningData!.tracing! expect(traces[0]!.execution_metadata!.agent_log).toEqual([ - { ...first.data, ...updated.data }, - second.data, + { + node_execution_id: 'execution-1', + message_id: 'm1', + node_id: 'n1', + label: 'Tool call', + data: { result: 'completed' }, + status: 'success', + }, + { + node_execution_id: 'execution-1', + message_id: 'm2', + node_id: 'n1', + label: 'Tool call', + data: { result: 'initial' }, + status: 'start', + }, ]) expect(traces[1]).toEqual(other) }) + +it('skips Agent v2 tool snapshots so they never enter node tracing', () => { + const tracing = createNodeTracing({ node_id: 'n1' }) + const { result, store } = renderWorkflowHook(useWorkflowAgentLog, { + initialStoreState: { + workflowRunningData: baseRunningData({ tracing: [tracing] }), + }, + }) + act(() => + result.current.handleWorkflowAgentLog( + event('tool-1', { + metadata: { agent_node_version: '2', kind: 'tool' }, + data: { tool_name: 'shell_run', tool_call_id: 'call-1' }, + }), + ), + ) + const traces = store.getState().workflowRunningData!.tracing! + expect(traces).toHaveLength(1) + expect(traces[0]!.execution_metadata?.agent_log).toBeUndefined() +}) diff --git a/web/app/components/workflow/hooks/use-workflow-run-event/use-workflow-agent-log.ts b/web/app/components/workflow/hooks/use-workflow-run-event/use-workflow-agent-log.ts index 336af598fda..f36c9306bd1 100644 --- a/web/app/components/workflow/hooks/use-workflow-run-event/use-workflow-agent-log.ts +++ b/web/app/components/workflow/hooks/use-workflow-run-event/use-workflow-agent-log.ts @@ -1,41 +1,67 @@ -import type { AgentLogResponse } from '@/types/workflow' +import type { AgentLogItem, AgentLogStreamData } from '@/types/workflow' import { produce } from 'immer' import { useCallback } from 'react' +import { isWorkflowAgentToolLog } from '@/app/components/base/chat/workflow-agent-tool-activity' import { useWorkflowStore } from '@/app/components/workflow/store' +const agentLogMetadata = ( + metadata: Record | undefined, +): AgentLogItem['metadata'] => { + if (!metadata) return undefined + const narrowed: NonNullable = {} + if (typeof metadata.elapsed_time === 'number') narrowed.elapsed_time = metadata.elapsed_time + if (typeof metadata.provider === 'string') narrowed.provider = metadata.provider + if (typeof metadata.icon === 'string') narrowed.icon = metadata.icon + return Object.keys(narrowed).length > 0 ? narrowed : undefined +} + +export const agentLogItemFromStream = (data: AgentLogStreamData): AgentLogItem => ({ + node_execution_id: data.node_execution_id, + message_id: data.id, + node_id: data.node_id, + parent_id: data.parent_id ?? undefined, + label: data.label, + data: data.data, + error: data.error ?? undefined, + status: data.status, + metadata: agentLogMetadata(data.metadata), +}) + export const useWorkflowAgentLog = () => { const workflowStore = useWorkflowStore() const handleWorkflowAgentLog = useCallback( - (params: AgentLogResponse) => { + (params: { data: AgentLogStreamData }) => { const { data } = params + if (isWorkflowAgentToolLog(data)) return + const item = agentLogItemFromStream(data) const { workflowRunningData, setWorkflowRunningData } = workflowStore.getState() setWorkflowRunningData( produce(workflowRunningData!, (draft) => { - const currentIndex = draft.tracing!.findIndex((item) => item.node_id === data.node_id) + const currentIndex = draft.tracing!.findIndex((node) => node.node_id === data.node_id) if (currentIndex > -1) { const current = draft.tracing![currentIndex] if (current!.execution_metadata) { if (current!.execution_metadata.agent_log) { const currentLogIndex = current!.execution_metadata.agent_log.findIndex( - (log) => log.message_id === data.message_id, + (log) => log.message_id === item.message_id, ) if (currentLogIndex > -1) { current!.execution_metadata.agent_log[currentLogIndex] = { ...current!.execution_metadata.agent_log[currentLogIndex], - ...data, + ...item, } } else { - current!.execution_metadata.agent_log.push(data) + current!.execution_metadata.agent_log.push(item) } } else { - current!.execution_metadata.agent_log = [data] + current!.execution_metadata.agent_log = [item] } } else { current!.execution_metadata = { - agent_log: [data], + agent_log: [item], } as any } } diff --git a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/sse-callbacks.spec.ts b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/sse-callbacks.spec.ts index 3068448e43b..13db5073146 100644 --- a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/sse-callbacks.spec.ts +++ b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/sse-callbacks.spec.ts @@ -710,20 +710,20 @@ describe('useChat – handleSend SSE callbacks', () => { }) it.each([undefined, { parallel_id: 'p1' }])( - 'accumulates agent logs by message ID without losing metadata: %j', + 'accumulates agent logs by stream id without losing metadata: %j', (metadata) => { const { result } = setupAndSend() startWorkflow() startNode('agent-node', 'trace-agent', { execution_metadata: metadata }) act(() => { capturedCallbacks.onAgentLog({ - data: { node_id: 'agent-node', message_id: 'log-1', data: { text: 'initial' } }, + data: { node_id: 'agent-node', id: 'log-1', data: { text: 'initial' } }, }) capturedCallbacks.onAgentLog({ - data: { node_id: 'agent-node', message_id: 'log-2', data: { text: 'second' } }, + data: { node_id: 'agent-node', id: 'log-2', data: { text: 'second' } }, }) capturedCallbacks.onAgentLog({ - data: { node_id: 'agent-node', message_id: 'log-1', data: { text: 'updated' } }, + data: { node_id: 'agent-node', id: 'log-1', data: { text: 'updated' } }, }) }) const trace = result.current.chatList.find((item) => item.isAnswer)!.workflowProcess! @@ -738,6 +738,42 @@ describe('useChat – handleSend SSE callbacks', () => { }, ) + it('routes Agent v2 tool snapshots to workflowAgentActivities without touching tracing', () => { + const { result } = setupAndSend() + startWorkflow() + startNode('agent-node', 'trace-agent', { execution_metadata: { parallel_id: 'p1' } }) + act(() => { + capturedCallbacks.onAgentLog({ + data: { + node_id: 'agent-node', + node_execution_id: 'exec-1', + id: 'run-1:call-1', + label: 'shell_run', + status: 'running', + data: { + tool_call_id: 'call-1', + tool_name: 'shell_run', + tool_input: '{"command":"ls"}', + tool_output: '', + node_title: 'Agent', + }, + metadata: { agent_node_version: '2', kind: 'tool' }, + }, + }) + }) + const answer = result.current.chatList.find( + (item) => item.isAnswer && !item.isOpeningStatement, + )! + expect(answer.workflowAgentActivities).toHaveLength(1) + expect(answer.workflowAgentActivities![0]).toMatchObject({ + id: 'run-1:call-1', + node_execution_id: 'exec-1', + status: 'running', + }) + const trace = answer.workflowProcess!.tracing[0]! + expect(trace.execution_metadata).toEqual({ parallel_id: 'p1' }) + }) + describe('onHumanInputRequired', () => { it('should add form data to humanInputFormDataList', () => { const { result } = setupAndSend() diff --git a/web/app/components/workflow/panel/debug-and-preview/hooks.ts b/web/app/components/workflow/panel/debug-and-preview/hooks.ts index f9c06b00888..da5dbef6b44 100644 --- a/web/app/components/workflow/panel/debug-and-preview/hooks.ts +++ b/web/app/components/workflow/panel/debug-and-preview/hooks.ts @@ -18,6 +18,10 @@ import { } from '@/app/components/base/chat/chat/answer/human-input-content/form-state' import { getProcessedInputs, processOpeningStatement } from '@/app/components/base/chat/chat/utils' import { getThreadMessages } from '@/app/components/base/chat/utils' +import { + isWorkflowAgentToolLog, + upsertWorkflowToolActivity, +} from '@/app/components/base/chat/workflow-agent-tool-activity' import { getProcessedFiles, getProcessedFilesFromResponse, @@ -33,6 +37,7 @@ import { DEFAULT_ITER_TIMES, DEFAULT_LOOP_TIMES } from '../../constants' import { useHooksStore } from '../../hooks-store' import { useSetWorkflowVarsWithValue } from '../../hooks/use-set-workflow-vars-with-value' import { useWorkflowRun } from '../../hooks/use-workflow-run' +import { agentLogItemFromStream } from '../../hooks/use-workflow-run-event/use-workflow-agent-log' import { useWorkflowStore } from '../../store' import { NodeRunningStatus, WorkflowRunningStatus } from '../../types' @@ -592,45 +597,49 @@ export const useChat = ( } }, onAgentLog: ({ data }) => { - const currentNodeIndex = responseItem.workflowProcess!.tracing!.findIndex( - (item) => item.node_id === data.node_id, - ) - if (currentNodeIndex > -1) { - const current = responseItem.workflowProcess!.tracing![currentNodeIndex]! + upsertWorkflowToolActivity(responseItem, data) + if (!isWorkflowAgentToolLog(data)) { + const item = agentLogItemFromStream(data) + const currentNodeIndex = responseItem.workflowProcess!.tracing!.findIndex( + (tracing) => tracing.node_id === item.node_id, + ) + if (currentNodeIndex > -1) { + const current = responseItem.workflowProcess!.tracing![currentNodeIndex]! - if (current!.execution_metadata) { - if (current!.execution_metadata.agent_log) { - const currentLogIndex = current!.execution_metadata.agent_log.findIndex( - (log) => log.message_id === data.message_id, - ) - if (currentLogIndex > -1) { - current!.execution_metadata.agent_log[currentLogIndex] = { - ...current!.execution_metadata.agent_log[currentLogIndex], - ...data, + if (current!.execution_metadata) { + if (current!.execution_metadata.agent_log) { + const currentLogIndex = current!.execution_metadata.agent_log.findIndex( + (log) => log.message_id === item.message_id, + ) + if (currentLogIndex > -1) { + current!.execution_metadata.agent_log[currentLogIndex] = { + ...current!.execution_metadata.agent_log[currentLogIndex], + ...item, + } + } else { + current!.execution_metadata.agent_log.push(item) } } else { - current!.execution_metadata.agent_log.push(data) + current!.execution_metadata.agent_log = [item] } } else { - current!.execution_metadata.agent_log = [data] + current!.execution_metadata = { + agent_log: [item], + } as any } - } else { - current!.execution_metadata = { - agent_log: [data], - } as any - } - responseItem.workflowProcess!.tracing[currentNodeIndex] = { - ...current, + responseItem.workflowProcess!.tracing[currentNodeIndex] = { + ...current, + } } - - updateCurrentQAOnTree({ - placeholderQuestionId, - questionItem, - responseItem, - parentId: params.parent_message_id, - }) } + + updateCurrentQAOnTree({ + placeholderQuestionId, + questionItem, + responseItem, + parentId: params.parent_message_id, + }) }, onHumanInputRequired: ({ data }) => { updatePendingHumanInputForm(responseItem, data) @@ -954,6 +963,11 @@ export const useChat = ( responseItem.workflowProcess!.status = WorkflowRunningStatus.Paused }) }, + onAgentLog: ({ data }) => { + updateChatTreeNode(messageId, (responseItem) => { + upsertWorkflowToolActivity(responseItem, data) + }) + }, } if (workflowEventsAbortControllerRef.current) workflowEventsAbortControllerRef.current.abort() diff --git a/web/i18n/locales/ar-TN/agent-v-2.json b/web/i18n/locales/ar-TN/agent-v-2.json index 933132d9690..cee433b26ca 100644 --- a/web/i18n/locales/ar-TN/agent-v-2.json +++ b/web/i18n/locales/ar-TN/agent-v-2.json @@ -65,6 +65,7 @@ "agentDetail.configure.advancedSettings.label": "الإعدادات المتقدمة", "agentDetail.configure.answer.activity.ranCommands": "تم تشغيل الأوامر", "agentDetail.configure.answer.activity.runningCommands": "جارٍ تشغيل الأوامر", + "agentDetail.configure.answer.activity.startingCommands": "جارٍ بدء تشغيل الأوامر", "agentDetail.configure.answer.duration.minute": "{{count}} د", "agentDetail.configure.answer.duration.second": "{{count}} ث", "agentDetail.configure.answer.responseEnded": "انتهت الاستجابة", diff --git a/web/i18n/locales/az-AZ/agent-v-2.json b/web/i18n/locales/az-AZ/agent-v-2.json index ffe07fea910..7d981a02d85 100644 --- a/web/i18n/locales/az-AZ/agent-v-2.json +++ b/web/i18n/locales/az-AZ/agent-v-2.json @@ -65,6 +65,7 @@ "agentDetail.configure.advancedSettings.label": "Əlavə parametrlər", "agentDetail.configure.answer.activity.ranCommands": "İcra edilmiş əmrlər", "agentDetail.configure.answer.activity.runningCommands": "Əmrlər icra olunur", + "agentDetail.configure.answer.activity.startingCommands": "Əmrlər başladılır", "agentDetail.configure.answer.duration.minute": "{{count}} dəq", "agentDetail.configure.answer.duration.second": "{{count}} san", "agentDetail.configure.answer.responseEnded": "Cavab tamamlandı", diff --git a/web/i18n/locales/de-DE/agent-v-2.json b/web/i18n/locales/de-DE/agent-v-2.json index fef3a4a2bf8..8f526eeb2c2 100644 --- a/web/i18n/locales/de-DE/agent-v-2.json +++ b/web/i18n/locales/de-DE/agent-v-2.json @@ -65,6 +65,7 @@ "agentDetail.configure.advancedSettings.label": "Erweiterte Einstellungen", "agentDetail.configure.answer.activity.ranCommands": "Befehle ausgeführt", "agentDetail.configure.answer.activity.runningCommands": "Befehle werden ausgeführt", + "agentDetail.configure.answer.activity.startingCommands": "Befehle werden gestartet", "agentDetail.configure.answer.duration.minute": "{{count}} Min.", "agentDetail.configure.answer.duration.second": "{{count}} s", "agentDetail.configure.answer.responseEnded": "Antwort beendet", diff --git a/web/i18n/locales/en-US/agent-v-2.json b/web/i18n/locales/en-US/agent-v-2.json index 2b40e297a2d..5c49dbcf30e 100644 --- a/web/i18n/locales/en-US/agent-v-2.json +++ b/web/i18n/locales/en-US/agent-v-2.json @@ -65,6 +65,7 @@ "agentDetail.configure.advancedSettings.label": "Advanced Settings", "agentDetail.configure.answer.activity.ranCommands": "Ran commands", "agentDetail.configure.answer.activity.runningCommands": "Running commands", + "agentDetail.configure.answer.activity.startingCommands": "Starting commands", "agentDetail.configure.answer.duration.minute": "{{count}}m", "agentDetail.configure.answer.duration.second": "{{count}}s", "agentDetail.configure.answer.responseEnded": "Response ended", diff --git a/web/i18n/locales/es-ES/agent-v-2.json b/web/i18n/locales/es-ES/agent-v-2.json index 2af16d57d40..c01e7f6c768 100644 --- a/web/i18n/locales/es-ES/agent-v-2.json +++ b/web/i18n/locales/es-ES/agent-v-2.json @@ -65,6 +65,7 @@ "agentDetail.configure.advancedSettings.label": "Configuración avanzada", "agentDetail.configure.answer.activity.ranCommands": "Comandos ejecutados", "agentDetail.configure.answer.activity.runningCommands": "Ejecutando comandos", + "agentDetail.configure.answer.activity.startingCommands": "Iniciando comandos", "agentDetail.configure.answer.duration.minute": "{{count}} min", "agentDetail.configure.answer.duration.second": "{{count}} s", "agentDetail.configure.answer.responseEnded": "La respuesta ha terminado", diff --git a/web/i18n/locales/fa-IR/agent-v-2.json b/web/i18n/locales/fa-IR/agent-v-2.json index 8ac3b709332..0ff50d6b52d 100644 --- a/web/i18n/locales/fa-IR/agent-v-2.json +++ b/web/i18n/locales/fa-IR/agent-v-2.json @@ -65,6 +65,7 @@ "agentDetail.configure.advancedSettings.label": "تنظیمات پیشرفته", "agentDetail.configure.answer.activity.ranCommands": "دستورات اجرا شدند", "agentDetail.configure.answer.activity.runningCommands": "در حال اجرای دستورات", + "agentDetail.configure.answer.activity.startingCommands": "در حال شروع اجرای دستورات", "agentDetail.configure.answer.duration.minute": "{{count}} دقیقه", "agentDetail.configure.answer.duration.second": "{{count}} ثانیه", "agentDetail.configure.answer.responseEnded": "پاسخ پایان یافت", diff --git a/web/i18n/locales/fr-FR/agent-v-2.json b/web/i18n/locales/fr-FR/agent-v-2.json index 303afb98ead..0ada4848186 100644 --- a/web/i18n/locales/fr-FR/agent-v-2.json +++ b/web/i18n/locales/fr-FR/agent-v-2.json @@ -65,6 +65,7 @@ "agentDetail.configure.advancedSettings.label": "Paramètres avancés", "agentDetail.configure.answer.activity.ranCommands": "Commandes exécutées", "agentDetail.configure.answer.activity.runningCommands": "Exécution des commandes", + "agentDetail.configure.answer.activity.startingCommands": "Démarrage des commandes", "agentDetail.configure.answer.duration.minute": "{{count}} min", "agentDetail.configure.answer.duration.second": "{{count}} s", "agentDetail.configure.answer.responseEnded": "La réponse est terminée", diff --git a/web/i18n/locales/hi-IN/agent-v-2.json b/web/i18n/locales/hi-IN/agent-v-2.json index daa5530b105..41b561be747 100644 --- a/web/i18n/locales/hi-IN/agent-v-2.json +++ b/web/i18n/locales/hi-IN/agent-v-2.json @@ -65,6 +65,7 @@ "agentDetail.configure.advancedSettings.label": "उन्नत सेटिंग्स", "agentDetail.configure.answer.activity.ranCommands": "कमांड चलाए गए", "agentDetail.configure.answer.activity.runningCommands": "कमांड चलाए जा रहे हैं", + "agentDetail.configure.answer.activity.startingCommands": "कमांड शुरू हो रहे हैं", "agentDetail.configure.answer.duration.minute": "{{count}} मिनट", "agentDetail.configure.answer.duration.second": "{{count}} सेकंड", "agentDetail.configure.answer.responseEnded": "उत्तर समाप्त हुआ", diff --git a/web/i18n/locales/id-ID/agent-v-2.json b/web/i18n/locales/id-ID/agent-v-2.json index 4fedddfd5c0..c9eec47fe91 100644 --- a/web/i18n/locales/id-ID/agent-v-2.json +++ b/web/i18n/locales/id-ID/agent-v-2.json @@ -65,6 +65,7 @@ "agentDetail.configure.advancedSettings.label": "Pengaturan Lanjutan", "agentDetail.configure.answer.activity.ranCommands": "Perintah dijalankan", "agentDetail.configure.answer.activity.runningCommands": "Menjalankan perintah", + "agentDetail.configure.answer.activity.startingCommands": "Memulai perintah", "agentDetail.configure.answer.duration.minute": "{{count}} mnt", "agentDetail.configure.answer.duration.second": "{{count}} dtk", "agentDetail.configure.answer.responseEnded": "Respons berakhir", diff --git a/web/i18n/locales/it-IT/agent-v-2.json b/web/i18n/locales/it-IT/agent-v-2.json index 731d8a624f9..96fa4fa5da2 100644 --- a/web/i18n/locales/it-IT/agent-v-2.json +++ b/web/i18n/locales/it-IT/agent-v-2.json @@ -65,6 +65,7 @@ "agentDetail.configure.advancedSettings.label": "Impostazioni avanzate", "agentDetail.configure.answer.activity.ranCommands": "Comandi eseguiti", "agentDetail.configure.answer.activity.runningCommands": "Esecuzione dei comandi", + "agentDetail.configure.answer.activity.startingCommands": "Avvio dei comandi", "agentDetail.configure.answer.duration.minute": "{{count}} min", "agentDetail.configure.answer.duration.second": "{{count}} s", "agentDetail.configure.answer.responseEnded": "La risposta è terminata", diff --git a/web/i18n/locales/ja-JP/agent-v-2.json b/web/i18n/locales/ja-JP/agent-v-2.json index 74505625211..0c339aa227d 100644 --- a/web/i18n/locales/ja-JP/agent-v-2.json +++ b/web/i18n/locales/ja-JP/agent-v-2.json @@ -65,6 +65,7 @@ "agentDetail.configure.advancedSettings.label": "詳細設定", "agentDetail.configure.answer.activity.ranCommands": "コマンドを実行しました", "agentDetail.configure.answer.activity.runningCommands": "コマンドを実行中", + "agentDetail.configure.answer.activity.startingCommands": "コマンドを開始中", "agentDetail.configure.answer.duration.minute": "{{count}}分", "agentDetail.configure.answer.duration.second": "{{count}}秒", "agentDetail.configure.answer.responseEnded": "応答が終了しました", diff --git a/web/i18n/locales/ko-KR/agent-v-2.json b/web/i18n/locales/ko-KR/agent-v-2.json index 5c3abfbb8d2..366afac5e92 100644 --- a/web/i18n/locales/ko-KR/agent-v-2.json +++ b/web/i18n/locales/ko-KR/agent-v-2.json @@ -65,6 +65,7 @@ "agentDetail.configure.advancedSettings.label": "고급 설정", "agentDetail.configure.answer.activity.ranCommands": "명령 실행됨", "agentDetail.configure.answer.activity.runningCommands": "명령 실행 중", + "agentDetail.configure.answer.activity.startingCommands": "명령 시작 중", "agentDetail.configure.answer.duration.minute": "{{count}}분", "agentDetail.configure.answer.duration.second": "{{count}}초", "agentDetail.configure.answer.responseEnded": "응답이 종료되었습니다", diff --git a/web/i18n/locales/lo-LA/agent-v-2.json b/web/i18n/locales/lo-LA/agent-v-2.json index b14f57dcf6b..03db44e9850 100644 --- a/web/i18n/locales/lo-LA/agent-v-2.json +++ b/web/i18n/locales/lo-LA/agent-v-2.json @@ -65,6 +65,7 @@ "agentDetail.configure.advancedSettings.label": "ການຕັ້ງຄ່າຂັ້ນສູງ", "agentDetail.configure.answer.activity.ranCommands": "ຄຳສັ່ງທີ່ເຮັດວຽກແລ້ວ", "agentDetail.configure.answer.activity.runningCommands": "ກຳລັງປະຕິບັດຄຳສັ່ງ", + "agentDetail.configure.answer.activity.startingCommands": "ກຳລັງເລີ່ມປະຕິບັດຄຳສັ່ງ", "agentDetail.configure.answer.duration.minute": "{{count}} ນາທີ", "agentDetail.configure.answer.duration.second": "{{count}} ວິນາທີ", "agentDetail.configure.answer.responseEnded": "ການຕອບກັບສິ້ນສຸດແລ້ວ", diff --git a/web/i18n/locales/nl-NL/agent-v-2.json b/web/i18n/locales/nl-NL/agent-v-2.json index 1303e8cb453..9182419178e 100644 --- a/web/i18n/locales/nl-NL/agent-v-2.json +++ b/web/i18n/locales/nl-NL/agent-v-2.json @@ -65,6 +65,7 @@ "agentDetail.configure.advancedSettings.label": "Geavanceerde instellingen", "agentDetail.configure.answer.activity.ranCommands": "Opdrachten uitgevoerd", "agentDetail.configure.answer.activity.runningCommands": "Opdrachten uitvoeren", + "agentDetail.configure.answer.activity.startingCommands": "Opdrachten starten", "agentDetail.configure.answer.duration.minute": "{{count}} min", "agentDetail.configure.answer.duration.second": "{{count}} s", "agentDetail.configure.answer.responseEnded": "Antwoord beëindigd", diff --git a/web/i18n/locales/pl-PL/agent-v-2.json b/web/i18n/locales/pl-PL/agent-v-2.json index a4853490389..ec8dc9f8f98 100644 --- a/web/i18n/locales/pl-PL/agent-v-2.json +++ b/web/i18n/locales/pl-PL/agent-v-2.json @@ -65,6 +65,7 @@ "agentDetail.configure.advancedSettings.label": "Ustawienia zaawansowane", "agentDetail.configure.answer.activity.ranCommands": "Uruchomiono polecenia", "agentDetail.configure.answer.activity.runningCommands": "Uruchamianie poleceń", + "agentDetail.configure.answer.activity.startingCommands": "Rozpoczynanie poleceń", "agentDetail.configure.answer.duration.minute": "{{count}} min", "agentDetail.configure.answer.duration.second": "{{count}} s", "agentDetail.configure.answer.responseEnded": "Odpowiedź zakończona", diff --git a/web/i18n/locales/pt-BR/agent-v-2.json b/web/i18n/locales/pt-BR/agent-v-2.json index d2f1950aae2..71ac353f703 100644 --- a/web/i18n/locales/pt-BR/agent-v-2.json +++ b/web/i18n/locales/pt-BR/agent-v-2.json @@ -65,6 +65,7 @@ "agentDetail.configure.advancedSettings.label": "Configurações avançadas", "agentDetail.configure.answer.activity.ranCommands": "Comandos executados", "agentDetail.configure.answer.activity.runningCommands": "Executando comandos", + "agentDetail.configure.answer.activity.startingCommands": "Iniciando comandos", "agentDetail.configure.answer.duration.minute": "{{count}} min", "agentDetail.configure.answer.duration.second": "{{count}} s", "agentDetail.configure.answer.responseEnded": "A resposta terminou", diff --git a/web/i18n/locales/ro-RO/agent-v-2.json b/web/i18n/locales/ro-RO/agent-v-2.json index bcfb694c404..9e59c914645 100644 --- a/web/i18n/locales/ro-RO/agent-v-2.json +++ b/web/i18n/locales/ro-RO/agent-v-2.json @@ -65,6 +65,7 @@ "agentDetail.configure.advancedSettings.label": "Setări avansate", "agentDetail.configure.answer.activity.ranCommands": "Comenzi executate", "agentDetail.configure.answer.activity.runningCommands": "Se execută comenzile", + "agentDetail.configure.answer.activity.startingCommands": "Se pornesc comenzile", "agentDetail.configure.answer.duration.minute": "{{count}} min", "agentDetail.configure.answer.duration.second": "{{count}} s", "agentDetail.configure.answer.responseEnded": "Răspunsul s-a încheiat", diff --git a/web/i18n/locales/ru-RU/agent-v-2.json b/web/i18n/locales/ru-RU/agent-v-2.json index 806471a58ae..12e3f4bf634 100644 --- a/web/i18n/locales/ru-RU/agent-v-2.json +++ b/web/i18n/locales/ru-RU/agent-v-2.json @@ -65,6 +65,7 @@ "agentDetail.configure.advancedSettings.label": "Расширенные настройки", "agentDetail.configure.answer.activity.ranCommands": "Команды выполнены", "agentDetail.configure.answer.activity.runningCommands": "Выполнение команд", + "agentDetail.configure.answer.activity.startingCommands": "Запуск команд", "agentDetail.configure.answer.duration.minute": "{{count}} мин", "agentDetail.configure.answer.duration.second": "{{count}} с", "agentDetail.configure.answer.responseEnded": "Ответ завершён", diff --git a/web/i18n/locales/sl-SI/agent-v-2.json b/web/i18n/locales/sl-SI/agent-v-2.json index 7440257bf8f..5483e5f5486 100644 --- a/web/i18n/locales/sl-SI/agent-v-2.json +++ b/web/i18n/locales/sl-SI/agent-v-2.json @@ -65,6 +65,7 @@ "agentDetail.configure.advancedSettings.label": "Napredne nastavitve", "agentDetail.configure.answer.activity.ranCommands": "Ukazi izvedeni", "agentDetail.configure.answer.activity.runningCommands": "Izvajanje ukazov", + "agentDetail.configure.answer.activity.startingCommands": "Začenjanje ukazov", "agentDetail.configure.answer.duration.minute": "{{count}} min", "agentDetail.configure.answer.duration.second": "{{count}} s", "agentDetail.configure.answer.responseEnded": "Odgovor je končan", diff --git a/web/i18n/locales/th-TH/agent-v-2.json b/web/i18n/locales/th-TH/agent-v-2.json index dabf226086e..488401dca5a 100644 --- a/web/i18n/locales/th-TH/agent-v-2.json +++ b/web/i18n/locales/th-TH/agent-v-2.json @@ -65,6 +65,7 @@ "agentDetail.configure.advancedSettings.label": "การตั้งค่าขั้นสูง", "agentDetail.configure.answer.activity.ranCommands": "เรียกใช้คำสั่งแล้ว", "agentDetail.configure.answer.activity.runningCommands": "กำลังเรียกใช้คำสั่ง", + "agentDetail.configure.answer.activity.startingCommands": "กำลังเริ่มเรียกใช้คำสั่ง", "agentDetail.configure.answer.duration.minute": "{{count}} นาที", "agentDetail.configure.answer.duration.second": "{{count}} วินาที", "agentDetail.configure.answer.responseEnded": "การตอบกลับสิ้นสุดแล้ว", diff --git a/web/i18n/locales/tr-TR/agent-v-2.json b/web/i18n/locales/tr-TR/agent-v-2.json index 2e92f785083..196d8c4fcc0 100644 --- a/web/i18n/locales/tr-TR/agent-v-2.json +++ b/web/i18n/locales/tr-TR/agent-v-2.json @@ -65,6 +65,7 @@ "agentDetail.configure.advancedSettings.label": "Gelişmiş Ayarlar", "agentDetail.configure.answer.activity.ranCommands": "Komutlar çalıştırıldı", "agentDetail.configure.answer.activity.runningCommands": "Komutlar çalıştırılıyor", + "agentDetail.configure.answer.activity.startingCommands": "Komutlar başlatılıyor", "agentDetail.configure.answer.duration.minute": "{{count}} dk", "agentDetail.configure.answer.duration.second": "{{count}} sn", "agentDetail.configure.answer.responseEnded": "Yanıt sona erdi", diff --git a/web/i18n/locales/uk-UA/agent-v-2.json b/web/i18n/locales/uk-UA/agent-v-2.json index fbf6270c837..a586bffd30d 100644 --- a/web/i18n/locales/uk-UA/agent-v-2.json +++ b/web/i18n/locales/uk-UA/agent-v-2.json @@ -65,6 +65,7 @@ "agentDetail.configure.advancedSettings.label": "Розширені налаштування", "agentDetail.configure.answer.activity.ranCommands": "Команди виконано", "agentDetail.configure.answer.activity.runningCommands": "Виконання команд", + "agentDetail.configure.answer.activity.startingCommands": "Запуск команд", "agentDetail.configure.answer.duration.minute": "{{count}} хв", "agentDetail.configure.answer.duration.second": "{{count}} с", "agentDetail.configure.answer.responseEnded": "Відповідь завершено", diff --git a/web/i18n/locales/vi-VN/agent-v-2.json b/web/i18n/locales/vi-VN/agent-v-2.json index 805bdbaaaab..00002ad62d5 100644 --- a/web/i18n/locales/vi-VN/agent-v-2.json +++ b/web/i18n/locales/vi-VN/agent-v-2.json @@ -65,6 +65,7 @@ "agentDetail.configure.advancedSettings.label": "Cài đặt nâng cao", "agentDetail.configure.answer.activity.ranCommands": "Đã chạy lệnh", "agentDetail.configure.answer.activity.runningCommands": "Đang chạy lệnh", + "agentDetail.configure.answer.activity.startingCommands": "Đang bắt đầu chạy lệnh", "agentDetail.configure.answer.duration.minute": "{{count}} phút", "agentDetail.configure.answer.duration.second": "{{count}} giây", "agentDetail.configure.answer.responseEnded": "Phản hồi đã kết thúc", diff --git a/web/i18n/locales/zh-Hans/agent-v-2.json b/web/i18n/locales/zh-Hans/agent-v-2.json index bbb9cc61176..04fbb4a5727 100644 --- a/web/i18n/locales/zh-Hans/agent-v-2.json +++ b/web/i18n/locales/zh-Hans/agent-v-2.json @@ -65,6 +65,7 @@ "agentDetail.configure.advancedSettings.label": "高级设置", "agentDetail.configure.answer.activity.ranCommands": "已运行命令", "agentDetail.configure.answer.activity.runningCommands": "正在运行命令", + "agentDetail.configure.answer.activity.startingCommands": "开始运行命令", "agentDetail.configure.answer.duration.minute": "{{count}}分", "agentDetail.configure.answer.duration.second": "{{count}}秒", "agentDetail.configure.answer.responseEnded": "回复已结束", diff --git a/web/i18n/locales/zh-Hant/agent-v-2.json b/web/i18n/locales/zh-Hant/agent-v-2.json index d95f6e69794..4687d62d85c 100644 --- a/web/i18n/locales/zh-Hant/agent-v-2.json +++ b/web/i18n/locales/zh-Hant/agent-v-2.json @@ -65,6 +65,7 @@ "agentDetail.configure.advancedSettings.label": "進階設定", "agentDetail.configure.answer.activity.ranCommands": "已執行命令", "agentDetail.configure.answer.activity.runningCommands": "正在執行命令", + "agentDetail.configure.answer.activity.startingCommands": "開始執行命令", "agentDetail.configure.answer.duration.minute": "{{count}}分", "agentDetail.configure.answer.duration.second": "{{count}}秒", "agentDetail.configure.answer.responseEnded": "回覆已結束", diff --git a/web/i18n/resources.generated.d.ts b/web/i18n/resources.generated.d.ts index f2e690164ee..84ceeb2cb47 100644 --- a/web/i18n/resources.generated.d.ts +++ b/web/i18n/resources.generated.d.ts @@ -297,6 +297,7 @@ export default interface Resources { 'agentDetail.configure.advancedSettings.label': 'Advanced Settings' 'agentDetail.configure.answer.activity.ranCommands': 'Ran commands' 'agentDetail.configure.answer.activity.runningCommands': 'Running commands' + 'agentDetail.configure.answer.activity.startingCommands': 'Starting commands' 'agentDetail.configure.answer.duration.minute': '{{count}}m' 'agentDetail.configure.answer.duration.second': '{{count}}s' 'agentDetail.configure.answer.responseEnded': 'Response ended' diff --git a/web/types/workflow.ts b/web/types/workflow.ts index f36cdf34dd8..ccd0ab04db6 100644 --- a/web/types/workflow.ts +++ b/web/types/workflow.ts @@ -338,10 +338,22 @@ export type TextReplaceResponse = { } } +export type AgentLogStreamData = { + node_execution_id: string + id: string + label: string + parent_id?: string | null + error?: string | null + status: string + data: Record + metadata?: Record + node_id: string +} + export type AgentLogResponse = { task_id: string event: string - data: AgentLogItemWithChildren + data: AgentLogStreamData } export type HumanInputFormData = {