chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动

演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
wuzilongandCursor committed 2026-11-18 13:59:25 +08:00
1 parent 60158935f4
commit 6519682885
15831 files changed
+3063428

No files matched your search

@@ -0,0 +1,118 @@
import { createEdge, createNode } from '../../__tests__/fixtures'
import {
parseWorkflowClipboardText,
readWorkflowClipboard,
writeWorkflowClipboard,
} from '../clipboard'
describe('workflow clipboard storage', () => {
const currentVersion = '0.6.0'
const readTextMock = vi.fn<() => Promise<string>>()
const writeTextMock = vi.fn<(text: string) => Promise<void>>()
const originalClipboard = Object.getOwnPropertyDescriptor(navigator, 'clipboard')
beforeEach(() => {
readTextMock.mockReset()
writeTextMock.mockReset()
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: {
readText: readTextMock,
writeText: writeTextMock,
},
})
})
afterEach(() => {
if (originalClipboard) Object.defineProperty(navigator, 'clipboard', originalClipboard)
else Reflect.deleteProperty(navigator, 'clipboard')
})
it('should return empty clipboard data when clipboard text is empty', async () => {
readTextMock.mockResolvedValue('')
await expect(readWorkflowClipboard(currentVersion)).resolves.toEqual({
nodes: [],
edges: [],
isVersionMismatch: false,
})
})
it('should write and read clipboard data', async () => {
const nodes = [createNode({ id: 'node-1' })]
const edges = [createEdge({ id: 'edge-1', source: 'node-1', target: 'node-2' })]
await writeWorkflowClipboard({ nodes, edges }, currentVersion)
expect(writeTextMock).toHaveBeenCalledTimes(1)
const serialized = writeTextMock.mock.calls[0]![0]
expect(JSON.parse(serialized)).toEqual({
kind: 'dify-workflow-clipboard',
version: currentVersion,
nodes,
edges,
})
readTextMock.mockResolvedValue(serialized)
await expect(readWorkflowClipboard(currentVersion)).resolves.toEqual({
nodes,
edges,
sourceVersion: currentVersion,
isVersionMismatch: false,
})
})
it('should allow reading clipboard data with different version', async () => {
const nodes = [createNode({ id: 'node-1' })]
const edges = [createEdge({ id: 'edge-1', source: 'node-1', target: 'node-2' })]
readTextMock.mockResolvedValue(
JSON.stringify({
kind: 'dify-workflow-clipboard',
version: '0.5.0',
nodes,
edges,
}),
)
await expect(readWorkflowClipboard(currentVersion)).resolves.toEqual({
nodes,
edges,
sourceVersion: '0.5.0',
isVersionMismatch: true,
})
})
it('should return empty clipboard data for invalid JSON', () => {
expect(parseWorkflowClipboardText('{invalid-json', currentVersion)).toEqual({
nodes: [],
edges: [],
isVersionMismatch: false,
})
})
it('should return empty clipboard data for invalid structure', () => {
expect(
parseWorkflowClipboardText(
JSON.stringify({
kind: 'unknown',
version: 1,
nodes: [],
edges: [],
}),
currentVersion,
),
).toEqual({
nodes: [],
edges: [],
isVersionMismatch: false,
})
})
it('should return empty clipboard data when clipboard read fails', async () => {
readTextMock.mockRejectedValue(new Error('clipboard denied'))
await expect(readWorkflowClipboard(currentVersion)).resolves.toEqual({
nodes: [],
edges: [],
isVersionMismatch: false,
})
})
})
@@ -0,0 +1,21 @@
import { formatWorkflowRunIdentifier } from '../common'
describe('formatWorkflowRunIdentifier', () => {
it('should return fallback text when finishedAt is undefined', () => {
expect(formatWorkflowRunIdentifier()).toBe(' (Running)')
})
it('should return fallback text when finishedAt is 0', () => {
expect(formatWorkflowRunIdentifier(0)).toBe(' (Running)')
})
it('should capitalize custom fallback text', () => {
expect(formatWorkflowRunIdentifier(undefined, 'pending')).toBe(' (Pending)')
})
it('should format a valid timestamp', () => {
const timestamp = 1704067200 // 2024-01-01 00:00:00 UTC
const result = formatWorkflowRunIdentifier(timestamp)
expect(result).toMatch(/^ \(\d{2}:\d{2}:\d{2}( [AP]M)?\)$/)
})
})
@@ -0,0 +1,113 @@
import type { DatasourceParameter } from '@dify/contracts/api/console/rag/types.gen'
import type { DataSourceNodeType } from '../../nodes/data-source/types'
import { FormTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
import { createDatasourceProvider } from '@/app/components/rag-pipeline/__tests__/datasource-fixtures'
import { BlockEnum } from '../../types'
import { datasourceParametersToFormSchemas, getDataSourceCheckParams } from '../data-source'
const node: DataSourceNodeType = {
title: 'Datasource',
desc: '',
type: BlockEnum.DataSource,
plugin_id: 'langgenius/file',
provider_type: 'local_file',
provider_name: 'file',
datasource_name: 'local-file',
datasource_label: 'File',
datasource_parameters: {},
datasource_configurations: {},
}
const parameter = (
type: DatasourceParameter['type'],
defaultValue: DatasourceParameter['default'],
) =>
({
name: type,
type,
default: defaultValue,
label: { en_US: 'Parameter', zh_Hans: null },
description: { en_US: 'Actual datasource description', ja_JP: null },
required: true,
}) satisfies DatasourceParameter
it('projects datasource descriptions, nullable locale fallbacks, and exact default values at the form boundary', () => {
const schemas = datasourceParametersToFormSchemas([
{ ...parameter('number', 0), min: 0, max: 10, placeholder: { en_US: 'Count', zh_Hans: null } },
parameter('boolean', false),
parameter('string', ''),
parameter('secret-input', null),
{
...parameter('select', 'one'),
options: [{ value: 'one', label: { en_US: 'One', zh_Hans: null }, icon: null }],
},
parameter('system-files', []),
])
expect(schemas.map((schema) => schema.default)).toEqual([0, false, '', null, 'one', []])
expect(schemas[0]).toMatchObject({
type: FormTypeEnum.textNumber,
min: 0,
max: 10,
tooltip: { en_US: 'Actual datasource description', ja_JP: 'Actual datasource description' },
label: { zh_Hans: 'Parameter' },
placeholder: { zh_Hans: 'Count' },
})
expect(schemas[1]).toMatchObject({ type: FormTypeEnum.checkbox, _type: FormTypeEnum.boolean })
expect(schemas[4]?.options?.[0]).toMatchObject({ value: 'one', label: { zh_Hans: 'One' } })
expect(schemas[5]?.type).toBe(FormTypeEnum.files)
})
it('derives only required-input metadata and keeps local-file authorization independent', () => {
const provider = createDatasourceProvider({ is_authorized: false })
provider.declaration.datasources![0]!.parameters = [parameter('string', '')]
expect(getDataSourceCheckParams(node, [provider], 'zh_Hans')).toEqual({
dataSourceInputsSchema: [{ label: 'Parameter', variable: 'string', required: true }],
notAuthed: false,
language: 'zh_Hans',
})
expect(
getDataSourceCheckParams({ ...node, provider_type: 'online_document' }, [provider], 'en_US')
.notAuthed,
).toBe(true)
expect(
getDataSourceCheckParams({ ...node, provider_type: 'online_document' }, [], 'en_US').notAuthed,
).toBe(false)
})
it('finds a saved provider without version metadata and leaves missing datasource parameters empty', () => {
const provider = createDatasourceProvider()
expect(
getDataSourceCheckParams(
{ ...node, plugin_id: '', provider_name: provider.provider },
[provider],
'en_US',
).notAuthed,
).toBe(false)
expect(
getDataSourceCheckParams({ ...node, datasource_name: 'missing' }, [provider], 'en_US')
.dataSourceInputsSchema,
).toEqual([])
})
it('uses the saved plugin authorization and parameter schema when providers share a name', () => {
const official = createDatasourceProvider({ is_authorized: true })
official.declaration.datasources![0]!.parameters = [
{ ...parameter('string', ''), name: 'official_input' },
]
const fork = createDatasourceProvider({
plugin_id: 'acme/file',
plugin_unique_identifier: 'acme/file:1.0.0',
is_authorized: false,
})
fork.declaration.datasources![0]!.parameters = [
{ ...parameter('string', ''), name: 'fork_input' },
]
const result = getDataSourceCheckParams(
{ ...node, provider_type: 'online_document' },
[fork, official],
'en_US',
)
expect(result.notAuthed).toBe(false)
expect(result.dataSourceInputsSchema).toEqual([
{ label: 'Parameter', variable: 'official_input', required: true },
])
})
@@ -0,0 +1,41 @@
import { NodeRunningStatus } from '../../types'
import { getEdgeColor } from '../edge'
describe('getEdgeColor', () => {
it('should return success color when status is Succeeded', () => {
expect(getEdgeColor(NodeRunningStatus.Succeeded)).toBe(
'var(--color-workflow-link-line-success-handle)',
)
})
it('should return error color when status is Failed', () => {
expect(getEdgeColor(NodeRunningStatus.Failed)).toBe(
'var(--color-workflow-link-line-error-handle)',
)
})
it('should return failure color when status is Exception', () => {
expect(getEdgeColor(NodeRunningStatus.Exception)).toBe(
'var(--color-workflow-link-line-failure-handle)',
)
})
it('should return default running color when status is Running and not fail branch', () => {
expect(getEdgeColor(NodeRunningStatus.Running)).toBe('var(--color-workflow-link-line-handle)')
})
it('should return failure color when status is Running and is fail branch', () => {
expect(getEdgeColor(NodeRunningStatus.Running, true)).toBe(
'var(--color-workflow-link-line-failure-handle)',
)
})
it('should return normal color when status is undefined', () => {
expect(getEdgeColor()).toBe('var(--color-workflow-link-line-normal)')
})
it('should return normal color for other statuses', () => {
expect(getEdgeColor(NodeRunningStatus.Waiting)).toBe('var(--color-workflow-link-line-normal)')
expect(getEdgeColor(NodeRunningStatus.NotStart)).toBe('var(--color-workflow-link-line-normal)')
})
})
@@ -0,0 +1,107 @@
import type { CommonEdgeType, CommonNodeType, Edge, Node } from '../../types'
import { createEdge, createNode, resetFixtureCounters } from '../../__tests__/fixtures'
import { CUSTOM_NODE } from '../../constants'
import { BlockEnum } from '../../types'
type ElkChild = Record<string, unknown> & {
id: string
width?: number
height?: number
x?: number
y?: number
children?: ElkChild[]
ports?: Array<{ id: string; layoutOptions?: Record<string, string> }>
layoutOptions?: Record<string, string>
}
type ElkGraph = Record<string, unknown> & {
id: string
children?: ElkChild[]
edges?: Array<Record<string, unknown>>
}
let layoutCallArgs: ElkGraph | null = null
let mockReturnOverride: ((graph: ElkGraph) => ElkGraph) | null = null
vi.mock('elkjs/lib/elk.bundled.js', () => {
return {
default: class MockELK {
async layout(graph: ElkGraph) {
layoutCallArgs = graph
if (mockReturnOverride) return mockReturnOverride(graph)
const children = (graph.children || []).map((child: ElkChild, i: number) => ({
...child,
x: 100 + i * 300,
y: 50 + i * 100,
width: child.width || 244,
height: child.height || 100,
}))
return { ...graph, children }
}
},
}
})
const { getLayoutByELK } = await import('../elk-layout')
function makeWorkflowNode(
overrides: Omit<Partial<Node>, 'data'> & {
data?: Partial<CommonNodeType> & Record<string, unknown>
} = {},
): Node {
return createNode({
type: CUSTOM_NODE,
...overrides,
})
}
function makeWorkflowEdge(
overrides: Omit<Partial<Edge>, 'data'> & {
data?: Partial<CommonEdgeType> & Record<string, unknown>
} = {},
): Edge {
return createEdge(overrides)
}
beforeEach(() => {
resetFixtureCounters()
layoutCallArgs = null
mockReturnOverride = null
})
describe('getLayoutByELK', () => {
it('should sort Human Input v2 action edges with __timeout last', async () => {
const nodes = [
makeWorkflowNode({
id: 'hi-1',
data: {
type: BlockEnum.HumanInput,
version: '2',
title: '',
desc: '',
recipients_spec: [{ type: 'initiator' }],
message_template: { subject: 'Review', body: 'Body' },
debug_mode: { enabled: false, channels: [] },
form_content: '',
inputs: [],
user_actions: [{ id: 'a1' }, { id: 'a2' }],
timeout: 36,
timeout_unit: 'hour',
},
}),
makeWorkflowNode({ id: 'x', data: { type: BlockEnum.Code, title: '', desc: '' } }),
makeWorkflowNode({ id: 'y', data: { type: BlockEnum.Code, title: '', desc: '' } }),
makeWorkflowNode({ id: 'z', data: { type: BlockEnum.Code, title: '', desc: '' } }),
]
const edges = [
makeWorkflowEdge({ id: 'e-timeout', source: 'hi-1', target: 'z', sourceHandle: '__timeout' }),
makeWorkflowEdge({ id: 'e-a1', source: 'hi-1', target: 'x', sourceHandle: 'a1' }),
makeWorkflowEdge({ id: 'e-a2', source: 'hi-1', target: 'y', sourceHandle: 'a2' }),
]
await getLayoutByELK(nodes, edges)
const hiNode = layoutCallArgs!.children!.find((c: ElkChild) => c.id === 'hi-1')!
const portIds = hiNode.ports!.map((p: { id: string }) => p.id)
expect(portIds[portIds.length - 1]).toContain('__timeout')
})
})
@@ -0,0 +1,258 @@
import type { CommonNodeType, Edge, Node } from '../../types'
import type { LayoutResult } from '../elk-layout'
import { createEdge, createNode, resetFixtureCounters } from '../../__tests__/fixtures'
import { CUSTOM_NODE } from '../../constants'
import { CUSTOM_ITERATION_START_NODE } from '../../nodes/iteration-start/constants'
import { CUSTOM_LOOP_START_NODE } from '../../nodes/loop-start/constants'
import { BlockEnum } from '../../types'
import { getLayoutByELK, getLayoutForChildNodes } from '../elk-layout'
const node = (
id: string,
data: Partial<CommonNodeType> & Record<string, unknown> = {},
extra: Partial<Node> = {},
) => createNode({ id, type: CUSTOM_NODE, data: { type: BlockEnum.Code, ...data }, ...extra })
const edge = (
source: string,
target: string,
sourceHandle?: string,
data?: Partial<Edge['data']>,
) => createEdge({ source, target, sourceHandle, data })
function expectUsableLayout(result: LayoutResult, ids: string[]) {
expect([...result.nodes.keys()].sort()).toEqual([...ids].sort())
expect(result.bounds.minX).toBe(0)
expect(result.bounds.minY).toBe(0)
const boxes = [...result.nodes.values()]
for (const box of boxes) {
expect([box.x, box.y, box.width, box.height].every(Number.isFinite)).toBe(true)
expect(box.width).toBeGreaterThan(0)
expect(box.height).toBeGreaterThan(0)
expect(box.x).toBeGreaterThanOrEqual(0)
expect(box.y).toBeGreaterThanOrEqual(0)
}
for (let i = 0; i < boxes.length; i++) {
for (let j = i + 1; j < boxes.length; j++) {
const a = boxes[i]!
const b = boxes[j]!
expect(
a.x + a.width <= b.x ||
b.x + b.width <= a.x ||
a.y + a.height <= b.y ||
b.y + b.height <= a.y,
).toBe(true)
}
}
expect(result.bounds.maxX).toBeCloseTo(Math.max(...boxes.map((box) => box.x + box.width)))
expect(result.bounds.maxY).toBeCloseTo(Math.max(...boxes.map((box) => box.y + box.height)))
}
const branchCases = [
{
type: BlockEnum.IfElse,
config: { cases: [{ case_id: 'first' }, { case_id: 'second' }] },
handles: ['first', 'second', 'false'],
},
{
type: BlockEnum.HumanInput,
config: { user_actions: [{ id: 'first' }, { id: 'second' }] },
handles: ['first', 'second', '__timeout'],
},
{
type: BlockEnum.QuestionClassifier,
config: {
classes: [
{ id: 'first', name: 'First' },
{ id: 'second', name: 'Second' },
{ id: 'third', name: 'Third' },
],
},
handles: ['first', 'second', 'third'],
},
]
beforeEach(resetFixtureCounters)
describe('getLayoutByELK with the real layout engine', () => {
it('lays a linear graph left to right, normalizes bounds and leaves its inputs unchanged', async () => {
const nodes = [
node('a', { type: BlockEnum.Start }),
node('b', {}, { width: 320, height: 180 }),
node('c', { type: BlockEnum.End }),
]
const edges = [edge('a', 'b'), edge('b', 'c')]
const snapshot = structuredClone({ nodes, edges })
const result = await getLayoutByELK(nodes, edges)
expectUsableLayout(result, ['a', 'b', 'c'])
expect(result.nodes.get('a')!.x + result.nodes.get('a')!.width).toBeLessThan(
result.nodes.get('b')!.x,
)
expect(result.nodes.get('b')!.x + 320).toBeLessThan(result.nodes.get('c')!.x)
expect(result.nodes.get('b')).toMatchObject({ width: 320, height: 180 })
expect({ nodes, edges }).toEqual(snapshot)
})
it('uses default dimensions for an unmeasured node', async () => {
const unmeasured = node('a', {}, { width: undefined, height: undefined })
const result = await getLayoutByELK([unmeasured], [])
expect(result.nodes.get('a')).toMatchObject({ x: 0, y: 0, width: 244, height: 100 })
})
it('returns zero bounds for an empty graph', async () => {
const result = await getLayoutByELK([], [])
expect(result.nodes.size).toBe(0)
expect(result.bounds).toEqual({ minX: 0, minY: 0, maxX: 0, maxY: 0 })
})
it.each(branchCases)(
'orders $type branches by configured handles with the fallback last',
async ({ type, config, handles }) => {
const nodes = [
node('branch', { type, ...config }),
node('last'),
node('middle'),
node('first'),
]
const edges = [
edge('branch', 'last', handles[2]),
edge('branch', 'middle', handles[1]),
edge('branch', 'first', handles[0]),
]
const result = await getLayoutByELK(nodes, edges)
expectUsableLayout(
result,
nodes.map((item) => item.id),
)
expect(result.nodes.get('first')!.y).toBeLessThan(result.nodes.get('middle')!.y)
expect(result.nodes.get('middle')!.y).toBeLessThan(result.nodes.get('last')!.y)
for (const id of ['first', 'middle', 'last'])
expect(result.nodes.get(id)!.x).toBeGreaterThan(result.nodes.get('branch')!.x)
},
)
it('supports several edges sharing one output handle', async () => {
const nodes = [node('start'), node('first'), node('second'), node('end')]
const result = await getLayoutByELK(nodes, [
edge('start', 'first', 'source'),
edge('start', 'second', 'source'),
edge('first', 'end'),
edge('second', 'end'),
])
expectUsableLayout(
result,
nodes.map((item) => item.id),
)
expect(result.nodes.get('start')!.x).toBeLessThan(result.nodes.get('first')!.x)
expect(result.nodes.get('start')!.x).toBeLessThan(result.nodes.get('second')!.x)
expect(result.nodes.get('end')!.x).toBeGreaterThan(result.nodes.get('second')!.x)
})
it.each([BlockEnum.IfElse, BlockEnum.HumanInput, BlockEnum.QuestionClassifier])(
'lays out incomplete %s configuration without dropping targets',
async (type) => {
const nodes = [node('branch', { type }), node('first'), node('second')]
const result = await getLayoutByELK(nodes, [
edge('branch', 'first', 'unknown'),
edge('branch', 'second'),
])
expectUsableLayout(
result,
nodes.map((item) => item.id),
)
},
)
it('keeps cycles and disconnected nodes in a finite nonoverlapping layout', async () => {
const nodes = [node('a'), node('b'), node('c'), node('isolated')]
const result = await getLayoutByELK(nodes, [edge('a', 'b'), edge('b', 'c'), edge('c', 'a')])
expectUsableLayout(
result,
nodes.map((item) => item.id),
)
})
it('excludes nested nodes, special start nodes and edges whose endpoints are outside the root graph', async () => {
const nodes = [
node('parent', { type: BlockEnum.Iteration }),
node('root'),
node('child', {}, { parentId: 'parent' }),
node('start', { type: BlockEnum.IterationStart }, { type: CUSTOM_ITERATION_START_NODE }),
]
const result = await getLayoutByELK(nodes, [
edge('parent', 'root'),
edge('start', 'child', undefined, { isInIteration: true, iteration_id: 'parent' }),
edge('root', 'child'),
edge('root', 'deleted'),
edge('missing', 'root'),
])
expectUsableLayout(result, ['parent', 'root'])
expect(result.nodes.get('root')!.x).toBeGreaterThan(result.nodes.get('parent')!.x)
})
})
describe('getLayoutForChildNodes', () => {
it('returns null when the requested parent has no children', async () => {
expect(await getLayoutForChildNodes('parent', [node('parent')], [])).toBeNull()
})
it.each([
{
type: CUSTOM_ITERATION_START_NODE,
block: BlockEnum.IterationStart,
data: { isInIteration: true, iteration_id: 'parent' },
},
{
type: CUSTOM_LOOP_START_NODE,
block: BlockEnum.LoopStart,
data: { isInLoop: true, loop_id: 'parent' },
},
])('lays out only the requested container using $type', async ({ type, block, data }) => {
const nodes = [
node('parent'),
node('start', { type: block }, { type, parentId: 'parent' }),
node('child', {}, { parentId: 'parent' }),
node('elsewhere', {}, { parentId: 'other' }),
]
const edges = [
edge('start', 'child', undefined, data),
edge('child', 'elsewhere', undefined, data),
edge('unknown', 'child', undefined, data),
]
const snapshot = structuredClone({ nodes, edges })
const result = await getLayoutForChildNodes('parent', nodes, edges)
expect(result).not.toBeNull()
expectUsableLayout(result!, ['start', 'child'])
expect(result!.nodes.get('start')!.x).toBeLessThan(result!.nodes.get('child')!.x)
expect({ nodes, edges }).toEqual(snapshot)
})
it('preserves branch order inside an iteration', async () => {
const data = { isInIteration: true, iteration_id: 'parent' }
const nodes = [
node(
'start',
{ type: BlockEnum.IterationStart },
{ type: CUSTOM_ITERATION_START_NODE, parentId: 'parent' },
),
node(
'branch',
{ type: BlockEnum.QuestionClassifier, classes: [{ id: 'first' }, { id: 'second' }] },
{ parentId: 'parent' },
),
node('upper', {}, { parentId: 'parent' }),
node('lower', {}, { parentId: 'parent' }),
]
const result = await getLayoutForChildNodes('parent', nodes, [
edge('start', 'branch', undefined, data),
edge('branch', 'lower', 'second', data),
edge('branch', 'upper', 'first', data),
])
expectUsableLayout(
result!,
nodes.map((item) => item.id),
)
expect(result!.nodes.get('upper')!.y).toBeLessThan(result!.nodes.get('lower')!.y)
})
})
@@ -0,0 +1,62 @@
import {
scrollToWorkflowNode,
selectWorkflowNode,
setupNodeSelectionListener,
setupScrollToNodeListener,
} from '../node-navigation'
it('selects without moving the viewport by default, and focuses a requested node after selection', () => {
vi.useFakeTimers()
const handleSelect = vi.fn()
const setCenter = vi.fn<Parameters<typeof setupScrollToNodeListener>[1]['setCenter']>()
const removeSelection = setupNodeSelectionListener(handleSelect)
const removeScroll = setupScrollToNodeListener([{ id: 'node', position: { x: 100, y: 200 } }], {
setCenter,
})
try {
selectWorkflowNode('node')
expect(handleSelect).toHaveBeenCalledExactlyOnceWith('node')
vi.advanceTimersByTime(100)
expect(setCenter).not.toHaveBeenCalled()
selectWorkflowNode('node', true)
expect(handleSelect).toHaveBeenCalledTimes(2)
expect(setCenter).not.toHaveBeenCalled()
vi.advanceTimersByTime(100)
expect(setCenter).toHaveBeenCalledExactlyOnceWith(
100 + window.innerWidth * 0.25,
200 + window.innerHeight * 0.25,
{ zoom: 1, duration: 800 },
)
removeSelection()
removeScroll()
selectWorkflowNode('node', true)
scrollToWorkflowNode('node')
vi.advanceTimersByTime(100)
expect(handleSelect).toHaveBeenCalledTimes(2)
expect(setCenter).toHaveBeenCalledTimes(1)
} finally {
removeSelection()
removeScroll()
vi.clearAllTimers()
vi.useRealTimers()
}
})
it('ignores empty selection ids and scroll targets absent from the current graph', () => {
const handleSelect = vi.fn()
const setCenter = vi.fn<Parameters<typeof setupScrollToNodeListener>[1]['setCenter']>()
const removeSelection = setupNodeSelectionListener(handleSelect)
const removeScroll = setupScrollToNodeListener([{ id: 'node', position: { x: 0, y: 0 } }], {
setCenter,
})
try {
selectWorkflowNode('')
scrollToWorkflowNode('')
scrollToWorkflowNode('deleted')
expect(handleSelect).not.toHaveBeenCalled()
expect(setCenter).not.toHaveBeenCalled()
} finally {
removeSelection()
removeScroll()
}
})
@@ -0,0 +1,248 @@
import type { IterationNodeType } from '../../nodes/iteration/types'
import type { LoopNodeType } from '../../nodes/loop/types'
import type { CommonNodeType, Node } from '../../types'
import { CUSTOM_NODE, NESTED_ELEMENT_Z_INDEX } from '../../constants'
import { CUSTOM_ITERATION_START_NODE } from '../../nodes/iteration-start/constants'
import { CUSTOM_LOOP_START_NODE } from '../../nodes/loop-start/constants'
import { CUSTOM_SIMPLE_NODE } from '../../simple-node/constants'
import { BlockEnum } from '../../types'
import {
generateNewNode,
genNewNodeTitleFromOld,
getIterationStartNode,
getLoopStartNode,
getNestedNodePosition,
getNodeCatalogType,
getNodeCustomTypeByNodeDataType,
getTopLeftNodePosition,
hasRetryNode,
} from '../node'
describe('getNodeCatalogType', () => {
it('should use Agent V2 catalog type for graph agent nodes with the Agent V2 discriminator', () => {
expect(
getNodeCatalogType({
title: 'Agent',
desc: '',
type: BlockEnum.Agent,
agent_node_kind: 'dify_agent',
version: '2',
} as CommonNodeType),
).toBe(BlockEnum.AgentV2)
})
it('should keep the graph node type for regular nodes and legacy Agent nodes', () => {
expect(
getNodeCatalogType({
title: 'Code',
desc: '',
type: BlockEnum.Code,
}),
).toBe(BlockEnum.Code)
expect(
getNodeCatalogType({
title: 'Agent',
desc: '',
type: BlockEnum.Agent,
}),
).toBe(BlockEnum.Agent)
})
it('routes only exact persisted Human Input v2 data to its catalog identity', () => {
const humanInput = (version?: unknown) =>
({
title: 'Human Input',
desc: '',
type: BlockEnum.HumanInput,
...(version === undefined ? {} : { version }),
}) as CommonNodeType
expect(getNodeCatalogType(humanInput('2'))).toBe(BlockEnum.HumanInputV2)
expect(getNodeCatalogType(humanInput())).toBe(BlockEnum.HumanInput)
expect(getNodeCatalogType(humanInput('1'))).toBe(BlockEnum.HumanInput)
expect(getNodeCatalogType(humanInput(2))).toBe(BlockEnum.HumanInput)
})
})
describe('generateNewNode', () => {
it('should create a basic node with default CUSTOM_NODE type', () => {
const { newNode } = generateNewNode({
data: { title: 'Test', desc: '', type: BlockEnum.Code } as CommonNodeType,
position: { x: 100, y: 200 },
})
expect(newNode.type).toBe(CUSTOM_NODE)
expect(newNode.position).toEqual({ x: 100, y: 200 })
expect(newNode.data.title).toBe('Test')
expect(newNode.id).toBeDefined()
})
it('should use provided id when given', () => {
const { newNode } = generateNewNode({
id: 'custom-id',
data: { title: 'Test', desc: '', type: BlockEnum.Code } as CommonNodeType,
position: { x: 0, y: 0 },
})
expect(newNode.id).toBe('custom-id')
})
it('should create an iteration start node for iteration type', () => {
const { newNode, newIterationStartNode } = generateNewNode({
id: 'iter-1',
data: { title: 'Iter', desc: '', type: BlockEnum.Iteration } as CommonNodeType,
position: { x: 0, y: 0 },
})
expect(newNode.zIndex).toBe(0)
expect(newIterationStartNode!.zIndex).toBeGreaterThan(1000)
expect(newIterationStartNode!.id).toBe('iter-1start')
expect(newIterationStartNode!.data.type).toBe(BlockEnum.IterationStart)
expect((newNode.data as IterationNodeType).start_node_id).toBe('iter-1start')
expect((newNode.data as CommonNodeType)._children).toEqual([
{ nodeId: 'iter-1start', nodeType: BlockEnum.IterationStart },
])
})
it('should create a loop start node for loop type', () => {
const { newNode, newLoopStartNode } = generateNewNode({
id: 'loop-1',
data: { title: 'Loop', desc: '', type: BlockEnum.Loop } as CommonNodeType,
position: { x: 0, y: 0 },
})
expect(newNode.zIndex).toBe(0)
expect(newLoopStartNode!.zIndex).toBeGreaterThan(1000)
expect(newLoopStartNode!.id).toBe('loop-1start')
expect(newLoopStartNode!.data.type).toBe(BlockEnum.LoopStart)
expect((newNode.data as LoopNodeType).start_node_id).toBe('loop-1start')
expect((newNode.data as CommonNodeType)._children).toEqual([
{ nodeId: 'loop-1start', nodeType: BlockEnum.LoopStart },
])
})
it('should not create child start nodes for regular types', () => {
const result = generateNewNode({
data: { title: 'Code', desc: '', type: BlockEnum.Code } as CommonNodeType,
position: { x: 0, y: 0 },
})
expect(result.newIterationStartNode).toBeUndefined()
expect(result.newLoopStartNode).toBeUndefined()
})
})
describe('getIterationStartNode', () => {
it('should create a properly configured iteration start node', () => {
const node = getIterationStartNode('parent-iter')
expect(node.id).toBe('parent-iterstart')
expect(node.type).toBe(CUSTOM_ITERATION_START_NODE)
expect(node.data.type).toBe(BlockEnum.IterationStart)
expect(node.data.isInIteration).toBe(true)
expect(node.parentId).toBe('parent-iter')
expect(node.selectable).toBe(false)
expect(node.draggable).toBe(false)
expect(node.zIndex).toBe(NESTED_ELEMENT_Z_INDEX)
expect(node.position).toEqual({ x: 24, y: 68 })
})
})
describe('getLoopStartNode', () => {
it('should create a properly configured loop start node', () => {
const node = getLoopStartNode('parent-loop')
expect(node.id).toBe('parent-loopstart')
expect(node.type).toBe(CUSTOM_LOOP_START_NODE)
expect(node.data.type).toBe(BlockEnum.LoopStart)
expect(node.data.isInLoop).toBe(true)
expect(node.parentId).toBe('parent-loop')
expect(node.selectable).toBe(false)
expect(node.draggable).toBe(false)
expect(node.zIndex).toBe(NESTED_ELEMENT_Z_INDEX)
expect(node.position).toEqual({ x: 24, y: 68 })
})
})
describe('genNewNodeTitleFromOld', () => {
it('should append (1) to a title without a counter', () => {
expect(genNewNodeTitleFromOld('LLM')).toBe('LLM (1)')
})
it('should increment existing counter', () => {
expect(genNewNodeTitleFromOld('LLM (1)')).toBe('LLM (2)')
expect(genNewNodeTitleFromOld('LLM (99)')).toBe('LLM (100)')
})
it('should handle titles with spaces around counter', () => {
expect(genNewNodeTitleFromOld('My Node (3)')).toBe('My Node (4)')
})
it('should handle titles that happen to contain parentheses in the name', () => {
expect(genNewNodeTitleFromOld('Node (special) name')).toBe('Node (special) name (1)')
})
})
describe('getTopLeftNodePosition', () => {
it('should return the minimum x and y from nodes', () => {
const nodes = [
{ position: { x: 100, y: 50 } },
{ position: { x: 20, y: 200 } },
{ position: { x: 50, y: 10 } },
] as Node[]
expect(getTopLeftNodePosition(nodes)).toEqual({ x: 20, y: 10 })
})
it('should handle a single node', () => {
const nodes = [{ position: { x: 42, y: 99 } }] as Node[]
expect(getTopLeftNodePosition(nodes)).toEqual({ x: 42, y: 99 })
})
it('should handle negative positions', () => {
const nodes = [{ position: { x: -10, y: -20 } }, { position: { x: 5, y: -30 } }] as Node[]
expect(getTopLeftNodePosition(nodes)).toEqual({ x: -10, y: -30 })
})
})
describe('getNestedNodePosition', () => {
it('should compute relative position of child to parent', () => {
const node = { position: { x: 150, y: 200 } } as Node
const parent = { position: { x: 100, y: 80 } } as Node
expect(getNestedNodePosition(node, parent)).toEqual({ x: 50, y: 120 })
})
})
describe('hasRetryNode', () => {
it.each([BlockEnum.LLM, BlockEnum.Tool, BlockEnum.HttpRequest, BlockEnum.Code])(
'should return true for %s',
(nodeType) => {
expect(hasRetryNode(nodeType)).toBe(true)
},
)
it.each([BlockEnum.Start, BlockEnum.End, BlockEnum.IfElse, BlockEnum.Iteration])(
'should return false for %s',
(nodeType) => {
expect(hasRetryNode(nodeType)).toBe(false)
},
)
it('should return false when nodeType is undefined', () => {
expect(hasRetryNode()).toBe(false)
})
})
describe('getNodeCustomTypeByNodeDataType', () => {
it('should return CUSTOM_SIMPLE_NODE for LoopEnd', () => {
expect(getNodeCustomTypeByNodeDataType(BlockEnum.LoopEnd)).toBe(CUSTOM_SIMPLE_NODE)
})
it('should return undefined for other types', () => {
expect(getNodeCustomTypeByNodeDataType(BlockEnum.Code)).toBeUndefined()
expect(getNodeCustomTypeByNodeDataType(BlockEnum.LLM)).toBeUndefined()
})
})
@@ -0,0 +1,239 @@
import type { TriggerWithProvider } from '../../block-selector/types'
import type { CommonNodeType, ToolWithProvider } from '../../types'
import { createDatasourceProvider } from '@/app/components/rag-pipeline/__tests__/datasource-fixtures'
import { CollectionType } from '@/app/components/tools/types'
import { BlockEnum } from '../../types'
import {
isNodePluginMissing,
matchDataSource,
matchToolInCollection,
matchTriggerProvider,
} from '../plugin-install-check'
const createTool = (overrides: Partial<ToolWithProvider> = {}): ToolWithProvider =>
({
id: 'langgenius/search/search',
name: 'search',
plugin_id: 'plugin-search',
provider: 'search-provider',
plugin_unique_identifier: 'plugin-search@1.0.0',
...overrides,
}) as ToolWithProvider
const createTriggerProvider = (overrides: Partial<TriggerWithProvider> = {}): TriggerWithProvider =>
({
id: 'trigger-provider-id',
name: 'trigger-provider',
plugin_id: 'trigger-plugin',
...overrides,
}) as TriggerWithProvider
describe('plugin install check', () => {
describe('matchToolInCollection', () => {
const collection = [createTool()]
it('should match a tool by plugin id', () => {
expect(matchToolInCollection(collection, { plugin_id: 'plugin-search' })).toEqual(
collection[0],
)
})
it('should match a tool by legacy provider id', () => {
expect(matchToolInCollection(collection, { provider_id: 'search' })).toEqual(collection[0])
})
it('should match a tool by provider name', () => {
expect(matchToolInCollection(collection, { provider_name: 'search' })).toEqual(collection[0])
})
it('should return undefined when no tool matches', () => {
expect(matchToolInCollection(collection, { plugin_id: 'missing-plugin' })).toBeUndefined()
})
})
describe('matchTriggerProvider', () => {
const providers = [createTriggerProvider()]
it('should match a trigger provider by name', () => {
expect(matchTriggerProvider(providers, { provider_name: 'trigger-provider' })).toEqual(
providers[0],
)
})
it('should match a trigger provider by id', () => {
expect(matchTriggerProvider(providers, { provider_id: 'trigger-provider-id' })).toEqual(
providers[0],
)
})
it('should match a trigger provider by plugin id', () => {
expect(matchTriggerProvider(providers, { plugin_id: 'trigger-plugin' })).toEqual(providers[0])
})
})
describe('matchDataSource', () => {
const dataSources = [
createDatasourceProvider({
provider: 'knowledge-provider',
plugin_id: 'knowledge-plugin',
plugin_unique_identifier: 'knowledge-plugin@1.0.0',
}),
]
it('should match a data source by unique identifier', () => {
expect(
matchDataSource(dataSources, { plugin_unique_identifier: 'knowledge-plugin@1.0.0' }),
).toEqual(dataSources[0])
})
it('should match a data source by plugin id', () => {
expect(matchDataSource(dataSources, { plugin_id: 'knowledge-plugin' })).toEqual(
dataSources[0],
)
})
it('should match a data source by provider name', () => {
expect(matchDataSource(dataSources, { provider_name: 'knowledge-provider' })).toEqual(
dataSources[0],
)
})
it('keeps plugin identity authoritative when another plugin has the same provider name', () => {
const fork = createDatasourceProvider({
provider: 'notion',
plugin_id: 'acme/notion',
plugin_unique_identifier: 'acme/notion:1.0.0',
is_authorized: false,
})
const official = createDatasourceProvider({
provider: 'notion',
plugin_id: 'langgenius/notion',
plugin_unique_identifier: 'langgenius/notion:2.0.0',
is_authorized: true,
})
const savedNode = {
plugin_id: official.plugin_id,
plugin_unique_identifier: official.plugin_unique_identifier,
provider_name: 'notion',
}
expect(matchDataSource([fork, official], savedNode)).toBe(official)
expect(
matchDataSource([fork, official], {
...savedNode,
plugin_unique_identifier: 'langgenius/notion:1.0.0',
}),
).toBe(official)
expect(matchDataSource([fork], savedNode)).toBeUndefined()
expect(
matchDataSource([fork], {
plugin_unique_identifier: official.plugin_unique_identifier,
provider_name: 'notion',
}),
).toBeUndefined()
expect(
isNodePluginMissing(
{ ...savedNode, type: BlockEnum.DataSource, title: 'Notion', desc: '' },
{ dataSourceList: [fork] },
),
).toBe(true)
})
})
describe('isNodePluginMissing', () => {
it('should report missing tool plugins when the collection is loaded but unmatched', () => {
const node = {
type: BlockEnum.Tool,
title: 'Tool',
desc: '',
provider_type: CollectionType.builtIn,
provider_id: 'missing-provider',
plugin_unique_identifier: 'missing-plugin@1.0.0',
} as CommonNodeType
expect(isNodePluginMissing(node, { builtInTools: [createTool()] })).toBe(true)
})
it('should keep tool nodes installable when the collection has not loaded yet', () => {
const node = {
type: BlockEnum.Tool,
title: 'Tool',
desc: '',
provider_type: CollectionType.builtIn,
provider_id: 'missing-provider',
plugin_unique_identifier: 'missing-plugin@1.0.0',
} as CommonNodeType
expect(isNodePluginMissing(node, { builtInTools: undefined })).toBe(false)
})
it('should ignore unmatched tool nodes without plugin identifiers', () => {
const node = {
type: BlockEnum.Tool,
title: 'Tool',
desc: '',
provider_type: CollectionType.builtIn,
provider_id: 'missing-provider',
} as CommonNodeType
expect(isNodePluginMissing(node, { builtInTools: [createTool()] })).toBe(false)
})
it('should report missing trigger plugins when no provider matches', () => {
const node = {
type: BlockEnum.TriggerPlugin,
title: 'Trigger',
desc: '',
provider_id: 'missing-trigger',
plugin_unique_identifier: 'trigger-plugin@1.0.0',
} as CommonNodeType
expect(isNodePluginMissing(node, { triggerPlugins: [createTriggerProvider()] })).toBe(true)
})
it('should keep trigger plugin nodes installable when the provider list has not loaded yet', () => {
const node = {
type: BlockEnum.TriggerPlugin,
title: 'Trigger',
desc: '',
provider_id: 'missing-trigger',
plugin_unique_identifier: 'trigger-plugin@1.0.0',
} as CommonNodeType
expect(isNodePluginMissing(node, { triggerPlugins: undefined })).toBe(false)
})
it('should report missing data source plugins when the list is loaded but unmatched', () => {
const node = {
type: BlockEnum.DataSource,
title: 'Data Source',
desc: '',
provider_name: 'missing-provider',
plugin_unique_identifier: 'missing-data-source@1.0.0',
} as CommonNodeType
expect(isNodePluginMissing(node, { dataSourceList: [createDatasourceProvider()] })).toBe(true)
})
it('should keep data source nodes installable when the list has not loaded yet', () => {
const node = {
type: BlockEnum.DataSource,
title: 'Data Source',
desc: '',
provider_name: 'missing-provider',
plugin_unique_identifier: 'missing-data-source@1.0.0',
} as CommonNodeType
expect(isNodePluginMissing(node, { dataSourceList: undefined })).toBe(false)
})
it('should return false for unsupported node types', () => {
const node = {
type: BlockEnum.LLM,
title: 'LLM',
desc: '',
} as CommonNodeType
expect(isNodePluginMissing(node, {})).toBe(false)
})
})
})
@@ -0,0 +1,11 @@
import { extractPluginId } from '../plugin'
describe('extractPluginId', () => {
it('returns the provider prefix for nested plugin paths', () => {
expect(extractPluginId('langgenius/openai/tools/chat')).toBe('langgenius/openai')
})
it('returns the original provider when it has no nested path', () => {
expect(extractPluginId('langgenius')).toBe('langgenius')
})
})
@@ -0,0 +1,156 @@
import type { ToolNodeType } from '../../nodes/tool/types'
import type { ToolWithProvider } from '../../types'
import { CollectionType } from '@/app/components/tools/types'
import { createTool, createToolProvider } from '../../block-selector/__tests__/factories'
import { BlockEnum } from '../../types'
import { getToolCheckParams, wrapStructuredVarItem } from '../tool'
function createToolData(overrides: Partial<ToolNodeType> = {}): ToolNodeType {
return {
title: 'Tool',
desc: '',
type: BlockEnum.Tool,
provider_id: 'builtin-search',
provider_type: CollectionType.builtIn,
provider_name: 'Search',
tool_label: 'Google Search',
tool_name: 'google_search',
tool_parameters: {},
tool_configurations: {},
...overrides,
}
}
function createToolCollection(overrides: Partial<ToolWithProvider> = {}): ToolWithProvider {
return createToolProvider({
id: 'builtin-search',
name: 'Search',
allow_delete: true,
is_team_authorization: false,
tools: [
{
...createTool('google_search', 'Google Search'),
parameters: [
{
name: 'query',
label: { en_US: 'Query', zh_Hans: '查询' },
type: 'string',
required: true,
form: 'llm',
human_description: { en_US: '', zh_Hans: '' },
llm_description: '',
multiple: false,
},
{
name: 'api_key',
label: { en_US: 'API Key', zh_Hans: 'API Key' },
type: 'string',
required: true,
form: 'credential',
human_description: { en_US: '', zh_Hans: '' },
llm_description: '',
multiple: false,
},
],
},
],
...overrides,
})
}
describe('getToolCheckParams', () => {
it('should separate llm inputs from settings', () => {
const result = getToolCheckParams(createToolData(), [createToolCollection()], [], [], 'en_US')
expect(result.toolInputsSchema).toEqual([
{ label: 'Query', variable: 'query', type: 'text-input', required: true },
])
expect(result.notAuthed).toBe(true)
expect(result.toolSettingSchema).toHaveLength(1)
expect(result.toolSettingSchema[0]!.variable).toBe('api_key')
})
it('should mark authed when is_team_authorization is true', () => {
const result = getToolCheckParams(
createToolData(),
[createToolCollection({ is_team_authorization: true })],
[],
[],
'en_US',
)
expect(result.notAuthed).toBe(false)
})
it('should use custom tools when provider_type is custom', () => {
const customTool = createToolCollection({ id: 'custom-tool' })
const result = getToolCheckParams(
createToolData({ provider_id: 'custom-tool', provider_type: CollectionType.custom }),
[],
[customTool],
[],
'en_US',
)
expect(result.toolInputsSchema).toEqual([
{ label: 'Query', variable: 'query', type: 'text-input', required: true },
])
})
it('should return empty schemas when tool is not found', () => {
const result = getToolCheckParams(
createToolData({ provider_id: 'non-existent' }),
[],
[],
[],
'en_US',
)
expect(result.toolInputsSchema).toEqual([])
expect(result.toolSettingSchema).toEqual([])
})
it('should use workflowTools when provider_type is workflow', () => {
const workflowTool = createToolCollection({ id: 'wf-tool' })
const result = getToolCheckParams(
createToolData({ provider_id: 'wf-tool', provider_type: CollectionType.workflow }),
[],
[],
[workflowTool],
'en_US',
)
expect(result.toolInputsSchema).toEqual([
{ label: 'Query', variable: 'query', type: 'text-input', required: true },
])
})
it('should fallback to en_US label when language key is missing', () => {
const tool = createToolCollection()
const result = getToolCheckParams(createToolData(), [tool], [], [], 'ja_JP')
expect(result.toolInputsSchema[0]!.label).toBe('Query')
const localized = getToolCheckParams(createToolData(), [tool], [], [], 'zh_Hans')
expect(localized.toolInputsSchema[0]!.label).toBe('查询')
})
})
describe('wrapStructuredVarItem', () => {
it('should wrap an output item into StructuredOutput format', () => {
const outputItem = {
name: 'result',
value: { type: 'string', description: 'test' },
}
const result = wrapStructuredVarItem(outputItem, 'json_schema')
expect(result.schema.type).toBe('object')
expect(result.schema.additionalProperties).toBe(false)
expect(result.schema.properties.result).toEqual({
type: 'string',
description: 'test',
schemaType: 'json_schema',
})
})
})
@@ -0,0 +1,145 @@
import type { TriggerWithProvider } from '../../block-selector/types'
import type { PluginTriggerNodeType } from '../../nodes/trigger-plugin/types'
import { CollectionType } from '@/app/components/tools/types'
import { BlockEnum } from '../../types'
import { getTriggerCheckParams } from '../trigger'
function createTriggerData(overrides: Partial<PluginTriggerNodeType> = {}): PluginTriggerNodeType {
return {
title: 'Trigger',
desc: '',
type: BlockEnum.TriggerPlugin,
provider_id: 'provider-1',
provider_type: CollectionType.builtIn,
provider_name: 'my-provider',
event_name: 'on_message',
event_label: 'On Message',
event_parameters: {},
event_configurations: {},
output_schema: {},
...overrides,
}
}
type Parameter = TriggerWithProvider['events'][number]['parameters'][number]
const createParameter = (overrides: Partial<Parameter> = {}): Parameter => ({
name: 'channel',
label: { en_US: 'Channel', zh_Hans: '频道' },
human_description: { en_US: '', zh_Hans: '' },
type: 'string',
form: 'form',
llm_description: '',
required: true,
multiple: false,
default: '',
...overrides,
})
function createTriggerProvider(overrides: Partial<TriggerWithProvider> = {}): TriggerWithProvider {
return {
id: 'provider-1',
name: 'my-provider',
plugin_id: 'plugin-1',
author: 'Dify',
description: { en_US: '', zh_Hans: '' },
icon: 'icon',
label: { en_US: 'Provider', zh_Hans: 'Provider' },
type: CollectionType.trigger,
team_credentials: {},
is_team_authorization: false,
allow_delete: false,
labels: [],
plugin_unique_identifier: 'plugin-1@1.0.0',
meta: { version: '1.0.0' },
supported_creation_methods: [],
events: [
{
name: 'on_message',
author: 'Dify',
label: { en_US: 'On Message', zh_Hans: '收到消息' },
description: { en_US: '', zh_Hans: '' },
labels: [],
output_schema: {},
parameters: [
createParameter(),
createParameter({
name: 'filter',
label: { en_US: 'Filter', zh_Hans: '' },
required: false,
}),
],
},
],
...overrides,
}
}
describe('getTriggerCheckParams', () => {
it('should return empty schema when triggerProviders is undefined', () => {
const result = getTriggerCheckParams(createTriggerData(), undefined, 'en_US')
expect(result).toEqual({
triggerInputsSchema: [],
isReadyForCheckValid: false,
})
})
it('should match provider by name and extract parameters', () => {
const result = getTriggerCheckParams(createTriggerData(), [createTriggerProvider()], 'en_US')
expect(result.isReadyForCheckValid).toBe(true)
expect(result.triggerInputsSchema).toEqual([
{ variable: 'channel', label: 'Channel', required: true },
{ variable: 'filter', label: 'Filter', required: false },
])
})
it('should use the requested language for labels', () => {
const result = getTriggerCheckParams(createTriggerData(), [createTriggerProvider()], 'zh_Hans')
expect(result.triggerInputsSchema.map((field) => field.label)).toEqual(['频道', 'Filter'])
})
it('should fall back to en_US when language label is missing', () => {
const result = getTriggerCheckParams(createTriggerData(), [createTriggerProvider()], 'ja_JP')
expect(result.triggerInputsSchema[0]!.label).toBe('Channel')
})
it('should fall back to parameter name when no labels exist', () => {
const provider = createTriggerProvider()
provider.events[0]!.parameters = [
createParameter({ name: 'raw_param', label: { en_US: '', zh_Hans: '' } }),
]
const result = getTriggerCheckParams(createTriggerData(), [provider], 'en_US')
expect(result.triggerInputsSchema[0]!.label).toBe('raw_param')
})
it('should match provider by provider_id', () => {
const trigger = createTriggerData({
provider_name: 'different-name',
provider_id: 'provider-1',
})
const provider = createTriggerProvider({ name: 'other-name', id: 'provider-1' })
const result = getTriggerCheckParams(trigger, [provider], 'en_US')
expect(result.isReadyForCheckValid).toBe(true)
})
it('should match provider by plugin_id', () => {
const trigger = createTriggerData({ provider_name: 'x', provider_id: 'plugin-1' })
const provider = createTriggerProvider({ name: 'y', id: 'z', plugin_id: 'plugin-1' })
const result = getTriggerCheckParams(trigger, [provider], 'en_US')
expect(result.isReadyForCheckValid).toBe(true)
})
it('should return empty schema when event is not found', () => {
const trigger = createTriggerData({ event_name: 'non_existent_event' })
const result = getTriggerCheckParams(trigger, [createTriggerProvider()], 'en_US')
expect(result.triggerInputsSchema).toEqual([])
expect(result.isReadyForCheckValid).toBe(true)
})
})
@@ -0,0 +1,42 @@
import { BlockEnum } from '../../types'
import { isExceptionVariable, variableTransformer } from '../variable'
describe('variableTransformer', () => {
it.each([
['{{#node1.output#}}', ['node1', 'output']],
['{{#node1.data.items.0.name#}}', ['node1', 'data', 'items', '0', 'name']],
] as const)('converts %s between template text and its selector', (template, selector) => {
expect(variableTransformer(template)).toEqual(selector)
expect(variableTransformer([...selector])).toBe(template)
})
})
describe('isExceptionVariable', () => {
const errorHandleTypes = [
BlockEnum.LLM,
BlockEnum.Tool,
BlockEnum.HttpRequest,
BlockEnum.Code,
BlockEnum.Agent,
]
it.each(errorHandleTypes)('recognizes both exception outputs for %s', (nodeType) => {
expect(isExceptionVariable('error_message', nodeType)).toBe(true)
expect(isExceptionVariable('error_type', nodeType)).toBe(true)
})
it('should return false for error_message with non-error-handle node types', () => {
expect(isExceptionVariable('error_message', BlockEnum.Start)).toBe(false)
expect(isExceptionVariable('error_message', BlockEnum.End)).toBe(false)
expect(isExceptionVariable('error_message', BlockEnum.IfElse)).toBe(false)
})
it('should return false for normal variables with error-handle node types', () => {
expect(isExceptionVariable('output', BlockEnum.LLM)).toBe(false)
expect(isExceptionVariable('text', BlockEnum.Tool)).toBe(false)
})
it('should return false when nodeType is undefined', () => {
expect(isExceptionVariable('error_message')).toBe(false)
})
})
@@ -0,0 +1,39 @@
import { getWorkflowVersionName } from '../version'
describe('getWorkflowVersionName', () => {
it('prefers a marked name over the version number', () => {
expect(
getWorkflowVersionName(
{
marked_name: 'Production',
version_number: 7,
},
'Untitled Version',
),
).toBe('Production')
})
it('uses the version number when the marked name is empty', () => {
expect(
getWorkflowVersionName(
{
marked_name: '',
version_number: 7,
},
'Untitled Version',
),
).toBe('# 7')
})
it('uses the default name for legacy versions without a version number', () => {
expect(
getWorkflowVersionName(
{
marked_name: '',
version_number: null,
},
'Untitled Version',
),
).toBe('Untitled Version')
})
})
@@ -0,0 +1,82 @@
import {
createNode,
createStartNode,
createTriggerNode,
resetFixtureCounters,
} from '../../__tests__/fixtures'
import { BlockEnum } from '../../types'
import { getWorkflowEntryNode, isTriggerWorkflow, isWorkflowEntryNode } from '../workflow-entry'
beforeEach(() => {
resetFixtureCounters()
})
describe('getWorkflowEntryNode', () => {
it.each([BlockEnum.TriggerWebhook, BlockEnum.TriggerSchedule, BlockEnum.TriggerPlugin])(
'prefers the %s trigger over the start node',
(type) => {
const nodes = [
createStartNode({ id: 'start' }),
createTriggerNode(type, { id: 'trigger' }),
createNode({ id: 'code', data: { type: BlockEnum.Code, title: '', desc: '' } }),
]
const entry = getWorkflowEntryNode(nodes)
expect(entry?.id).toBe('trigger')
},
)
it('should return the start node when no trigger node exists', () => {
const nodes = [
createStartNode({ id: 'start' }),
createNode({ id: 'code', data: { type: BlockEnum.Code, title: '', desc: '' } }),
]
const entry = getWorkflowEntryNode(nodes)
expect(entry?.id).toBe('start')
})
it('should return undefined when no entry node exists', () => {
const nodes = [createNode({ id: 'code', data: { type: BlockEnum.Code, title: '', desc: '' } })]
expect(getWorkflowEntryNode(nodes)).toBeUndefined()
})
})
describe('isWorkflowEntryNode', () => {
it('should return true for Start', () => {
expect(isWorkflowEntryNode(BlockEnum.Start)).toBe(true)
})
it.each([BlockEnum.TriggerSchedule, BlockEnum.TriggerWebhook, BlockEnum.TriggerPlugin])(
'should return true for %s',
(type) => {
expect(isWorkflowEntryNode(type)).toBe(true)
},
)
it('should return false for non-entry types', () => {
expect(isWorkflowEntryNode(BlockEnum.Code)).toBe(false)
expect(isWorkflowEntryNode(BlockEnum.LLM)).toBe(false)
expect(isWorkflowEntryNode(BlockEnum.End)).toBe(false)
})
})
describe('isTriggerWorkflow', () => {
it('should return true when nodes contain a trigger node', () => {
const nodes = [createStartNode(), createTriggerNode(BlockEnum.TriggerWebhook)]
expect(isTriggerWorkflow(nodes)).toBe(true)
})
it('should return false when no trigger nodes exist', () => {
const nodes = [
createStartNode(),
createNode({ data: { type: BlockEnum.Code, title: '', desc: '' } }),
]
expect(isTriggerWorkflow(nodes)).toBe(false)
})
it('should return false for empty nodes', () => {
expect(isTriggerWorkflow([])).toBe(false)
})
})
@@ -0,0 +1,624 @@
import type { IfElseNodeType } from '../../nodes/if-else/types'
import type { IterationNodeType } from '../../nodes/iteration/types'
import type { KnowledgeRetrievalNodeType } from '../../nodes/knowledge-retrieval/types'
import type { LLMNodeType } from '../../nodes/llm/types'
import type { LoopNodeType } from '../../nodes/loop/types'
import type { ParameterExtractorNodeType } from '../../nodes/parameter-extractor/types'
import type { ToolNodeType } from '../../nodes/tool/types'
import {
CUSTOM_NODE,
DEFAULT_RETRY_INTERVAL,
DEFAULT_RETRY_MAX,
NESTED_ELEMENT_Z_INDEX,
} from '@/app/components/workflow/constants'
import { CUSTOM_ITERATION_START_NODE } from '@/app/components/workflow/nodes/iteration-start/constants'
import { CUSTOM_LOOP_START_NODE } from '@/app/components/workflow/nodes/loop-start/constants'
import { BlockEnum, ErrorHandleMode } from '@/app/components/workflow/types'
import { createEdge, createNode, resetFixtureCounters } from '../../__tests__/fixtures'
import { initialEdges, initialNodes, preprocessNodesAndEdges } from '../workflow-init'
beforeEach(() => {
resetFixtureCounters()
vi.clearAllMocks()
})
describe.each([
[BlockEnum.Iteration, BlockEnum.IterationStart, CUSTOM_ITERATION_START_NODE],
[BlockEnum.Loop, BlockEnum.LoopStart, CUSTOM_LOOP_START_NODE],
])('migrates legacy %s containers', (containerType, startType, customType) => {
it.each([undefined, 'missing-child'])(
'creates a valid start when the old reference is %s',
(startId) => {
const container = createNode({
id: 'container',
data: { type: containerType, title: '', desc: '', start_node_id: startId },
})
const result = preprocessNodesAndEdges([container], [])
const start = result.nodes.find((node) => node.data.type === startType)!
expect(start).toMatchObject({ parentId: 'container', type: customType })
expect(result.nodes.find((node) => node.id === 'container')!.data).toMatchObject({
start_node_id: start.id,
})
expect(result.edges).toEqual([])
expect(preprocessNodesAndEdges(result.nodes, result.edges)).toEqual(result)
},
)
it('connects the new start to the previous entry and preserves existing child edges', () => {
const nodes = [
createNode({
id: 'container',
data: { type: containerType, title: '', desc: '', start_node_id: 'child' },
}),
createNode({
id: 'child',
parentId: 'container',
data: { type: BlockEnum.Code, title: '', desc: '' },
}),
createNode({
id: 'next',
parentId: 'container',
data: { type: BlockEnum.Code, title: '', desc: '' },
}),
]
const existing = createEdge({ source: 'child', target: 'next' })
const result = preprocessNodesAndEdges(nodes, [existing])
const start = result.nodes.find((node) => node.data.type === startType)!
expect(result.nodes.find((node) => node.id === 'container')!.data).toMatchObject({
start_node_id: start.id,
})
expect(result.edges).toEqual([
existing,
expect.objectContaining({
source: start.id,
target: 'child',
sourceHandle: 'source',
targetHandle: 'target',
data: expect.objectContaining({
sourceType: startType,
targetType: BlockEnum.Code,
isInIteration: containerType === BlockEnum.Iteration,
isInLoop: containerType === BlockEnum.Loop,
}),
}),
])
expect(preprocessNodesAndEdges(result.nodes, result.edges)).toEqual(result)
})
})
describe('initialNodes', () => {
it('should normalize legacy container and nested node layers regardless of node order', () => {
const nodes = [
createNode({
id: 'child-1',
parentId: 'iter-1',
zIndex: 1002,
data: { type: BlockEnum.Code, title: '', desc: '' },
}),
createNode({
id: 'iter-1',
selected: true,
zIndex: 1,
data: { type: BlockEnum.Iteration, title: '', desc: '' },
}),
createNode({
id: 'root-1',
zIndex: 1002,
data: { type: BlockEnum.Code, title: '', desc: '' },
}),
]
const result = initialNodes(nodes, [])
const parentNode = result.find((node) => node.id === 'iter-1')!
const childNode = result.find((node) => node.id === 'child-1')!
expect(parentNode.zIndex).toBe(0)
expect(childNode.zIndex).toBe(NESTED_ELEMENT_Z_INDEX)
expect(result.find((node) => node.id === 'root-1')!.zIndex).toBe(0)
expect(parentNode.zIndex! + 1000).toBeLessThan(childNode.zIndex!)
})
it('should set positions when first node has no position', () => {
const nodes = [
createNode({ id: 'n1', data: { type: BlockEnum.Start, title: '', desc: '' } }),
createNode({ id: 'n2', data: { type: BlockEnum.Code, title: '', desc: '' } }),
]
nodes.forEach((n) => Reflect.deleteProperty(n, 'position'))
const result = initialNodes(nodes, [])
expect(result[0]!.position).toBeDefined()
expect(result[1]!.position).toBeDefined()
expect(result[1]!.position.x).toBeGreaterThan(result[0]!.position.x)
})
it('should set type to CUSTOM_NODE when type is missing', () => {
const nodes = [createNode({ id: 'n1', data: { type: BlockEnum.Start, title: '', desc: '' } })]
Reflect.deleteProperty(nodes[0]!, 'type')
const result = initialNodes(nodes, [])
expect(result[0]!.type).toBe(CUSTOM_NODE)
})
it('should set connected source and target handle ids', () => {
const nodes = [
createNode({ id: 'a', data: { type: BlockEnum.Start, title: '', desc: '' } }),
createNode({ id: 'b', data: { type: BlockEnum.Code, title: '', desc: '' } }),
]
const edges = [
createEdge({ source: 'a', target: 'b', sourceHandle: 'source', targetHandle: 'target' }),
]
const result = initialNodes(nodes, edges)
expect(result[0]!.data._connectedSourceHandleIds).toContain('source')
expect(result[1]!.data._connectedTargetHandleIds).toContain('target')
})
it('should handle IfElse node with cases', () => {
const nodes = [
createNode({
id: 'if-1',
data: {
type: BlockEnum.IfElse,
title: '',
desc: '',
cases: [{ case_id: 'case-1', logical_operator: 'and', conditions: [] }],
},
}),
]
const result = initialNodes(nodes, [])
expect(result[0]!.data._targetBranches?.map((branch) => branch.id)).toEqual(['case-1', 'false'])
})
it('should migrate legacy IfElse node without cases to cases format', () => {
const nodes = [
createNode({
id: 'if-1',
data: {
type: BlockEnum.IfElse,
title: '',
desc: '',
logical_operator: 'and',
conditions: [{ id: 'c1', value: 'test' }],
cases: undefined,
},
}),
]
const result = initialNodes(nodes, [])
const data = result[0]!.data as IfElseNodeType
expect(data.cases).toEqual([
{ case_id: 'true', logical_operator: 'and', conditions: [{ id: 'c1', value: 'test' }] },
])
expect(data.conditions).toBeUndefined()
expect(data.logical_operator).toBeUndefined()
})
it('should delete legacy conditions/logical_operator when cases exist', () => {
const nodes = [
createNode({
id: 'if-1',
data: {
type: BlockEnum.IfElse,
title: '',
desc: '',
logical_operator: 'and',
conditions: [{ id: 'c1', value: 'test' }],
cases: [
{ case_id: 'true', logical_operator: 'and', conditions: [{ id: 'c1', value: 'test' }] },
],
},
}),
]
const result = initialNodes(nodes, [])
const data = result[0]!.data as IfElseNodeType
expect(data.conditions).toBeUndefined()
expect(data.logical_operator).toBeUndefined()
})
it('should set _targetBranches for QuestionClassifier nodes', () => {
const nodes = [
createNode({
id: 'qc-1',
data: {
type: BlockEnum.QuestionClassifier,
title: '',
desc: '',
classes: [{ id: 'cls-1', name: 'Class 1' }],
model: { provider: 'openai' },
},
}),
]
const result = initialNodes(nodes, [])
expect(result[0]!.data._targetBranches).toEqual([{ id: 'cls-1', name: 'Class 1' }])
})
it('should set iteration node defaults', () => {
const nodes = [
createNode({
id: 'iter-1',
data: {
type: BlockEnum.Iteration,
title: '',
desc: '',
},
}),
]
const result = initialNodes(nodes, [])
const iterNode = result.find((n) => n.id === 'iter-1')!
const data = iterNode.data as IterationNodeType
expect(data.is_parallel).toBe(false)
expect(data.parallel_nums).toBe(10)
expect(data.error_handle_mode).toBe(ErrorHandleMode.Terminated)
expect(data._children).toBeDefined()
})
it('should set loop node defaults', () => {
const nodes = [
createNode({
id: 'loop-1',
data: {
type: BlockEnum.Loop,
title: '',
desc: '',
},
}),
]
const result = initialNodes(nodes, [])
const loopNode = result.find((n) => n.id === 'loop-1')!
const data = loopNode.data as LoopNodeType
expect(data.error_handle_mode).toBe(ErrorHandleMode.Terminated)
expect(data._children).toBeDefined()
})
it('should populate _children for iteration nodes with child nodes', () => {
const nodes = [
createNode({
id: 'iter-1',
data: { type: BlockEnum.Iteration, title: '', desc: '' },
}),
createNode({
id: 'child-1',
parentId: 'iter-1',
data: { type: BlockEnum.Code, title: '', desc: '' },
}),
]
const result = initialNodes(nodes, [])
const iterNode = result.find((n) => n.id === 'iter-1')!
const data = iterNode.data as IterationNodeType
expect(data._children).toEqual(
expect.arrayContaining([
expect.objectContaining({ nodeId: 'child-1', nodeType: BlockEnum.Code }),
]),
)
})
it('should correct model provider for LLM nodes', () => {
const nodes = [
createNode({
id: 'llm-1',
data: {
type: BlockEnum.LLM,
title: '',
desc: '',
model: { provider: 'openai' },
},
}),
]
const result = initialNodes(nodes, [])
expect((result[0]!.data as LLMNodeType).model.provider).toBe('langgenius/openai/openai')
})
it('should correct model provider for KnowledgeRetrieval reranking_model', () => {
const nodes = [
createNode({
id: 'kr-1',
data: {
type: BlockEnum.KnowledgeRetrieval,
title: '',
desc: '',
multiple_retrieval_config: {
reranking_model: { provider: 'cohere' },
},
},
}),
]
const result = initialNodes(nodes, [])
expect(
(result[0]!.data as KnowledgeRetrievalNodeType).multiple_retrieval_config!.reranking_model!
.provider,
).toBe('langgenius/cohere/cohere')
})
it('should correct model provider for ParameterExtractor nodes', () => {
const nodes = [
createNode({
id: 'pe-1',
data: {
type: BlockEnum.ParameterExtractor,
title: '',
desc: '',
model: { provider: 'anthropic' },
},
}),
]
const result = initialNodes(nodes, [])
expect((result[0]!.data as ParameterExtractorNodeType).model.provider).toBe(
'langgenius/anthropic/anthropic',
)
})
it('should add default retry_config for HttpRequest nodes', () => {
const nodes = [
createNode({
id: 'http-1',
data: {
type: BlockEnum.HttpRequest,
title: '',
desc: '',
},
}),
]
const result = initialNodes(nodes, [])
expect(result[0]!.data.retry_config).toEqual({
retry_enabled: true,
max_retries: DEFAULT_RETRY_MAX,
retry_interval: DEFAULT_RETRY_INTERVAL,
})
})
it('should not overwrite existing retry_config for HttpRequest nodes', () => {
const existingConfig = { retry_enabled: false, max_retries: 1, retry_interval: 50 }
const nodes = [
createNode({
id: 'http-1',
data: {
type: BlockEnum.HttpRequest,
title: '',
desc: '',
retry_config: existingConfig,
},
}),
]
const result = initialNodes(nodes, [])
expect(result[0]!.data.retry_config).toEqual(existingConfig)
})
it('should migrate legacy Tool node configurations', () => {
const nodes = [
createNode({
id: 'tool-1',
data: {
type: BlockEnum.Tool,
title: '',
desc: '',
tool_configurations: {
api_key: 'secret-key',
optional_key: null,
nested: { type: 'constant', value: 'already-migrated' },
},
},
}),
]
const result = initialNodes(nodes, [])
const data = result[0]!.data as ToolNodeType
expect(data.tool_node_version).toBe('2')
expect(data.tool_configurations.optional_key).toEqual({ type: 'constant', value: null })
expect(data.tool_configurations.api_key).toEqual({
type: 'constant',
value: 'secret-key',
})
expect(data.tool_configurations.nested).toEqual({
type: 'constant',
value: 'already-migrated',
})
})
it('should not migrate Tool node when version already exists', () => {
const nodes = [
createNode({
id: 'tool-1',
data: {
type: BlockEnum.Tool,
title: '',
desc: '',
version: '1',
tool_configurations: { key: 'val' },
},
}),
]
const result = initialNodes(nodes, [])
const data = result[0]!.data as ToolNodeType
expect(data.tool_configurations).toEqual({ key: 'val' })
})
it('should not migrate Tool node when tool_node_version already exists', () => {
const nodes = [
createNode({
id: 'tool-1',
data: {
type: BlockEnum.Tool,
title: '',
desc: '',
tool_node_version: '2',
tool_configurations: { key: 'val' },
},
}),
]
const result = initialNodes(nodes, [])
const data = result[0]!.data as ToolNodeType
expect(data.tool_configurations).toEqual({ key: 'val' })
})
it('should normalize legacy nested and root edge layers', () => {
const nodes = [
createNode({ id: 'iter-1', data: { type: BlockEnum.Iteration, title: '', desc: '' } }),
createNode({
id: 'child-1',
parentId: 'iter-1',
data: { type: BlockEnum.Code, title: '', desc: '' },
}),
createNode({
id: 'child-2',
parentId: 'iter-1',
data: { type: BlockEnum.Code, title: '', desc: '' },
}),
createNode({ id: 'root-1', data: { type: BlockEnum.Code, title: '', desc: '' } }),
]
const edges = [
createEdge({ id: 'nested-edge', source: 'child-1', target: 'child-2', zIndex: 1002 }),
createEdge({ id: 'boundary-edge', source: 'child-2', target: 'root-1', zIndex: 1002 }),
createEdge({ id: 'root-edge', source: 'root-1', target: 'iter-1', zIndex: 1002 }),
]
const result = initialEdges(edges, nodes)
expect(result.find((edge) => edge.id === 'nested-edge')!.zIndex).toBe(NESTED_ELEMENT_Z_INDEX)
expect(result.find((edge) => edge.id === 'boundary-edge')!.zIndex).toBe(NESTED_ELEMENT_Z_INDEX)
expect(result.find((edge) => edge.id === 'root-edge')!.zIndex).toBe(0)
expect(result.find((edge) => edge.id === 'nested-edge')!.data).toEqual(
expect.objectContaining({
isInIteration: true,
iteration_id: 'iter-1',
isInLoop: false,
loop_id: undefined,
}),
)
expect(result.find((edge) => edge.id === 'boundary-edge')!.data).toEqual(
expect.objectContaining({
isInIteration: true,
iteration_id: 'iter-1',
isInLoop: false,
loop_id: undefined,
}),
)
expect(result.find((edge) => edge.id === 'root-edge')!.data).toEqual(
expect.objectContaining({
isInIteration: false,
iteration_id: undefined,
isInLoop: false,
loop_id: undefined,
}),
)
})
it('should set default sourceHandle and targetHandle', () => {
const nodes = [
createNode({ id: 'a', data: { type: BlockEnum.Start, title: '', desc: '' } }),
createNode({ id: 'b', data: { type: BlockEnum.Code, title: '', desc: '' } }),
]
const edge = createEdge({ source: 'a', target: 'b' })
Reflect.deleteProperty(edge, 'sourceHandle')
Reflect.deleteProperty(edge, 'targetHandle')
const result = initialEdges([edge], nodes)
expect(result[0]!).toMatchObject({
type: 'custom',
data: { sourceType: BlockEnum.Start, targetType: BlockEnum.Code },
})
expect(result[0]!.sourceHandle).toBe('source')
expect(result[0]!.targetHandle).toBe('target')
})
it('should set _connectedNodeIsSelected when a node is selected', () => {
const nodes = [
createNode({ id: 'a', data: { type: BlockEnum.Start, title: '', desc: '', selected: true } }),
createNode({ id: 'b', data: { type: BlockEnum.Code, title: '', desc: '' } }),
]
const edges = [createEdge({ source: 'a', target: 'b' })]
const result = initialEdges(edges, nodes)
expect(result[0]!.data!._connectedNodeIsSelected).toBe(true)
})
it('should filter cycle edges', () => {
const nodes = [
createNode({ id: 'a', data: { type: BlockEnum.Start, title: '', desc: '' } }),
createNode({ id: 'b', data: { type: BlockEnum.Code, title: '', desc: '' } }),
createNode({ id: 'c', data: { type: BlockEnum.Code, title: '', desc: '' } }),
]
const edges = [
createEdge({ source: 'a', target: 'b' }),
createEdge({ source: 'b', target: 'c' }),
createEdge({ source: 'c', target: 'b' }),
]
const result = initialEdges(edges, nodes)
expect(result.map((edge) => [edge.source, edge.target])).toEqual([['a', 'b']])
})
it('should handle edges where source/target node is missing from nodesMap', () => {
const nodes = [createNode({ id: 'a', data: { type: BlockEnum.Start, title: '', desc: '' } })]
const edges = [createEdge({ source: 'a', target: 'missing' })]
const result = initialEdges(edges, nodes)
expect(result).toHaveLength(1)
})
it('should set _connectedNodeIsSelected for edge target matching selected node', () => {
const nodes = [
createNode({ id: 'a', data: { type: BlockEnum.Start, title: '', desc: '' } }),
createNode({ id: 'b', data: { type: BlockEnum.Code, title: '', desc: '', selected: true } }),
]
const edges = [createEdge({ source: 'a', target: 'b' })]
const result = initialEdges(edges, nodes)
expect(result[0]!.data!._connectedNodeIsSelected).toBe(true)
})
it('should not set default sourceHandle when sourceHandle already exists', () => {
const nodes = [
createNode({ id: 'a', data: { type: BlockEnum.Start, title: '', desc: '' } }),
createNode({ id: 'b', data: { type: BlockEnum.Code, title: '', desc: '' } }),
]
const edges = [
createEdge({
source: 'a',
target: 'b',
sourceHandle: 'custom-src',
targetHandle: 'custom-tgt',
}),
]
const result = initialEdges(edges, nodes)
expect(result[0]!.sourceHandle).toBe('custom-src')
expect(result[0]!.targetHandle).toBe('custom-tgt')
})
it('removes cycle edges while preserving connections into, out of, and between cycles', () => {
const nodes = ['start', 'a', 'b', 'c', 'd', 'self', 'end'].map((id) => createNode({ id }))
const pairs = [
['start', 'a'],
['a', 'b'],
['b', 'a'],
['b', 'c'],
['c', 'd'],
['d', 'c'],
['d', 'end'],
['start', 'self'],
['self', 'self'],
['self', 'end'],
]
const edges = pairs.map(([source, target]) => createEdge({ source: source!, target: target! }))
expect(initialEdges(edges, nodes).map((edge) => [edge.source, edge.target])).toEqual([
['start', 'a'],
['b', 'c'],
['d', 'end'],
['start', 'self'],
['self', 'end'],
])
})
})
@@ -0,0 +1,422 @@
import { createEdge, createNode, resetFixtureCounters } from '../../__tests__/fixtures'
import { BlockEnum } from '../../types'
import {
canRunBySingle,
getNodesConnectedSourceOrTargetHandleIdsMap,
getValidTreeNodes,
hasErrorHandleNode,
isSupportCustomRunForm,
} from '../workflow'
beforeEach(() => {
resetFixtureCounters()
})
describe('canRunBySingle', () => {
const runnableTypes = [
BlockEnum.LLM,
BlockEnum.KnowledgeRetrieval,
BlockEnum.Code,
BlockEnum.TemplateTransform,
BlockEnum.QuestionClassifier,
BlockEnum.HttpRequest,
BlockEnum.Tool,
BlockEnum.ParameterExtractor,
BlockEnum.Iteration,
BlockEnum.Agent,
BlockEnum.AgentV2,
BlockEnum.DocExtractor,
BlockEnum.Loop,
BlockEnum.Start,
BlockEnum.IfElse,
BlockEnum.VariableAggregator,
BlockEnum.Assigner,
BlockEnum.HumanInput,
BlockEnum.DataSource,
BlockEnum.TriggerSchedule,
BlockEnum.TriggerWebhook,
BlockEnum.TriggerPlugin,
]
it.each(runnableTypes)('should return true for %s when not a child node', (type) => {
expect(canRunBySingle(type, false)).toBe(true)
})
it('should return false for Assigner when it is a child node', () => {
expect(canRunBySingle(BlockEnum.Assigner, true)).toBe(false)
})
it('should return true for LLM even as a child node', () => {
expect(canRunBySingle(BlockEnum.LLM, true)).toBe(true)
})
it('should return false for End node', () => {
expect(canRunBySingle(BlockEnum.End, false)).toBe(false)
})
it('should return false for Answer node', () => {
expect(canRunBySingle(BlockEnum.Answer, false)).toBe(false)
})
})
describe('isSupportCustomRunForm', () => {
it('should return true for DataSource', () => {
expect(isSupportCustomRunForm(BlockEnum.DataSource)).toBe(true)
})
it('should return false for other types', () => {
expect(isSupportCustomRunForm(BlockEnum.LLM)).toBe(false)
expect(isSupportCustomRunForm(BlockEnum.Code)).toBe(false)
})
})
describe('hasErrorHandleNode', () => {
it.each([
BlockEnum.LLM,
BlockEnum.Tool,
BlockEnum.HttpRequest,
BlockEnum.Code,
BlockEnum.Agent,
BlockEnum.AgentV2,
])('should return true for %s', (type) => {
expect(hasErrorHandleNode(type)).toBe(true)
})
it('should return false for non-error-handle types', () => {
expect(hasErrorHandleNode(BlockEnum.Start)).toBe(false)
expect(hasErrorHandleNode(BlockEnum.Iteration)).toBe(false)
})
it('should return false when undefined', () => {
expect(hasErrorHandleNode()).toBe(false)
})
})
describe('getNodesConnectedSourceOrTargetHandleIdsMap', () => {
it('should add handle ids when type is add', () => {
const node1 = createNode({ id: 'a', data: { type: BlockEnum.Start, title: '', desc: '' } })
const node2 = createNode({ id: 'b', data: { type: BlockEnum.Code, title: '', desc: '' } })
const edge = createEdge({
source: 'a',
target: 'b',
sourceHandle: 'src-handle',
targetHandle: 'tgt-handle',
})
const result = getNodesConnectedSourceOrTargetHandleIdsMap(
[{ type: 'add', edge }],
[node1, node2],
)
expect(result.a._connectedSourceHandleIds).toContain('src-handle')
expect(result.b._connectedTargetHandleIds).toContain('tgt-handle')
})
it('should remove handle ids when type is remove', () => {
const node1 = createNode({
id: 'a',
data: {
type: BlockEnum.Start,
title: '',
desc: '',
_connectedSourceHandleIds: ['src-handle'],
},
})
const node2 = createNode({
id: 'b',
data: {
type: BlockEnum.Code,
title: '',
desc: '',
_connectedTargetHandleIds: ['tgt-handle'],
},
})
const edge = createEdge({
source: 'a',
target: 'b',
sourceHandle: 'src-handle',
targetHandle: 'tgt-handle',
})
const result = getNodesConnectedSourceOrTargetHandleIdsMap(
[{ type: 'remove', edge }],
[node1, node2],
)
expect(result.a._connectedSourceHandleIds).not.toContain('src-handle')
expect(result.b._connectedTargetHandleIds).not.toContain('tgt-handle')
})
it('should use default handle ids when sourceHandle/targetHandle are missing', () => {
const node1 = createNode({ id: 'a', data: { type: BlockEnum.Start, title: '', desc: '' } })
const node2 = createNode({ id: 'b', data: { type: BlockEnum.Code, title: '', desc: '' } })
const edge = createEdge({ source: 'a', target: 'b' })
Reflect.deleteProperty(edge, 'sourceHandle')
Reflect.deleteProperty(edge, 'targetHandle')
const result = getNodesConnectedSourceOrTargetHandleIdsMap(
[{ type: 'add', edge }],
[node1, node2],
)
expect(result.a._connectedSourceHandleIds).toContain('source')
expect(result.b._connectedTargetHandleIds).toContain('target')
})
it('should skip when source node is not found', () => {
const node2 = createNode({ id: 'b', data: { type: BlockEnum.Code, title: '', desc: '' } })
const edge = createEdge({ source: 'missing', target: 'b', sourceHandle: 'src' })
const result = getNodesConnectedSourceOrTargetHandleIdsMap([{ type: 'add', edge }], [node2])
expect(result.missing).toBeUndefined()
expect(result.b._connectedTargetHandleIds).toBeDefined()
})
it('should skip when target node is not found', () => {
const node1 = createNode({ id: 'a', data: { type: BlockEnum.Start, title: '', desc: '' } })
const edge = createEdge({ source: 'a', target: 'missing', targetHandle: 'tgt' })
const result = getNodesConnectedSourceOrTargetHandleIdsMap([{ type: 'add', edge }], [node1])
expect(result.a._connectedSourceHandleIds).toBeDefined()
expect(result.missing).toBeUndefined()
})
it('should reuse existing map entry for same node across multiple changes', () => {
const node1 = createNode({ id: 'a', data: { type: BlockEnum.Start, title: '', desc: '' } })
const node2 = createNode({ id: 'b', data: { type: BlockEnum.Code, title: '', desc: '' } })
const node3 = createNode({ id: 'c', data: { type: BlockEnum.Code, title: '', desc: '' } })
const edge1 = createEdge({ source: 'a', target: 'b', sourceHandle: 'h1' })
const edge2 = createEdge({ source: 'a', target: 'c', sourceHandle: 'h2' })
const result = getNodesConnectedSourceOrTargetHandleIdsMap(
[
{ type: 'add', edge: edge1 },
{ type: 'add', edge: edge2 },
],
[node1, node2, node3],
)
expect(result.a._connectedSourceHandleIds).toEqual(['h1', 'h2'])
expect(node1.data._connectedSourceHandleIds ?? []).toEqual([])
})
})
describe('removing connection handles', () => {
it('preserves unrelated handles when the removed edge is no longer tracked', () => {
const nodes = [
createNode({ id: 'a', data: { _connectedSourceHandleIds: ['keep-source'] } }),
createNode({ id: 'b', data: { _connectedTargetHandleIds: ['keep-target'] } }),
]
const result = getNodesConnectedSourceOrTargetHandleIdsMap(
[
{
type: 'remove',
edge: createEdge({
source: 'a',
target: 'b',
sourceHandle: 'missing',
targetHandle: 'missing',
}),
},
],
nodes,
)
expect(result.a._connectedSourceHandleIds).toEqual(['keep-source'])
expect(result.b._connectedTargetHandleIds).toEqual(['keep-target'])
})
it('removes default handles while preserving other connections and caller data', () => {
const nodes = [
createNode({ id: 'a', data: { _connectedSourceHandleIds: ['source', 'keep-source'] } }),
createNode({ id: 'b', data: { _connectedTargetHandleIds: ['target', 'keep-target'] } }),
]
const edge = createEdge({ source: 'a', target: 'b', sourceHandle: null, targetHandle: null })
const result = getNodesConnectedSourceOrTargetHandleIdsMap([{ type: 'remove', edge }], nodes)
expect(result.a._connectedSourceHandleIds).toEqual(['keep-source'])
expect(result.b._connectedTargetHandleIds).toEqual(['keep-target'])
expect(nodes[0]!.data._connectedSourceHandleIds).toEqual(['source', 'keep-source'])
expect(nodes[1]!.data._connectedTargetHandleIds).toEqual(['target', 'keep-target'])
})
})
describe('getValidTreeNodes', () => {
it('should return empty when there are no start/trigger nodes', () => {
const nodes = [createNode({ id: 'n1', data: { type: BlockEnum.Code, title: '', desc: '' } })]
const result = getValidTreeNodes(nodes, [])
expect(result.validNodes).toEqual([])
expect(result.maxDepth).toBe(0)
})
it('should traverse a linear graph from Start', () => {
const nodes = [
createNode({ id: 'start', data: { type: BlockEnum.Start, title: '', desc: '' } }),
createNode({ id: 'llm', data: { type: BlockEnum.LLM, title: '', desc: '' } }),
createNode({ id: 'end', data: { type: BlockEnum.End, title: '', desc: '' } }),
]
const edges = [
createEdge({ source: 'start', target: 'llm' }),
createEdge({ source: 'llm', target: 'end' }),
]
const result = getValidTreeNodes(nodes, edges)
expect(result.validNodes.map((n) => n.id)).toEqual(['start', 'llm', 'end'])
expect(result.maxDepth).toBe(3)
})
it('should traverse from trigger nodes', () => {
const nodes = [
createNode({ id: 'trigger', data: { type: BlockEnum.TriggerWebhook, title: '', desc: '' } }),
createNode({ id: 'code', data: { type: BlockEnum.Code, title: '', desc: '' } }),
]
const edges = [createEdge({ source: 'trigger', target: 'code' })]
const result = getValidTreeNodes(nodes, edges)
expect(result.validNodes.map((n) => n.id)).toContain('trigger')
expect(result.validNodes.map((n) => n.id)).toContain('code')
})
it('should include iteration children as valid nodes', () => {
const nodes = [
createNode({ id: 'start', data: { type: BlockEnum.Start, title: '', desc: '' } }),
createNode({ id: 'iter', data: { type: BlockEnum.Iteration, title: '', desc: '' } }),
createNode({
id: 'child1',
data: { type: BlockEnum.Code, title: '', desc: '' },
parentId: 'iter',
}),
]
const edges = [createEdge({ source: 'start', target: 'iter' })]
const result = getValidTreeNodes(nodes, edges)
expect(result.validNodes.map((n) => n.id)).toContain('child1')
})
it('should include loop children when loop has outgoers', () => {
const nodes = [
createNode({ id: 'start', data: { type: BlockEnum.Start, title: '', desc: '' } }),
createNode({ id: 'loop', data: { type: BlockEnum.Loop, title: '', desc: '' } }),
createNode({
id: 'loop-child',
data: { type: BlockEnum.Code, title: '', desc: '' },
parentId: 'loop',
}),
createNode({ id: 'end', data: { type: BlockEnum.End, title: '', desc: '' } }),
]
const edges = [
createEdge({ source: 'start', target: 'loop' }),
createEdge({ source: 'loop', target: 'end' }),
]
const result = getValidTreeNodes(nodes, edges)
expect(result.validNodes.map((n) => n.id)).toContain('loop-child')
})
it('should include loop children as valid nodes when loop is a leaf', () => {
const nodes = [
createNode({ id: 'start', data: { type: BlockEnum.Start, title: '', desc: '' } }),
createNode({ id: 'loop', data: { type: BlockEnum.Loop, title: '', desc: '' } }),
createNode({
id: 'loop-child',
data: { type: BlockEnum.Code, title: '', desc: '' },
parentId: 'loop',
}),
]
const edges = [createEdge({ source: 'start', target: 'loop' })]
const result = getValidTreeNodes(nodes, edges)
expect(result.validNodes.map((n) => n.id)).toContain('loop-child')
})
it('should handle cycles without infinite loop', () => {
const nodes = [
createNode({ id: 'start', data: { type: BlockEnum.Start, title: '', desc: '' } }),
createNode({ id: 'a', data: { type: BlockEnum.Code, title: '', desc: '' } }),
createNode({ id: 'b', data: { type: BlockEnum.Code, title: '', desc: '' } }),
]
const edges = [
createEdge({ source: 'start', target: 'a' }),
createEdge({ source: 'a', target: 'b' }),
createEdge({ source: 'b', target: 'a' }),
]
const result = getValidTreeNodes(nodes, edges)
expect(result.validNodes.map((node) => node.id)).toEqual(['start', 'a', 'b'])
})
it('should exclude disconnected nodes', () => {
const nodes = [
createNode({ id: 'start', data: { type: BlockEnum.Start, title: '', desc: '' } }),
createNode({ id: 'connected', data: { type: BlockEnum.Code, title: '', desc: '' } }),
createNode({ id: 'isolated', data: { type: BlockEnum.Code, title: '', desc: '' } }),
]
const edges = [createEdge({ source: 'start', target: 'connected' })]
const result = getValidTreeNodes(nodes, edges)
expect(result.validNodes.map((n) => n.id)).not.toContain('isolated')
})
it('should handle multiple start nodes without double-traversal', () => {
const nodes = [
createNode({ id: 'start1', data: { type: BlockEnum.Start, title: '', desc: '' } }),
createNode({ id: 'trigger', data: { type: BlockEnum.TriggerSchedule, title: '', desc: '' } }),
createNode({ id: 'shared', data: { type: BlockEnum.Code, title: '', desc: '' } }),
]
const edges = [
createEdge({ source: 'start1', target: 'shared' }),
createEdge({ source: 'trigger', target: 'shared' }),
]
const result = getValidTreeNodes(nodes, edges)
expect(result.validNodes.map((node) => node.id).sort()).toEqual(['shared', 'start1', 'trigger'])
})
it('should not increase maxDepth when visiting nodes at same or lower depth', () => {
const nodes = [
createNode({ id: 'start', data: { type: BlockEnum.Start, title: '', desc: '' } }),
createNode({ id: 'a', data: { type: BlockEnum.Code, title: '', desc: '' } }),
createNode({ id: 'b', data: { type: BlockEnum.Code, title: '', desc: '' } }),
]
const edges = [
createEdge({ source: 'start', target: 'a' }),
createEdge({ source: 'start', target: 'b' }),
]
const result = getValidTreeNodes(nodes, edges)
expect(result.maxDepth).toBe(2)
})
it('should traverse from all trigger types', () => {
const nodes = [
createNode({ id: 'ts', data: { type: BlockEnum.TriggerSchedule, title: '', desc: '' } }),
createNode({ id: 'tp', data: { type: BlockEnum.TriggerPlugin, title: '', desc: '' } }),
createNode({ id: 'code1', data: { type: BlockEnum.Code, title: '', desc: '' } }),
createNode({ id: 'code2', data: { type: BlockEnum.Code, title: '', desc: '' } }),
]
const edges = [
createEdge({ source: 'ts', target: 'code1' }),
createEdge({ source: 'tp', target: 'code2' }),
]
const result = getValidTreeNodes(nodes, edges)
expect(result.validNodes).toHaveLength(4)
})
it('should skip start nodes already visited by a previous start node traversal', () => {
const nodes = [
createNode({ id: 'start1', data: { type: BlockEnum.Start, title: '', desc: '' } }),
createNode({ id: 'start2', data: { type: BlockEnum.TriggerWebhook, title: '', desc: '' } }),
createNode({ id: 'shared', data: { type: BlockEnum.Code, title: '', desc: '' } }),
]
const edges = [
createEdge({ source: 'start1', target: 'start2' }),
createEdge({ source: 'start2', target: 'shared' }),
]
const result = getValidTreeNodes(nodes, edges)
expect(result.validNodes.map((n) => n.id)).toContain('start1')
expect(result.validNodes.map((n) => n.id)).toContain('start2')
expect(result.validNodes.map((n) => n.id)).toContain('shared')
})
})
@@ -0,0 +1,194 @@
import type { Edge, Node } from '../types'
const WORKFLOW_CLIPBOARD_KIND = 'dify-workflow-clipboard'
type WorkflowClipboardPayload = {
kind: string
version: string
nodes: Node[]
edges: Edge[]
}
type WorkflowClipboardData = {
nodes: Node[]
edges: Edge[]
}
type WorkflowClipboardReadResult = WorkflowClipboardData & {
sourceVersion?: string
isVersionMismatch: boolean
}
const emptyClipboardData: WorkflowClipboardData = {
nodes: [],
edges: [],
}
const emptyClipboardReadResult: WorkflowClipboardReadResult = {
...emptyClipboardData,
isVersionMismatch: false,
}
const isNodeArray = (value: unknown): value is Node[] => Array.isArray(value)
const isEdgeArray = (value: unknown): value is Edge[] => Array.isArray(value)
const isPlainObject = (value: unknown): value is Record<string, unknown> =>
value !== null && typeof value === 'object' && !Array.isArray(value)
export const sanitizeClipboardValueByDefault = (
defaultValue: unknown,
incomingValue: unknown,
): unknown => {
if (defaultValue === undefined) return incomingValue
if (Array.isArray(defaultValue))
return Array.isArray(incomingValue) ? incomingValue : [...defaultValue]
if (isPlainObject(defaultValue)) {
if (!isPlainObject(incomingValue)) {
return Object.fromEntries(
Object.entries(defaultValue).map(([key, value]) => [
key,
sanitizeClipboardValueByDefault(value, undefined),
]),
)
}
const merged: Record<string, unknown> = {}
const keys = new Set([...Object.keys(defaultValue), ...Object.keys(incomingValue)])
keys.forEach((key) => {
const hasDefault = Object.hasOwn(defaultValue, key)
const hasIncoming = Object.hasOwn(incomingValue, key)
if (hasDefault && hasIncoming) {
merged[key] = sanitizeClipboardValueByDefault(defaultValue[key], incomingValue[key])
return
}
if (hasIncoming) {
merged[key] = incomingValue[key]
return
}
merged[key] = sanitizeClipboardValueByDefault(defaultValue[key], undefined)
})
return merged
}
if (typeof defaultValue === 'number')
return typeof incomingValue === 'number' && Number.isFinite(incomingValue)
? incomingValue
: defaultValue
return typeof incomingValue === typeof defaultValue ? incomingValue : defaultValue
}
export const isClipboardValueCompatibleWithDefault = (
defaultValue: unknown,
incomingValue: unknown,
): boolean => {
if (incomingValue === undefined) return true
if (defaultValue === undefined) return true
if (Array.isArray(defaultValue)) return Array.isArray(incomingValue)
if (isPlainObject(defaultValue)) {
if (!isPlainObject(incomingValue)) return false
return Object.entries(defaultValue).every(([key, value]) => {
return isClipboardValueCompatibleWithDefault(value, incomingValue[key])
})
}
if (typeof defaultValue === 'number')
return typeof incomingValue === 'number' && Number.isFinite(incomingValue)
return typeof incomingValue === typeof defaultValue
}
export const isClipboardNodeStructurallyValid = (value: unknown): value is Node => {
if (!isPlainObject(value)) return false
if (typeof value.id !== 'string' || typeof value.type !== 'string') return false
if (!isPlainObject(value.data) || !isPlainObject(value.position)) return false
return Number.isFinite(value.position.x) && Number.isFinite(value.position.y)
}
export const isClipboardEdgeStructurallyValid = (value: unknown): value is Edge => {
if (!isPlainObject(value)) return false
return (
typeof value.id === 'string' &&
typeof value.source === 'string' &&
typeof value.target === 'string'
)
}
export const parseWorkflowClipboardText = (
text: string,
currentClipboardVersion: string,
): WorkflowClipboardReadResult => {
if (!text) return emptyClipboardReadResult
try {
const parsed = JSON.parse(text) as Partial<WorkflowClipboardPayload>
if (
parsed.kind !== WORKFLOW_CLIPBOARD_KIND ||
typeof parsed.version !== 'string' ||
!isNodeArray(parsed.nodes) ||
!isEdgeArray(parsed.edges)
) {
return emptyClipboardReadResult
}
const sourceVersion = parsed.version
const validatedNodes = parsed.nodes.filter(isClipboardNodeStructurallyValid)
const validatedEdges = parsed.edges.filter(isClipboardEdgeStructurallyValid)
return {
nodes: validatedNodes,
edges: validatedEdges,
sourceVersion,
isVersionMismatch: sourceVersion !== currentClipboardVersion,
}
} catch {
return emptyClipboardReadResult
}
}
const stringifyWorkflowClipboardData = (
payload: WorkflowClipboardData,
currentClipboardVersion: string,
): string => {
const data: WorkflowClipboardPayload = {
kind: WORKFLOW_CLIPBOARD_KIND,
version: currentClipboardVersion,
nodes: payload.nodes,
edges: payload.edges,
}
return JSON.stringify(data)
}
export const writeWorkflowClipboard = async (
payload: WorkflowClipboardData,
currentClipboardVersion: string,
): Promise<void> => {
const text = stringifyWorkflowClipboardData(payload, currentClipboardVersion)
await navigator.clipboard.writeText(text)
}
export const readWorkflowClipboard = async (
currentClipboardVersion: string,
): Promise<WorkflowClipboardReadResult> => {
try {
const text = await navigator.clipboard.readText()
return parseWorkflowClipboardText(text, currentClipboardVersion)
} catch {
return emptyClipboardReadResult
}
}
@@ -0,0 +1,20 @@
/**
* Format workflow run identifier using finished_at timestamp
* @param finishedAt - Unix timestamp in seconds
* @param fallbackText - Text to show when finishedAt is not available (default: 'Running')
* @returns Formatted string like " (14:30:25)" or " (Running)"
*/
export function formatWorkflowRunIdentifier(finishedAt?: number, fallbackText = 'Running'): string {
if (!finishedAt) {
const capitalized = fallbackText.charAt(0).toUpperCase() + fallbackText.slice(1)
return ` (${capitalized})`
}
const date = new Date(finishedAt * 1000)
const timeStr = date.toLocaleTimeString([], {
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
})
return ` (${timeStr})`
}
@@ -0,0 +1,79 @@
import type {
DatasourceParameter,
I18nObject,
RagPipelineDatasourceProviderResponse,
} from '@dify/contracts/api/console/rag/types.gen'
import type { FormInputSchema } from '../nodes/_base/components/form-input-item.helpers'
import type { DataSourceNodeType } from '../nodes/data-source/types'
import type { TypeWithI18N } from '@/app/components/header/account-setting/model-provider-page/declarations'
import { FormTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
import { DataSourceClassification } from '../nodes/data-source/types'
import { matchDataSource } from './plugin-install-check'
const toFormLabel = (label: I18nObject): TypeWithI18N => ({
en_US: label.en_US,
zh_Hans: label.zh_Hans ?? label.en_US,
ja_JP: label.ja_JP ?? label.en_US,
pt_BR: label.pt_BR ?? label.en_US,
})
export const datasourceParametersToFormSchemas = (
parameters: DatasourceParameter[] = [],
): FormInputSchema[] =>
parameters.map((parameter) => {
const types = {
string: FormTypeEnum.textInput,
number: FormTypeEnum.textNumber,
boolean: FormTypeEnum.checkbox,
select: FormTypeEnum.select,
'secret-input': FormTypeEnum.secretInput,
file: FormTypeEnum.file,
files: FormTypeEnum.files,
'system-files': FormTypeEnum.files,
}
return {
name: parameter.name,
variable: parameter.name,
label: toFormLabel(parameter.label),
type: types[parameter.type],
_type: parameter.type === 'boolean' ? FormTypeEnum.boolean : types[parameter.type],
required: parameter.required ?? false,
default: parameter.default,
tooltip: toFormLabel(parameter.description),
placeholder: parameter.placeholder ? toFormLabel(parameter.placeholder) : undefined,
min: parameter.min ?? undefined,
max: parameter.max ?? undefined,
scope: parameter.scope ?? undefined,
show_on: [],
options: parameter.options?.map((option) => ({
label: toFormLabel(option.label),
value: option.value,
icon: option.icon ?? undefined,
show_on: [],
})),
}
})
export const getDataSourceCheckParams = (
data: DataSourceNodeType,
dataSourceList: RagPipelineDatasourceProviderResponse[],
language: string,
) => {
const currentDataSource = matchDataSource(dataSourceList, data)
const datasource = currentDataSource?.declaration.datasources?.find(
(item) => item.identity.name === data.datasource_name,
)
const formSchemas = datasourceParametersToFormSchemas(datasource?.parameters)
return {
dataSourceInputsSchema: formSchemas.map((item) => ({
label: item.label[language] || item.label.en_US,
variable: item.variable,
required: item.required,
})),
notAuthed:
data.provider_type !== DataSourceClassification.localFile &&
!!currentDataSource &&
!currentDataSource.is_authorized,
language,
}
}
@@ -0,0 +1,20 @@
import { NodeRunningStatus } from '../types'
export const getEdgeColor = (nodeRunningStatus?: NodeRunningStatus, isFailBranch?: boolean) => {
if (nodeRunningStatus === NodeRunningStatus.Succeeded)
return 'var(--color-workflow-link-line-success-handle)'
if (nodeRunningStatus === NodeRunningStatus.Failed)
return 'var(--color-workflow-link-line-error-handle)'
if (nodeRunningStatus === NodeRunningStatus.Exception)
return 'var(--color-workflow-link-line-failure-handle)'
if (nodeRunningStatus === NodeRunningStatus.Running) {
if (isFailBranch) return 'var(--color-workflow-link-line-failure-handle)'
return 'var(--color-workflow-link-line-handle)'
}
return 'var(--color-workflow-link-line-normal)'
}
@@ -0,0 +1,568 @@
import type { ElkNode, LayoutOptions } from 'elkjs/lib/elk-api'
import type { HumanInputSharedNodeType } from '@/app/components/workflow/nodes/human-input/shared/types'
import type { CaseItem, IfElseNodeType } from '@/app/components/workflow/nodes/if-else/types'
import type { QuestionClassifierNodeType } from '@/app/components/workflow/nodes/question-classifier/types'
import type { Edge, Node } from '@/app/components/workflow/types'
import { cloneDeep } from 'es-toolkit/object'
import {
CUSTOM_NODE,
NODE_LAYOUT_HORIZONTAL_PADDING,
NODE_LAYOUT_VERTICAL_PADDING,
} from '@/app/components/workflow/constants'
import { hasAgentV2OutputRoutes } from '@/app/components/workflow/nodes/agent-v2/types'
import { HUMAN_INPUT_TIMEOUT_HANDLE } from '@/app/components/workflow/nodes/human-input/shared/constants'
import { CUSTOM_ITERATION_START_NODE } from '@/app/components/workflow/nodes/iteration-start/constants'
import { CUSTOM_LOOP_START_NODE } from '@/app/components/workflow/nodes/loop-start/constants'
import { BlockEnum } from '@/app/components/workflow/types'
let elk: import('elkjs/lib/elk-api').ELK | undefined
async function getELK() {
if (!elk) {
const { default: ELK } = await import('elkjs/lib/elk.bundled.js')
elk = new ELK()
}
return elk
}
const DEFAULT_NODE_WIDTH = 244
const DEFAULT_NODE_HEIGHT = 100
const ROOT_LAYOUT_OPTIONS = {
'elk.algorithm': 'layered',
'elk.direction': 'RIGHT',
// === Spacing - Maximum spacing to prevent any overlap ===
'elk.layered.spacing.nodeNodeBetweenLayers': '100',
'elk.spacing.nodeNode': '80',
'elk.spacing.edgeNode': '50',
'elk.spacing.edgeEdge': '30',
'elk.spacing.edgeLabel': '10',
'elk.spacing.portPort': '20',
// === Port Configuration ===
'elk.portConstraints': 'FIXED_ORDER',
'elk.layered.considerModelOrder.strategy': 'NODES_AND_EDGES',
'elk.layered.crossingMinimization.forceNodeModelOrder': 'true',
// === Node Placement - Balanced centering ===
'elk.layered.nodePlacement.strategy': 'BRANDES_KOEPF',
'elk.layered.nodePlacement.favorStraightEdges': 'true',
'elk.layered.nodePlacement.bk.fixedAlignment': 'BALANCED',
// === Edge Routing - Maximum quality ===
'elk.edgeRouting': 'SPLINES',
'elk.layered.edgeRouting.selfLoopPlacement': 'NORTH',
'elk.layered.edgeRouting.sloppySplineRouting': 'false',
'elk.layered.edgeRouting.splines.mode': 'CONSERVATIVE',
'elk.layered.edgeRouting.splines.sloppy.layerSpacingFactor': '1.2',
// === Crossing Minimization - Most aggressive ===
'elk.layered.crossingMinimization.strategy': 'LAYER_SWEEP',
'elk.layered.crossingMinimization.greedySwitch.type': 'TWO_SIDED',
'elk.layered.crossingMinimization.greedySwitchHierarchical.type': 'TWO_SIDED',
'elk.layered.crossingMinimization.semiInteractive': 'false',
'elk.layered.crossingMinimization.hierarchicalSweepiness': '0.9',
// === Layering Strategy - Best quality ===
'elk.layered.layering.strategy': 'NETWORK_SIMPLEX',
'elk.layered.layering.networkSimplex.nodeFlexibility': 'NODE_SIZE',
'elk.layered.layering.layerConstraint': 'NONE',
'elk.layered.layering.minWidth.upperBoundOnWidth': '4',
// === Cycle Breaking ===
'elk.layered.cycleBreaking.strategy': 'DEPTH_FIRST',
// === Connected Components ===
'elk.separateConnectedComponents': 'true',
'elk.spacing.componentComponent': '100',
// === Node Size Constraints ===
'elk.nodeSize.constraints': 'NODE_LABELS',
'elk.nodeSize.options': 'DEFAULT_MINIMUM_SIZE MINIMUM_SIZE_ACCOUNTS_FOR_PADDING',
// === Edge Label Placement ===
'elk.edgeLabels.placement': 'CENTER',
'elk.edgeLabels.inline': 'true',
// === Compaction ===
'elk.layered.compaction.postCompaction.strategy': 'EDGE_LENGTH',
'elk.layered.compaction.postCompaction.constraints': 'EDGE_LENGTH',
// === High-Quality Mode ===
'elk.layered.thoroughness': '10',
'elk.layered.wrapping.strategy': 'OFF',
'elk.hierarchyHandling': 'INCLUDE_CHILDREN',
// === Additional Optimizations ===
'elk.layered.feedbackEdges': 'true',
'elk.layered.mergeEdges': 'false',
'elk.layered.mergeHierarchyEdges': 'false',
'elk.layered.allowNonFlowPortsToSwitchSides': 'false',
'elk.layered.northOrSouthPort': 'false',
'elk.partitioning.activate': 'false',
'elk.junctionPoints': 'true',
// === Content Alignment ===
'elk.contentAlignment': 'V_TOP H_LEFT',
'elk.alignment': 'AUTOMATIC',
}
const CHILD_LAYOUT_OPTIONS = {
'elk.algorithm': 'layered',
'elk.direction': 'RIGHT',
// === Spacing - High quality for child nodes ===
'elk.layered.spacing.nodeNodeBetweenLayers': '80',
'elk.spacing.nodeNode': '60',
'elk.spacing.edgeNode': '40',
'elk.spacing.edgeEdge': '25',
'elk.spacing.edgeLabel': '8',
'elk.spacing.portPort': '15',
// === Port Configuration ===
'elk.portConstraints': 'FIXED_ORDER',
'elk.layered.considerModelOrder.strategy': 'NODES_AND_EDGES',
'elk.layered.crossingMinimization.forceNodeModelOrder': 'true',
// === Node Placement - Balanced centering ===
'elk.layered.nodePlacement.strategy': 'BRANDES_KOEPF',
'elk.layered.nodePlacement.favorStraightEdges': 'true',
'elk.layered.nodePlacement.bk.fixedAlignment': 'BALANCED',
// === Edge Routing - Maximum quality ===
'elk.edgeRouting': 'SPLINES',
'elk.layered.edgeRouting.sloppySplineRouting': 'false',
'elk.layered.edgeRouting.splines.mode': 'CONSERVATIVE',
// === Crossing Minimization - Aggressive ===
'elk.layered.crossingMinimization.strategy': 'LAYER_SWEEP',
'elk.layered.crossingMinimization.greedySwitch.type': 'TWO_SIDED',
'elk.layered.crossingMinimization.semiInteractive': 'false',
// === Layering Strategy ===
'elk.layered.layering.strategy': 'NETWORK_SIMPLEX',
'elk.layered.layering.networkSimplex.nodeFlexibility': 'NODE_SIZE',
// === Cycle Breaking ===
'elk.layered.cycleBreaking.strategy': 'DEPTH_FIRST',
// === Node Size ===
'elk.nodeSize.constraints': 'NODE_LABELS',
// === Compaction ===
'elk.layered.compaction.postCompaction.strategy': 'EDGE_LENGTH',
// === High-Quality Mode ===
'elk.layered.thoroughness': '10',
'elk.hierarchyHandling': 'INCLUDE_CHILDREN',
// === Additional Optimizations ===
'elk.layered.feedbackEdges': 'true',
'elk.layered.mergeEdges': 'false',
'elk.junctionPoints': 'true',
}
type LayoutInfo = {
x: number
y: number
width: number
height: number
layer?: number
}
type LayoutBounds = {
minX: number
minY: number
maxX: number
maxY: number
}
export type LayoutResult = {
nodes: Map<string, LayoutInfo>
bounds: LayoutBounds
}
// ELK Port definition for native port support
type ElkPortShape = {
id: string
layoutOptions?: LayoutOptions
}
type ElkNodeShape = {
id: string
width: number
height: number
ports?: ElkPortShape[]
layoutOptions?: LayoutOptions
children?: ElkNodeShape[]
}
type ElkEdgeShape = {
id: string
sources: string[]
targets: string[]
}
let edgeCounter = 0
const nextEdgeId = () => `elk-edge-${edgeCounter++}`
const createEdge = (
source: string,
target: string,
sourcePort?: string,
targetPort?: string,
): ElkEdgeShape => ({
id: nextEdgeId(),
sources: [sourcePort ?? source],
targets: [targetPort ?? target],
})
const collectLayout = (graph: ElkNode, predicate: (id: string) => boolean): LayoutResult => {
const result = new Map<string, LayoutInfo>()
let minX = Infinity
let minY = Infinity
let maxX = -Infinity
let maxY = -Infinity
const visit = (node: ElkNode) => {
node.children?.forEach((child: ElkNode) => {
if (predicate(child.id)) {
const x = child.x ?? 0
const y = child.y ?? 0
const width = child.width ?? DEFAULT_NODE_WIDTH
const height = child.height ?? DEFAULT_NODE_HEIGHT
const layer = child?.layoutOptions?.['org.eclipse.elk.layered.layerIndex']
result.set(child.id, {
x,
y,
width,
height,
layer: layer ? Number.parseInt(layer) : undefined,
})
minX = Math.min(minX, x)
minY = Math.min(minY, y)
maxX = Math.max(maxX, x + width)
maxY = Math.max(maxY, y + height)
}
if (child.children?.length) visit(child)
})
}
visit(graph)
if (!Number.isFinite(minX) || !Number.isFinite(minY)) {
minX = 0
minY = 0
maxX = 0
maxY = 0
}
return {
nodes: result,
bounds: {
minX,
minY,
maxX,
maxY,
},
}
}
const sortIfElseOutEdges = (ifElseNode: Node, outEdges: Edge[]): Edge[] => {
return [...outEdges].sort((edgeA, edgeB) => {
const handleA = edgeA.sourceHandle
const handleB = edgeB.sourceHandle
if (handleA && handleB) {
const cases = (ifElseNode.data as IfElseNodeType).cases || []
if (handleA === 'false') return 1
if (handleB === 'false') return -1
const indexA = cases.findIndex((c: CaseItem) => c.case_id === handleA)
const indexB = cases.findIndex((c: CaseItem) => c.case_id === handleB)
if (indexA !== -1 && indexB !== -1) return indexA - indexB
}
return 0
})
}
const sortQuestionClassifierOutEdges = (classifierNode: Node, outEdges: Edge[]): Edge[] => {
return [...outEdges].sort((edgeA, edgeB) => {
const handleA = edgeA.sourceHandle
const handleB = edgeB.sourceHandle
if (handleA && handleB) {
const classes = hasAgentV2OutputRoutes(classifierNode.data)
? (classifierNode.data.agent_output_routes?.routes ?? [])
: (classifierNode.data as QuestionClassifierNodeType).classes || []
const indexA = classes.findIndex((t) => t.id === handleA)
const indexB = classes.findIndex((t) => t.id === handleB)
if (indexA !== -1 && indexB !== -1) return indexA - indexB
}
return 0
})
}
const sortHumanInputOutEdges = (humanInputNode: Node, outEdges: Edge[]): Edge[] => {
return [...outEdges].sort((edgeA, edgeB) => {
const handleA = edgeA.sourceHandle
const handleB = edgeB.sourceHandle
if (handleA && handleB) {
const userActions = (humanInputNode.data as HumanInputSharedNodeType).user_actions || []
if (handleA === HUMAN_INPUT_TIMEOUT_HANDLE) return 1
if (handleB === HUMAN_INPUT_TIMEOUT_HANDLE) return -1
const indexA = userActions.findIndex((action) => action.id === handleA)
const indexB = userActions.findIndex((action) => action.id === handleB)
if (indexA !== -1 && indexB !== -1) return indexA - indexB
}
return 0
})
}
const normaliseBounds = (layout: LayoutResult): LayoutResult => {
const { nodes, bounds } = layout
if (nodes.size === 0) return layout
const offsetX = bounds.minX
const offsetY = bounds.minY
const adjustedNodes = new Map<string, LayoutInfo>()
nodes.forEach((info, id) => {
adjustedNodes.set(id, {
...info,
x: info.x - offsetX,
y: info.y - offsetY,
})
})
return {
nodes: adjustedNodes,
bounds: {
minX: 0,
minY: 0,
maxX: bounds.maxX - offsetX,
maxY: bounds.maxY - offsetY,
},
}
}
/**
* Build ELK nodes with output ports (sorted for branching types)
* and edges ordered by a DFS traversal that follows port order.
*/
const buildPortAwareGraph = (nodes: Node[], originEdges: Edge[]) => {
const nodeIdSet = new Set(nodes.map((node) => node.id))
const edges = originEdges.filter(
(edge) => nodeIdSet.has(edge.source) && nodeIdSet.has(edge.target),
)
const outEdgesByNode = new Map<string, Edge[]>()
edges.forEach((edge) => {
if (!outEdgesByNode.has(edge.source)) outEdgesByNode.set(edge.source, [])
outEdgesByNode.get(edge.source)!.push(edge)
})
const elkNodes: ElkNodeShape[] = []
const elkEdges: ElkEdgeShape[] = []
const sourcePortMap = new Map<string, string>()
const sortedOutEdgesByNode = new Map<string, Edge[]>()
nodes.forEach((node) => {
let outEdges = outEdgesByNode.get(node.id) || []
if (node.data.type === BlockEnum.IfElse) outEdges = sortIfElseOutEdges(node, outEdges)
else if (node.data.type === BlockEnum.QuestionClassifier || hasAgentV2OutputRoutes(node.data))
outEdges = sortQuestionClassifierOutEdges(node, outEdges)
else if (node.data.type === BlockEnum.HumanInput)
outEdges = sortHumanInputOutEdges(node, outEdges)
sortedOutEdgesByNode.set(node.id, outEdges)
const ports: ElkPortShape[] = []
const portIds = new Set<string>()
outEdges.forEach((edge) => {
const portId = `${node.id}-out-${edge.sourceHandle || edge.id}`
sourcePortMap.set(edge.id, portId)
if (portIds.has(portId)) return
portIds.add(portId)
ports.push({
id: portId,
layoutOptions: {
'elk.port.side': 'EAST',
'elk.port.index': String(ports.length),
},
})
})
elkNodes.push({
id: node.id,
width: node.width ?? DEFAULT_NODE_WIDTH,
height: node.height ?? DEFAULT_NODE_HEIGHT,
...(ports.length > 0 && {
ports,
layoutOptions: { 'elk.portConstraints': 'FIXED_ORDER' },
}),
})
})
// DFS in port order to determine the definitive vertical ordering of nodes.
// forceNodeModelOrder makes ELK respect the children-array order within each layer.
const visited = new Set<string>()
const orderedIds: string[] = []
const dfs = (id: string) => {
if (visited.has(id) || !nodeIdSet.has(id)) return
visited.add(id)
orderedIds.push(id)
const outEdges = sortedOutEdgesByNode.get(id) || []
outEdges.forEach((e) => dfs(e.target))
}
nodes.forEach((n) => {
if (!edges.some((e) => e.target === n.id)) dfs(n.id)
})
nodes.forEach((n) => dfs(n.id))
const nodeOrder = new Map(orderedIds.map((id, i) => [id, i]))
elkNodes.sort((a, b) => (nodeOrder.get(a.id) ?? 0) - (nodeOrder.get(b.id) ?? 0))
orderedIds.forEach((id) => {
const outEdges = sortedOutEdgesByNode.get(id) || []
outEdges.forEach((edge) => {
elkEdges.push(createEdge(edge.source, edge.target, sourcePortMap.get(edge.id)))
})
})
return { elkNodes, elkEdges }
}
export const getLayoutByELK = async (
originNodes: Node[],
originEdges: Edge[],
): Promise<LayoutResult> => {
edgeCounter = 0
const nodes = cloneDeep(originNodes).filter((node) => !node.parentId && node.type === CUSTOM_NODE)
const edges = cloneDeep(originEdges).filter(
(edge) => !edge.data?.isInIteration && !edge.data?.isInLoop,
)
const { elkNodes, elkEdges } = buildPortAwareGraph(nodes, edges)
const graph = {
id: 'workflow-root',
layoutOptions: ROOT_LAYOUT_OPTIONS,
children: elkNodes,
edges: elkEdges,
}
const layoutedGraph = await (await getELK()).layout(graph)
const layout = collectLayout(layoutedGraph, () => true)
return normaliseBounds(layout)
}
const normaliseChildLayout = (layout: LayoutResult, nodes: Node[]): LayoutResult => {
const result = new Map<string, LayoutInfo>()
layout.nodes.forEach((info, id) => {
result.set(id, info)
})
// Ensure iteration / loop start nodes do not collapse into the children.
const startNode = nodes.find(
(node) =>
node.type === CUSTOM_ITERATION_START_NODE ||
node.type === CUSTOM_LOOP_START_NODE ||
node.data?.type === BlockEnum.LoopStart ||
node.data?.type === BlockEnum.IterationStart,
)
if (startNode) {
const startLayout = result.get(startNode.id)
if (startLayout) {
const desiredMinX = NODE_LAYOUT_HORIZONTAL_PADDING / 1.5
if (startLayout.x > desiredMinX) {
const shiftX = startLayout.x - desiredMinX
result.forEach((value, key) => {
result.set(key, {
...value,
x: value.x - shiftX,
})
})
}
const desiredMinY = startLayout.y
const deltaY = NODE_LAYOUT_VERTICAL_PADDING / 2
result.forEach((value, key) => {
result.set(key, {
...value,
y: value.y - desiredMinY + deltaY,
})
})
}
}
let minX = Infinity
let minY = Infinity
let maxX = -Infinity
let maxY = -Infinity
result.forEach((value) => {
minX = Math.min(minX, value.x)
minY = Math.min(minY, value.y)
maxX = Math.max(maxX, value.x + value.width)
maxY = Math.max(maxY, value.y + value.height)
})
if (!Number.isFinite(minX) || !Number.isFinite(minY)) return layout
return normaliseBounds({
nodes: result,
bounds: {
minX,
minY,
maxX,
maxY,
},
})
}
export const getLayoutForChildNodes = async (
parentNodeId: string,
originNodes: Node[],
originEdges: Edge[],
): Promise<LayoutResult | null> => {
edgeCounter = 0
const nodes = cloneDeep(originNodes).filter((node) => node.parentId === parentNodeId)
if (!nodes.length) return null
const edges = cloneDeep(originEdges).filter(
(edge) =>
(edge.data?.isInIteration && edge.data?.iteration_id === parentNodeId) ||
(edge.data?.isInLoop && edge.data?.loop_id === parentNodeId),
)
const { elkNodes, elkEdges } = buildPortAwareGraph(nodes, edges)
const graph = {
id: parentNodeId,
layoutOptions: CHILD_LAYOUT_OPTIONS,
children: elkNodes,
edges: elkEdges,
}
const layoutedGraph = await (await getELK()).layout(graph)
const layout = collectLayout(layoutedGraph, () => true)
return normaliseChildLayout(layout, nodes)
}
@@ -0,0 +1,46 @@
import type { BlockEnum } from '@/app/components/workflow/types'
import type { UseDifyNodesPath } from '@/types/doc-paths'
import { BlockClassification } from '@/app/components/workflow/block-selector/types'
type NodeHelpLinkUri = UseDifyNodesPath | `${UseDifyNodesPath}#${string}`
type GenNodeMetaDataParams = {
classification?: BlockClassification
sort: number
type: BlockEnum
title?: string
author?: string
helpLinkUri?: NodeHelpLinkUri
isRequired?: boolean
isUndeletable?: boolean
isStart?: boolean
isSingleton?: boolean
isTypeFixed?: boolean
}
export const genNodeMetaData = ({
classification = BlockClassification.Default,
sort,
type,
title = '',
author = 'Dify',
helpLinkUri,
isRequired = false,
isUndeletable = false,
isStart = false,
isSingleton = false,
isTypeFixed = false,
}: GenNodeMetaDataParams) => {
return {
classification,
sort,
type,
title,
author,
helpLinkUri: helpLinkUri || type,
isRequired,
isUndeletable,
isStart,
isSingleton,
isTypeFixed,
}
}
@@ -0,0 +1,10 @@
export * from './clipboard'
export * from './common'
export * from './data-source'
export * from './edge'
export * from './gen-node-meta-data'
export * from './node'
export * from './tool'
export * from './variable'
export * from './workflow'
export * from './workflow-init'
@@ -0,0 +1,18 @@
import type { KeyboardEvent } from 'react'
export function getKeyboardMovement(
event: Pick<KeyboardEvent, 'key' | 'shiftKey' | 'altKey' | 'ctrlKey' | 'metaKey'>,
) {
if (event.altKey || event.ctrlKey || event.metaKey) return
const step = event.shiftKey ? 20 : 5
switch (event.key) {
case 'ArrowLeft':
return { x: -step, y: 0 }
case 'ArrowRight':
return { x: step, y: 0 }
case 'ArrowUp':
return { x: 0, y: -step }
case 'ArrowDown':
return { x: 0, y: step }
}
}
@@ -0,0 +1,113 @@
import type { Node, ReactFlowInstance } from 'reactflow'
/**
* Node navigation utilities for workflow
* This module provides functions for node selection, focusing and scrolling in workflow
*/
/**
* Interface for node selection event detail
*/
type NodeSelectionDetail = {
nodeId: string
focus?: boolean
}
/**
* Select a node in the workflow
* @param nodeId - The ID of the node to select
* @param focus - Whether to focus/scroll to the node
*/
export function selectWorkflowNode(nodeId: string, focus = false): void {
// Create and dispatch a custom event for node selection
const event = new CustomEvent('workflow:select-node', {
detail: {
nodeId,
focus,
},
})
document.dispatchEvent(event)
}
/**
* Scroll to a specific node in the workflow
* @param nodeId - The ID of the node to scroll to
*/
export function scrollToWorkflowNode(nodeId: string): void {
// Create and dispatch a custom event for scrolling to node
const event = new CustomEvent('workflow:scroll-to-node', {
detail: { nodeId },
})
document.dispatchEvent(event)
}
/**
* Setup node selection event listener
* @param handleNodeSelect - Function to handle node selection
* @returns Cleanup function
*/
export function setupNodeSelectionListener(handleNodeSelect: (nodeId: string) => void): () => void {
// Event handler for node selection
const handleNodeSelection = (event: CustomEvent<NodeSelectionDetail>) => {
const { nodeId, focus } = event.detail
if (nodeId) {
// Select the node
handleNodeSelect(nodeId)
// If focus is requested, scroll to the node
if (focus) {
// Use a small timeout to ensure node selection happens first
setTimeout(() => {
scrollToWorkflowNode(nodeId)
}, 100)
}
}
}
// Add event listener
document.addEventListener('workflow:select-node', handleNodeSelection as EventListener)
// Return cleanup function
return () => {
document.removeEventListener('workflow:select-node', handleNodeSelection as EventListener)
}
}
/**
* Setup scroll to node event listener with ReactFlow
* @param nodes - The workflow nodes
* @param reactflow - The ReactFlow instance
* @returns Cleanup function
*/
export function setupScrollToNodeListener(
nodes: Pick<Node, 'id' | 'position'>[],
reactflow: Pick<ReactFlowInstance, 'setCenter'>,
): () => void {
// Event handler for scrolling to node
const handleScrollToNode = (event: CustomEvent<NodeSelectionDetail>) => {
const { nodeId } = event.detail
if (nodeId) {
// Find the target node
const node = nodes.find((n) => n.id === nodeId)
if (node) {
// Use ReactFlow's fitView API to scroll to the node
const nodePosition = { x: node.position.x, y: node.position.y }
// Calculate position to place node in top-left area
// Move the center point right and down to show node in top-left
const targetX = nodePosition.x + window.innerWidth * 0.25
const targetY = nodePosition.y + window.innerHeight * 0.25
reactflow.setCenter(targetX, targetY, { zoom: 1, duration: 800 })
}
}
}
// Add event listener
document.addEventListener('workflow:scroll-to-node', handleScrollToNode as EventListener)
// Return cleanup function
return () => {
document.removeEventListener('workflow:scroll-to-node', handleScrollToNode as EventListener)
}
}
@@ -0,0 +1,189 @@
import type { IterationNodeType } from '../nodes/iteration/types'
import type { LoopNodeType } from '../nodes/loop/types'
import type { CommonNodeType, Node } from '../types'
import { Position } from 'reactflow'
import { CUSTOM_SIMPLE_NODE } from '@/app/components/workflow/simple-node/constants'
import { CUSTOM_NODE, NESTED_ELEMENT_Z_INDEX } from '../constants'
import { isAgentV2NodeData } from '../nodes/agent-v2/types'
import { isHumanInputV2NodeData } from '../nodes/human-input-v2/types'
import { CUSTOM_ITERATION_START_NODE } from '../nodes/iteration-start/constants'
import { CUSTOM_LOOP_START_NODE } from '../nodes/loop-start/constants'
import { BlockEnum } from '../types'
export function getNodeCatalogType(data: CommonNodeType): BlockEnum {
if (isAgentV2NodeData(data)) return BlockEnum.AgentV2
if (isHumanInputV2NodeData(data)) return BlockEnum.HumanInputV2
return data.type
}
export function getNodePersistedType(catalogType: BlockEnum): BlockEnum {
if (catalogType === BlockEnum.AgentV2) return BlockEnum.Agent
if (catalogType === BlockEnum.HumanInputV2) return BlockEnum.HumanInput
return catalogType
}
export function generateNewNode({
data,
position,
id,
zIndex,
type,
...rest
}: Omit<Node, 'id'> & { id?: string }): {
newNode: Node
newIterationStartNode?: Node
newLoopStartNode?: Node
} {
const newNode = {
id: id || `${Date.now()}`,
type: type || CUSTOM_NODE,
data,
position,
targetPosition: Position.Left,
sourcePosition: Position.Right,
zIndex: data.type === BlockEnum.Iteration || data.type === BlockEnum.Loop ? 0 : zIndex,
...rest,
} as Node
if (data.type === BlockEnum.Iteration) {
const newIterationStartNode = getIterationStartNode(newNode.id)
;(newNode.data as IterationNodeType).start_node_id = newIterationStartNode.id
;(newNode.data as IterationNodeType)._children = [
{ nodeId: newIterationStartNode.id, nodeType: BlockEnum.IterationStart },
]
return {
newNode,
newIterationStartNode,
}
}
if (data.type === BlockEnum.Loop) {
const newLoopStartNode = getLoopStartNode(newNode.id)
;(newNode.data as LoopNodeType).start_node_id = newLoopStartNode.id
;(newNode.data as LoopNodeType)._children = [
{ nodeId: newLoopStartNode.id, nodeType: BlockEnum.LoopStart },
]
return {
newNode,
newLoopStartNode,
}
}
return {
newNode,
}
}
export function getIterationStartNode(iterationId: string): Node {
return generateNewNode({
id: `${iterationId}start`,
type: CUSTOM_ITERATION_START_NODE,
data: {
title: '',
desc: '',
type: BlockEnum.IterationStart,
isInIteration: true,
},
position: {
x: 24,
y: 68,
},
zIndex: NESTED_ELEMENT_Z_INDEX,
parentId: iterationId,
selectable: false,
draggable: false,
}).newNode
}
export function getLoopStartNode(loopId: string): Node {
return generateNewNode({
id: `${loopId}start`,
type: CUSTOM_LOOP_START_NODE,
data: {
title: '',
desc: '',
type: BlockEnum.LoopStart,
isInLoop: true,
},
position: {
x: 24,
y: 68,
},
zIndex: NESTED_ELEMENT_Z_INDEX,
parentId: loopId,
selectable: false,
draggable: false,
}).newNode
}
export const genNewNodeTitleFromOld = (oldTitle: string) => {
const regex = /^(.+?)\s*\((\d+)\)\s*$/
const match = regex.exec(oldTitle)
if (match) {
const title = match[1]
const num = Number.parseInt(match[2]!, 10)
return `${title} (${num + 1})`
} else {
return `${oldTitle} (1)`
}
}
export const getTopLeftNodePosition = (nodes: Node[]) => {
let minX = Infinity
let minY = Infinity
nodes.forEach((node) => {
if (node.position.x < minX) minX = node.position.x
if (node.position.y < minY) minY = node.position.y
})
return {
x: minX,
y: minY,
}
}
export const getNestedNodePosition = (node: Node, parentNode: Node) => {
return {
x: node.position.x - parentNode.position.x,
y: node.position.y - parentNode.position.y,
}
}
export const getNodesWithSameDefaultDataType = (
nodes: Node[],
nodeType: BlockEnum,
defaultValue: Partial<Node['data']>,
) => {
const dataType = (defaultValue.type as BlockEnum | undefined) ?? nodeType
const discriminatorEntries = (['agent_node_kind', 'version'] as const)
.map((key) => [key, (defaultValue as Record<string, unknown>)[key]] as const)
.filter(([, value]) => value !== undefined)
if (dataType !== nodeType && discriminatorEntries.length > 0) {
return nodes.filter(
(node) =>
node.data.type === dataType &&
discriminatorEntries.every(
([key, value]) => (node.data as Record<string, unknown>)[key] === value,
),
)
}
return nodes.filter((node) => node.data.type === dataType)
}
export const hasRetryNode = (nodeType?: BlockEnum) => {
return (
nodeType === BlockEnum.LLM ||
nodeType === BlockEnum.Tool ||
nodeType === BlockEnum.HttpRequest ||
nodeType === BlockEnum.Code
)
}
export const getNodeCustomTypeByNodeDataType = (nodeType: BlockEnum) => {
if (nodeType === BlockEnum.LoopEnd) return CUSTOM_SIMPLE_NODE
}
@@ -0,0 +1,17 @@
import { BlockEnum } from '../types'
export const normalizeWorkflowNodes = <T extends { data: Record<string, unknown> }>(
nodes: T[],
appMode?: string,
): T[] => {
if (appMode !== 'workflow') return nodes
return nodes.map((node) => {
if (node.data.type !== BlockEnum.LLM || !('memory' in node.data)) return node
// A memory object implicitly requires sys.query, which plain Workflows do not provide.
const data = { ...node.data }
delete data.memory
return { ...node, data }
})
}
@@ -0,0 +1,97 @@
import type { RagPipelineDatasourceProviderResponse } from '@dify/contracts/api/console/rag/types.gen'
import type { TriggerWithProvider } from '../block-selector/types'
import type { DataSourceNodeType } from '../nodes/data-source/types'
import type { ToolNodeType } from '../nodes/tool/types'
import type { PluginTriggerNodeType } from '../nodes/trigger-plugin/types'
import type { CommonNodeType, ToolWithProvider } from '../types'
import { CollectionType } from '@/app/components/tools/types'
import { matchesProviderReference } from '@/utils/provider-reference'
import { BlockEnum } from '../types'
export function matchToolInCollection(
collection: ToolWithProvider[],
data: { plugin_id?: string; provider_id?: string; provider_name?: string },
): ToolWithProvider | undefined {
return collection.find(
(tool) =>
(data.plugin_id && tool.plugin_id === data.plugin_id) ||
matchesProviderReference(tool, data.provider_id) ||
tool.name === data.provider_name,
)
}
export function matchTriggerProvider(
providers: TriggerWithProvider[],
data: { provider_name?: string; provider_id?: string; plugin_id?: string },
): TriggerWithProvider | undefined {
return providers.find(
(provider) =>
provider.name === data.provider_name ||
provider.id === data.provider_id ||
(data.plugin_id && provider.plugin_id === data.plugin_id),
)
}
export function matchDataSource(
list: RagPipelineDatasourceProviderResponse[],
data: { plugin_unique_identifier?: string; plugin_id?: string; provider_name?: string },
): RagPipelineDatasourceProviderResponse | undefined {
if (data.plugin_unique_identifier) {
const installedVersion = list.find(
(item) => item.plugin_unique_identifier === data.plugin_unique_identifier,
)
if (installedVersion) return installedVersion
}
if (data.plugin_id) return list.find((item) => item.plugin_id === data.plugin_id)
if (data.plugin_unique_identifier) return undefined
return list.find((item) => item.provider === data.provider_name)
}
type PluginInstallCheckContext = {
builtInTools?: ToolWithProvider[]
customTools?: ToolWithProvider[]
workflowTools?: ToolWithProvider[]
mcpTools?: ToolWithProvider[]
triggerPlugins?: TriggerWithProvider[]
dataSourceList?: RagPipelineDatasourceProviderResponse[]
}
export function isNodePluginMissing(
data: CommonNodeType,
context: PluginInstallCheckContext,
): boolean {
switch (data.type as BlockEnum) {
case BlockEnum.Tool: {
const toolData = data as ToolNodeType
const collectionMap: Partial<Record<CollectionType, ToolWithProvider[] | undefined>> = {
[CollectionType.builtIn]: context.builtInTools,
[CollectionType.custom]: context.customTools,
[CollectionType.workflow]: context.workflowTools,
[CollectionType.mcp]: context.mcpTools,
}
const collection = collectionMap[toolData.provider_type]
if (!collection) return false
return (
!matchToolInCollection(collection, toolData) && Boolean(toolData.plugin_unique_identifier)
)
}
case BlockEnum.TriggerPlugin: {
const triggerData = data as PluginTriggerNodeType
if (!context.triggerPlugins) return false
return (
!matchTriggerProvider(context.triggerPlugins, triggerData) &&
Boolean(triggerData.plugin_unique_identifier)
)
}
case BlockEnum.DataSource: {
const dataSourceData = data as DataSourceNodeType
if (!context.dataSourceList) return false
return (
!matchDataSource(context.dataSourceList, dataSourceData) &&
Boolean(dataSourceData.plugin_unique_identifier)
)
}
default:
return false
}
}
@@ -0,0 +1,4 @@
export function extractPluginId(provider: string): string {
const parts = provider.split('/')
return parts.length >= 2 ? `${parts[0]}/${parts[1]}` : provider
}
@@ -0,0 +1,65 @@
import type { ToolNodeType } from '../nodes/tool/types'
import type { InputVar, ToolWithProvider } from '../types'
import type { StructuredOutput } from '@/app/components/workflow/nodes/llm/types'
import { CollectionType } from '@/app/components/tools/types'
import { toolParametersToFormSchemas } from '@/app/components/tools/utils/to-form-schema'
import { Type } from '@/app/components/workflow/nodes/llm/types'
import { isToolAuthorizationRequired } from '@/app/components/workflow/nodes/tool/auth'
import { matchesProviderReference } from '@/utils/provider-reference'
export const getToolCheckParams = (
toolData: ToolNodeType,
buildInTools: ToolWithProvider[],
customTools: ToolWithProvider[],
workflowTools: ToolWithProvider[],
language: string,
) => {
const { provider_id, provider_type, tool_name } = toolData
const currentTools =
provider_type === CollectionType.builtIn
? buildInTools
: provider_type === CollectionType.custom
? customTools
: workflowTools
const currCollection = currentTools.find((item) => matchesProviderReference(item, provider_id))
const currTool = currCollection?.tools.find((tool) => tool.name === tool_name)
const formSchemas = currTool ? toolParametersToFormSchemas(currTool.parameters) : []
const toolInputVarSchema = formSchemas.filter((item) => item.form === 'llm')
const toolSettingSchema = formSchemas.filter((item) => item.form !== 'llm')
return {
toolInputsSchema: (() => {
const formInputs: InputVar[] = []
toolInputVarSchema.forEach((item: any) => {
formInputs.push({
label: item.label[language] || item.label.en_US,
variable: item.variable,
type: item.type,
required: item.required,
})
})
return formInputs
})(),
notAuthed: isToolAuthorizationRequired(provider_type, currCollection),
toolSettingSchema,
language,
}
}
export const wrapStructuredVarItem = (
outputItem: any,
matchedSchemaType: string,
): StructuredOutput => {
const dataType = Type.object
return {
schema: {
type: dataType,
properties: {
[outputItem.name]: {
...outputItem.value,
schemaType: matchedSchemaType,
},
},
additionalProperties: false,
},
}
}
@@ -0,0 +1,49 @@
import type { TriggerWithProvider } from '@/app/components/workflow/block-selector/types'
import type { PluginTriggerNodeType } from '@/app/components/workflow/nodes/trigger-plugin/types'
type TriggerCheckParams = {
triggerInputsSchema: Array<{
variable: string
label: string
required?: boolean
}>
isReadyForCheckValid: boolean
}
export const getTriggerCheckParams = (
triggerData: PluginTriggerNodeType,
triggerProviders: TriggerWithProvider[] | undefined,
language: string,
): TriggerCheckParams => {
if (!triggerProviders) {
return {
triggerInputsSchema: [],
isReadyForCheckValid: false,
}
}
const { provider_id, provider_name, event_name } = triggerData
const provider = triggerProviders.find(
(item) =>
item.name === provider_name ||
item.id === provider_id ||
(provider_id && item.plugin_id === provider_id),
)
const currentEvent = provider?.events.find((event) => event.name === event_name)
const triggerInputsSchema = (currentEvent?.parameters || []).map((parameter) => {
const label = parameter.label?.[language] || parameter.label?.en_US || parameter.name
return {
variable: parameter.name,
label,
required: parameter.required,
}
})
return {
triggerInputsSchema,
isReadyForCheckValid: true,
}
}
@@ -0,0 +1,14 @@
import type { BlockEnum, ValueSelector } from '../types'
import { hasErrorHandleNode } from '.'
export const variableTransformer = (v: ValueSelector | string) => {
if (typeof v === 'string') return v.replace(/^\{\{#|#\}\}$/g, '').split('.')
return `{{#${v.join('.')}#}}`
}
export const normalizeWorkflowOutputName = (name?: string) => name?.trim() ?? ''
export const isExceptionVariable = (variable: string, nodeType?: BlockEnum) => {
return (variable === 'error_message' || variable === 'error_type') && hasErrorHandleNode(nodeType)
}
@@ -0,0 +1,14 @@
export type WorkflowVersionNameSource = {
marked_name?: string | null
version_number?: number | null
}
export const getWorkflowVersionName = (
version: WorkflowVersionNameSource | null | undefined,
defaultName: string,
): string => {
if (version?.marked_name) return version.marked_name
if (version?.version_number) return `# ${version.version_number}`
return defaultName
}
@@ -0,0 +1,27 @@
import type { Node } from '../types'
import { BlockEnum, isTriggerNode } from '../types'
/**
* Get the workflow entry node
* Priority: trigger nodes > start node
*/
export function getWorkflowEntryNode(nodes: Node[]): Node | undefined {
const triggerNode = nodes.find((node) => isTriggerNode(node.data.type))
if (triggerNode) return triggerNode
return nodes.find((node) => node.data.type === BlockEnum.Start)
}
/**
* Check if a node type is a workflow entry node
*/
export function isWorkflowEntryNode(nodeType: BlockEnum): boolean {
return nodeType === BlockEnum.Start || isTriggerNode(nodeType)
}
/**
* Check if workflow is in trigger mode
*/
export function isTriggerWorkflow(nodes: Node[]): boolean {
return nodes.some((node) => isTriggerNode(node.data.type))
}
@@ -0,0 +1,404 @@
import type { IfElseNodeType } from '../nodes/if-else/types'
import type { IterationNodeType } from '../nodes/iteration/types'
import type { LoopNodeType } from '../nodes/loop/types'
import type { QuestionClassifierNodeType } from '../nodes/question-classifier/types'
import type { ToolNodeType } from '../nodes/tool/types'
import type { Edge, Node } from '../types'
import { cloneDeep } from 'es-toolkit/object'
import { getConnectedEdges } from 'reactflow'
import {
hasAgentV2OutputRoutes,
isAgentV2NodeData,
} from '@/app/components/workflow/nodes/agent-v2/types'
import { correctModelProvider } from '@/utils'
import { getIterationStartNode, getLoopStartNode } from '.'
import {
CUSTOM_NODE,
DEFAULT_RETRY_INTERVAL,
DEFAULT_RETRY_MAX,
NESTED_ELEMENT_Z_INDEX,
NODE_WIDTH_X_OFFSET,
START_INITIAL_POSITION,
} from '../constants'
import { branchNameCorrect } from '../nodes/if-else/utils'
import { CUSTOM_ITERATION_START_NODE } from '../nodes/iteration-start/constants'
import { CUSTOM_LOOP_START_NODE } from '../nodes/loop-start/constants'
import { BlockEnum, ErrorHandleMode } from '../types'
// An edge belongs to a cycle exactly when both endpoints belong to the same
// strongly connected component. Ancestors and links between cycles must survive.
const getCycleEdges = (nodes: Node[], edges: Edge[]) => {
const adjacency = new Map(nodes.map((node) => [node.id, [] as string[]]))
for (const edge of edges) {
if (adjacency.has(edge.target)) adjacency.get(edge.source)?.push(edge.target)
}
const indices = new Map<string, number>()
const lowLinks = new Map<string, number>()
const components = new Map<string, number>()
const stack: string[] = []
const onStack = new Set<string>()
let nextIndex = 0
let component = 0
const visit = (id: string) => {
indices.set(id, nextIndex)
lowLinks.set(id, nextIndex++)
stack.push(id)
onStack.add(id)
for (const target of adjacency.get(id)!) {
if (!indices.has(target)) {
visit(target)
lowLinks.set(id, Math.min(lowLinks.get(id)!, lowLinks.get(target)!))
} else if (onStack.has(target)) {
lowLinks.set(id, Math.min(lowLinks.get(id)!, indices.get(target)!))
}
}
if (lowLinks.get(id) === indices.get(id)) {
let member: string
do {
member = stack.pop()!
onStack.delete(member)
components.set(member, component)
} while (member !== id)
component++
}
}
for (const node of nodes) {
if (!indices.has(node.id)) visit(node.id)
}
return edges.filter(
(edge) =>
components.has(edge.source) && components.get(edge.source) === components.get(edge.target),
)
}
export const preprocessNodesAndEdges = (nodes: Node[], edges: Edge[]) => {
const hasIterationNode = nodes.some((node) => node.data.type === BlockEnum.Iteration)
const hasLoopNode = nodes.some((node) => node.data.type === BlockEnum.Loop)
if (!hasIterationNode && !hasLoopNode) {
return {
nodes,
edges,
}
}
const nodesMap = nodes.reduce(
(prev, next) => {
prev[next.id] = next
return prev
},
{} as Record<string, Node>,
)
const iterationNodesWithStartNode = []
const iterationNodesWithoutStartNode = []
const loopNodesWithStartNode = []
const loopNodesWithoutStartNode = []
for (let i = 0; i < nodes.length; i++) {
const currentNode = nodes[i] as Node<IterationNodeType | LoopNodeType>
if (currentNode.data.type === BlockEnum.Iteration) {
if (currentNode.data.start_node_id && nodesMap[currentNode.data.start_node_id]) {
if (nodesMap[currentNode.data.start_node_id]?.type !== CUSTOM_ITERATION_START_NODE)
iterationNodesWithStartNode.push(currentNode)
} else {
iterationNodesWithoutStartNode.push(currentNode)
}
}
if (currentNode.data.type === BlockEnum.Loop) {
if (currentNode.data.start_node_id && nodesMap[currentNode.data.start_node_id]) {
if (nodesMap[currentNode.data.start_node_id]?.type !== CUSTOM_LOOP_START_NODE)
loopNodesWithStartNode.push(currentNode)
} else {
loopNodesWithoutStartNode.push(currentNode)
}
}
}
const newIterationStartNodesMap = {} as Record<string, Node>
const newIterationStartNodes = [
...iterationNodesWithStartNode,
...iterationNodesWithoutStartNode,
].map((iterationNode, index) => {
const newNode = getIterationStartNode(iterationNode.id)
newNode.id = newNode.id + index
newIterationStartNodesMap[iterationNode.id] = newNode
return newNode
})
const newLoopStartNodesMap = {} as Record<string, Node>
const newLoopStartNodes = [...loopNodesWithStartNode, ...loopNodesWithoutStartNode].map(
(loopNode, index) => {
const newNode = getLoopStartNode(loopNode.id)
newNode.id = newNode.id + index
newLoopStartNodesMap[loopNode.id] = newNode
return newNode
},
)
const newEdges = [...iterationNodesWithStartNode, ...loopNodesWithStartNode].map((nodeItem) => {
const isIteration = nodeItem.data.type === BlockEnum.Iteration
const newNode = (isIteration ? newIterationStartNodesMap : newLoopStartNodesMap)[nodeItem.id]
const startNode = nodesMap[nodeItem.data.start_node_id]
const source = newNode!.id
const sourceHandle = 'source'
const target = startNode!.id
const targetHandle = 'target'
const parentNode = nodes.find((node) => node.id === startNode!.parentId) || null
const isInIteration = !!parentNode && parentNode.data.type === BlockEnum.Iteration
const isInLoop = !!parentNode && parentNode.data.type === BlockEnum.Loop
return {
id: `${source}-${sourceHandle}-${target}-${targetHandle}`,
type: 'custom',
source,
sourceHandle,
target,
targetHandle,
data: {
sourceType: newNode!.data.type,
targetType: startNode!.data.type,
isInIteration,
iteration_id: isInIteration ? startNode!.parentId : undefined,
isInLoop,
loop_id: isInLoop ? startNode!.parentId : undefined,
_connectedNodeIsSelected: true,
},
zIndex: NESTED_ELEMENT_Z_INDEX,
}
})
nodes.forEach((node) => {
if (node.data.type === BlockEnum.Iteration && newIterationStartNodesMap[node.id])
(node.data as IterationNodeType).start_node_id = newIterationStartNodesMap[node.id]!.id
if (node.data.type === BlockEnum.Loop && newLoopStartNodesMap[node.id])
(node.data as LoopNodeType).start_node_id = newLoopStartNodesMap[node.id]!.id
})
return {
nodes: [...nodes, ...newIterationStartNodes, ...newLoopStartNodes],
edges: [...edges, ...newEdges],
}
}
export const initialNodes = (originNodes: Node[], originEdges: Edge[]) => {
const { nodes, edges } = preprocessNodesAndEdges(cloneDeep(originNodes), cloneDeep(originEdges))
const firstNode = nodes[0]
const nodesById = new Map(nodes.map((node) => [node.id, node]))
if (!firstNode?.position) {
nodes.forEach((node, index) => {
node.position = {
x: START_INITIAL_POSITION.x + index * NODE_WIDTH_X_OFFSET,
y: START_INITIAL_POSITION.y,
}
})
}
const iterationOrLoopNodeMap = nodes.reduce(
(acc, node) => {
if (node.parentId) {
if (acc[node.parentId])
acc[node.parentId]!.push({ nodeId: node.id, nodeType: node.data.type })
else acc[node.parentId] = [{ nodeId: node.id, nodeType: node.data.type }]
}
return acc
},
{} as Record<string, { nodeId: string; nodeType: BlockEnum }[]>,
)
return nodes.map((node) => {
const parentNode = node.parentId ? nodesById.get(node.parentId) : undefined
const isNested =
parentNode?.data.type === BlockEnum.Iteration || parentNode?.data.type === BlockEnum.Loop
node.zIndex = isNested ? NESTED_ELEMENT_Z_INDEX : 0
if (!node.type) node.type = CUSTOM_NODE
const connectedEdges = getConnectedEdges([node], edges)
node.data._connectedSourceHandleIds = connectedEdges
.filter((edge) => edge.source === node.id)
.map((edge) => edge.sourceHandle || 'source')
node.data._connectedTargetHandleIds = connectedEdges
.filter((edge) => edge.target === node.id)
.map((edge) => edge.targetHandle || 'target')
if (node.data.type === BlockEnum.IfElse) {
const nodeData = node.data as IfElseNodeType
if (!nodeData.cases && nodeData.logical_operator && nodeData.conditions) {
;(node.data as IfElseNodeType).cases = [
{
case_id: 'true',
logical_operator: nodeData.logical_operator,
conditions: nodeData.conditions,
},
]
}
node.data._targetBranches = branchNameCorrect([
...(node.data as IfElseNodeType).cases.map((item) => ({ id: item.case_id, name: '' })),
{ id: 'false', name: '' },
])
// delete conditions and logical_operator if cases is not empty
if (nodeData.cases.length > 0 && nodeData.conditions && nodeData.logical_operator) {
delete nodeData.conditions
delete nodeData.logical_operator
}
}
if (node.data.type === BlockEnum.QuestionClassifier) {
node.data._targetBranches = (node.data as QuestionClassifierNodeType).classes.map((topic) => {
return topic
})
}
if (hasAgentV2OutputRoutes(node.data))
node.data._targetBranches = (node.data.agent_output_routes?.routes ?? []).map((route) => ({
id: route.id,
name: route.name ?? '',
}))
else if (isAgentV2NodeData(node.data)) node.data._targetBranches = []
if (node.data.type === BlockEnum.Iteration) {
const iterationNodeData = node.data as IterationNodeType
iterationNodeData._children = iterationOrLoopNodeMap[node.id] || []
iterationNodeData.is_parallel = iterationNodeData.is_parallel || false
iterationNodeData.parallel_nums = iterationNodeData.parallel_nums || 10
iterationNodeData.error_handle_mode =
iterationNodeData.error_handle_mode || ErrorHandleMode.Terminated
}
// TODO: loop error handle mode
if (node.data.type === BlockEnum.Loop) {
const loopNodeData = node.data as LoopNodeType
loopNodeData._children = iterationOrLoopNodeMap[node.id] || []
loopNodeData.error_handle_mode = loopNodeData.error_handle_mode || ErrorHandleMode.Terminated
}
// legacy provider handle
if (node.data.type === BlockEnum.LLM)
(node as any).data.model.provider = correctModelProvider((node as any).data.model.provider)
if (
node.data.type === BlockEnum.KnowledgeRetrieval &&
(node as any).data.multiple_retrieval_config?.reranking_model
)
(node as any).data.multiple_retrieval_config.reranking_model.provider = correctModelProvider(
(node as any).data.multiple_retrieval_config?.reranking_model.provider,
)
if (node.data.type === BlockEnum.QuestionClassifier)
(node as any).data.model.provider = correctModelProvider((node as any).data.model.provider)
if (node.data.type === BlockEnum.ParameterExtractor)
(node as any).data.model.provider = correctModelProvider((node as any).data.model.provider)
if (node.data.type === BlockEnum.HttpRequest && !node.data.retry_config) {
node.data.retry_config = {
retry_enabled: true,
max_retries: DEFAULT_RETRY_MAX,
retry_interval: DEFAULT_RETRY_INTERVAL,
}
}
if (
node.data.type === BlockEnum.Tool &&
!(node as Node<ToolNodeType>).data.version &&
!(node as Node<ToolNodeType>).data.tool_node_version
) {
;(node as Node<ToolNodeType>).data.tool_node_version = '2'
const toolConfigurations = (node as Node<ToolNodeType>).data.tool_configurations
if (toolConfigurations && Object.keys(toolConfigurations).length > 0) {
const newValues = { ...toolConfigurations }
Object.keys(toolConfigurations).forEach((key) => {
if (typeof toolConfigurations[key] !== 'object' || toolConfigurations[key] === null) {
newValues[key] = {
type: 'constant',
value: toolConfigurations[key],
}
}
})
;(node as Node<ToolNodeType>).data.tool_configurations = newValues
}
}
return node
})
}
export const initialEdges = (originEdges: Edge[], originNodes: Node[]) => {
const { nodes, edges } = preprocessNodesAndEdges(cloneDeep(originNodes), cloneDeep(originEdges))
let selectedNode: Node | null = null
const nodesMap = nodes.reduce(
(acc, node) => {
acc[node.id] = node
if (node.data?.selected) selectedNode = node
return acc
},
{} as Record<string, Node>,
)
const cycleEdges = getCycleEdges(nodes, edges)
return edges
.filter((edge) => {
return !cycleEdges.find(
(cycEdge) => cycEdge.source === edge.source && cycEdge.target === edge.target,
)
})
.map((edge) => {
edge.type = 'custom'
if (!edge.sourceHandle) edge.sourceHandle = 'source'
if (!edge.targetHandle) edge.targetHandle = 'target'
if (!edge.data?.sourceType && edge.source && nodesMap[edge.source]) {
edge.data = {
...edge.data,
sourceType: nodesMap[edge.source]!.data.type!,
} as any
}
if (!edge.data?.targetType && edge.target && nodesMap[edge.target]) {
edge.data = {
...edge.data,
targetType: nodesMap[edge.target]!.data.type!,
} as any
}
if (selectedNode) {
edge.data = {
...edge.data,
_connectedNodeIsSelected:
edge.source === selectedNode.id || edge.target === selectedNode.id,
} as any
}
const sourceNode = nodesMap[edge.source]
const targetNode = nodesMap[edge.target]
const sourceParentNode = sourceNode?.parentId ? nodesMap[sourceNode.parentId] : undefined
const targetParentNode = targetNode?.parentId ? nodesMap[targetNode.parentId] : undefined
const nestedParentNode = [sourceParentNode, targetParentNode].find(
(node) => node?.data.type === BlockEnum.Iteration || node?.data.type === BlockEnum.Loop,
)
const isInIteration = nestedParentNode?.data.type === BlockEnum.Iteration
const isInLoop = nestedParentNode?.data.type === BlockEnum.Loop
edge.data = {
...edge.data,
isInIteration,
iteration_id: isInIteration ? nestedParentNode.id : undefined,
isInLoop,
loop_id: isInLoop ? nestedParentNode.id : undefined,
} as Edge['data']
edge.zIndex = nestedParentNode ? NESTED_ELEMENT_Z_INDEX : 0
return edge
})
}
@@ -0,0 +1,182 @@
import type { Edge, Node } from '../types'
import { uniqBy } from 'es-toolkit/compat'
import { getOutgoers } from 'reactflow'
import { BlockEnum } from '../types'
export const canRunBySingle = (nodeType: BlockEnum, isChildNode: boolean) => {
// child node means in iteration or loop. Set value to iteration(or loop) may cause variable not exit problem in backend.
if (isChildNode && nodeType === BlockEnum.Assigner) return false
return (
nodeType === BlockEnum.LLM ||
nodeType === BlockEnum.KnowledgeRetrieval ||
nodeType === BlockEnum.KnowledgeRetrievalV2 ||
nodeType === BlockEnum.Code ||
nodeType === BlockEnum.TemplateTransform ||
nodeType === BlockEnum.QuestionClassifier ||
nodeType === BlockEnum.HttpRequest ||
nodeType === BlockEnum.Tool ||
nodeType === BlockEnum.ParameterExtractor ||
nodeType === BlockEnum.Iteration ||
nodeType === BlockEnum.Agent ||
nodeType === BlockEnum.AgentV2 ||
nodeType === BlockEnum.DocExtractor ||
nodeType === BlockEnum.Loop ||
nodeType === BlockEnum.Start ||
nodeType === BlockEnum.IfElse ||
nodeType === BlockEnum.VariableAggregator ||
nodeType === BlockEnum.Assigner ||
nodeType === BlockEnum.HumanInput ||
nodeType === BlockEnum.DataSource ||
nodeType === BlockEnum.TriggerSchedule ||
nodeType === BlockEnum.TriggerWebhook ||
nodeType === BlockEnum.TriggerPlugin
)
}
export const isSupportCustomRunForm = (nodeType: BlockEnum) => {
return nodeType === BlockEnum.DataSource
}
type ConnectedSourceOrTargetNodesChange = {
type: string
edge: Edge
}[]
export const getNodesConnectedSourceOrTargetHandleIdsMap = (
changes: ConnectedSourceOrTargetNodesChange,
nodes: Node[],
) => {
const nodesConnectedSourceOrTargetHandleIdsMap = {} as Record<string, any>
changes.forEach((change) => {
const { edge, type } = change
const sourceNode = nodes.find((node) => node.id === edge.source)!
if (sourceNode) {
nodesConnectedSourceOrTargetHandleIdsMap[sourceNode.id] =
nodesConnectedSourceOrTargetHandleIdsMap[sourceNode.id] || {
_connectedSourceHandleIds: [...(sourceNode?.data._connectedSourceHandleIds || [])],
_connectedTargetHandleIds: [...(sourceNode?.data._connectedTargetHandleIds || [])],
}
}
const targetNode = nodes.find((node) => node.id === edge.target)!
if (targetNode) {
nodesConnectedSourceOrTargetHandleIdsMap[targetNode.id] =
nodesConnectedSourceOrTargetHandleIdsMap[targetNode.id] || {
_connectedSourceHandleIds: [...(targetNode?.data._connectedSourceHandleIds || [])],
_connectedTargetHandleIds: [...(targetNode?.data._connectedTargetHandleIds || [])],
}
}
if (sourceNode) {
if (type === 'remove') {
const index = nodesConnectedSourceOrTargetHandleIdsMap[
sourceNode.id
]._connectedSourceHandleIds.findIndex(
(handleId: string) => handleId === (edge.sourceHandle || 'source'),
)
if (index >= 0)
nodesConnectedSourceOrTargetHandleIdsMap[sourceNode.id]._connectedSourceHandleIds.splice(
index,
1,
)
}
if (type === 'add')
nodesConnectedSourceOrTargetHandleIdsMap[sourceNode.id]._connectedSourceHandleIds.push(
edge.sourceHandle || 'source',
)
}
if (targetNode) {
if (type === 'remove') {
const index = nodesConnectedSourceOrTargetHandleIdsMap[
targetNode.id
]._connectedTargetHandleIds.findIndex(
(handleId: string) => handleId === (edge.targetHandle || 'target'),
)
if (index >= 0)
nodesConnectedSourceOrTargetHandleIdsMap[targetNode.id]._connectedTargetHandleIds.splice(
index,
1,
)
}
if (type === 'add')
nodesConnectedSourceOrTargetHandleIdsMap[targetNode.id]._connectedTargetHandleIds.push(
edge.targetHandle || 'target',
)
}
})
return nodesConnectedSourceOrTargetHandleIdsMap
}
export const getValidTreeNodes = (nodes: Node[], edges: Edge[]) => {
// Find all start nodes (Start and Trigger nodes)
const startNodes = nodes.filter(
(node) =>
node.data.type === BlockEnum.Start ||
node.data.type === BlockEnum.TriggerSchedule ||
node.data.type === BlockEnum.TriggerWebhook ||
node.data.type === BlockEnum.TriggerPlugin,
)
if (startNodes.length === 0) {
return {
validNodes: [],
maxDepth: 0,
}
}
const list: Node[] = []
let maxDepth = 0
const traverse = (root: Node, depth: number) => {
// Add the current node to the list
list.push(root)
if (depth > maxDepth) maxDepth = depth
const outgoers = getOutgoers(root, nodes, edges)
if (outgoers.length) {
outgoers.forEach((outgoer) => {
// Only traverse if we haven't processed this node yet (avoid cycles)
if (!list.find((n) => n.id === outgoer.id)) {
if (outgoer.data.type === BlockEnum.Iteration)
list.push(...nodes.filter((node) => node.parentId === outgoer.id))
if (outgoer.data.type === BlockEnum.Loop)
list.push(...nodes.filter((node) => node.parentId === outgoer.id))
traverse(outgoer, depth + 1)
}
})
} else {
// Leaf node - add iteration/loop children if any
if (root.data.type === BlockEnum.Iteration)
list.push(...nodes.filter((node) => node.parentId === root.id))
if (root.data.type === BlockEnum.Loop)
list.push(...nodes.filter((node) => node.parentId === root.id))
}
}
// Start traversal from all start nodes
startNodes.forEach((startNode) => {
if (!list.find((n) => n.id === startNode.id)) traverse(startNode, 1)
})
return {
validNodes: uniqBy(list, 'id'),
maxDepth,
}
}
export const hasErrorHandleNode = (nodeType?: BlockEnum) => {
return (
nodeType === BlockEnum.LLM ||
nodeType === BlockEnum.Tool ||
nodeType === BlockEnum.HttpRequest ||
nodeType === BlockEnum.Code ||
nodeType === BlockEnum.Agent ||
nodeType === BlockEnum.AgentV2
)
}