Skip to content

armgit / dify

Public Imported from GitHub
0

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

feat(workflow): add nested tool trace drilldown (#42822)

-LAN-03866e18018e
diff --git a/web/app/components/app/workflow-log/__tests__/detail.spec.tsx b/web/app/components/app/workflow-log/__tests__/detail.spec.tsx
index 62c24525846..aacac43eaa2 100644
--- a/web/app/components/app/workflow-log/__tests__/detail.spec.tsx
+++ b/web/app/components/app/workflow-log/__tests__/detail.spec.tsx
@@ -24,8 +24,17 @@ vi.mock('@/next/navigation', () => ({
// Mock the Run component as it has complex dependencies
vi.mock('@/app/components/workflow/run', () => ({
- default: ({ runDetailUrl, tracingListUrl }: { runDetailUrl: string; tracingListUrl: string }) => (
+ default: ({
+ appId,
+ runDetailUrl,
+ tracingListUrl,
+ }: {
+ appId: string
+ runDetailUrl: string
+ tracingListUrl: string
+ }) => (
<div data-testid="workflow-run">
+ <span data-testid="run-app-id">{appId}</span>
<span data-testid="run-detail-url">{runDetailUrl}</span>
<span data-testid="tracing-list-url">{tracingListUrl}</span>
</div>
@@ -51,6 +60,7 @@ describe('DetailPanel', () => {
render(<DetailPanel appId={appId} runID="run-789" onClose={defaultOnClose} />)
expect(screen.getByTestId('workflow-run')).toBeInTheDocument()
+ expect(screen.getByTestId('run-app-id')).toHaveTextContent('app-456')
expect(screen.getByTestId('run-detail-url')).toHaveTextContent(
'/apps/app-456/workflow-runs/run-789',
)
diff --git a/web/app/components/app/workflow-log/detail.tsx b/web/app/components/app/workflow-log/detail.tsx
index 2d773e13260..0ae73af5ffa 100644
--- a/web/app/components/app/workflow-log/detail.tsx
+++ b/web/app/components/app/workflow-log/detail.tsx
@@ -58,6 +58,7 @@ const DetailPanel: FC<ILogDetail> = ({ appId, runID, onClose, canReplay = false
</div>
<WorkflowContextProvider>
<Run
+ appId={appId}
runDetailUrl={runID ? `/apps/${appId}/workflow-runs/${runID}` : ''}
tracingListUrl={runID ? `/apps/${appId}/workflow-runs/${runID}/node-executions` : ''}
/>
diff --git a/web/app/components/base/chat/chat/answer/workflow-process.tsx b/web/app/components/base/chat/chat/answer/workflow-process.tsx
index 807a0528286..0702d0cb6c4 100644
--- a/web/app/components/base/chat/chat/answer/workflow-process.tsx
+++ b/web/app/components/base/chat/chat/answer/workflow-process.tsx
@@ -1,7 +1,10 @@
import type { ChatItem, WorkflowProcess } from '../../types'
import { cn } from '@langgenius/dify-ui/cn'
-import { useEffect, useState } from 'react'
+import { useStore as useAtomStore } from 'jotai'
+import { use, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
+import { WorkflowContext } from '@/app/components/workflow/context'
+import { editorAppIdAtom } from '@/app/components/workflow/editor-resource/state'
import TracingPanel from '@/app/components/workflow/run/tracing-panel'
import { WorkflowRunningStatus } from '@/app/components/workflow/types'
@@ -15,12 +18,16 @@ type WorkflowProcessProps = {
}
const WorkflowProcessItem = ({
data,
+ item,
expand = false,
hideInfo = false,
hideProcessDetail = false,
readonly = false,
}: WorkflowProcessProps) => {
const { t } = useTranslation(['workflow'])
+ const workflowStore = use(WorkflowContext)
+ const atomStore = useAtomStore()
+ const appId = workflowStore ? atomStore.get(editorAppIdAtom) : undefined
const [collapse, setCollapse] = useState(!expand)
const running = data.status === WorkflowRunningStatus.Running
const succeeded = data.status === WorkflowRunningStatus.Succeeded
@@ -130,7 +137,13 @@ const WorkflowProcessItem = ({
)}
{data.tracing.length > 0 && (
<TracingPanel
+ key={item?.workflow_run_id}
list={data.tracing}
+ workflowRun={
+ appId && item?.workflow_run_id
+ ? { appId, runId: item.workflow_run_id, status: data.status }
+ : undefined
+ }
hideNodeInfo={hideInfo}
hideNodeProcessDetail={hideProcessDetail}
/>
diff --git a/web/app/components/base/message-log-modal/__tests__/index.spec.tsx b/web/app/components/base/message-log-modal/__tests__/index.spec.tsx
index 1f1d2fc6a6e..889d22ba400 100644
--- a/web/app/components/base/message-log-modal/__tests__/index.spec.tsx
+++ b/web/app/components/base/message-log-modal/__tests__/index.spec.tsx
@@ -44,6 +44,7 @@ it.each([false, true])(
)
expect(run).toHaveBeenLastCalledWith(
expect.objectContaining({
+ appId: 'inspected-app',
activeTab: 'TRACING',
hideResult: true,
runDetailUrl: '/apps/inspected-app/workflow-runs/run-1',
diff --git a/web/app/components/base/message-log-modal/index.tsx b/web/app/components/base/message-log-modal/index.tsx
index 9f0b529c505..95998f83f4d 100644
--- a/web/app/components/base/message-log-modal/index.tsx
+++ b/web/app/components/base/message-log-modal/index.tsx
@@ -58,6 +58,7 @@ const MessageLogModal: FC<MessageLogModalProps> = ({
<span className="i-ri-close-line size-4 text-text-tertiary" aria-hidden="true" />
</button>
<Run
+ appId={appId}
hideResult
activeTab={activeTab}
runDetailUrl={`/apps/${appId}/workflow-runs/${currentLogItem.workflow_run_id}`}
@@ -108,6 +109,7 @@ const MessageLogModal: FC<MessageLogModalProps> = ({
<span className="i-ri-close-line size-4 text-text-tertiary" aria-hidden="true" />
</button>
<Run
+ appId={appId}
hideResult
activeTab={activeTab}
runDetailUrl={`/apps/${appId}/workflow-runs/${currentLogItem.workflow_run_id}`}
diff --git a/web/app/components/workflow/panel/__tests__/record.spec.tsx b/web/app/components/workflow/panel/__tests__/record.spec.tsx
index 1afc0e64dff..99b56ef661b 100644
--- a/web/app/components/workflow/panel/__tests__/record.spec.tsx
+++ b/web/app/components/workflow/panel/__tests__/record.spec.tsx
@@ -20,10 +20,12 @@ vi.mock('../../hooks/use-workflow-update', async (importOriginal) => {
vi.mock('@/app/components/workflow/run', () => ({
default: ({
+ appId,
runDetailUrl,
tracingListUrl,
getResultCallback,
}: {
+ appId?: string
runDetailUrl: string
tracingListUrl: string
getResultCallback: (res: WorkflowRunDetailResponse) => void
@@ -31,6 +33,7 @@ vi.mock('@/app/components/workflow/run', () => ({
latestGetResultCallback = getResultCallback
return (
<div
+ data-app-id={appId}
data-run-detail-url={runDetailUrl}
data-testid="run"
data-tracing-list-url={tracingListUrl}
@@ -73,6 +76,7 @@ describe('Record', () => {
}))
renderWorkflowComponent(<Record />, {
+ resource: { kind: 'app', appId: 'history-app', mode: 'workflow' },
initialStoreState: {
historyWorkflowData: {
id: 'run-1',
@@ -86,6 +90,7 @@ describe('Record', () => {
})
expect(screen.getByText(/^Test Run/)).toBeInTheDocument()
+ expect(screen.getByTestId('run')).toHaveAttribute('data-app-id', 'history-app')
expect(screen.getByTestId('run')).toHaveAttribute('data-run-detail-url', '/runs/run-1')
expect(screen.getByTestId('run')).toHaveAttribute('data-tracing-list-url', '/traces/run-1')
})
diff --git a/web/app/components/workflow/panel/__tests__/workflow-preview.spec.tsx b/web/app/components/workflow/panel/__tests__/workflow-preview.spec.tsx
index 7170594b38e..78850dc9a5e 100644
--- a/web/app/components/workflow/panel/__tests__/workflow-preview.spec.tsx
+++ b/web/app/components/workflow/panel/__tests__/workflow-preview.spec.tsx
@@ -10,13 +10,29 @@ import {
createWorkflowRunningData,
} from '@/app/components/workflow/__tests__/fixtures'
import { UserActionButtonType } from '@/app/components/workflow/nodes/human-input/types'
-import { InputVarType, WorkflowRunningStatus } from '@/app/components/workflow/types'
+import { BlockEnum, InputVarType, WorkflowRunningStatus } from '@/app/components/workflow/types'
import { toast } from '@/app/notifications'
import { submitHumanInputForm } from '@/service/workflow'
import { renderWorkflowEditor } from '@/test/workflow-editor'
import WorkflowPreview from '../workflow-preview'
vi.mock('copy-to-clipboard', () => ({ default: vi.fn() }))
+const getChildExecutions = vi.hoisted(() =>
+ vi.fn<
+ typeof import('@/service/console').consoleClient.apps.byAppId.workflowRuns.byRunId.nodeExecutions.byNodeExecutionId.children.get
+ >(),
+)
+vi.mock('@/service/console', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/console')>()
+ const { withConsoleResponses } = await import('@/test/console/service-responses')
+ return {
+ ...actual,
+ consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'apps.byAppId.workflowRuns.byRunId.nodeExecutions.byNodeExecutionId.children.get':
+ getChildExecutions,
+ }),
+ }
+})
vi.mock('@/service/workflow', async (importOriginal) => ({
...(await importOriginal<typeof import('@/service/workflow')>()),
submitHumanInputForm: vi.fn(),
@@ -94,6 +110,7 @@ const createHumanInputFilledFormData = (
})
beforeEach(() => {
+ getChildExecutions.mockReset()
mockSubmitHumanInputForm.mockReset().mockResolvedValue({ result: 'success' })
vi.mocked(copy).mockReset().mockResolvedValue(true)
vi.spyOn(toast, 'success')
@@ -279,3 +296,40 @@ it('opens the trace from the partial-success warning', async () => {
expect(screen.getByText('Recoverable error')).toBeInTheDocument()
expect(screen.queryByRole('link', { name: /TRACING/ })).not.toBeInTheDocument()
})
+
+it('loads nested tool traces using the editor app identity and preview run ID', async () => {
+ const user = userEvent.setup()
+ getChildExecutions.mockResolvedValue({ data: [] })
+ renderPreview({
+ resource: { kind: 'app', appId: 'preview-app', mode: 'workflow' },
+ initialStoreState: {
+ workflowRunningData: createPreviewRunningData({
+ result: createWorkflowResult({
+ id: 'preview-run',
+ status: WorkflowRunningStatus.Succeeded,
+ }),
+ resultText: 'Completed',
+ tracing: [
+ createNodeTracing({
+ id: 'preview-tool',
+ node_type: BlockEnum.Tool,
+ title: 'Nested workflow',
+ status: 'succeeded',
+ expand: true,
+ extras: { workflow_tool: true },
+ }),
+ ],
+ }),
+ },
+ })
+
+ await user.click(await screen.findByRole('button', { name: 'runLog.tracing' }))
+ expect(await screen.findByText('common.noData')).toBeInTheDocument()
+ expect(getChildExecutions).toHaveBeenCalledWith({
+ params: {
+ app_id: 'preview-app',
+ run_id: 'preview-run',
+ node_execution_id: 'preview-tool',
+ },
+ })
+})
diff --git a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks.spec.ts b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks.spec.tsx
similarity index 53%
rename from web/app/components/workflow/panel/debug-and-preview/__tests__/hooks.spec.ts
rename to web/app/components/workflow/panel/debug-and-preview/__tests__/hooks.spec.tsx
index 8bf3d8453a7..bd7f7844d3b 100644
--- a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks.spec.ts
+++ b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks.spec.tsx
@@ -1,8 +1,13 @@
import type { useWorkflowRun } from '../../../hooks/use-workflow-run'
import type { Node } from '../../../types'
-import { act } from '@testing-library/react'
-import { createNode } from '../../../__tests__/fixtures'
-import { renderWorkflowCanvasHook } from '../../../__tests__/workflow-test-env'
+import { act, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import WorkflowProcessItem from '@/app/components/base/chat/chat/answer/workflow-process'
+import { createNode, createNodeTracing } from '../../../__tests__/fixtures'
+import {
+ renderWorkflowCanvasHook,
+ renderWorkflowComponent,
+} from '../../../__tests__/workflow-test-env'
import { fullWorkflowAccessControl } from '../../../hooks-store'
import { BlockEnum, WorkflowRunningStatus } from '../../../types'
import { useChat } from '../hooks'
@@ -15,10 +20,12 @@ const mockFetchInspectVars = vi.hoisted(() => vi.fn())
const mockInvalidAllLastRun = vi.hoisted(() => vi.fn())
const mockSubmitHumanInputForm = vi.hoisted(() => vi.fn())
const mockSseGet = vi.hoisted(() => vi.fn())
+const mockRequest = vi.hoisted(() => vi.fn())
vi.mock('@/service/base', async (importOriginal) => ({
...(await importOriginal<typeof import('@/service/base')>()),
sseGet: (...args: unknown[]) => mockSseGet(...args),
+ request: mockRequest,
}))
vi.mock('@/service/use-workflow', async (importOriginal) => ({
@@ -35,10 +42,11 @@ const renderChat = (
options: {
canRun?: boolean
nodes?: Node[]
+ mode?: 'workflow' | 'advanced-chat'
} = {},
) =>
renderWorkflowCanvasHook(() => useChat({}), {
- resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },
+ resource: { kind: 'app', appId: 'app-1', mode: options.mode ?? 'workflow' },
nodes: options.nodes,
hooksStoreProps: {
handleRun: mockHandleRun,
@@ -161,6 +169,158 @@ describe('useChat', () => {
expect(mockInvalidAllLastRun).toHaveBeenCalledOnce()
})
+ it('keeps workflow-tool tracing available after resuming a sibling with pending human input', async () => {
+ const user = userEvent.setup()
+ let sendCallbacks: RunCallbacks | undefined
+ let resumeCallbacks: RunCallbacks | undefined
+ mockHandleRun.mockImplementation((_params, callbacks) => {
+ sendCallbacks = callbacks
+ })
+ mockSseGet.mockImplementation((_url: unknown, _options: unknown, callbacks: RunCallbacks) => {
+ resumeCallbacks = callbacks
+ })
+ mockRequest.mockImplementation(() => Promise.resolve(Response.json({ data: [] })))
+ const envelope = { task_id: 'task-1', workflow_run_id: 'workflow-run-1' }
+ const started = {
+ ...envelope,
+ event: 'workflow_started',
+ message_id: 'message-1',
+ data: { id: 'workflow-run-1', workflow_id: 'workflow-1', created_at: 1 },
+ }
+ const tool = createNodeTracing({
+ id: 'tool-execution',
+ node_id: 'tool-node',
+ node_type: BlockEnum.Tool,
+ title: 'Downstream workflow tool',
+ })
+ const { result } = renderChat({ mode: 'advanced-chat' })
+
+ act(() => {
+ result.current.handleSend({ query: 'test' }, {})
+ })
+ act(() => {
+ sendCallbacks!.onWorkflowStarted!(started)
+ sendCallbacks!.onHumanInputRequired!({
+ ...envelope,
+ event: 'human_input_required',
+ data: {
+ form_id: 'form-1',
+ node_id: 'human-node',
+ node_title: 'Human approval',
+ form_content: 'Approve this workflow?',
+ form_token: 'form-token',
+ inputs: [],
+ actions: [{ id: 'approve', title: 'Approve', button_style: 'primary' }],
+ resolved_default_values: {},
+ display_in_ui: true,
+ expiration_time: null,
+ },
+ })
+ sendCallbacks!.onWorkflowPaused!({
+ ...envelope,
+ event: 'workflow_paused',
+ data: {
+ workflow_run_id: envelope.workflow_run_id,
+ paused_nodes: ['human-node'],
+ reasons: [],
+ outputs: {},
+ },
+ })
+ })
+ await act(async () => {
+ await sendCallbacks!.onCompleted!(false)
+ })
+ act(() => {
+ result.current.handleSend({ query: 'test' }, {})
+ })
+ act(() => {
+ sendCallbacks!.onWorkflowStarted!({
+ ...started,
+ workflow_run_id: 'workflow-run-2',
+ task_id: 'task-2',
+ message_id: 'message-2',
+ data: { ...started.data, id: 'workflow-run-2' },
+ })
+ })
+ await act(async () => {
+ await sendCallbacks!.onCompleted!(false)
+ })
+ act(() => {
+ result.current.handleSwitchSibling('message-1', {})
+ })
+
+ expect(mockSseGet).toHaveBeenCalledWith(
+ '/workflow/workflow-run-1/events?include_state_snapshot=true&continue_on_pause=true',
+ {},
+ expect.objectContaining({ onCompleted: expect.any(Function), onData: expect.any(Function) }),
+ )
+ act(() => {
+ resumeCallbacks!.onWorkflowStarted!(started)
+ resumeCallbacks!.onHumanInputFormFilled!({
+ ...envelope,
+ event: 'human_input_form_filled',
+ data: {
+ form_id: 'form-1',
+ node_id: 'human-node',
+ node_title: 'Human approval',
+ rendered_content: 'Approve this workflow?',
+ action_id: 'approve',
+ action_text: 'Approve',
+ },
+ })
+ resumeCallbacks!.onNodeStarted!({
+ ...envelope,
+ event: 'node_started',
+ data: {
+ ...tool,
+ extras: { workflow_tool: true, icon: { content: '✅', background: '#fff' } },
+ },
+ })
+ resumeCallbacks!.onNodeFinished!({
+ ...envelope,
+ event: 'node_finished',
+ data: { ...tool, status: 'succeeded', elapsed_time: 1, finished_at: 2 },
+ })
+ resumeCallbacks!.onWorkflowFinished!({
+ ...envelope,
+ event: 'workflow_finished',
+ data: {
+ ...started.data,
+ status: 'succeeded',
+ outputs: {},
+ error: '',
+ elapsed_time: 1,
+ total_tokens: 0,
+ total_steps: 2,
+ created_by: tool.created_by,
+ finished_at: 2,
+ },
+ })
+ })
+ await act(async () => {
+ await resumeCallbacks!.onCompleted!(false)
+ })
+
+ const answer = result.current.chatList.find((item) => item.id === 'message-1')!
+ renderWorkflowComponent(
+ <WorkflowProcessItem item={answer} data={answer.workflowProcess!} expand />,
+ { resource: { kind: 'app', appId: 'app-1', mode: 'advanced-chat' } },
+ )
+ expect(
+ screen.getByRole('img', { name: 'workflow.common.workflowProcessSucceeded' }),
+ ).toBeVisible()
+ await user.click(screen.getByRole('button', { name: /Downstream workflow tool/ }))
+ await user.click(screen.getByRole('button', { name: 'runLog.tracing' }))
+ expect(await screen.findByText('common.noData')).toBeVisible()
+ expect(mockRequest).toHaveBeenCalledWith(
+ expect.stringContaining(
+ '/apps/app-1/workflow-runs/workflow-run-1/node-executions/tool-execution/children',
+ ),
+ expect.anything(),
+ expect.anything(),
+ )
+ })
+
it('does not create chat state or start a run without run permission', () => {
const { result } = renderChat({ canRun: false })
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 f070fc10b2c..91e1fe14e32 100644
--- a/web/app/components/workflow/panel/debug-and-preview/hooks.ts
+++ b/web/app/components/workflow/panel/debug-and-preview/hooks.ts
@@ -885,8 +885,12 @@ export const useChat = (
nodeFinishedData.execution_metadata?.parallel_id
)
})
- if (currentIndex > -1)
- responseItem.workflowProcess.tracing[currentIndex] = nodeFinishedData
+ if (currentIndex > -1) {
+ responseItem.workflowProcess.tracing[currentIndex] = {
+ ...responseItem.workflowProcess.tracing[currentIndex],
+ ...nodeFinishedData,
+ }
+ }
})
},
onLoopStart: ({ data: loopStartedData }) => {
diff --git a/web/app/components/workflow/panel/record.tsx b/web/app/components/workflow/panel/record.tsx
index 57b9895cea2..172a6d7e246 100644
--- a/web/app/components/workflow/panel/record.tsx
+++ b/web/app/components/workflow/panel/record.tsx
@@ -1,5 +1,7 @@
import type { WorkflowRunDetailResponse } from '@/models/log'
+import { useAtomValue } from 'jotai'
import { memo, useCallback } from 'react'
+import { editorAppIdAtom } from '../editor-resource/state'
import { useHooksStore } from '../hooks-store'
import { useWorkflowUpdate } from '../hooks/use-workflow-update'
import Run from '../run'
@@ -7,6 +9,7 @@ import { useStore } from '../store'
import { formatWorkflowRunIdentifier } from '../utils'
const Record = () => {
+ const appId = useAtomValue(editorAppIdAtom)
const historyWorkflowData = useStore((s) => s.historyWorkflowData)
const { handleUpdateWorkflowCanvas } = useWorkflowUpdate()
const getWorkflowRunAndTraceUrl = useHooksStore((s) => s.getWorkflowRunAndTraceUrl)
@@ -29,6 +32,7 @@ const Record = () => {
{`Test Run${formatWorkflowRunIdentifier(historyWorkflowData?.finished_at, historyWorkflowData?.status)}`}
</div>
<Run
+ appId={appId}
runDetailUrl={getWorkflowRunAndTraceUrl(historyWorkflowData?.id).runUrl}
tracingListUrl={getWorkflowRunAndTraceUrl(historyWorkflowData?.id).traceUrl}
getResultCallback={handleResultCallback}
diff --git a/web/app/components/workflow/panel/workflow-preview.tsx b/web/app/components/workflow/panel/workflow-preview.tsx
index 6dd8720fabb..1a915954c09 100644
--- a/web/app/components/workflow/panel/workflow-preview.tsx
+++ b/web/app/components/workflow/panel/workflow-preview.tsx
@@ -2,6 +2,7 @@ import type { HumanInputFormSubmitData } from '@/app/components/base/chat/chat/a
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import copy from 'copy-to-clipboard'
+import { useAtomValue } from 'jotai'
import { memo, useCallback, useEffect, useId, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useStore as useReactFlowStore } from 'reactflow'
@@ -10,6 +11,7 @@ import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
import ResizeHandle from '@/app/components/base/resize-handle'
import { toast } from '@/app/notifications'
import { submitHumanInputForm } from '@/service/workflow'
+import { editorAppIdAtom } from '../editor-resource/state'
import { useWorkflowInteractions } from '../hooks/use-workflow-panel-interactions'
import ResultPanel from '../run/result-panel'
import ResultText from '../run/result-text'
@@ -27,6 +29,7 @@ const WorkflowPreview = () => {
const panelId = useId()
const { handleCancelDebugAndPreviewPanel } = useWorkflowInteractions()
const workflowRunningData = useStore((s) => s.workflowRunningData)
+ const appId = useAtomValue(editorAppIdAtom)
const isListening = useStore((s) => s.isListening)
const showInputsPanel = useStore((s) => s.showInputsPanel)
const workflowCanvasWidth = useStore((s) => s.workflowCanvasWidth)
@@ -278,8 +281,18 @@ const WorkflowPreview = () => {
)}
{currentTab === 'TRACING' && (
<TracingPanel
+ key={workflowRunningData?.result.id}
className="bg-background-section-burn"
list={workflowRunningData?.tracing || []}
+ workflowRun={
+ appId && workflowRunningData?.result.id
+ ? {
+ appId,
+ runId: workflowRunningData.result.id,
+ status: workflowRunningData.result.status,
+ }
+ : undefined
+ }
/>
)}
{currentTab === 'TRACING' && !workflowRunningData?.tracing?.length && (
diff --git a/web/app/components/workflow/run/__tests__/index.spec.tsx b/web/app/components/workflow/run/__tests__/index.spec.tsx
index 5c7c6bbf74d..195de50009e 100644
--- a/web/app/components/workflow/run/__tests__/index.spec.tsx
+++ b/web/app/components/workflow/run/__tests__/index.spec.tsx
@@ -7,11 +7,14 @@ import { renderWorkflowComponent } from '../../__tests__/workflow-test-env'
import { BlockEnum, NodeRunningStatus } from '../../types'
import RunPanel from '../index'
-const { mockFetchRunDetail, mockFetchTracingList, mockToastError } = vi.hoisted(() => ({
- mockFetchRunDetail: vi.fn(),
- mockFetchTracingList: vi.fn(),
- mockToastError: vi.fn(),
-}))
+const { mockFetchRunDetail, mockFetchTracingList, mockToastError, mockRequest } = vi.hoisted(
+ () => ({
+ mockFetchRunDetail: vi.fn(),
+ mockFetchTracingList: vi.fn(),
+ mockToastError: vi.fn(),
+ mockRequest: vi.fn(),
+ }),
+)
const originalClientHeightDescriptor = Object.getOwnPropertyDescriptor(
HTMLElement.prototype,
@@ -23,6 +26,11 @@ vi.mock('@/service/log', () => ({
fetchTracingList: (...args: unknown[]) => mockFetchTracingList(...args),
}))
+vi.mock('@/service/base', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/service/base')>()),
+ request: mockRequest,
+}))
+
vi.mock('@/app/notifications', async (importOriginal) => ({
...(await importOriginal()),
toast: {
@@ -212,6 +220,39 @@ describe('RunPanel', () => {
await waitFor(() => expect(mockFetchTracingList).toHaveBeenCalledTimes(2))
})
+ it('loads nested workflow-tool executions for the inspected app and run', async () => {
+ const user = userEvent.setup()
+ mockFetchTracingList.mockResolvedValue({
+ data: [
+ createTracingNode({
+ node_type: BlockEnum.Tool,
+ expand: true,
+ extras: { workflow_tool: true, icon: { content: '✅', background: '#fff' } },
+ }),
+ ],
+ } satisfies NodeTracingListResponse)
+ mockRequest.mockResolvedValue(Response.json({ data: [] }))
+
+ renderWorkflowComponent(
+ <RunPanel
+ appId="inspected-app"
+ activeTab="TRACING"
+ runDetailUrl="/apps/inspected-app/workflow-runs/run-1"
+ tracingListUrl="/apps/inspected-app/workflow-runs/run-1/node-executions"
+ />,
+ )
+
+ await user.click(await screen.findByRole('button', { name: 'runLog.tracing' }))
+ await screen.findByText('common.noData')
+ expect(mockRequest).toHaveBeenCalledWith(
+ expect.stringContaining(
+ '/apps/inspected-app/workflow-runs/run-1/node-executions/trace-1/children',
+ ),
+ expect.anything(),
+ expect.anything(),
+ )
+ })
+
it('reports run-detail and tracing failures through toast.error', async () => {
mockFetchRunDetail.mockRejectedValueOnce(
createHttpError(new Response(null, { status: 500 }), { message: 'detail boom' }),
diff --git a/web/app/components/workflow/run/__tests__/workflow-tool-tracing.spec.tsx b/web/app/components/workflow/run/__tests__/workflow-tool-tracing.spec.tsx
new file mode 100644
index 00000000000..ebbc7dfce4e
--- /dev/null
+++ b/web/app/components/workflow/run/__tests__/workflow-tool-tracing.spec.tsx
@@ -0,0 +1,334 @@
+import type { NodeTracing } from '@/types/workflow'
+import { screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import WorkflowProcessItem from '@/app/components/base/chat/chat/answer/workflow-process'
+import { renderWithConsoleQuery } from '@/test/console/query-data'
+import { createNodeTracing } from '../../__tests__/fixtures'
+import { renderWorkflowComponent } from '../../__tests__/workflow-test-env'
+import { BlockEnum, WorkflowRunningStatus } from '../../types'
+import TracingPanel from '../tracing-panel'
+
+const mockRequest = vi.hoisted(() => vi.fn())
+
+vi.mock('@/service/base', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/service/base')>()),
+ request: mockRequest,
+}))
+
+// Monaco is an independent editor boundary; preserve its displayed trace content.
+vi.mock('@/app/components/workflow/nodes/_base/components/editor/code-editor', () => ({
+ default: ({ value }: { value: unknown }) => <pre>{JSON.stringify(value)}</pre>,
+}))
+
+const createTrace = (id: string, overrides: Partial<NodeTracing> = {}): NodeTracing =>
+ createNodeTracing({
+ id,
+ node_id: id,
+ node_type: BlockEnum.Tool,
+ title: id,
+ status: 'succeeded',
+ extras: { workflow_tool: true, icon: { content: '✅', background: '#fff' } },
+ ...overrides,
+ })
+
+describe('Workflow tool tracing', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it.each([true, false])(
+ 'exposes chat tool internals only with console workflow scope: %s',
+ async (hasWorkflowStore) => {
+ const user = userEvent.setup()
+ const root = createTrace('chat-tool-execution', { expand: true })
+ mockRequest.mockImplementation(() => Promise.resolve(Response.json({ data: [] })))
+ const processItem = (
+ <WorkflowProcessItem
+ item={{ id: 'answer', isAnswer: true, content: '', workflow_run_id: 'chat-run' }}
+ data={{ tracing: [root], status: WorkflowRunningStatus.Succeeded }}
+ expand
+ />
+ )
+ if (hasWorkflowStore)
+ renderWorkflowComponent(processItem, {
+ resource: { kind: 'app', appId: 'chat-app', mode: 'advanced-chat' },
+ })
+ else renderWithConsoleQuery(processItem)
+
+ if (!hasWorkflowStore) {
+ expect(screen.queryByRole('button', { name: 'runLog.tracing' })).not.toBeInTheDocument()
+ expect(mockRequest).not.toHaveBeenCalled()
+ return
+ }
+ await user.click(screen.getByRole('button', { name: 'runLog.tracing' }))
+ await screen.findByText('common.noData')
+ expect(mockRequest).toHaveBeenCalledWith(
+ expect.stringContaining(
+ '/apps/chat-app/workflow-runs/chat-run/node-executions/chat-tool-execution/children',
+ ),
+ expect.anything(),
+ expect.anything(),
+ )
+ },
+ )
+
+ it.each([
+ [BlockEnum.Iteration, BlockEnum.Loop],
+ [BlockEnum.Loop, BlockEnum.Iteration],
+ ])('preserves internal Tool details through %s → %s ancestry', async (outerType, innerType) => {
+ const user = userEvent.setup()
+ const metadata = { total_tokens: 0, total_price: 0, currency: 'USD' }
+ const outer = createTrace('outer', {
+ node_type: outerType,
+ expand: true,
+ execution_metadata: { ...metadata, [`${outerType}_duration_map`]: { 0: 1 } },
+ })
+ const inner = createTrace('inner', {
+ index: 2,
+ node_type: innerType,
+ execution_metadata: {
+ ...metadata,
+ [`${outerType}_id`]: outer.node_id,
+ [`${outerType}_index`]: 0,
+ [`${innerType}_duration_map`]: { 0: 1 },
+ },
+ })
+ const tool = createTrace('nested-tool', {
+ index: 3,
+ inputs: { request: 'Nested request' },
+ outputs: { result: 'Nested result' },
+ execution_metadata: {
+ ...metadata,
+ [`${outerType}_id`]: outer.node_id,
+ [`${outerType}_index`]: 0,
+ [`${innerType}_id`]: inner.node_id,
+ [`${innerType}_index`]: 0,
+ },
+ })
+ renderWithConsoleQuery(<TracingPanel list={[outer, inner, tool]} />)
+
+ await user.click(
+ screen.getByRole('button', { name: new RegExp(`workflowLogic.nodes.${outerType}`) }),
+ )
+ await user.click(screen.getByText(`workflow.singleRun.${outerType} 1`))
+ await user.click(screen.getByText('inner'))
+ await user.click(
+ screen.getByRole('button', { name: new RegExp(`workflowLogic.nodes.${innerType}`) }),
+ )
+ await user.click(screen.getByText(`workflow.singleRun.${innerType} 1`))
+ await user.click(screen.getByText('nested-tool'))
+ expect(screen.getByText(/Nested request/)).toBeInTheDocument()
+ expect(screen.getByText(/Nested result/)).toBeInTheDocument()
+ })
+
+ it('keeps workflow-tool tracing on the execution instead of individual retry attempts', async () => {
+ const user = userEvent.setup()
+ const root = createTrace('root-execution', { node_id: 'approval-tool', expand: true })
+ const retry = createTrace('root-execution:retry:1', {
+ node_id: root.node_id,
+ status: 'retry',
+ retry_index: 1,
+ error: 'Approval service unavailable',
+ expand: true,
+ })
+ mockRequest.mockImplementation(() => Promise.resolve(Response.json({ data: [] })))
+
+ renderWithConsoleQuery(
+ <TracingPanel
+ list={[retry, root]}
+ workflowRun={{ appId: 'root-app', runId: 'run', status: 'succeeded' }}
+ />,
+ )
+
+ expect(await screen.findByRole('button', { name: 'runLog.tracing' })).toBeInTheDocument()
+ await user.click(screen.getByRole('button', { name: /workflow.nodes.common.retry.retries/ }))
+ expect(await screen.findByText('Approval service unavailable')).toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'runLog.tracing' })).not.toBeInTheDocument()
+ expect(mockRequest).not.toHaveBeenCalled()
+
+ await user.click(screen.getByRole('button', { name: 'workflow.singleRun.back' }))
+ await user.click(await screen.findByRole('button', { name: 'runLog.tracing' }))
+ await screen.findByText('common.noData')
+ expect(mockRequest).toHaveBeenCalledWith(
+ expect.stringContaining('/node-executions/root-execution/children'),
+ expect.anything(),
+ expect.anything(),
+ )
+ })
+
+ it('loads the selected invocation lazily and drills through a child iteration to nested execution details', async () => {
+ const user = userEvent.setup()
+ const root = createTrace('root-execution', { title: 'Approval tool', expand: true })
+ const iteration = createTrace('iteration-execution', {
+ node_id: 'iteration-node',
+ title: 'Approval batch',
+ node_type: BlockEnum.Iteration,
+ execution_metadata: {
+ total_tokens: 0,
+ total_price: 0,
+ currency: 'USD',
+ iteration_duration_map: { 0: 1 },
+ },
+ })
+ const nestedTool = {
+ ...createTrace('nested-database-id', {
+ index: 2,
+ title: 'Nested approval tool',
+ execution_metadata: {
+ total_tokens: 0,
+ total_price: 0,
+ currency: 'USD',
+ iteration_id: 'iteration-node',
+ iteration_index: 0,
+ },
+ }),
+ node_execution_id: 'nested-engine-execution',
+ }
+ const humanInput = createTrace('human-execution', {
+ node_type: BlockEnum.HumanInput,
+ title: 'Human approval',
+ inputs: { request: 'Review request' },
+ process_data: { action: 'approve' },
+ outputs: { approved_text: 'Approved result' },
+ })
+ mockRequest.mockImplementation((url: string) => {
+ if (url.endsWith('/root-execution/children'))
+ return Promise.resolve(Response.json({ data: [iteration, nestedTool] }))
+ if (url.endsWith('/nested-engine-execution/children'))
+ return Promise.resolve(Response.json({ data: [humanInput] }))
+ throw new Error(`Unexpected request: ${url}`)
+ })
+
+ renderWithConsoleQuery(
+ <TracingPanel
+ list={[root]}
+ workflowRun={{ appId: 'root-app', runId: 'run', status: 'succeeded' }}
+ />,
+ )
+ expect(mockRequest).not.toHaveBeenCalled()
+
+ await user.click(await screen.findByRole('button', { name: 'runLog.tracing' }))
+ await user.click(await screen.findByText('Approval batch'))
+ await user.click(
+ screen.getByRole('button', { name: /workflowLogic.nodes.iteration.iteration/ }),
+ )
+ await user.click(screen.getByText('workflow.singleRun.iteration 1'))
+ await user.click(screen.getByText('Nested approval tool'))
+ await user.click(screen.getByRole('button', { name: 'runLog.tracing' }))
+ await user.click(await screen.findByText('Human approval'))
+
+ expect(screen.getByText(/Review request/)).toBeInTheDocument()
+ expect(screen.getByText(/"action":"approve"/)).toBeInTheDocument()
+ expect(screen.getByText(/Approved result/)).toBeInTheDocument()
+ expect(mockRequest).toHaveBeenCalledWith(
+ expect.stringContaining(
+ '/apps/root-app/workflow-runs/run/node-executions/nested-engine-execution/children',
+ ),
+ expect.anything(),
+ expect.anything(),
+ )
+
+ await user.click(screen.getAllByRole('button', { name: 'workflow.singleRun.back' }).at(-1)!)
+ expect(screen.getByText('Nested approval tool')).toBeInTheDocument()
+ expect(screen.queryByText('Human approval')).not.toBeInTheDocument()
+ })
+
+ it.each([BlockEnum.Iteration, BlockEnum.Loop])(
+ 'refreshes an open source %s after its human input is submitted',
+ async (containerType) => {
+ const user = userEvent.setup()
+ const root = createTrace('root-execution', { title: 'Approval tool', expand: true })
+ const container = createTrace('batch-execution', {
+ node_id: 'batch',
+ title: 'Approval batch',
+ node_type: containerType,
+ status: 'paused',
+ parallel_id: 'parallel',
+ parallel_start_node_id: 'branch',
+ })
+ const branch = createTrace('branch-execution', {
+ node_id: 'branch',
+ node_type: BlockEnum.TemplateTransform,
+ parallel_id: 'parallel',
+ parallel_start_node_id: 'branch',
+ })
+ const approval = createTrace('approval-execution', {
+ index: 2,
+ title: 'Human approval',
+ node_type: BlockEnum.HumanInput,
+ status: 'paused',
+ execution_metadata: {
+ total_tokens: 0,
+ total_price: 0,
+ currency: 'USD',
+ [`${containerType}_id`]: 'batch',
+ [`${containerType}_index`]: 0,
+ },
+ })
+ mockRequest.mockImplementation(() =>
+ Promise.resolve(Response.json({ data: [branch, container, approval] })),
+ )
+ const { rerender } = renderWithConsoleQuery(
+ <TracingPanel
+ list={[root]}
+ workflowRun={{ appId: 'app', runId: 'run', status: 'paused' }}
+ />,
+ )
+
+ await user.click(await screen.findByRole('button', { name: 'runLog.tracing' }))
+ await user.click(await screen.findByText('Approval batch'))
+ await user.click(
+ screen.getByRole('button', { name: new RegExp(`workflowLogic.nodes.${containerType}`) }),
+ )
+ await user.click(screen.getByText(`workflow.singleRun.${containerType} 1`))
+ await user.click(screen.getByText('Human approval'))
+ expect(
+ screen.getByText('workflowHumanInput.nodes.humanInput.log.reasonContent'),
+ ).toBeInTheDocument()
+
+ mockRequest.mockImplementation(() =>
+ Promise.resolve(
+ Response.json({
+ data: [
+ branch,
+ {
+ ...container,
+ status: 'succeeded',
+ execution_metadata: {
+ total_tokens: 0,
+ total_price: 0,
+ currency: 'USD',
+ [`${containerType}_duration_map`]: { 0: 2 },
+ loop_variable_map: { 0: { decision: 'Updated loop variables' } },
+ },
+ },
+ { ...approval, status: 'succeeded', outputs: { decision: 'Approved result' } },
+ createTrace('next-execution', {
+ index: 3,
+ title: 'After approval',
+ node_type: BlockEnum.TemplateTransform,
+ execution_metadata: approval.execution_metadata,
+ }),
+ ],
+ }),
+ ),
+ )
+ rerender(
+ <TracingPanel
+ list={[root]}
+ workflowRun={{ appId: 'app', runId: 'run', status: 'succeeded' }}
+ />,
+ )
+
+ expect(await screen.findByText(/Approved result/)).toBeInTheDocument()
+ expect(screen.getByText('After approval')).toBeInTheDocument()
+ expect(screen.getByText('2.00s')).toBeInTheDocument()
+ if (containerType === BlockEnum.Loop)
+ expect(screen.getByText(/Updated loop variables/)).toBeInTheDocument()
+ expect(
+ screen.queryByText('workflowHumanInput.nodes.humanInput.log.reasonContent'),
+ ).not.toBeInTheDocument()
+ expect(screen.getByText(`workflow.singleRun.${containerType} 1`)).toBeInTheDocument()
+ },
+ )
+})
diff --git a/web/app/components/workflow/run/index.tsx b/web/app/components/workflow/run/index.tsx
index 0ce931ee3f5..d7bc66dc00e 100644
--- a/web/app/components/workflow/run/index.tsx
+++ b/web/app/components/workflow/run/index.tsx
@@ -16,6 +16,7 @@ import StatusPanel from './status'
import TracingPanel from './tracing-panel'
type RunProps = {
+ appId?: string
hideResult?: boolean
activeTab?: 'RESULT' | 'DETAIL' | 'TRACING'
getResultCallback?: (result: WorkflowRunDetailResponse) => void
@@ -33,6 +34,7 @@ type RequestLifetime = {
}
const RunPanel: FC<RunProps> = ({
+ appId,
activeTab = 'RESULT',
hideResult,
getResultCallback,
@@ -49,6 +51,7 @@ const RunPanel: FC<RunProps> = ({
return (
<RunSession
key={JSON.stringify([runDetailUrl, tracingListUrl])}
+ appId={appId}
hideResult={hideResult}
getResultCallback={getResultCallback}
runDetailUrl={runDetailUrl}
@@ -67,6 +70,7 @@ type RunSessionProps = Omit<RunProps, 'activeTab'> & {
}
function RunSession({
+ appId,
hideResult,
getResultCallback,
runDetailUrl,
@@ -248,7 +252,18 @@ function RunSession({
)}
</TabsPanel>
<TabsPanel value="TRACING">
- {!loading && <TracingPanel className="bg-background-section-burn" list={list} />}
+ {!loading && (
+ <TracingPanel
+ key={runDetail?.id}
+ className="bg-background-section-burn"
+ list={list}
+ workflowRun={
+ appId && runDetail
+ ? { appId, runId: runDetail.id, status: runDetail.status }
+ : undefined
+ }
+ />
+ )}
</TabsPanel>
</div>
</Tabs>
diff --git a/web/app/components/workflow/run/iteration-log/iteration-log-trigger.tsx b/web/app/components/workflow/run/iteration-log/iteration-log-trigger.tsx
index 5ee14bbcda9..99a374e628c 100644
--- a/web/app/components/workflow/run/iteration-log/iteration-log-trigger.tsx
+++ b/web/app/components/workflow/run/iteration-log/iteration-log-trigger.tsx
@@ -3,6 +3,7 @@ import { Button } from '@langgenius/dify-ui/button'
import { RiArrowRightSLine } from '@remixicon/react'
import { useTranslation } from 'react-i18next'
import { NodeRunningStatus } from '@/app/components/workflow/types'
+import { getIterationDurationMap, getIterationResultList } from '../utils/format-log/iteration'
type IterationLogTriggerProps = {
nodeInfo: NodeTracing
@@ -13,10 +14,6 @@ type IterationLogTriggerProps = {
) => void
}
-const getIterationDurationMap = (nodeInfo: NodeTracing) => {
- return nodeInfo.iterDurationMap || nodeInfo.execution_metadata?.iteration_duration_map || {}
-}
-
const getDisplayIterationCount = (nodeInfo: NodeTracing) => {
const iterationDurationMap = nodeInfo.execution_metadata?.iteration_duration_map
if (iterationDurationMap) return Object.keys(iterationDurationMap).length
@@ -63,67 +60,14 @@ const IterationLogTrigger = ({
}: IterationLogTriggerProps) => {
const { t } = useTranslation(['workflow', 'workflowLogic'])
- const getNodesForInstance = (key: string): NodeTracing[] => {
- if (!allExecutions) return []
-
- const parallelNodes = allExecutions.filter(
- (exec) => exec.execution_metadata?.parallel_mode_run_id === key,
- )
- if (parallelNodes.length > 0) return parallelNodes
-
- const serialIndex = Number.parseInt(key, 10)
- if (!Number.isNaN(serialIndex)) {
- const serialNodes = allExecutions.filter(
- (exec) =>
- exec.execution_metadata?.iteration_id === nodeInfo.node_id &&
- exec.execution_metadata?.iteration_index === serialIndex,
- )
- if (serialNodes.length > 0) return serialNodes
- }
-
- return []
- }
-
- const getStructuredIterationList = () => {
- const iterationNodeMeta = nodeInfo.execution_metadata
-
- if (!iterationNodeMeta?.iteration_duration_map) return nodeInfo.details || []
-
- const structuredList = Object.keys(iterationNodeMeta.iteration_duration_map)
- .map(getNodesForInstance)
- .filter((branchNodes) => branchNodes.length > 0)
-
- if (!allExecutions || !nodeInfo.details?.length) return structuredList
-
- const existingIterationIndices = new Set<number>()
- structuredList.forEach((iteration) => {
- iteration.forEach((node) => {
- if (node.execution_metadata?.iteration_index !== undefined)
- existingIterationIndices.add(node.execution_metadata.iteration_index)
- })
- })
-
- nodeInfo.details.forEach((iteration, index) => {
- if (
- !existingIterationIndices.has(index) &&
- iteration.some((node) => node.status === NodeRunningStatus.Failed)
- ) {
- structuredList.push(iteration)
- }
- })
-
- return structuredList.sort((a, b) => {
- const aIndex = a[0]?.execution_metadata?.iteration_index ?? 0
- const bIndex = b[0]?.execution_metadata?.iteration_index ?? 0
- return aIndex - bIndex
- })
- }
-
const handleOnShowIterationDetail = (e: React.MouseEvent<HTMLButtonElement>) => {
e.stopPropagation()
e.nativeEvent.stopImmediatePropagation()
- onShowIterationResultList(getStructuredIterationList(), getIterationDurationMap(nodeInfo))
+ onShowIterationResultList(
+ getIterationResultList(nodeInfo, allExecutions),
+ getIterationDurationMap(nodeInfo),
+ )
}
const displayIterationCount = getDisplayIterationCount(nodeInfo)
diff --git a/web/app/components/workflow/run/loop-log/__tests__/loop-log-trigger.spec.tsx b/web/app/components/workflow/run/loop-log/__tests__/loop-log-trigger.spec.tsx
index b1cabc62c56..8ddc87107cf 100644
--- a/web/app/components/workflow/run/loop-log/__tests__/loop-log-trigger.spec.tsx
+++ b/web/app/components/workflow/run/loop-log/__tests__/loop-log-trigger.spec.tsx
@@ -65,64 +65,5 @@ describe('LoopLogTrigger', () => {
loopVariableMap,
)
})
-
- it('should reconstruct loop detail groups from execution metadata when details are absent', async () => {
- const user = userEvent.setup()
- const onShowLoopResultList =
- vi.fn<NonNullable<React.ComponentProps<typeof LoopLogTrigger>['onShowLoopResultList']>>()
- const loopDurationMap: LoopDurationMap = {
- 'parallel-1': 1.5,
- '2': 2.2,
- }
- const allExecutions = [
- createNodeTracing({
- id: 'parallel-child',
- execution_metadata: {
- total_tokens: 0,
- total_price: 0,
- currency: 'USD',
- parallel_mode_run_id: 'parallel-1',
- },
- }),
- createNodeTracing({
- id: 'serial-child',
- execution_metadata: {
- total_tokens: 0,
- total_price: 0,
- currency: 'USD',
- loop_id: 'loop-node',
- loop_index: 2,
- },
- }),
- ]
-
- render(
- <LoopLogTrigger
- nodeInfo={createNodeTracing({
- details: undefined,
- execution_metadata: {
- total_tokens: 0,
- total_price: 0,
- currency: 'USD',
- loop_duration_map: loopDurationMap,
- loop_variable_map: {},
- },
- })}
- allExecutions={allExecutions}
- onShowLoopResultList={onShowLoopResultList}
- />,
- )
-
- await user.click(screen.getByRole('button'))
-
- expect(onShowLoopResultList).toHaveBeenCalledTimes(1)
- const [structuredList, durations, variableMap] = onShowLoopResultList.mock.calls[0]!
- expect(structuredList).toHaveLength(2)
- expect(structuredList).toEqual(
- expect.arrayContaining([[allExecutions[0]], [allExecutions[1]]]),
- )
- expect(durations).toEqual(loopDurationMap)
- expect(variableMap).toEqual({})
- })
})
})
diff --git a/web/app/components/workflow/run/loop-log/loop-log-trigger.tsx b/web/app/components/workflow/run/loop-log/loop-log-trigger.tsx
index 1764ab3d28a..8d4f7b092cf 100644
--- a/web/app/components/workflow/run/loop-log/loop-log-trigger.tsx
+++ b/web/app/components/workflow/run/loop-log/loop-log-trigger.tsx
@@ -5,56 +5,23 @@ import { useTranslation } from 'react-i18next'
type LoopLogTriggerProps = {
nodeInfo: NodeTracing
- allExecutions?: NodeTracing[]
onShowLoopResultList: (
loopResultList: NodeTracing[][],
loopResultDurationMap: LoopDurationMap,
loopVariableMap: LoopVariableMap,
) => void
}
-const LoopLogTrigger = ({ nodeInfo, allExecutions, onShowLoopResultList }: LoopLogTriggerProps) => {
+const LoopLogTrigger = ({ nodeInfo, onShowLoopResultList }: LoopLogTriggerProps) => {
const { t } = useTranslation(['workflow', 'workflowLogic'])
- const filterNodesForInstance = (key: string): NodeTracing[] => {
- if (!allExecutions) return []
-
- const parallelNodes = allExecutions.filter(
- (exec) => exec.execution_metadata?.parallel_mode_run_id === key,
- )
- if (parallelNodes.length > 0) return parallelNodes
-
- const serialIndex = Number.parseInt(key, 10)
- if (!Number.isNaN(serialIndex)) {
- const serialNodes = allExecutions.filter(
- (exec) =>
- exec.execution_metadata?.loop_id === nodeInfo.node_id &&
- exec.execution_metadata?.loop_index === serialIndex,
- )
- if (serialNodes.length > 0) return serialNodes
- }
-
- return []
- }
-
const handleOnShowLoopDetail = (e: React.MouseEvent<HTMLButtonElement>) => {
e.stopPropagation()
e.nativeEvent.stopImmediatePropagation()
-
const loopNodeMeta = nodeInfo.execution_metadata
const loopDurMap = nodeInfo?.loopDurationMap || loopNodeMeta?.loop_duration_map || {}
const loopVarMap = loopNodeMeta?.loop_variable_map || {}
- let structuredList: NodeTracing[][] = []
- if (nodeInfo.details?.length) {
- structuredList = nodeInfo.details
- } else if (loopNodeMeta?.loop_duration_map) {
- const instanceKeys = Object.keys(loopNodeMeta.loop_duration_map)
- structuredList = instanceKeys
- .map((key) => filterNodesForInstance(key))
- .filter((branchNodes) => branchNodes.length > 0)
- }
-
- onShowLoopResultList(structuredList, loopDurMap, loopVarMap)
+ onShowLoopResultList(nodeInfo.details ?? [], loopDurMap, loopVarMap)
}
let displayLoopCount = 0
diff --git a/web/app/components/workflow/run/node.tsx b/web/app/components/workflow/run/node.tsx
index 0a676f524ec..fc2c8efab42 100644
--- a/web/app/components/workflow/run/node.tsx
+++ b/web/app/components/workflow/run/node.tsx
@@ -7,6 +7,7 @@ import type {
LoopVariableMap,
NodeTracing,
} from '@/types/workflow'
+import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
import {
@@ -17,7 +18,7 @@ import {
RiLoader2Line,
RiPauseCircleFill,
} from '@remixicon/react'
-import { useCallback, useEffect, useId, useMemo, useState } from 'react'
+import { use, useCallback, useEffect, useId, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import CodeEditor from '@/app/components/workflow/nodes/_base/components/editor/code-editor'
import ErrorHandleTip from '@/app/components/workflow/nodes/_base/components/error-handle/error-handle-tip'
@@ -32,6 +33,7 @@ import { AgentLogTrigger } from './agent-log/agent-log-trigger'
import { IterationLogTrigger } from './iteration-log'
import { LoopLogTrigger } from './loop-log'
import { RetryLogTrigger } from './retry-log'
+import { WorkflowToolTracingContext } from './workflow-tool-tracing-context'
type Props = {
readonly className?: string
@@ -69,6 +71,7 @@ const NodePanel: FC<Props> = ({
notShowIterationNav,
notShowLoopNav,
}) => {
+ const workflowToolTracing = use(WorkflowToolTracingContext)
const [collapseState, doSetCollapseState] = useState<boolean>(true)
const setCollapseState = useCallback(
(state: boolean) => {
@@ -77,7 +80,7 @@ const NodePanel: FC<Props> = ({
},
[hideProcessDetail],
)
- const { t } = useTranslation(['workflow', 'workflowLogic', 'workflowHumanInput'])
+ const { t } = useTranslation(['workflow', 'workflowLogic', 'workflowHumanInput', 'runLog'])
const docLink = useDocLink()
const detailsId = useId()
const Header = hideProcessDetail ? 'div' : 'button'
@@ -245,11 +248,7 @@ const NodePanel: FC<Props> = ({
)}
{/* The nav to the Loop detail */}
{isLoopNode && !notShowLoopNav && onShowLoopDetail && (
- <LoopLogTrigger
- nodeInfo={nodeInfo}
- allExecutions={allExecutions}
- onShowLoopResultList={onShowLoopDetail}
- />
+ <LoopLogTrigger nodeInfo={nodeInfo} onShowLoopResultList={onShowLoopDetail} />
)}
{isRetryNode && onShowRetryDetail && (
<RetryLogTrigger nodeInfo={nodeInfo} onShowRetryResultList={onShowRetryDetail} />
@@ -260,6 +259,20 @@ const NodePanel: FC<Props> = ({
onShowAgentOrToolLog={onShowAgentOrToolLog}
/>
)}
+ {/* ponytail: enable retry drilldown when traces carry invocation identity. */}
+ {nodeInfo.node_type === BlockEnum.Tool &&
+ nodeInfo.status !== 'retry' &&
+ nodeInfo.extras?.workflow_tool === true &&
+ workflowToolTracing && (
+ <Button
+ variant="ghost"
+ className="mb-1 w-full justify-between"
+ onClick={() => workflowToolTracing.onShowWorkflowTool(nodeInfo)}
+ >
+ {t(($) => $.tracing, { ns: 'runLog' })}
+ <span aria-hidden className="i-ri-arrow-right-line size-4" />
+ </Button>
+ )}
<div className={cn('mb-1', hideInfo && 'px-2! py-0.5!')}>
{nodeInfo.status === 'stopped' && (
<StatusContainer status="stopped">
diff --git a/web/app/components/workflow/run/tracing-panel.tsx b/web/app/components/workflow/run/tracing-panel.tsx
index 28e96eb8e44..a231b8350fe 100644
--- a/web/app/components/workflow/run/tracing-panel.tsx
+++ b/web/app/components/workflow/run/tracing-panel.tsx
@@ -1,21 +1,35 @@
'use client'
import type { FC } from 'react'
+import type { WorkflowRunInfo } from './workflow-tool-tracing-context'
import type { NodeTracing } from '@/types/workflow'
import { cn } from '@langgenius/dify-ui/cn'
import * as React from 'react'
-import { useCallback, useState } from 'react'
+import { use, useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
import formatNodeList from '@/app/components/workflow/run/utils/format-log'
+import { BlockEnum } from '../types'
import { getHoveredParallelId } from './get-hovered-parallel-id'
import { useLogs } from './hooks'
import NodePanel from './node'
import SpecialResultPanel from './special-result-panel'
+import { getIterationDurationMap, getIterationResultList } from './utils/format-log/iteration'
+import WorkflowToolTracing from './workflow-tool-tracing'
+import { WorkflowToolTracingContext } from './workflow-tool-tracing-context'
type TracingPanelProps = {
list: NodeTracing[]
className?: string
hideNodeInfo?: boolean
hideNodeProcessDetail?: boolean
+ workflowRun?: WorkflowRunInfo
+}
+
+function findExecution(nodes: NodeTracing[], id: string): NodeTracing | undefined {
+ for (const node of nodes) {
+ if (node.id === id) return node
+ const child = node.parallelDetail?.children && findExecution(node.parallelDetail.children, id)
+ if (child) return child
+ }
}
const TracingPanel: FC<TracingPanelProps> = ({
@@ -23,9 +37,17 @@ const TracingPanel: FC<TracingPanelProps> = ({
className,
hideNodeInfo = false,
hideNodeProcessDetail = false,
+ workflowRun,
}) => {
+ const parentTracing = use(WorkflowToolTracingContext)
+ const currentWorkflowRun = workflowRun ?? parentTracing?.workflowRun
+ const [workflowTool, setWorkflowTool] = useState<NodeTracing | null>(null)
const { t } = useTranslation(['workflow'])
const treeNodes = formatNodeList(list, t)
+ const [containerId, setContainerId] = useState<string | null>(null)
+ const container = containerId ? findExecution(treeNodes, containerId) : undefined
+ const iteration = container?.node_type === BlockEnum.Iteration ? container : undefined
+ const loop = container?.node_type === BlockEnum.Loop ? container : undefined
const [collapsedNodes, setCollapsedNodes] = useState<Set<string>>(() => new Set())
const [hoveredParallel, setHoveredParallel] = useState<string | null>(null)
@@ -47,31 +69,7 @@ const TracingPanel: FC<TracingPanelProps> = ({
setHoveredParallel(getHoveredParallelId(e.relatedTarget))
}, [])
- const {
- showSpecialResultPanel,
-
- showRetryDetail,
- setShowRetryDetailFalse,
- retryResultList,
- handleShowRetryResultList,
-
- showIteratingDetail,
- setShowIteratingDetailFalse,
- iterationResultList,
- iterationResultDurationMap,
- handleShowIterationResultList,
-
- showLoopingDetail,
- setShowLoopingDetailFalse,
- loopResultList,
- loopResultDurationMap,
- loopResultVariableMap,
- handleShowLoopResultList,
-
- agentOrToolLogItemStack,
- agentOrToolLogListMap,
- handleShowAgentOrToolLog,
- } = useLogs()
+ const logs = useLogs()
const renderNode = (node: NodeTracing) => {
const isParallelFirstNode = !!node.parallelDetail?.isParallelStartNode
@@ -144,10 +142,10 @@ const TracingPanel: FC<TracingPanelProps> = ({
<NodePanel
nodeInfo={node!}
allExecutions={list}
- onShowIterationDetail={handleShowIterationResultList}
- onShowLoopDetail={handleShowLoopResultList}
- onShowRetryDetail={handleShowRetryResultList}
- onShowAgentOrToolLog={handleShowAgentOrToolLog}
+ onShowIterationDetail={() => setContainerId(node.id)}
+ onShowLoopDetail={() => setContainerId(node.id)}
+ onShowRetryDetail={logs.handleShowRetryResultList}
+ onShowAgentOrToolLog={logs.handleShowAgentOrToolLog}
hideInfo={hideNodeInfo}
hideProcessDetail={hideNodeProcessDetail}
/>
@@ -156,38 +154,49 @@ const TracingPanel: FC<TracingPanelProps> = ({
}
}
- if (showSpecialResultPanel) {
- return (
+ const content =
+ workflowTool && currentWorkflowRun ? (
+ <WorkflowToolTracing
+ key={workflowTool.id}
+ node={workflowTool}
+ workflowRun={currentWorkflowRun}
+ onBack={() => setWorkflowTool(null)}
+ />
+ ) : container || logs.showSpecialResultPanel ? (
<SpecialResultPanel
- showRetryDetail={showRetryDetail}
- setShowRetryDetailFalse={setShowRetryDetailFalse}
- retryResultList={retryResultList}
- showIteratingDetail={showIteratingDetail}
- setShowIteratingDetailFalse={setShowIteratingDetailFalse}
- iterationResultList={iterationResultList}
- iterationResultDurationMap={iterationResultDurationMap}
- showLoopingDetail={showLoopingDetail}
- setShowLoopingDetailFalse={setShowLoopingDetailFalse}
- loopResultList={loopResultList}
- loopResultDurationMap={loopResultDurationMap}
- loopResultVariableMap={loopResultVariableMap}
- agentOrToolLogItemStack={agentOrToolLogItemStack}
- agentOrToolLogListMap={agentOrToolLogListMap}
- handleShowAgentOrToolLog={handleShowAgentOrToolLog}
+ {...logs}
+ showIteratingDetail={!!iteration}
+ setShowIteratingDetailFalse={() => setContainerId(null)}
+ iterationResultList={iteration ? getIterationResultList(iteration, list) : undefined}
+ iterationResultDurationMap={iteration ? getIterationDurationMap(iteration) : undefined}
+ showLoopingDetail={!!loop}
+ setShowLoopingDetailFalse={() => setContainerId(null)}
+ loopResultList={loop?.details}
+ loopResultDurationMap={loop?.loopDurationMap || loop?.execution_metadata?.loop_duration_map}
+ loopResultVariableMap={loop?.execution_metadata?.loop_variable_map}
/>
+ ) : (
+ <div
+ className={cn('py-2', className)}
+ onClick={(e) => {
+ e.stopPropagation()
+ e.nativeEvent.stopImmediatePropagation()
+ }}
+ >
+ {treeNodes.map(renderNode)}
+ </div>
)
- }
return (
- <div
- className={cn('py-2', className)}
- onClick={(e) => {
- e.stopPropagation()
- e.nativeEvent.stopImmediatePropagation()
- }}
+ <WorkflowToolTracingContext
+ value={
+ currentWorkflowRun
+ ? { workflowRun: currentWorkflowRun, onShowWorkflowTool: setWorkflowTool }
+ : null
+ }
>
- {treeNodes.map(renderNode)}
- </div>
+ {content}
+ </WorkflowToolTracingContext>
)
}
diff --git a/web/app/components/workflow/run/utils/format-log/human-input/__tests__/index.spec.ts b/web/app/components/workflow/run/utils/format-log/human-input/__tests__/index.spec.ts
index e867309b961..c70d04b0af6 100644
--- a/web/app/components/workflow/run/utils/format-log/human-input/__tests__/index.spec.ts
+++ b/web/app/components/workflow/run/utils/format-log/human-input/__tests__/index.spec.ts
@@ -1,5 +1,8 @@
+import type { WorkflowTranslate } from '../../parallel'
import { createNodeTracing } from '@/app/components/workflow/__tests__/fixtures'
-import { BlockEnum } from '@/app/components/workflow/types'
+import { BlockEnum, NodeRunningStatus } from '@/app/components/workflow/types'
+import { withSelectorKey } from '@/test/i18n-mock'
+import formatToTracingNodeList from '../../index'
import formatHumanInputNode from '../index'
describe('formatHumanInputNode', () => {
@@ -34,4 +37,63 @@ describe('formatHumanInputNode', () => {
expect(formatHumanInputNode(list)).toEqual([list[2], list[1]])
})
+
+ it('merges statuses within an execution without discarding another approval', () => {
+ const first = {
+ ...createNodeTracing({
+ node_type: BlockEnum.HumanInput,
+ index: 1,
+ status: NodeRunningStatus.Paused,
+ }),
+ node_execution_id: 'first-approval',
+ }
+ const second = {
+ ...createNodeTracing({
+ id: 'trace-2',
+ node_type: BlockEnum.HumanInput,
+ index: 2,
+ status: NodeRunningStatus.Succeeded,
+ }),
+ node_execution_id: 'second-approval',
+ }
+ const resumed = { ...first, id: 'trace-3', index: 3, status: NodeRunningStatus.Succeeded }
+
+ expect(formatHumanInputNode([first, second, resumed])).toEqual([resumed, second])
+ })
+
+ it.each([BlockEnum.Loop, BlockEnum.Iteration])(
+ 'preserves every approval when grouping %s traces without an explicit execution ID',
+ (containerType) => {
+ const container = createNodeTracing({
+ id: 'container-execution',
+ node_id: 'container',
+ node_type: containerType,
+ })
+ const approvals = [0, 1].map((index) =>
+ createNodeTracing({
+ id: `approval-${index}`,
+ index: index + 1,
+ node_type: BlockEnum.HumanInput,
+ status: index ? NodeRunningStatus.Paused : NodeRunningStatus.Succeeded,
+ execution_metadata: {
+ total_tokens: 0,
+ total_price: 0,
+ currency: 'USD',
+ [`${containerType}_id`]: container.node_id,
+ [`${containerType}_index`]: index,
+ },
+ }),
+ )
+
+ const result = formatToTracingNodeList(
+ [container, ...approvals],
+ withSelectorKey((key: string) => key, 'workflow') as WorkflowTranslate,
+ )
+
+ expect(result[0]?.details?.map((row) => row.map((node) => node.id))).toEqual([
+ ['approval-0'],
+ ['approval-1'],
+ ])
+ },
+ )
})
diff --git a/web/app/components/workflow/run/utils/format-log/human-input/index.ts b/web/app/components/workflow/run/utils/format-log/human-input/index.ts
index fa7e5e80ae7..a0d52308328 100644
--- a/web/app/components/workflow/run/utils/format-log/human-input/index.ts
+++ b/web/app/components/workflow/run/utils/format-log/human-input/index.ts
@@ -1,53 +1,29 @@
import type { NodeTracing } from '@/types/workflow'
import { BlockEnum } from '@/app/components/workflow/types'
-/**
- * Format human-input nodes to ensure only the latest status is kept for each node.
- * Human-input nodes can have multiple log entries as their status changes
- * (e.g., running -> paused -> succeeded/failed).
- * This function keeps only the entry with the latest index for each unique node_id.
- */
+/** Keep the latest status of each approval without merging separate container executions. */
const formatHumanInputNode = (list: NodeTracing[]): NodeTracing[] => {
- // Group human-input nodes by node_id
- const humanInputNodeMap = new Map<string, NodeTracing>()
-
- // Track which node_ids are human-input type
- const humanInputNodeIds = new Set<string>()
+ const result: NodeTracing[] = []
+ const humanInputPositions = new Map<string, number>()
- // First pass: identify human-input nodes and keep the one with the highest index
list.forEach((item) => {
- if (item.node_type === BlockEnum.HumanInput) {
- humanInputNodeIds.add(item.node_id)
-
- const existingNode = humanInputNodeMap.get(item.node_id)
- if (!existingNode || item.index > existingNode.index) {
- humanInputNodeMap.set(item.node_id, item)
- }
+ if (item.node_type !== BlockEnum.HumanInput) {
+ result.push(item)
+ return
}
- })
- // If no human-input nodes, return the list as is
- if (humanInputNodeIds.size === 0) return list
-
- // Second pass: filter the list to remove duplicate human-input nodes
- // and keep only the latest one for each node_id
- const result: NodeTracing[] = []
- const addedHumanInputNodeIds = new Set<string>()
-
- list.forEach((item) => {
- if (item.node_type === BlockEnum.HumanInput) {
- // Only add the human-input node with the highest index
- if (!addedHumanInputNodeIds.has(item.node_id)) {
- const latestNode = humanInputNodeMap.get(item.node_id)
- if (latestNode) {
- result.push(latestNode)
- addedHumanInputNodeIds.add(item.node_id)
- }
- }
- // Skip duplicate human-input nodes
- } else {
- // Keep all non-human-input nodes
+ const metadata = item.execution_metadata
+ const inLoopOrIteration =
+ item.iteration_id || item.loop_id || metadata?.iteration_id || metadata?.loop_id
+ // Legacy top-level traces may use different row IDs for successive statuses.
+ // Container execution IDs survive pause/resume and distinguish repeated approvals.
+ const key = item.node_execution_id ?? (inLoopOrIteration ? item.id : item.node_id)
+ const index = humanInputPositions.get(key)
+ if (index === undefined) {
+ humanInputPositions.set(key, result.length)
result.push(item)
+ } else if (item.index > result[index]!.index) {
+ result[index] = item
}
})
diff --git a/web/app/components/workflow/run/utils/format-log/iteration/index.ts b/web/app/components/workflow/run/utils/format-log/iteration/index.ts
index 0c379d6cdd4..18ff35496f8 100644
--- a/web/app/components/workflow/run/utils/format-log/iteration/index.ts
+++ b/web/app/components/workflow/run/utils/format-log/iteration/index.ts
@@ -1,4 +1,5 @@
import type { NodeTracing } from '@/types/workflow'
+import { NodeRunningStatus } from '@/app/components/workflow/types'
export function addChildrenToIterationNode(
iterationNode: NodeTracing,
@@ -32,3 +33,64 @@ export function addChildrenToIterationNode(
details,
}
}
+
+export const getIterationDurationMap = (nodeInfo: NodeTracing) => {
+ return nodeInfo.iterDurationMap || nodeInfo.execution_metadata?.iteration_duration_map || {}
+}
+
+const getIterationExecutions = (
+ key: string,
+ nodeInfo: NodeTracing,
+ allExecutions: NodeTracing[] | undefined,
+) => {
+ if (!allExecutions) return []
+
+ const parallelExecutions = allExecutions.filter(
+ (execution) => execution.execution_metadata?.parallel_mode_run_id === key,
+ )
+ if (parallelExecutions.length) return parallelExecutions
+
+ const index = Number.parseInt(key, 10)
+ if (Number.isNaN(index)) return []
+
+ return allExecutions.filter(
+ (execution) =>
+ execution.execution_metadata?.iteration_id === nodeInfo.node_id &&
+ execution.execution_metadata?.iteration_index === index,
+ )
+}
+
+export const getIterationResultList = (nodeInfo: NodeTracing, allExecutions?: NodeTracing[]) => {
+ const iterationMetadata = nodeInfo.execution_metadata
+
+ if (!iterationMetadata?.iteration_duration_map) return nodeInfo.details || []
+
+ const iterations = Object.keys(iterationMetadata.iteration_duration_map)
+ .map((key) => getIterationExecutions(key, nodeInfo, allExecutions))
+ .filter((branchNodes) => branchNodes.length > 0)
+
+ if (!allExecutions || !nodeInfo.details?.length) return iterations
+
+ const listedIterationIndexes = new Set<number>()
+ iterations.forEach((iteration) => {
+ iteration.forEach((node) => {
+ if (node.execution_metadata?.iteration_index !== undefined)
+ listedIterationIndexes.add(node.execution_metadata.iteration_index)
+ })
+ })
+
+ nodeInfo.details.forEach((iteration, index) => {
+ if (
+ !listedIterationIndexes.has(index) &&
+ iteration.some((node) => node.status === NodeRunningStatus.Failed)
+ ) {
+ iterations.push(iteration)
+ }
+ })
+
+ return iterations.sort((a, b) => {
+ const aIndex = a[0]?.execution_metadata?.iteration_index ?? 0
+ const bIndex = b[0]?.execution_metadata?.iteration_index ?? 0
+ return aIndex - bIndex
+ })
+}
diff --git a/web/app/components/workflow/run/workflow-tool-tracing-context.ts b/web/app/components/workflow/run/workflow-tool-tracing-context.ts
new file mode 100644
index 00000000000..2cc9bd3f80a
--- /dev/null
+++ b/web/app/components/workflow/run/workflow-tool-tracing-context.ts
@@ -0,0 +1,13 @@
+import type { NodeTracing } from '@/types/workflow'
+import { createContext } from 'react'
+
+export type WorkflowRunInfo = {
+ appId: string
+ runId: string
+ status: string
+}
+
+export const WorkflowToolTracingContext = createContext<{
+ workflowRun: WorkflowRunInfo
+ onShowWorkflowTool: (node: NodeTracing) => void
+} | null>(null)
diff --git a/web/app/components/workflow/run/workflow-tool-tracing.tsx b/web/app/components/workflow/run/workflow-tool-tracing.tsx
new file mode 100644
index 00000000000..e13f86b3872
--- /dev/null
+++ b/web/app/components/workflow/run/workflow-tool-tracing.tsx
@@ -0,0 +1,74 @@
+import type { WorkflowRunInfo } from './workflow-tool-tracing-context'
+import type { NodeTracing } from '@/types/workflow'
+import { Button } from '@langgenius/dify-ui/button'
+import { noop, useQuery } from '@tanstack/react-query'
+import { useEffect } from 'react'
+import { useTranslation } from 'react-i18next'
+import { SkeletonContainer, SkeletonRectangle } from '@/app/components/base/skeleton'
+import { consoleQuery } from '@/service/console'
+import TracingPanel from './tracing-panel'
+
+export default function WorkflowToolTracing({
+ node,
+ workflowRun,
+ onBack,
+}: {
+ node: NodeTracing
+ workflowRun: WorkflowRunInfo
+ onBack: () => void
+}) {
+ const { t } = useTranslation(['workflow', 'common'])
+ const isActive = workflowRun.status === 'running' || workflowRun.status === 'paused'
+ const { data, isPending, isError, refetch } = useQuery(
+ consoleQuery.apps.byAppId.workflowRuns.byRunId.nodeExecutions.byNodeExecutionId.children.get.queryOptions(
+ {
+ input: {
+ params: {
+ app_id: workflowRun.appId,
+ run_id: workflowRun.runId,
+ node_execution_id: node.node_execution_id ?? node.id,
+ },
+ },
+ refetchInterval: isActive ? 2000 : false,
+ },
+ ),
+ )
+
+ // Refresh the persisted child executions when the live run finishes.
+ useEffect(() => {
+ if (!isActive) refetch().catch(noop)
+ }, [isActive, refetch])
+
+ return (
+ <div className="bg-background-section-burn">
+ <Button variant="ghost" className="w-full justify-start" onClick={onBack}>
+ <span aria-hidden className="i-ri-arrow-left-line size-4" />
+ {t(($) => $['singleRun.back'], { ns: 'workflow' })}
+ </Button>
+ <div className="px-4 py-2 system-sm-semibold text-text-primary">{node.title}</div>
+ {isPending && (
+ <SkeletonContainer
+ role="status"
+ aria-label={t(($) => $.loading, { ns: 'common' })}
+ className="px-4"
+ >
+ <SkeletonRectangle className="h-10" />
+ <SkeletonRectangle className="h-10" />
+ </SkeletonContainer>
+ )}
+ {isError && (
+ <div role="alert" className="space-y-2 px-4 py-2 text-text-destructive">
+ <div>{t(($) => $['api.actionFailed'], { ns: 'common' })}</div>
+ <Button onClick={() => refetch().catch(noop)}>
+ {t(($) => $['operation.retry'], { ns: 'common' })}
+ </Button>
+ </div>
+ )}
+ {data && !data.data.length && (
+ <div className="px-4 py-2 text-text-tertiary">{t(($) => $.noData, { ns: 'common' })}</div>
+ )}
+ {/* The legacy renderer also types optional live-event fields as required. */}
+ {data && <TracingPanel list={data.data as unknown as NodeTracing[]} />}
+ </div>
+ )
+}
diff --git a/web/app/components/workflow/types.ts b/web/app/components/workflow/types.ts
index 2fec245f97d..53fc69dd710 100644
--- a/web/app/components/workflow/types.ts
+++ b/web/app/components/workflow/types.ts
@@ -462,6 +462,7 @@ export type WorkflowRunningData = {
message_id?: string
conversation_id?: string
result: {
+ id?: string
workflow_id?: string
inputs?: string
inputs_truncated: boolean
diff --git a/web/types/workflow.ts b/web/types/workflow.ts
index 4dcf760b812..4b6461a59bf 100644
--- a/web/types/workflow.ts
+++ b/web/types/workflow.ts
@@ -43,6 +43,7 @@ export type AgentLogItemWithChildren = AgentLogItem & {
export type NodeTracing = {
id: string
+ node_execution_id?: string | null
index: number
predecessor_node_id: string
node_id: string