chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动
演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
60158935f4
commit
6519682885
15831 files changed
+3063428
No files matched your search
@@ -0,0 +1,94 @@
|
||||
import type { TFunction } from 'i18next'
|
||||
import { describe, expect, it } from 'vite-plus/test'
|
||||
import { VarType } from '@/app/components/workflow/types'
|
||||
import { withSelectorKey } from '@/test/i18n-mock'
|
||||
import {
|
||||
buildWorkflowToolRequestPayload,
|
||||
getReservedWorkflowOutputParameters,
|
||||
hasReservedWorkflowOutputConflict,
|
||||
isWorkflowToolNameValid,
|
||||
RESERVED_WORKFLOW_OUTPUTS,
|
||||
} from '../helpers'
|
||||
|
||||
describe('workflow-tool helpers', () => {
|
||||
it('validates workflow tool names', () => {
|
||||
expect(isWorkflowToolNameValid('')).toBe(true)
|
||||
expect(isWorkflowToolNameValid('workflow_tool_1')).toBe(true)
|
||||
expect(isWorkflowToolNameValid('workflow-tool')).toBe(false)
|
||||
expect(isWorkflowToolNameValid('workflow tool')).toBe(false)
|
||||
})
|
||||
|
||||
it('builds translated reserved workflow outputs', () => {
|
||||
const t = withSelectorKey(
|
||||
(key: string, options?: { ns?: string }) => `${options?.ns}:${key}`,
|
||||
) as TFunction<['workflow']>
|
||||
|
||||
expect(getReservedWorkflowOutputParameters(t)).toEqual([
|
||||
{
|
||||
name: 'text',
|
||||
type: VarType.string,
|
||||
reserved: true,
|
||||
description: 'workflow:nodes.tool.outputVars.text',
|
||||
},
|
||||
{
|
||||
name: 'files',
|
||||
type: VarType.arrayFile,
|
||||
reserved: true,
|
||||
description: 'workflow:nodes.tool.outputVars.files.title',
|
||||
},
|
||||
{
|
||||
name: 'json',
|
||||
type: VarType.arrayObject,
|
||||
reserved: true,
|
||||
description: 'workflow:nodes.tool.outputVars.json',
|
||||
},
|
||||
])
|
||||
})
|
||||
|
||||
it('detects reserved output conflicts', () => {
|
||||
expect(hasReservedWorkflowOutputConflict(RESERVED_WORKFLOW_OUTPUTS, 'text')).toBe(true)
|
||||
expect(hasReservedWorkflowOutputConflict(RESERVED_WORKFLOW_OUTPUTS, 'custom')).toBe(false)
|
||||
})
|
||||
|
||||
it('builds workflow tool request payload', () => {
|
||||
expect(
|
||||
buildWorkflowToolRequestPayload({
|
||||
name: 'workflow_tool',
|
||||
description: 'Workflow tool',
|
||||
emoji: {
|
||||
content: '🧠',
|
||||
background: '#ffffff',
|
||||
},
|
||||
label: 'Workflow Tool',
|
||||
labels: ['agent', 'workflow'],
|
||||
parameters: [
|
||||
{
|
||||
name: 'question',
|
||||
type: VarType.string,
|
||||
required: true,
|
||||
form: 'llm',
|
||||
description: 'Question to ask',
|
||||
},
|
||||
],
|
||||
privacyPolicy: 'https://example.com/privacy',
|
||||
}),
|
||||
).toEqual({
|
||||
name: 'workflow_tool',
|
||||
description: 'Workflow tool',
|
||||
icon: {
|
||||
content: '🧠',
|
||||
background: '#ffffff',
|
||||
},
|
||||
label: 'Workflow Tool',
|
||||
labels: ['agent', 'workflow'],
|
||||
parameters: [
|
||||
{
|
||||
name: 'question',
|
||||
description: 'Question to ask',
|
||||
form: 'llm',
|
||||
},
|
||||
],
|
||||
privacy_policy: 'https://example.com/privacy',
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,328 @@
|
||||
import type { WorkflowToolDrawerPayload } from '../index'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { render, screen, waitFor, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
|
||||
import { emojiCatalogOptions } from '@/app/components/base/icon-picker/emoji-data'
|
||||
import { WorkflowToolDrawer } from '../index'
|
||||
|
||||
const mockToastNotify = vi.fn()
|
||||
vi.mock('@/app/notifications', () => ({
|
||||
toast: {
|
||||
success: (message: string) => mockToastNotify({ type: 'success', message }),
|
||||
error: (message: string) => mockToastNotify({ type: 'error', message }),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/plugins/hooks', () => ({
|
||||
useTags: () => ({
|
||||
tags: [
|
||||
{ name: 'label1', label: 'Label 1' },
|
||||
{ name: 'label2', label: 'Label 2' },
|
||||
],
|
||||
}),
|
||||
}))
|
||||
|
||||
const createPayload = (
|
||||
overrides: Partial<WorkflowToolDrawerPayload> = {},
|
||||
): WorkflowToolDrawerPayload => ({
|
||||
icon: { content: '🔧', background: '#ffffff' },
|
||||
label: 'My Tool',
|
||||
name: 'my_tool',
|
||||
description: 'Tool description',
|
||||
parameters: [
|
||||
{ name: 'param1', description: 'Parameter 1', form: 'llm', required: true, type: 'string' },
|
||||
],
|
||||
outputParameters: [
|
||||
{ name: 'output1', description: 'Output 1' },
|
||||
{ name: 'text', description: 'Reserved output duplicate' },
|
||||
],
|
||||
labels: ['label1'],
|
||||
privacy_policy: '',
|
||||
workflow_app_id: 'workflow-app-1',
|
||||
workflow_tool_id: 'workflow-tool-1',
|
||||
...overrides,
|
||||
})
|
||||
|
||||
describe('WorkflowToolDrawer', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should create workflow tools with edited form values', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onCreate = vi.fn()
|
||||
|
||||
render(
|
||||
<WorkflowToolDrawer isAdd payload={createPayload()} onHide={vi.fn()} onCreate={onCreate} />,
|
||||
)
|
||||
|
||||
await user.clear(screen.getByPlaceholderText('tools.createTool.toolNamePlaceHolder'))
|
||||
await user.type(
|
||||
screen.getByPlaceholderText('tools.createTool.toolNamePlaceHolder'),
|
||||
'Created Tool',
|
||||
)
|
||||
await user.click(screen.getByRole('button', { name: 'Label 1' }))
|
||||
await user.click(screen.getByRole('checkbox', { name: 'Label 2' }))
|
||||
await user.keyboard('{Escape}')
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByRole('checkbox', { name: 'Label 2' })).not.toBeInTheDocument(),
|
||||
)
|
||||
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
|
||||
|
||||
expect(onCreate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
workflow_app_id: 'workflow-app-1',
|
||||
label: 'Created Tool',
|
||||
icon: { content: '🔧', background: '#ffffff' },
|
||||
labels: ['label1', 'label2'],
|
||||
}),
|
||||
)
|
||||
expect(onCreate.mock.calls[0]![0]).not.toHaveProperty('outputParameters')
|
||||
})
|
||||
|
||||
it('saves the confirmed icon without submitting the tool from the picker', async () => {
|
||||
const user = userEvent.setup()
|
||||
const client = new QueryClient()
|
||||
client.setQueryData(emojiCatalogOptions.queryKey, [])
|
||||
const onCreate = vi.fn()
|
||||
render(
|
||||
<QueryClientProvider client={client}>
|
||||
<WorkflowToolDrawer isAdd payload={createPayload()} onHide={vi.fn()} onCreate={onCreate} />
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'tools.createTool.changeIcon' }))
|
||||
await user.click(screen.getByRole('radio', { name: 'app.iconPicker.color.green' }))
|
||||
await user.click(screen.getByRole('button', { name: 'app.iconPicker.ok' }))
|
||||
expect(onCreate).not.toHaveBeenCalled()
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
screen.queryByRole('dialog', { name: 'app.iconPicker.title' }),
|
||||
).not.toBeInTheDocument(),
|
||||
)
|
||||
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
|
||||
expect(onCreate).toHaveBeenCalledExactlyOnceWith(
|
||||
expect.objectContaining({ icon: { content: '🔧', background: '#F3FEE7' } }),
|
||||
)
|
||||
client.clear()
|
||||
})
|
||||
|
||||
it('should block invalid tool-call names before saving', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onCreate = vi.fn()
|
||||
|
||||
render(
|
||||
<WorkflowToolDrawer
|
||||
isAdd
|
||||
payload={createPayload({ name: 'bad-name' })}
|
||||
onHide={vi.fn()}
|
||||
onCreate={onCreate}
|
||||
/>,
|
||||
)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
|
||||
|
||||
expect(onCreate).not.toHaveBeenCalled()
|
||||
expect(mockToastNotify).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: 'error',
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('should require confirmation before saving existing workflow tools', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onSave = vi.fn()
|
||||
|
||||
render(<WorkflowToolDrawer payload={createPayload()} onHide={vi.fn()} onSave={onSave} />)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
|
||||
expect(onSave).not.toHaveBeenCalled()
|
||||
await user.click(
|
||||
within(screen.getByRole('dialog', { name: 'tools.createTool.confirmTitle' })).getByRole(
|
||||
'button',
|
||||
{ name: 'common.operation.cancel' },
|
||||
),
|
||||
)
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
screen.queryByRole('dialog', { name: 'tools.createTool.confirmTitle' }),
|
||||
).not.toBeInTheDocument(),
|
||||
)
|
||||
expect(onSave).not.toHaveBeenCalled()
|
||||
await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
|
||||
await user.click(screen.getByRole('button', { name: 'common.operation.confirm' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(onSave).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
workflow_tool_id: 'workflow-tool-1',
|
||||
name: 'my_tool',
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
it('should not show output warnings when names are valid and unique', () => {
|
||||
render(
|
||||
<WorkflowToolDrawer
|
||||
isAdd
|
||||
payload={createPayload({
|
||||
outputParameters: [{ name: 'answer', description: 'Valid output' }],
|
||||
})}
|
||||
onHide={vi.fn()}
|
||||
onCreate={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(
|
||||
screen.queryByRole('button', {
|
||||
name: 'answer',
|
||||
}),
|
||||
).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should show one reserved-name warning on the user output only', () => {
|
||||
render(
|
||||
<WorkflowToolDrawer isAdd payload={createPayload()} onHide={vi.fn()} onCreate={vi.fn()} />,
|
||||
)
|
||||
|
||||
const userOutputRow = screen.getByRole('row', { name: /text.*Reserved output duplicate/ })
|
||||
expect(
|
||||
within(userOutputRow).getByRole('button', {
|
||||
name: 'text',
|
||||
}),
|
||||
).toBeInTheDocument()
|
||||
|
||||
const reservedOutputRow = screen.getByRole('row', {
|
||||
name: /text.*tools\.createTool\.toolOutput\.reserved.*string/,
|
||||
})
|
||||
expect(within(reservedOutputRow).queryByRole('button')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should identify the End node sources for duplicate outputs', async () => {
|
||||
const user = userEvent.setup()
|
||||
const outputParameters: WorkflowToolDrawerPayload['outputParameters'] = [
|
||||
{
|
||||
name: 'result',
|
||||
description: 'Success output',
|
||||
source: { nodeId: 'end-success', nodeTitle: 'Success End', outputIndex: 0 },
|
||||
},
|
||||
{
|
||||
name: 'result',
|
||||
description: 'Fallback output',
|
||||
source: { nodeId: 'end-fallback', nodeTitle: 'Fallback End', outputIndex: 0 },
|
||||
},
|
||||
]
|
||||
|
||||
render(
|
||||
<WorkflowToolDrawer
|
||||
isAdd
|
||||
payload={createPayload({ outputParameters })}
|
||||
onHide={vi.fn()}
|
||||
onCreate={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(
|
||||
screen.getByRole('row', { name: /result.*Success End.*Success output/ }),
|
||||
).toBeInTheDocument()
|
||||
expect(
|
||||
screen.getByRole('row', { name: /result.*Fallback End.*Fallback output/ }),
|
||||
).toBeInTheDocument()
|
||||
|
||||
const duplicateWarnings = screen.getAllByRole('button', {
|
||||
name: 'result',
|
||||
})
|
||||
expect(duplicateWarnings).toHaveLength(2)
|
||||
|
||||
await user.click(duplicateWarnings[0]!)
|
||||
|
||||
const duplicateDetails = (await screen.findAllByRole('dialog')).find((dialog) =>
|
||||
within(dialog).queryByText(/workflow\.errorMsg\.duplicateOutputVariable/),
|
||||
)!
|
||||
expect(duplicateDetails).toHaveTextContent('Success End')
|
||||
expect(duplicateDetails).toHaveTextContent('Fallback End')
|
||||
})
|
||||
|
||||
it('should combine reserved-name and duplicate-name issues into one warning per user output', async () => {
|
||||
const user = userEvent.setup()
|
||||
const outputParameters: WorkflowToolDrawerPayload['outputParameters'] = [
|
||||
{
|
||||
name: 'text',
|
||||
description: 'Success output',
|
||||
source: { nodeId: 'end-success', nodeTitle: 'Output', outputIndex: 0 },
|
||||
},
|
||||
{
|
||||
name: 'text',
|
||||
description: 'Fallback output',
|
||||
source: { nodeId: 'end-fallback', nodeTitle: 'Output', outputIndex: 0 },
|
||||
},
|
||||
]
|
||||
|
||||
render(
|
||||
<WorkflowToolDrawer
|
||||
isAdd
|
||||
payload={createPayload({ outputParameters })}
|
||||
onHide={vi.fn()}
|
||||
onCreate={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
const issueWarnings = screen.getAllByRole('button', {
|
||||
name: 'text',
|
||||
})
|
||||
expect(issueWarnings).toHaveLength(2)
|
||||
|
||||
await user.click(issueWarnings[0]!)
|
||||
|
||||
const issueDetails = (await screen.findAllByRole('dialog')).find((dialog) =>
|
||||
within(dialog).queryByText('tools.createTool.toolOutput.reservedParameterDuplicateTip'),
|
||||
)!
|
||||
expect(issueDetails).toHaveTextContent(
|
||||
'tools.createTool.toolOutput.reservedParameterDuplicateTip',
|
||||
)
|
||||
expect(issueDetails).toHaveTextContent('workflow.errorMsg.duplicateOutputVariable')
|
||||
expect(issueDetails).toHaveTextContent('Output (1/2)')
|
||||
expect(issueDetails).toHaveTextContent('Output (2/2)')
|
||||
expect(issueDetails).not.toHaveTextContent('end-succ')
|
||||
expect(issueDetails).not.toHaveTextContent('end-fall')
|
||||
|
||||
expect(screen.getByRole('row', { name: /Output \(1\/2\).*Success output/ })).toBeInTheDocument()
|
||||
expect(
|
||||
screen.getByRole('row', { name: /Output \(2\/2\).*Fallback output/ }),
|
||||
).toBeInTheDocument()
|
||||
|
||||
const reservedOutputRow = screen.getByRole('row', {
|
||||
name: /text.*tools\.createTool\.toolOutput\.reserved.*string/,
|
||||
})
|
||||
expect(within(reservedOutputRow).queryByRole('button')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should keep schema-derived outputs compact when source metadata is unavailable', () => {
|
||||
render(
|
||||
<WorkflowToolDrawer
|
||||
payload={createPayload({
|
||||
outputParameters: undefined,
|
||||
tool: {
|
||||
output_schema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
answer: {
|
||||
type: 'string',
|
||||
description: 'Published answer',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})}
|
||||
onHide={vi.fn()}
|
||||
onSave={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByRole('row', { name: /answer string Published answer/ })).toBeInTheDocument()
|
||||
expect(screen.queryByText('tools.createTool.toolOutput.sourceNode')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { describe, expect, it, vi } from 'vite-plus/test'
|
||||
import MethodSelector from '../method-selector'
|
||||
|
||||
describe('MethodSelector', () => {
|
||||
it.each([
|
||||
['llm', 'form', 'tools.createTool.toolInput.methodSettingTip'],
|
||||
['form', 'llm', 'tools.createTool.toolInput.methodParameterTip'],
|
||||
])('selects %s from the open menu', async (value, nextValue, optionTip) => {
|
||||
const user = userEvent.setup()
|
||||
const onChange = vi.fn()
|
||||
const { rerender } = render(<MethodSelector value={value} onChange={onChange} />)
|
||||
|
||||
await user.click(
|
||||
screen.getByText(
|
||||
value === 'llm'
|
||||
? 'tools.createTool.toolInput.methodParameter'
|
||||
: 'tools.createTool.toolInput.methodSetting',
|
||||
),
|
||||
)
|
||||
await user.click(await screen.findByText(optionTip))
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith(nextValue)
|
||||
await waitFor(() => expect(screen.queryByText(optionTip)).not.toBeInTheDocument())
|
||||
rerender(<MethodSelector value={nextValue} onChange={onChange} />)
|
||||
expect(
|
||||
screen.getByText(
|
||||
nextValue === 'llm'
|
||||
? 'tools.createTool.toolInput.methodParameter'
|
||||
: 'tools.createTool.toolInput.methodSetting',
|
||||
),
|
||||
).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,204 @@
|
||||
import type {
|
||||
WorkflowToolOutputSource,
|
||||
WorkflowToolProviderOutputParameter,
|
||||
WorkflowToolProviderOutputSchema,
|
||||
} from '../../types'
|
||||
import { VarType } from '@/app/components/workflow/types'
|
||||
import {
|
||||
buildWorkflowOutputParameters,
|
||||
getDuplicateWorkflowOutputGroups,
|
||||
getSourceNodeDisplayName,
|
||||
getUniqueWorkflowOutputSources,
|
||||
} from '../utils'
|
||||
|
||||
describe('workflow output sources', () => {
|
||||
const duplicateSources: WorkflowToolOutputSource[] = [
|
||||
{ nodeId: 'end-success', nodeTitle: 'Output', outputIndex: 0 },
|
||||
{ nodeId: 'end-fallback', nodeTitle: 'Output', outputIndex: 0 },
|
||||
]
|
||||
|
||||
it('deduplicates source nodes while preserving their order', () => {
|
||||
const outputs: WorkflowToolProviderOutputParameter[] = [
|
||||
{ name: 'result', description: '', source: duplicateSources[0] },
|
||||
{ name: 'result', description: '', source: duplicateSources[0] },
|
||||
{ name: 'result', description: '', source: duplicateSources[1] },
|
||||
]
|
||||
|
||||
expect(getUniqueWorkflowOutputSources(outputs)).toEqual(duplicateSources)
|
||||
})
|
||||
|
||||
it('numbers sources with the same title without exposing their node IDs', () => {
|
||||
expect(getSourceNodeDisplayName(duplicateSources[0]!, duplicateSources)).toBe('Output (1/2)')
|
||||
expect(getSourceNodeDisplayName(duplicateSources[1]!, duplicateSources)).toBe('Output (2/2)')
|
||||
})
|
||||
})
|
||||
|
||||
describe('getDuplicateWorkflowOutputGroups', () => {
|
||||
it('groups trimmed duplicate names while preserving their End node sources', () => {
|
||||
const params: WorkflowToolProviderOutputParameter[] = [
|
||||
{
|
||||
name: ' result ',
|
||||
description: 'Success output',
|
||||
source: { nodeId: 'end-success', nodeTitle: 'Success End', outputIndex: 0 },
|
||||
},
|
||||
{
|
||||
name: 'result',
|
||||
description: 'Fallback output',
|
||||
source: { nodeId: 'end-fallback', nodeTitle: 'Fallback End', outputIndex: 0 },
|
||||
},
|
||||
{
|
||||
name: 'unique',
|
||||
description: 'Unique output',
|
||||
source: { nodeId: 'end-unique', nodeTitle: 'Unique End', outputIndex: 0 },
|
||||
},
|
||||
]
|
||||
|
||||
const result = getDuplicateWorkflowOutputGroups(params)
|
||||
|
||||
expect([...result.keys()]).toEqual(['result'])
|
||||
expect(result.get('result')?.map((item) => item.source?.nodeTitle)).toEqual([
|
||||
'Success End',
|
||||
'Fallback End',
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildWorkflowOutputParameters', () => {
|
||||
it('returns provided output parameters when array input exists', () => {
|
||||
const params: WorkflowToolProviderOutputParameter[] = [
|
||||
{ name: 'text', description: 'final text', type: VarType.string },
|
||||
]
|
||||
|
||||
const result = buildWorkflowOutputParameters(params, null)
|
||||
|
||||
expect(result).toEqual(params)
|
||||
})
|
||||
|
||||
it('fills missing output description and type from schema when array input exists', () => {
|
||||
const params: WorkflowToolProviderOutputParameter[] = [
|
||||
{ name: 'answer', description: '', type: undefined },
|
||||
{ name: 'files', description: 'keep this description', type: VarType.arrayFile },
|
||||
]
|
||||
const schema: WorkflowToolProviderOutputSchema = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
answer: {
|
||||
type: VarType.string,
|
||||
description: 'Generated answer',
|
||||
},
|
||||
files: {
|
||||
type: VarType.arrayFile,
|
||||
description: 'Schema files description',
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
const result = buildWorkflowOutputParameters(params, schema)
|
||||
|
||||
expect(result).toEqual([
|
||||
{ name: 'answer', description: 'Generated answer', type: VarType.string },
|
||||
{ name: 'files', description: 'keep this description', type: VarType.arrayFile },
|
||||
])
|
||||
})
|
||||
|
||||
it('falls back to empty description when both payload and schema descriptions are missing', () => {
|
||||
const params: WorkflowToolProviderOutputParameter[] = [
|
||||
{ name: 'missing_desc', description: '', type: undefined },
|
||||
]
|
||||
const schema: WorkflowToolProviderOutputSchema = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
other_field: {
|
||||
type: VarType.string,
|
||||
description: 'Other',
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
const result = buildWorkflowOutputParameters(params, schema)
|
||||
|
||||
expect(result).toEqual([{ name: 'missing_desc', description: '', type: undefined }])
|
||||
})
|
||||
|
||||
it('derives parameters from schema when explicit array missing', () => {
|
||||
const schema: WorkflowToolProviderOutputSchema = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
answer: {
|
||||
type: VarType.string,
|
||||
description: 'AI answer',
|
||||
},
|
||||
attachments: {
|
||||
type: VarType.arrayFile,
|
||||
description: 'Supporting files',
|
||||
},
|
||||
unknown: {
|
||||
type: 'custom',
|
||||
description: 'Unsupported type',
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
const result = buildWorkflowOutputParameters(undefined, schema)
|
||||
|
||||
expect(result).toEqual([
|
||||
{ name: 'answer', description: 'AI answer', type: VarType.string },
|
||||
{ name: 'attachments', description: 'Supporting files', type: VarType.arrayFile },
|
||||
{ name: 'unknown', description: 'Unsupported type', type: undefined },
|
||||
])
|
||||
})
|
||||
|
||||
it('returns empty array when no source information is provided', () => {
|
||||
expect(buildWorkflowOutputParameters(null, null)).toEqual([])
|
||||
})
|
||||
|
||||
it('derives parameters from schema when explicit array is empty', () => {
|
||||
const schema: WorkflowToolProviderOutputSchema = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
output_text: {
|
||||
type: VarType.string,
|
||||
description: 'Output text',
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
const result = buildWorkflowOutputParameters([], schema)
|
||||
|
||||
expect(result).toEqual([
|
||||
{ name: 'output_text', description: 'Output text', type: VarType.string },
|
||||
])
|
||||
})
|
||||
|
||||
it('returns undefined type when schema output type is missing', () => {
|
||||
const schema = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
answer: {
|
||||
description: 'Answer without type',
|
||||
},
|
||||
},
|
||||
} as unknown as WorkflowToolProviderOutputSchema
|
||||
|
||||
const result = buildWorkflowOutputParameters(undefined, schema)
|
||||
|
||||
expect(result).toEqual([
|
||||
{ name: 'answer', description: 'Answer without type', type: undefined },
|
||||
])
|
||||
})
|
||||
|
||||
it('falls back to empty description when schema-derived description is missing', () => {
|
||||
const schema = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
answer: {
|
||||
type: VarType.string,
|
||||
},
|
||||
},
|
||||
} as unknown as WorkflowToolProviderOutputSchema
|
||||
|
||||
const result = buildWorkflowOutputParameters(undefined, schema)
|
||||
|
||||
expect(result).toEqual([{ name: 'answer', description: '', type: VarType.string }])
|
||||
})
|
||||
})
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { describe, expect, it, vi } from 'vite-plus/test'
|
||||
import ConfirmModal from '../index'
|
||||
|
||||
describe('ConfirmModal', () => {
|
||||
it('does not expose the dialog while hidden', () => {
|
||||
render(<ConfirmModal show={false} onClose={vi.fn()} />)
|
||||
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it.each([
|
||||
['common.operation.close', 'close button'],
|
||||
['common.operation.cancel', 'cancel button'],
|
||||
])('closes from the %s action', async (name) => {
|
||||
const user = userEvent.setup()
|
||||
const onClose = vi.fn()
|
||||
const onConfirm = vi.fn()
|
||||
render(<ConfirmModal show onClose={onClose} onConfirm={onConfirm} />)
|
||||
|
||||
await user.click(screen.getByRole('button', { name }))
|
||||
|
||||
expect(onClose).toHaveBeenCalledOnce()
|
||||
expect(onConfirm).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('confirms the destructive update', async () => {
|
||||
const onConfirm = vi.fn()
|
||||
const user = userEvent.setup()
|
||||
render(<ConfirmModal show onClose={vi.fn()} onConfirm={onConfirm} />)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'common.operation.confirm' }))
|
||||
|
||||
expect(onConfirm).toHaveBeenCalledOnce()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,57 @@
|
||||
'use client'
|
||||
|
||||
import { Button } from '@langgenius/dify-ui/button'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogHeaderCloseButton,
|
||||
DialogTitle,
|
||||
} from '@langgenius/dify-ui/dialog'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
type ConfirmModalProps = {
|
||||
show: boolean
|
||||
onConfirm?: () => void
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
const ConfirmModal = ({ show, onConfirm, onClose }: ConfirmModalProps) => {
|
||||
const { t } = useTranslation(['common', 'tools'])
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={show}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) onClose()
|
||||
}}
|
||||
disablePointerDismissal
|
||||
>
|
||||
<DialogContent backdropProps={{ forceRender: true }} className="w-150 max-w-150">
|
||||
<DialogHeader>
|
||||
<div className="mb-2 h-12 w-12 rounded-xl border-[0.5px] border-divider-regular bg-background-section p-3 shadow-xl">
|
||||
<span
|
||||
aria-hidden
|
||||
className="i-custom-vender-solid-alertsAndFeedback-alert-triangle h-6 w-6 text-[rgb(247,144,9)]"
|
||||
/>
|
||||
</div>
|
||||
<DialogTitle>{t(($) => $['createTool.confirmTitle'], { ns: 'tools' })}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{t(($) => $['createTool.confirmTip'], { ns: 'tools' })}
|
||||
</DialogDescription>
|
||||
<DialogHeaderCloseButton aria-label={t(($) => $['operation.close'], { ns: 'common' })} />
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button onClick={onClose}>{t(($) => $['operation.cancel'], { ns: 'common' })}</Button>
|
||||
<Button variant="primary" tone="destructive" onClick={onConfirm}>
|
||||
{t(($) => $['operation.confirm'], { ns: 'common' })}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
export default ConfirmModal
|
||||
@@ -0,0 +1,95 @@
|
||||
import type { TFunction } from 'i18next'
|
||||
import type {
|
||||
Emoji,
|
||||
WorkflowToolProviderOutputParameter,
|
||||
WorkflowToolProviderOutputSchema,
|
||||
WorkflowToolProviderParameter,
|
||||
WorkflowToolProviderRequest,
|
||||
} from '../types'
|
||||
import { VarType } from '@/app/components/workflow/types'
|
||||
import { buildWorkflowOutputParameters } from './utils'
|
||||
|
||||
export const RESERVED_WORKFLOW_OUTPUTS: WorkflowToolProviderOutputParameter[] = [
|
||||
{
|
||||
name: 'text',
|
||||
description: '',
|
||||
type: VarType.string,
|
||||
reserved: true,
|
||||
},
|
||||
{
|
||||
name: 'files',
|
||||
description: '',
|
||||
type: VarType.arrayFile,
|
||||
reserved: true,
|
||||
},
|
||||
{
|
||||
name: 'json',
|
||||
description: '',
|
||||
type: VarType.arrayObject,
|
||||
reserved: true,
|
||||
},
|
||||
]
|
||||
|
||||
export const isWorkflowToolNameValid = (name: string) => {
|
||||
if (name === '') return true
|
||||
|
||||
return /^\w+$/.test(name)
|
||||
}
|
||||
|
||||
export const getReservedWorkflowOutputParameters = (t: TFunction<['workflow']>) => {
|
||||
return RESERVED_WORKFLOW_OUTPUTS.map((output) => ({
|
||||
...output,
|
||||
description:
|
||||
output.name === 'text'
|
||||
? t(($) => $['nodes.tool.outputVars.text'], { ns: 'workflow' })
|
||||
: output.name === 'files'
|
||||
? t(($) => $['nodes.tool.outputVars.files.title'], { ns: 'workflow' })
|
||||
: t(($) => $['nodes.tool.outputVars.json'], { ns: 'workflow' }),
|
||||
}))
|
||||
}
|
||||
|
||||
export const hasReservedWorkflowOutputConflict = (
|
||||
reservedOutputParameters: WorkflowToolProviderOutputParameter[],
|
||||
name: string,
|
||||
) => {
|
||||
return reservedOutputParameters.some((parameter) => parameter.name === name)
|
||||
}
|
||||
|
||||
export const getWorkflowOutputParameters = (
|
||||
rawOutputParameters: WorkflowToolProviderOutputParameter[] | undefined,
|
||||
outputSchema?: WorkflowToolProviderOutputSchema,
|
||||
) => {
|
||||
return buildWorkflowOutputParameters(rawOutputParameters, outputSchema)
|
||||
}
|
||||
|
||||
export const buildWorkflowToolRequestPayload = ({
|
||||
description,
|
||||
emoji,
|
||||
label,
|
||||
labels,
|
||||
name,
|
||||
parameters,
|
||||
privacyPolicy,
|
||||
}: {
|
||||
description: string
|
||||
emoji: Emoji
|
||||
label: string
|
||||
labels: string[]
|
||||
name: string
|
||||
parameters: WorkflowToolProviderParameter[]
|
||||
privacyPolicy: string
|
||||
}): WorkflowToolProviderRequest & { label: string } => {
|
||||
return {
|
||||
name,
|
||||
description,
|
||||
icon: emoji,
|
||||
label,
|
||||
parameters: parameters.map((item) => ({
|
||||
name: item.name,
|
||||
description: item.description,
|
||||
form: item.form,
|
||||
})),
|
||||
labels,
|
||||
privacy_policy: privacyPolicy,
|
||||
}
|
||||
}
|
||||
+616
@@ -0,0 +1,616 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import type {
|
||||
WorkflowToolOutputVariable,
|
||||
WorkflowToolProviderRequest,
|
||||
WorkflowToolProviderResponse,
|
||||
} from '@/app/components/tools/types'
|
||||
import type { InputVar } from '@/app/components/workflow/types'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { act, renderHook, waitFor } from '@testing-library/react'
|
||||
import { createElement } from 'react'
|
||||
import { InputVarType } from '@/app/components/workflow/types'
|
||||
import { consoleQuery } from '@/service/console'
|
||||
import { isParametersOutdated, useConfigureButton } from '../use-configure-button'
|
||||
|
||||
const mockCreateWorkflowToolProvider = vi.fn()
|
||||
const mockSaveWorkflowToolProvider = vi.fn()
|
||||
vi.mock('@/service/tools', () => ({
|
||||
createWorkflowToolProvider: (...args: unknown[]) => mockCreateWorkflowToolProvider(...args),
|
||||
saveWorkflowToolProvider: (...args: unknown[]) => mockSaveWorkflowToolProvider(...args),
|
||||
}))
|
||||
|
||||
const getDetail = vi.fn()
|
||||
|
||||
let queryClient: QueryClient
|
||||
const wrapper = ({ children }: { children: ReactNode }) =>
|
||||
createElement(QueryClientProvider, { client: queryClient }, children)
|
||||
const workflowToolsKey = consoleQuery.workspaces.current.tools.workflow.get.queryKey()
|
||||
const detailKey = consoleQuery.workspaces.current.toolProvider.workflow.get.get.queryKey({
|
||||
input: { query: { workflow_app_id: 'app-123' } },
|
||||
})
|
||||
const isInvalidated = (queryKey: readonly unknown[]) =>
|
||||
queryClient.getQueryState(queryKey)?.isInvalidated
|
||||
|
||||
const mockToastNotify = vi.fn()
|
||||
vi.mock('@/app/notifications', () => ({
|
||||
toast: {
|
||||
success: (message: string) => mockToastNotify({ type: 'success', message }),
|
||||
error: (message: string) => mockToastNotify({ type: 'error', message }),
|
||||
warning: (message: string) => mockToastNotify({ type: 'warning', message }),
|
||||
info: (message: string) => mockToastNotify({ type: 'info', message }),
|
||||
},
|
||||
}))
|
||||
|
||||
const createMockEmoji = () => ({ content: '🔧', background: '#ffffff' })
|
||||
|
||||
const createMockInputVar = (overrides: Partial<InputVar> = {}): InputVar =>
|
||||
({
|
||||
variable: 'test_var',
|
||||
label: 'Test Variable',
|
||||
type: InputVarType.textInput,
|
||||
required: true,
|
||||
max_length: 100,
|
||||
options: [],
|
||||
...overrides,
|
||||
}) as InputVar
|
||||
|
||||
const createMockVariable = (
|
||||
overrides: Partial<WorkflowToolOutputVariable> = {},
|
||||
): WorkflowToolOutputVariable =>
|
||||
({
|
||||
variable: 'output_var',
|
||||
value_type: 'string',
|
||||
source: { nodeId: 'end-1', nodeTitle: 'Success End', outputIndex: 0 },
|
||||
...overrides,
|
||||
}) as WorkflowToolOutputVariable
|
||||
|
||||
const createMockDetail = (
|
||||
overrides: Partial<WorkflowToolProviderResponse> = {},
|
||||
): WorkflowToolProviderResponse => ({
|
||||
workflow_app_id: 'app-123',
|
||||
workflow_tool_id: 'tool-456',
|
||||
label: 'Test Tool',
|
||||
name: 'test_tool',
|
||||
icon: createMockEmoji(),
|
||||
description: 'A test workflow tool',
|
||||
synced: true,
|
||||
tool: {
|
||||
author: 'test-author',
|
||||
name: 'test_tool',
|
||||
label: { en_US: 'Test Tool', zh_Hans: '测试工具' },
|
||||
description: { en_US: 'Test description', zh_Hans: '测试描述' },
|
||||
labels: ['label1'],
|
||||
parameters: [
|
||||
{
|
||||
name: 'test_var',
|
||||
label: { en_US: 'Test Variable', zh_Hans: '测试变量' },
|
||||
human_description: { en_US: 'A test variable', zh_Hans: '测试变量' },
|
||||
type: 'string',
|
||||
form: 'llm',
|
||||
llm_description: 'Test variable description',
|
||||
required: true,
|
||||
default: '',
|
||||
},
|
||||
],
|
||||
output_schema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
output_var: { type: 'string', description: 'Output description' },
|
||||
},
|
||||
},
|
||||
},
|
||||
privacy_policy: 'https://example.com/privacy',
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const createDefaultOptions = (overrides = {}) => ({
|
||||
enabled: true,
|
||||
published: false,
|
||||
detailNeedUpdate: false,
|
||||
workflowAppId: 'app-123',
|
||||
icon: createMockEmoji(),
|
||||
name: 'Test Workflow',
|
||||
description: 'Test workflow description',
|
||||
inputs: [createMockInputVar()],
|
||||
outputs: [createMockVariable()],
|
||||
handlePublish: vi.fn().mockResolvedValue(undefined),
|
||||
onRefreshData: vi.fn(),
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const createMockRequest = (
|
||||
extra: Record<string, string> = {},
|
||||
): WorkflowToolProviderRequest & Record<string, unknown> => ({
|
||||
name: 'test_tool',
|
||||
description: 'desc',
|
||||
icon: createMockEmoji(),
|
||||
label: 'Test Tool',
|
||||
parameters: [{ name: 'test_var', description: '', form: 'llm' }],
|
||||
labels: [],
|
||||
privacy_policy: '',
|
||||
...extra,
|
||||
})
|
||||
|
||||
describe('isParametersOutdated', () => {
|
||||
it('should return false when detail is undefined', () => {
|
||||
expect(isParametersOutdated(undefined, [createMockInputVar()])).toBe(false)
|
||||
})
|
||||
|
||||
it('should return true when parameter count differs', () => {
|
||||
const detail = createMockDetail()
|
||||
const inputs = [
|
||||
createMockInputVar({ variable: 'test_var' }),
|
||||
createMockInputVar({ variable: 'extra_var' }),
|
||||
]
|
||||
expect(isParametersOutdated(detail, inputs)).toBe(true)
|
||||
})
|
||||
|
||||
it('should return true when parameter is not found in detail', () => {
|
||||
const detail = createMockDetail()
|
||||
const inputs = [createMockInputVar({ variable: 'unknown_var' })]
|
||||
expect(isParametersOutdated(detail, inputs)).toBe(true)
|
||||
})
|
||||
|
||||
it('should return true when required property differs', () => {
|
||||
const detail = createMockDetail()
|
||||
const inputs = [createMockInputVar({ variable: 'test_var', required: false })]
|
||||
expect(isParametersOutdated(detail, inputs)).toBe(true)
|
||||
})
|
||||
|
||||
it('should return true when paragraph type does not match string', () => {
|
||||
const detail = createMockDetail()
|
||||
detail.tool.parameters[0]!.type = 'number'
|
||||
const inputs = [createMockInputVar({ variable: 'test_var', type: InputVarType.paragraph })]
|
||||
expect(isParametersOutdated(detail, inputs)).toBe(true)
|
||||
})
|
||||
|
||||
it('should return true when text-input type does not match string', () => {
|
||||
const detail = createMockDetail()
|
||||
detail.tool.parameters[0]!.type = 'number'
|
||||
const inputs = [createMockInputVar({ variable: 'test_var', type: InputVarType.textInput })]
|
||||
expect(isParametersOutdated(detail, inputs)).toBe(true)
|
||||
})
|
||||
|
||||
it('should return false when paragraph type matches string', () => {
|
||||
const detail = createMockDetail()
|
||||
const inputs = [createMockInputVar({ variable: 'test_var', type: InputVarType.paragraph })]
|
||||
expect(isParametersOutdated(detail, inputs)).toBe(false)
|
||||
})
|
||||
|
||||
it('should return false when text-input type matches string', () => {
|
||||
const detail = createMockDetail()
|
||||
const inputs = [createMockInputVar({ variable: 'test_var', type: InputVarType.textInput })]
|
||||
expect(isParametersOutdated(detail, inputs)).toBe(false)
|
||||
})
|
||||
|
||||
it('should handle undefined inputs with empty detail parameters', () => {
|
||||
const detail = createMockDetail()
|
||||
detail.tool.parameters = []
|
||||
expect(isParametersOutdated(detail, undefined)).toBe(false)
|
||||
})
|
||||
|
||||
it('should return true when inputs undefined but detail has parameters', () => {
|
||||
const detail = createMockDetail()
|
||||
expect(isParametersOutdated(detail, undefined)).toBe(true)
|
||||
})
|
||||
|
||||
it('should handle empty inputs and empty detail parameters', () => {
|
||||
const detail = createMockDetail()
|
||||
detail.tool.parameters = []
|
||||
expect(isParametersOutdated(detail, [])).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('useConfigureButton', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false, staleTime: Infinity } },
|
||||
})
|
||||
queryClient.setQueryData(workflowToolsKey, [])
|
||||
queryClient.setQueryData<WorkflowToolProviderResponse>(detailKey, createMockDetail())
|
||||
getDetail.mockReturnValue(new Promise(() => {}))
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('Initialization', () => {
|
||||
it('should forward isLoading from query hook', () => {
|
||||
queryClient.removeQueries({ queryKey: detailKey })
|
||||
const { result } = renderHook(
|
||||
() => useConfigureButton(createDefaultOptions({ published: true })),
|
||||
{ wrapper },
|
||||
)
|
||||
expect(result.current.isLoading).toBe(true)
|
||||
})
|
||||
|
||||
it('fetches detail when published', async () => {
|
||||
queryClient.removeQueries({ queryKey: detailKey })
|
||||
renderHook(() => useConfigureButton(createDefaultOptions({ published: true })), {
|
||||
wrapper,
|
||||
})
|
||||
await waitFor(() =>
|
||||
expect(getDetail).toHaveBeenCalledWith({ query: { workflow_app_id: 'app-123' } }),
|
||||
)
|
||||
})
|
||||
|
||||
it('should call query hook with enabled=false when not published', () => {
|
||||
renderHook(() => useConfigureButton(createDefaultOptions({ published: false })), {
|
||||
wrapper,
|
||||
})
|
||||
expect(getDetail).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should call query hook with enabled=false when controller is disabled', () => {
|
||||
renderHook(
|
||||
() => useConfigureButton(createDefaultOptions({ enabled: false, published: true })),
|
||||
{ wrapper },
|
||||
)
|
||||
expect(getDetail).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
// Computed values
|
||||
describe('Computed - outdated', () => {
|
||||
it('should be false when not published (no detail)', () => {
|
||||
const { result } = renderHook(() => useConfigureButton(createDefaultOptions()), {
|
||||
wrapper,
|
||||
})
|
||||
expect(result.current.outdated).toBe(false)
|
||||
})
|
||||
|
||||
it('should be true when parameters differ', () => {
|
||||
const { result } = renderHook(
|
||||
() =>
|
||||
useConfigureButton(
|
||||
createDefaultOptions({
|
||||
published: true,
|
||||
inputs: [
|
||||
createMockInputVar({ variable: 'test_var' }),
|
||||
createMockInputVar({ variable: 'extra_var' }),
|
||||
],
|
||||
}),
|
||||
),
|
||||
{ wrapper },
|
||||
)
|
||||
expect(result.current.outdated).toBe(true)
|
||||
})
|
||||
|
||||
it('should be false when parameters match', () => {
|
||||
const { result } = renderHook(
|
||||
() =>
|
||||
useConfigureButton(
|
||||
createDefaultOptions({
|
||||
published: true,
|
||||
inputs: [createMockInputVar({ variable: 'test_var', required: true })],
|
||||
}),
|
||||
),
|
||||
{ wrapper },
|
||||
)
|
||||
expect(result.current.outdated).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Computed - payload', () => {
|
||||
it('should use prop values when not published', () => {
|
||||
queryClient.removeQueries({ queryKey: detailKey })
|
||||
const { result } = renderHook(() => useConfigureButton(createDefaultOptions()), {
|
||||
wrapper,
|
||||
})
|
||||
|
||||
expect(result.current.payload).toMatchObject({
|
||||
icon: createMockEmoji(),
|
||||
label: 'Test Workflow',
|
||||
name: '',
|
||||
description: 'Test workflow description',
|
||||
workflow_app_id: 'app-123',
|
||||
})
|
||||
expect(result.current.payload.parameters).toHaveLength(1)
|
||||
expect(result.current.payload.parameters[0]).toMatchObject({
|
||||
name: 'test_var',
|
||||
form: 'llm',
|
||||
description: '',
|
||||
})
|
||||
expect(result.current.payload.outputParameters[0]).toMatchObject({
|
||||
name: 'output_var',
|
||||
source: { nodeId: 'end-1', nodeTitle: 'Success End', outputIndex: 0 },
|
||||
})
|
||||
})
|
||||
|
||||
it('should use detail values when published with detail', () => {
|
||||
const { result } = renderHook(
|
||||
() => useConfigureButton(createDefaultOptions({ published: true })),
|
||||
{ wrapper },
|
||||
)
|
||||
|
||||
expect(result.current.payload).toMatchObject({
|
||||
icon: createMockEmoji(),
|
||||
label: 'Test Tool',
|
||||
name: 'test_tool',
|
||||
description: 'A test workflow tool',
|
||||
workflow_tool_id: 'tool-456',
|
||||
privacy_policy: 'https://example.com/privacy',
|
||||
labels: ['label1'],
|
||||
})
|
||||
expect(result.current.payload.parameters[0]).toMatchObject({
|
||||
name: 'test_var',
|
||||
description: 'Test variable description',
|
||||
form: 'llm',
|
||||
})
|
||||
expect(result.current.payload.outputParameters).toEqual([
|
||||
expect.objectContaining({ name: 'output_var', description: 'Output description' }),
|
||||
])
|
||||
})
|
||||
|
||||
it('should return empty parameters when published without detail', () => {
|
||||
queryClient.removeQueries({ queryKey: detailKey })
|
||||
const { result } = renderHook(
|
||||
() => useConfigureButton(createDefaultOptions({ published: true })),
|
||||
{ wrapper },
|
||||
)
|
||||
|
||||
expect(result.current.payload.parameters).toHaveLength(0)
|
||||
expect(result.current.payload.outputParameters).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('should handle undefined output_schema in detail', () => {
|
||||
const detail = createMockDetail()
|
||||
// @ts-expect-error - testing undefined case
|
||||
detail.tool.output_schema = undefined
|
||||
queryClient.setQueryData<WorkflowToolProviderResponse>(detailKey, detail)
|
||||
|
||||
const { result } = renderHook(
|
||||
() => useConfigureButton(createDefaultOptions({ published: true })),
|
||||
{ wrapper },
|
||||
)
|
||||
|
||||
expect(result.current.payload.outputParameters[0]).toMatchObject({
|
||||
name: 'output_var',
|
||||
description: '',
|
||||
})
|
||||
})
|
||||
|
||||
it('should convert paragraph type to string in existing parameters', () => {
|
||||
const { result } = renderHook(
|
||||
() =>
|
||||
useConfigureButton(
|
||||
createDefaultOptions({
|
||||
published: true,
|
||||
inputs: [createMockInputVar({ variable: 'test_var', type: InputVarType.paragraph })],
|
||||
}),
|
||||
),
|
||||
{ wrapper },
|
||||
)
|
||||
|
||||
expect(result.current.payload.parameters[0]!.type).toBe('string')
|
||||
})
|
||||
})
|
||||
|
||||
// Mutation handlers
|
||||
describe('handleCreate', () => {
|
||||
it('should publish before creating the provider', async () => {
|
||||
mockCreateWorkflowToolProvider.mockResolvedValue({})
|
||||
const handlePublish = vi.fn().mockResolvedValue(undefined)
|
||||
const { result } = renderHook(
|
||||
() => useConfigureButton(createDefaultOptions({ handlePublish })),
|
||||
{ wrapper },
|
||||
)
|
||||
|
||||
await act(async () => {
|
||||
await result.current.handleCreate(
|
||||
createMockRequest({ workflow_app_id: 'app-123' }) as WorkflowToolProviderRequest & {
|
||||
workflow_app_id: string
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
expect(handlePublish).toHaveBeenCalledOnce()
|
||||
expect(mockCreateWorkflowToolProvider).toHaveBeenCalledOnce()
|
||||
expect(handlePublish.mock.invocationCallOrder[0]).toBeLessThan(
|
||||
mockCreateWorkflowToolProvider.mock.invocationCallOrder[0]!,
|
||||
)
|
||||
})
|
||||
|
||||
it('should not create the provider when publishing fails', async () => {
|
||||
const handlePublish = vi.fn().mockRejectedValue(new Error('Publish failed'))
|
||||
const { result } = renderHook(
|
||||
() => useConfigureButton(createDefaultOptions({ handlePublish })),
|
||||
{ wrapper },
|
||||
)
|
||||
|
||||
await act(async () => {
|
||||
await result.current.handleCreate(
|
||||
createMockRequest({ workflow_app_id: 'app-123' }) as WorkflowToolProviderRequest & {
|
||||
workflow_app_id: string
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
expect(mockCreateWorkflowToolProvider).not.toHaveBeenCalled()
|
||||
expect(mockToastNotify).toHaveBeenCalledWith({ type: 'error', message: 'Publish failed' })
|
||||
})
|
||||
|
||||
it('should create provider, invalidate caches, refresh, and notify configured', async () => {
|
||||
mockCreateWorkflowToolProvider.mockResolvedValue({})
|
||||
const onRefreshData = vi.fn()
|
||||
const onConfigured = vi.fn()
|
||||
const { result } = renderHook(
|
||||
() => useConfigureButton(createDefaultOptions({ onRefreshData, onConfigured })),
|
||||
{ wrapper },
|
||||
)
|
||||
|
||||
await act(async () => {
|
||||
await result.current.handleCreate(
|
||||
createMockRequest({ workflow_app_id: 'app-123' }) as WorkflowToolProviderRequest & {
|
||||
workflow_app_id: string
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
expect(mockCreateWorkflowToolProvider).toHaveBeenCalledWith(
|
||||
createMockRequest({ workflow_app_id: 'app-123' }),
|
||||
{ silent: true },
|
||||
)
|
||||
expect(isInvalidated(workflowToolsKey)).toBe(true)
|
||||
expect(onRefreshData).toHaveBeenCalled()
|
||||
expect(isInvalidated(detailKey)).toBe(true)
|
||||
expect(mockToastNotify).toHaveBeenCalledWith({ type: 'success', message: expect.any(String) })
|
||||
expect(onConfigured).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should show error toast on failure', async () => {
|
||||
mockCreateWorkflowToolProvider.mockRejectedValue(new Error('Create failed'))
|
||||
const { result } = renderHook(() => useConfigureButton(createDefaultOptions()), {
|
||||
wrapper,
|
||||
})
|
||||
|
||||
await act(async () => {
|
||||
await result.current.handleCreate(
|
||||
createMockRequest({ workflow_app_id: 'app-123' }) as WorkflowToolProviderRequest & {
|
||||
workflow_app_id: string
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
expect(mockToastNotify).toHaveBeenCalledWith({ type: 'error', message: 'Create failed' })
|
||||
expect(isInvalidated(workflowToolsKey)).toBe(false)
|
||||
expect(isInvalidated(detailKey)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('handleUpdate', () => {
|
||||
it('should publish, save, invalidate caches, and notify configured', async () => {
|
||||
mockSaveWorkflowToolProvider.mockResolvedValue({})
|
||||
const handlePublish = vi.fn().mockResolvedValue(undefined)
|
||||
const onRefreshData = vi.fn()
|
||||
const onConfigured = vi.fn()
|
||||
const { result } = renderHook(
|
||||
() =>
|
||||
useConfigureButton(
|
||||
createDefaultOptions({
|
||||
published: true,
|
||||
handlePublish,
|
||||
onRefreshData,
|
||||
onConfigured,
|
||||
}),
|
||||
),
|
||||
{ wrapper },
|
||||
)
|
||||
|
||||
await act(async () => {
|
||||
await result.current.handleUpdate(createMockRequest({ workflow_tool_id: 'tool-456' }))
|
||||
})
|
||||
|
||||
expect(handlePublish).toHaveBeenCalled()
|
||||
expect(mockSaveWorkflowToolProvider).toHaveBeenCalledWith(
|
||||
createMockRequest({ workflow_tool_id: 'tool-456' }),
|
||||
{ silent: true },
|
||||
)
|
||||
expect(onRefreshData).toHaveBeenCalled()
|
||||
expect(isInvalidated(workflowToolsKey)).toBe(true)
|
||||
expect(isInvalidated(detailKey)).toBe(true)
|
||||
expect(mockToastNotify).toHaveBeenCalledWith({ type: 'success', message: expect.any(String) })
|
||||
expect(onConfigured).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should show error toast when publish fails', async () => {
|
||||
const handlePublish = vi.fn().mockRejectedValue(new Error('Publish failed'))
|
||||
const { result } = renderHook(
|
||||
() =>
|
||||
useConfigureButton(
|
||||
createDefaultOptions({
|
||||
published: true,
|
||||
handlePublish,
|
||||
}),
|
||||
),
|
||||
{ wrapper },
|
||||
)
|
||||
|
||||
await act(async () => {
|
||||
await result.current.handleUpdate(createMockRequest())
|
||||
})
|
||||
|
||||
expect(mockToastNotify).toHaveBeenCalledWith({ type: 'error', message: 'Publish failed' })
|
||||
})
|
||||
|
||||
it('should show error toast when save fails', async () => {
|
||||
mockSaveWorkflowToolProvider.mockRejectedValue(new Error('Save failed'))
|
||||
const { result } = renderHook(
|
||||
() => useConfigureButton(createDefaultOptions({ published: true })),
|
||||
{ wrapper },
|
||||
)
|
||||
|
||||
await act(async () => {
|
||||
await result.current.handleUpdate(createMockRequest())
|
||||
})
|
||||
|
||||
expect(mockToastNotify).toHaveBeenCalledWith({ type: 'error', message: 'Save failed' })
|
||||
expect(isInvalidated(workflowToolsKey)).toBe(false)
|
||||
expect(isInvalidated(detailKey)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
// Effects
|
||||
describe('Effects', () => {
|
||||
it('should invalidate detail when detailNeedUpdate becomes true', () => {
|
||||
const options = createDefaultOptions({ published: true, detailNeedUpdate: false })
|
||||
const { rerender } = renderHook(
|
||||
(props: ReturnType<typeof createDefaultOptions>) => useConfigureButton(props),
|
||||
{ initialProps: options, wrapper },
|
||||
)
|
||||
|
||||
expect(isInvalidated(detailKey)).toBe(false)
|
||||
rerender({ ...options, detailNeedUpdate: true })
|
||||
|
||||
expect(isInvalidated(detailKey)).toBe(true)
|
||||
})
|
||||
|
||||
it('should not invalidate detail while disabled', () => {
|
||||
renderHook(
|
||||
() =>
|
||||
useConfigureButton(
|
||||
createDefaultOptions({
|
||||
enabled: false,
|
||||
published: true,
|
||||
detailNeedUpdate: true,
|
||||
}),
|
||||
),
|
||||
{ wrapper },
|
||||
)
|
||||
|
||||
expect(isInvalidated(detailKey)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
// Edge cases
|
||||
describe('Edge Cases', () => {
|
||||
it('should handle undefined inputs and outputs', () => {
|
||||
const { result } = renderHook(
|
||||
() =>
|
||||
useConfigureButton(
|
||||
createDefaultOptions({
|
||||
inputs: undefined,
|
||||
outputs: undefined,
|
||||
}),
|
||||
),
|
||||
{ wrapper },
|
||||
)
|
||||
|
||||
expect(result.current.payload.parameters).toHaveLength(0)
|
||||
expect(result.current.payload.outputParameters).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
vi.mock('@/service/console', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/service/console')>()
|
||||
const { withConsoleResponses } = await import('@/test/console/service-responses')
|
||||
return {
|
||||
...actual,
|
||||
consoleQuery: withConsoleResponses(actual.consoleQuery, {
|
||||
'workspaces.current.toolProvider.workflow.get.get': (input) => getDetail(input),
|
||||
}),
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,233 @@
|
||||
import type {
|
||||
Emoji,
|
||||
WorkflowToolOutputVariable,
|
||||
WorkflowToolProviderOutputParameter,
|
||||
WorkflowToolProviderParameter,
|
||||
WorkflowToolProviderRequest,
|
||||
WorkflowToolProviderResponse,
|
||||
} from '@/app/components/tools/types'
|
||||
import type { InputVar } from '@/app/components/workflow/types'
|
||||
import type { PublishWorkflowParams } from '@/types/workflow'
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useEffect, useMemo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { selectWorkflowToolDetail } from '@/app/components/tools/utils/query-select'
|
||||
import { toast } from '@/app/notifications'
|
||||
import { consoleQuery } from '@/service/console'
|
||||
import { createWorkflowToolProvider, saveWorkflowToolProvider } from '@/service/tools'
|
||||
|
||||
// region Pure helpers
|
||||
|
||||
/**
|
||||
* Check if workflow tool parameters are outdated compared to current inputs.
|
||||
* Uses flat early-return style to reduce cyclomatic complexity.
|
||||
*/
|
||||
export function isParametersOutdated(
|
||||
detail: WorkflowToolProviderResponse | undefined,
|
||||
inputs: InputVar[] | undefined,
|
||||
): boolean {
|
||||
if (!detail) return false
|
||||
if (detail.tool.parameters.length !== (inputs?.length ?? 0)) return true
|
||||
|
||||
for (const item of inputs || []) {
|
||||
const param = detail.tool.parameters.find((p) => p.name === item.variable)
|
||||
if (!param) return true
|
||||
if (param.required !== item.required) return true
|
||||
const needsStringType = item.type === 'paragraph' || item.type === 'text-input'
|
||||
if (needsStringType && param.type !== 'string') return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
function buildNewParameters(inputs?: InputVar[]): WorkflowToolProviderParameter[] {
|
||||
return (inputs || []).map((item) => ({
|
||||
name: item.variable,
|
||||
description: '',
|
||||
form: 'llm',
|
||||
required: item.required,
|
||||
type: item.type,
|
||||
}))
|
||||
}
|
||||
|
||||
function buildExistingParameters(
|
||||
inputs: InputVar[] | undefined,
|
||||
detail: WorkflowToolProviderResponse,
|
||||
): WorkflowToolProviderParameter[] {
|
||||
return (inputs || []).map((item) => {
|
||||
const matched = detail.tool.parameters.find((p) => p.name === item.variable)
|
||||
return {
|
||||
name: item.variable,
|
||||
required: item.required,
|
||||
type: item.type === 'paragraph' ? 'string' : item.type,
|
||||
description: matched?.llm_description || '',
|
||||
form: matched?.form || 'llm',
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function buildNewOutputParameters(
|
||||
outputs?: WorkflowToolOutputVariable[],
|
||||
): WorkflowToolProviderOutputParameter[] {
|
||||
return (outputs || []).map((item) => ({
|
||||
name: item.variable,
|
||||
description: '',
|
||||
type: item.value_type,
|
||||
source: item.source,
|
||||
}))
|
||||
}
|
||||
|
||||
function buildExistingOutputParameters(
|
||||
outputs: WorkflowToolOutputVariable[] | undefined,
|
||||
detail: WorkflowToolProviderResponse,
|
||||
): WorkflowToolProviderOutputParameter[] {
|
||||
return (outputs || []).map((item) => {
|
||||
const found = detail.tool.output_schema?.properties?.[item.variable]
|
||||
return {
|
||||
name: item.variable,
|
||||
description: found ? found.description : '',
|
||||
type: item.value_type,
|
||||
source: item.source,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// endregion
|
||||
|
||||
type UseConfigureButtonOptions = {
|
||||
enabled: boolean
|
||||
published: boolean
|
||||
detailNeedUpdate: boolean
|
||||
workflowAppId: string
|
||||
icon: Emoji
|
||||
name: string
|
||||
description: string
|
||||
inputs?: InputVar[]
|
||||
outputs?: WorkflowToolOutputVariable[]
|
||||
handlePublish: (params?: PublishWorkflowParams) => Promise<void>
|
||||
onRefreshData?: () => void
|
||||
onConfigured?: () => void
|
||||
}
|
||||
|
||||
export function useConfigureButton(options: UseConfigureButtonOptions) {
|
||||
const {
|
||||
enabled,
|
||||
published,
|
||||
detailNeedUpdate,
|
||||
workflowAppId,
|
||||
icon,
|
||||
name,
|
||||
description,
|
||||
inputs,
|
||||
outputs,
|
||||
handlePublish,
|
||||
onRefreshData,
|
||||
onConfigured,
|
||||
} = options
|
||||
const { t } = useTranslation(['common'])
|
||||
|
||||
// Data fetching via React Query
|
||||
const queryClient = useQueryClient()
|
||||
const detailQueryKey = consoleQuery.workspaces.current.toolProvider.workflow.get.get.queryKey({
|
||||
input: { query: { workflow_app_id: workflowAppId } },
|
||||
})
|
||||
const { data: detail, isLoading } = useQuery(
|
||||
consoleQuery.workspaces.current.toolProvider.workflow.get.get.queryOptions({
|
||||
input: { query: { workflow_app_id: workflowAppId } },
|
||||
enabled: enabled && published && !!workflowAppId,
|
||||
select: selectWorkflowToolDetail,
|
||||
}),
|
||||
)
|
||||
|
||||
const invalidateDetail = () => queryClient.invalidateQueries({ queryKey: detailQueryKey })
|
||||
const invalidateAllWorkflowTools = () =>
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: consoleQuery.workspaces.current.tools.workflow.get.queryKey(),
|
||||
})
|
||||
|
||||
// Refetch when detailNeedUpdate becomes true
|
||||
useEffect(() => {
|
||||
if (enabled && detailNeedUpdate)
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: consoleQuery.workspaces.current.toolProvider.workflow.get.get.queryKey({
|
||||
input: { query: { workflow_app_id: workflowAppId } },
|
||||
}),
|
||||
})
|
||||
}, [detailNeedUpdate, enabled, queryClient, workflowAppId])
|
||||
|
||||
// Computed values
|
||||
const outdated = useMemo(() => isParametersOutdated(detail, inputs), [detail, inputs])
|
||||
|
||||
const payload = useMemo(() => {
|
||||
const hasPublishedDetail = published && detail?.tool
|
||||
|
||||
const parameters = !published
|
||||
? buildNewParameters(inputs)
|
||||
: hasPublishedDetail
|
||||
? buildExistingParameters(inputs, detail)
|
||||
: []
|
||||
|
||||
const outputParameters = !published
|
||||
? buildNewOutputParameters(outputs)
|
||||
: hasPublishedDetail
|
||||
? buildExistingOutputParameters(outputs, detail)
|
||||
: []
|
||||
|
||||
return {
|
||||
icon: detail?.icon || icon,
|
||||
label: detail?.label || name,
|
||||
name: detail?.name || '',
|
||||
description: detail?.description || description,
|
||||
parameters,
|
||||
outputParameters,
|
||||
labels: detail?.tool?.labels || [],
|
||||
privacy_policy: detail?.privacy_policy || '',
|
||||
...(published
|
||||
? { workflow_tool_id: detail?.workflow_tool_id }
|
||||
: { workflow_app_id: workflowAppId }),
|
||||
}
|
||||
}, [detail, published, workflowAppId, icon, name, description, inputs, outputs])
|
||||
|
||||
// Mutation handlers (not memoized — only used in conditionally-rendered modal)
|
||||
const handleCreate = async (data: WorkflowToolProviderRequest & { workflow_app_id: string }) => {
|
||||
try {
|
||||
await handlePublish()
|
||||
await createWorkflowToolProvider(data, { silent: true })
|
||||
invalidateAllWorkflowTools()
|
||||
onRefreshData?.()
|
||||
invalidateDetail()
|
||||
toast.success(t(($) => $['api.actionSuccess'], { ns: 'common' }))
|
||||
onConfigured?.()
|
||||
} catch (e) {
|
||||
toast.error((e as Error).message)
|
||||
}
|
||||
}
|
||||
|
||||
const handleUpdate = async (
|
||||
data: WorkflowToolProviderRequest &
|
||||
Partial<{
|
||||
workflow_app_id: string
|
||||
workflow_tool_id: string
|
||||
}>,
|
||||
) => {
|
||||
try {
|
||||
await handlePublish()
|
||||
await saveWorkflowToolProvider(data, { silent: true })
|
||||
onRefreshData?.()
|
||||
invalidateAllWorkflowTools()
|
||||
invalidateDetail()
|
||||
toast.success(t(($) => $['api.actionSuccess'], { ns: 'common' }))
|
||||
onConfigured?.()
|
||||
} catch (e) {
|
||||
toast.error((e as Error).message)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
isLoading,
|
||||
outdated,
|
||||
payload,
|
||||
handleCreate,
|
||||
handleUpdate,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
import type { Meta, StoryObj } from '@storybook/nextjs-vite'
|
||||
import type { WorkflowToolDrawerPayload } from '.'
|
||||
import { fn } from 'storybook/test'
|
||||
import { VarType } from '@/app/components/workflow/types'
|
||||
import { WorkflowToolDrawer } from '.'
|
||||
|
||||
const payload = {
|
||||
icon: {
|
||||
content: '🔀',
|
||||
background: '#EEF4FF',
|
||||
},
|
||||
label: 'Branching Workflow',
|
||||
name: 'branching_workflow',
|
||||
description: 'Returns different outputs depending on the executed branch.',
|
||||
parameters: [
|
||||
{
|
||||
name: 'route',
|
||||
description: 'Selects the branch to execute.',
|
||||
form: 'llm',
|
||||
required: true,
|
||||
type: 'string',
|
||||
},
|
||||
],
|
||||
outputParameters: [
|
||||
{
|
||||
name: 'aaa',
|
||||
description: 'Output from the first End node.',
|
||||
type: VarType.string,
|
||||
source: { nodeId: 'end-success', nodeTitle: 'Success End', outputIndex: 0 },
|
||||
},
|
||||
{
|
||||
name: 'bbb',
|
||||
description: 'Output from the second End node.',
|
||||
type: VarType.number,
|
||||
source: { nodeId: 'end-fallback', nodeTitle: 'Fallback End', outputIndex: 0 },
|
||||
},
|
||||
],
|
||||
labels: [],
|
||||
privacy_policy: '',
|
||||
workflow_app_id: 'workflow-app-story',
|
||||
} satisfies WorkflowToolDrawerPayload
|
||||
|
||||
const meta = {
|
||||
title: 'Tools/WorkflowTool/Drawer',
|
||||
component: WorkflowToolDrawer,
|
||||
parameters: {
|
||||
layout: 'fullscreen',
|
||||
docs: {
|
||||
description: {
|
||||
component:
|
||||
'Configures a published workflow as a tool. This story covers the union of outputs from multiple End nodes.',
|
||||
},
|
||||
},
|
||||
},
|
||||
args: {
|
||||
isAdd: true,
|
||||
payload,
|
||||
onCreate: fn(),
|
||||
onHide: fn(),
|
||||
},
|
||||
} satisfies Meta<typeof WorkflowToolDrawer>
|
||||
|
||||
export default meta
|
||||
type Story = StoryObj<typeof meta>
|
||||
|
||||
export const MultipleEndOutputs: Story = {}
|
||||
|
||||
export const PublishedOutputsWithoutDraftSources: Story = {
|
||||
args: {
|
||||
isAdd: false,
|
||||
payload: {
|
||||
...payload,
|
||||
outputParameters: undefined,
|
||||
tool: {
|
||||
output_schema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
answer: {
|
||||
type: VarType.string,
|
||||
description: 'Output loaded from the published tool schema.',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
workflow_tool_id: 'workflow-tool-story',
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
export const DuplicateEndOutputs: Story = {
|
||||
args: {
|
||||
payload: {
|
||||
...payload,
|
||||
outputParameters: [
|
||||
{
|
||||
name: 'result',
|
||||
description: 'Output from the successful branch.',
|
||||
type: VarType.string,
|
||||
source: { nodeId: 'end-success', nodeTitle: 'Success End', outputIndex: 0 },
|
||||
},
|
||||
{
|
||||
name: 'result',
|
||||
description: 'Output from the fallback branch.',
|
||||
type: VarType.number,
|
||||
source: { nodeId: 'end-fallback', nodeTitle: 'Fallback End', outputIndex: 0 },
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
export const DuplicateReservedEndOutputs: Story = {
|
||||
args: {
|
||||
payload: {
|
||||
...payload,
|
||||
outputParameters: [
|
||||
{
|
||||
name: 'text',
|
||||
description: 'Output from the successful branch.',
|
||||
type: VarType.string,
|
||||
source: { nodeId: 'end-success', nodeTitle: 'Output', outputIndex: 0 },
|
||||
},
|
||||
{
|
||||
name: 'text',
|
||||
description: 'Output from the fallback branch.',
|
||||
type: VarType.number,
|
||||
source: { nodeId: 'end-fallback', nodeTitle: 'Output', outputIndex: 0 },
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,605 @@
|
||||
'use client'
|
||||
import type {
|
||||
Emoji,
|
||||
WorkflowToolOutputSource,
|
||||
WorkflowToolProviderOutputParameter,
|
||||
WorkflowToolProviderOutputSchema,
|
||||
WorkflowToolProviderParameter,
|
||||
WorkflowToolProviderRequest,
|
||||
} from '../types'
|
||||
import { Button } from '@langgenius/dify-ui/button'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import {
|
||||
Drawer,
|
||||
DrawerBackdrop,
|
||||
DrawerClose,
|
||||
DrawerContent,
|
||||
DrawerPopup,
|
||||
DrawerPortal,
|
||||
DrawerTitle,
|
||||
DrawerViewport,
|
||||
} from '@langgenius/dify-ui/drawer'
|
||||
import { Field, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
|
||||
import { IconButton } from '@langgenius/dify-ui/icon-button'
|
||||
import { Infotip, InfotipContent, InfotipTrigger } from '@langgenius/dify-ui/infotip'
|
||||
import { Input } from '@langgenius/dify-ui/input'
|
||||
import { Textarea } from '@langgenius/dify-ui/textarea'
|
||||
import { produce } from 'immer'
|
||||
import * as React from 'react'
|
||||
import { useMemo, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import {
|
||||
IconPicker,
|
||||
IconPickerContent,
|
||||
IconPickerIcon,
|
||||
IconPickerTrigger,
|
||||
} from '@/app/components/base/icon-picker'
|
||||
import LabelSelector from '@/app/components/tools/labels/selector'
|
||||
import ConfirmModal from '@/app/components/tools/workflow-tool/confirm-modal'
|
||||
import MethodSelector from '@/app/components/tools/workflow-tool/method-selector'
|
||||
import { normalizeWorkflowOutputName } from '@/app/components/workflow/utils/variable'
|
||||
import { toast } from '@/app/notifications'
|
||||
import {
|
||||
buildWorkflowToolRequestPayload,
|
||||
getReservedWorkflowOutputParameters,
|
||||
getWorkflowOutputParameters,
|
||||
hasReservedWorkflowOutputConflict,
|
||||
isWorkflowToolNameValid,
|
||||
} from './helpers'
|
||||
import {
|
||||
getDuplicateWorkflowOutputGroups,
|
||||
getSourceNodeDisplayName,
|
||||
getUniqueWorkflowOutputSources,
|
||||
} from './utils'
|
||||
|
||||
export type WorkflowToolDrawerPayload = {
|
||||
icon: Emoji
|
||||
label: string
|
||||
name: string
|
||||
description: string
|
||||
parameters: WorkflowToolProviderParameter[]
|
||||
outputParameters?: WorkflowToolProviderOutputParameter[]
|
||||
labels: string[]
|
||||
privacy_policy: string
|
||||
tool?: {
|
||||
output_schema?: WorkflowToolProviderOutputSchema
|
||||
}
|
||||
workflow_tool_id?: string
|
||||
workflow_app_id?: string
|
||||
}
|
||||
|
||||
export type WorkflowToolDrawerProps = {
|
||||
isAdd?: boolean
|
||||
payload: WorkflowToolDrawerPayload
|
||||
onHide: () => void
|
||||
onRemove?: () => void
|
||||
onCreate?: (payload: WorkflowToolProviderRequest & { workflow_app_id: string }) => void
|
||||
onSave?: (
|
||||
payload: WorkflowToolProviderRequest &
|
||||
Partial<{
|
||||
workflow_app_id: string
|
||||
workflow_tool_id: string
|
||||
}>,
|
||||
) => void
|
||||
}
|
||||
|
||||
type WorkflowToolDrawerFrameProps = {
|
||||
title: string
|
||||
closeLabel: string
|
||||
onHide: () => void
|
||||
children: React.ReactNode
|
||||
}
|
||||
|
||||
const WorkflowToolDrawerFrame = ({
|
||||
title,
|
||||
closeLabel,
|
||||
onHide,
|
||||
children,
|
||||
}: WorkflowToolDrawerFrameProps) => {
|
||||
const handleOpenChange = React.useCallback(
|
||||
(open: boolean) => {
|
||||
if (!open) onHide()
|
||||
},
|
||||
[onHide],
|
||||
)
|
||||
|
||||
return (
|
||||
<Drawer
|
||||
open
|
||||
modal
|
||||
disablePointerDismissal
|
||||
swipeDirection="right"
|
||||
onOpenChange={handleOpenChange}
|
||||
>
|
||||
<DrawerPortal>
|
||||
<DrawerBackdrop />
|
||||
<DrawerViewport>
|
||||
<DrawerPopup
|
||||
className={cn(
|
||||
'data-[swipe-direction=right]:top-2 data-[swipe-direction=right]:right-2 data-[swipe-direction=right]:bottom-2 data-[swipe-direction=right]:h-[calc(100dvh-16px)] data-[swipe-direction=right]:w-160 data-[swipe-direction=right]:max-w-[calc(100vw-16px)]',
|
||||
'data-[swipe-direction=right]:rounded-xl data-[swipe-direction=right]:border-r-[0.5px] data-[swipe-direction=right]:border-divider-subtle',
|
||||
)}
|
||||
>
|
||||
<DrawerContent className="flex min-h-0 flex-1 flex-col overflow-hidden p-0 pb-0">
|
||||
<div className="shrink-0 border-b border-divider-subtle py-4">
|
||||
<div className="flex h-6 items-center justify-between pr-5 pl-6">
|
||||
<DrawerTitle className="min-w-0 truncate system-xl-semibold text-text-primary">
|
||||
{title}
|
||||
</DrawerTitle>
|
||||
<DrawerClose
|
||||
render={
|
||||
<IconButton aria-label={closeLabel} size="md">
|
||||
<span aria-hidden="true" className="i-ri-close-line size-4" />
|
||||
</IconButton>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grow overflow-hidden">{children}</div>
|
||||
</DrawerContent>
|
||||
</DrawerPopup>
|
||||
</DrawerViewport>
|
||||
</DrawerPortal>
|
||||
</Drawer>
|
||||
)
|
||||
}
|
||||
|
||||
const WorkflowToolOutputName = React.memo(
|
||||
({
|
||||
duplicateSources,
|
||||
item,
|
||||
reservedOutputParameters,
|
||||
}: {
|
||||
duplicateSources?: WorkflowToolOutputSource[]
|
||||
item: WorkflowToolProviderOutputParameter
|
||||
reservedOutputParameters: WorkflowToolProviderOutputParameter[]
|
||||
}) => {
|
||||
const outputNameId = React.useId()
|
||||
|
||||
const { t } = useTranslation(['tools', 'workflow'])
|
||||
const reservedOutputDuplicateTip = t(
|
||||
($) => $['createTool.toolOutput.reservedParameterDuplicateTip'],
|
||||
{ ns: 'tools' },
|
||||
)
|
||||
const sourceNodeLabel = t(($) => $['createTool.toolOutput.sourceNode'], { ns: 'tools' })
|
||||
const duplicateOutputTip = t(($) => $['errorMsg.duplicateOutputVariable'], {
|
||||
ns: 'workflow',
|
||||
variable: normalizeWorkflowOutputName(item.name),
|
||||
})
|
||||
const hasReservedNameConflict =
|
||||
!item.reserved && hasReservedWorkflowOutputConflict(reservedOutputParameters, item.name)
|
||||
const hasDuplicateNameConflict = !item.reserved && !!duplicateSources
|
||||
const sources = duplicateSources || []
|
||||
|
||||
return (
|
||||
<div className="text-[13px] leading-4.5">
|
||||
<div className="flex min-w-0 items-center gap-x-1">
|
||||
<span id={outputNameId} className="truncate font-medium text-text-primary">
|
||||
{item.name}
|
||||
</span>
|
||||
{item.reserved && (
|
||||
<span className="shrink-0 text-xs leading-4.5 text-[#ec4a0a]">
|
||||
{t(($) => $['createTool.toolOutput.reserved'], { ns: 'tools' })}
|
||||
</span>
|
||||
)}
|
||||
{hasReservedNameConflict || hasDuplicateNameConflict ? (
|
||||
<Infotip>
|
||||
<InfotipTrigger
|
||||
aria-labelledby={outputNameId}
|
||||
className="text-text-warning-secondary"
|
||||
iconSize="small"
|
||||
iconVariant="warning"
|
||||
/>
|
||||
<InfotipContent
|
||||
aria-labelledby={outputNameId}
|
||||
className={hasDuplicateNameConflict ? 'w-60' : 'w-45'}
|
||||
>
|
||||
<div className="space-y-2">
|
||||
{hasReservedNameConflict ? <p>{reservedOutputDuplicateTip}</p> : null}
|
||||
{hasDuplicateNameConflict ? (
|
||||
<div className="space-y-1.5">
|
||||
<p>{duplicateOutputTip}</p>
|
||||
{sources.length > 0 ? (
|
||||
<ul className="space-y-1">
|
||||
{sources.map((source) => {
|
||||
const sourceTitle = getSourceNodeDisplayName(source, sources)
|
||||
return (
|
||||
<li key={source.nodeId}>
|
||||
{sourceNodeLabel}: <span translate="no">{sourceTitle}</span>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</InfotipContent>
|
||||
</Infotip>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="text-text-tertiary">{item.type}</div>
|
||||
{hasDuplicateNameConflict && item.source ? (
|
||||
<div className="system-xs-regular wrap-break-word text-text-tertiary">
|
||||
{sourceNodeLabel} ·{' '}
|
||||
<span translate="no">{getSourceNodeDisplayName(item.source, sources)}</span>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
export function WorkflowToolDrawer({
|
||||
isAdd,
|
||||
payload,
|
||||
onHide,
|
||||
onRemove,
|
||||
onSave,
|
||||
onCreate,
|
||||
}: WorkflowToolDrawerProps) {
|
||||
const { t } = useTranslation(['workflow', 'common', 'tools', 'navigation'])
|
||||
const parameterId = React.useId()
|
||||
const toolNameLabelId = React.useId()
|
||||
|
||||
const [emoji, setEmoji] = useState<Emoji>(payload.icon)
|
||||
const [label, setLabel] = useState<string>(payload.label)
|
||||
const [name, setName] = useState(payload.name)
|
||||
const [description, setDescription] = useState(payload.description)
|
||||
const [parameters, setParameters] = useState<WorkflowToolProviderParameter[]>(payload.parameters)
|
||||
const rawOutputParameters = payload.outputParameters
|
||||
const outputSchema = payload.tool?.output_schema
|
||||
const outputParameters = useMemo<WorkflowToolProviderOutputParameter[]>(
|
||||
() => getWorkflowOutputParameters(rawOutputParameters, outputSchema),
|
||||
[rawOutputParameters, outputSchema],
|
||||
)
|
||||
const reservedOutputParameters = useMemo(() => getReservedWorkflowOutputParameters(t), [t])
|
||||
const duplicateOutputSourceGroups = useMemo(() => {
|
||||
const groups = getDuplicateWorkflowOutputGroups(outputParameters)
|
||||
const sourceGroups = new Map<string, WorkflowToolOutputSource[]>()
|
||||
|
||||
for (const [name, outputs] of groups)
|
||||
sourceGroups.set(name, getUniqueWorkflowOutputSources(outputs))
|
||||
|
||||
return sourceGroups
|
||||
}, [outputParameters])
|
||||
|
||||
const handleParameterChange = (key: string, value: string, index: number) => {
|
||||
const newData = produce(parameters, (draft: WorkflowToolProviderParameter[]) => {
|
||||
if (key === 'description') draft[index]!.description = value
|
||||
else draft[index]!.form = value
|
||||
})
|
||||
setParameters(newData)
|
||||
}
|
||||
const [labels, setLabels] = useState<string[]>(payload.labels)
|
||||
const handleLabelSelect = (value: string[]) => {
|
||||
setLabels(value)
|
||||
}
|
||||
const [privacyPolicy, setPrivacyPolicy] = useState(payload.privacy_policy)
|
||||
const [confirmModalOpen, setConfirmModalOpen] = useState(false)
|
||||
|
||||
const onConfirm = () => {
|
||||
let errorMessage = ''
|
||||
if (!label)
|
||||
errorMessage = t(($) => $['errorMsg.fieldRequired'], {
|
||||
ns: 'common',
|
||||
field: t(($) => $['createTool.name'], { ns: 'tools' }),
|
||||
})
|
||||
|
||||
if (!name)
|
||||
errorMessage = t(($) => $['errorMsg.fieldRequired'], {
|
||||
ns: 'common',
|
||||
field: t(($) => $['createTool.nameForToolCall'], { ns: 'tools' }),
|
||||
})
|
||||
|
||||
if (!isWorkflowToolNameValid(name))
|
||||
errorMessage =
|
||||
t(($) => $['createTool.nameForToolCall'], { ns: 'tools' }) +
|
||||
t(($) => $['createTool.nameForToolCallTip'], { ns: 'tools' })
|
||||
|
||||
if (errorMessage) {
|
||||
toast.error(errorMessage)
|
||||
return
|
||||
}
|
||||
|
||||
const requestParams = buildWorkflowToolRequestPayload({
|
||||
name,
|
||||
description,
|
||||
emoji,
|
||||
label,
|
||||
parameters,
|
||||
labels,
|
||||
privacyPolicy,
|
||||
})
|
||||
if (!isAdd) {
|
||||
onSave?.({
|
||||
...requestParams,
|
||||
workflow_tool_id: payload.workflow_tool_id!,
|
||||
})
|
||||
} else {
|
||||
onCreate?.({
|
||||
...requestParams,
|
||||
workflow_app_id: payload.workflow_app_id!,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<WorkflowToolDrawerFrame
|
||||
onHide={onHide}
|
||||
title={t(($) => $['common.workflowAsTool'], { ns: 'navigation' })!}
|
||||
closeLabel={t(($) => $['operation.close'], { ns: 'common' })!}
|
||||
>
|
||||
<form
|
||||
className="flex h-full flex-col"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault()
|
||||
if (isAdd) onConfirm()
|
||||
else setConfirmModalOpen(true)
|
||||
}}
|
||||
>
|
||||
<div className="h-0 grow space-y-4 overflow-y-auto px-6 py-3">
|
||||
{/* name & icon */}
|
||||
<IconPicker
|
||||
value={{
|
||||
type: 'emoji',
|
||||
icon: emoji.content,
|
||||
background: emoji.background,
|
||||
}}
|
||||
onValueChange={(payload) => {
|
||||
if (payload.type === 'emoji')
|
||||
setEmoji({ content: payload.icon, background: payload.background })
|
||||
}}
|
||||
>
|
||||
<Field name="label" className="gap-0">
|
||||
<FieldLabel className="py-2 text-text-primary">
|
||||
{t(($) => $['createTool.name'], { ns: 'tools' })}{' '}
|
||||
<span aria-hidden className="ml-1 text-text-destructive">
|
||||
*
|
||||
</span>
|
||||
</FieldLabel>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<IconPickerTrigger
|
||||
aria-label={t(($) => $['createTool.changeIcon'], { ns: 'tools' })}
|
||||
className="shrink-0 cursor-pointer rounded-[10px]"
|
||||
>
|
||||
<IconPickerIcon size="large" />
|
||||
</IconPickerTrigger>
|
||||
<Input
|
||||
className="h-10 min-w-0 flex-1"
|
||||
placeholder={t(($) => $['createTool.toolNamePlaceHolder'], { ns: 'tools' })!}
|
||||
value={label}
|
||||
onValueChange={(value) => setLabel(value)}
|
||||
/>
|
||||
</div>
|
||||
</Field>
|
||||
<IconPickerContent enableImageUpload={false} />
|
||||
</IconPicker>
|
||||
{/* name for tool call */}
|
||||
<Field name="name" className="gap-0" invalid={!isWorkflowToolNameValid(name)}>
|
||||
<div className="flex items-center py-2 system-sm-medium text-text-primary">
|
||||
<FieldLabel id={toolNameLabelId} className="py-0 text-text-primary">
|
||||
{t(($) => $['createTool.nameForToolCall'], { ns: 'tools' })}
|
||||
</FieldLabel>
|
||||
<span aria-hidden className="ml-1 text-text-destructive">
|
||||
*
|
||||
</span>
|
||||
<Infotip>
|
||||
<InfotipTrigger aria-labelledby={toolNameLabelId} className="ml-1 size-3.5" />
|
||||
<InfotipContent aria-labelledby={toolNameLabelId} className="w-45">
|
||||
{t(($) => $['createTool.nameForToolCallPlaceHolder'], { ns: 'tools' })}
|
||||
</InfotipContent>
|
||||
</Infotip>
|
||||
</div>
|
||||
<Input
|
||||
className="h-10"
|
||||
placeholder={t(($) => $['createTool.nameForToolCallPlaceHolder'], { ns: 'tools' })!}
|
||||
value={name}
|
||||
onValueChange={(value) => setName(value)}
|
||||
/>
|
||||
{!isWorkflowToolNameValid(name) && (
|
||||
<FieldError match className="py-0 text-xs leading-4.5">
|
||||
{t(($) => $['createTool.nameForToolCallTip'], { ns: 'tools' })}
|
||||
</FieldError>
|
||||
)}
|
||||
</Field>
|
||||
{/* description */}
|
||||
<Field name="description" className="gap-0">
|
||||
<FieldLabel className="py-2 text-text-primary">
|
||||
{t(($) => $['createTool.description'], { ns: 'tools' })}
|
||||
</FieldLabel>
|
||||
<Textarea
|
||||
placeholder={t(($) => $['createTool.descriptionPlaceholder'], { ns: 'tools' })}
|
||||
value={description}
|
||||
onValueChange={(value) => setDescription(value)}
|
||||
/>
|
||||
</Field>
|
||||
{/* Tool Input */}
|
||||
<div>
|
||||
<div className="py-2 system-sm-medium text-text-primary">
|
||||
{t(($) => $['createTool.toolInput.title'], { ns: 'tools' })}
|
||||
</div>
|
||||
<div className="w-full overflow-x-auto rounded-lg border border-divider-regular">
|
||||
<table className="w-full text-xs leading-4.5 font-normal text-text-secondary">
|
||||
<thead className="text-text-tertiary uppercase">
|
||||
<tr className="border-b border-divider-regular">
|
||||
<th className="w-39 p-2 pl-3 font-medium">
|
||||
{t(($) => $['createTool.toolInput.name'], { ns: 'tools' })}
|
||||
</th>
|
||||
<th className="w-25.5 p-2 pl-3 font-medium">
|
||||
{t(($) => $['createTool.toolInput.method'], { ns: 'tools' })}
|
||||
</th>
|
||||
<th id={`${parameterId}-description`} className="p-2 pl-3 font-medium">
|
||||
{t(($) => $['createTool.toolInput.description'], { ns: 'tools' })}
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{parameters.map((item, index) => (
|
||||
<tr key={index} className="border-b border-divider-regular last:border-0">
|
||||
<td className="max-w-39 p-2 pl-3">
|
||||
<div className="text-[13px] leading-4.5">
|
||||
<div className="flex">
|
||||
<span
|
||||
id={`${parameterId}-${index}-name`}
|
||||
className="truncate font-medium text-text-primary"
|
||||
>
|
||||
{item.name}
|
||||
</span>
|
||||
<span className="shrink-0 pl-1 text-xs leading-4.5 text-[#ec4a0a]">
|
||||
{item.required
|
||||
? t(($) => $['createTool.toolInput.required'], { ns: 'tools' })
|
||||
: ''}
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-text-tertiary">{item.type}</div>
|
||||
</div>
|
||||
</td>
|
||||
<td>
|
||||
{item.name === '__image' && (
|
||||
<div
|
||||
className={cn(
|
||||
'flex h-9 min-h-14 cursor-default items-center gap-1 bg-transparent px-3 py-2',
|
||||
)}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
'grow truncate text-[13px] leading-4.5 text-text-secondary',
|
||||
)}
|
||||
>
|
||||
{t(($) => $['createTool.toolInput.methodParameter'], {
|
||||
ns: 'tools',
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{item.name !== '__image' && (
|
||||
<MethodSelector
|
||||
value={item.form}
|
||||
onChange={(value) => handleParameterChange('form', value, index)}
|
||||
/>
|
||||
)}
|
||||
</td>
|
||||
<td className="w-59 p-2 pl-3 text-text-tertiary">
|
||||
<input
|
||||
type="text"
|
||||
aria-labelledby={`${parameterId}-${index}-name ${parameterId}-description`}
|
||||
className="w-full appearance-none rounded-sm bg-transparent text-[13px] leading-4.5 font-normal text-text-secondary caret-primary-600 outline-hidden placeholder:text-text-quaternary focus-visible:ring-2 focus-visible:ring-state-accent-solid"
|
||||
placeholder={t(
|
||||
($) => $['createTool.toolInput.descriptionPlaceholder'],
|
||||
{
|
||||
ns: 'tools',
|
||||
},
|
||||
)!}
|
||||
value={item.description}
|
||||
onChange={(e) =>
|
||||
handleParameterChange('description', e.target.value, index)
|
||||
}
|
||||
/>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
{/* Tool Output */}
|
||||
<div>
|
||||
<div className="py-2 system-sm-medium text-text-primary">
|
||||
{t(($) => $['createTool.toolOutput.title'], { ns: 'tools' })}
|
||||
</div>
|
||||
<div className="w-full overflow-x-auto rounded-lg border border-divider-regular">
|
||||
<table className="w-full text-xs leading-4.5 font-normal text-text-secondary">
|
||||
<thead className="text-text-tertiary uppercase">
|
||||
<tr className="border-b border-divider-regular">
|
||||
<th className="w-39 p-2 pl-3 font-medium">
|
||||
{t(($) => $['createTool.name'], { ns: 'tools' })}
|
||||
</th>
|
||||
<th className="p-2 pl-3 font-medium">
|
||||
{t(($) => $['createTool.toolOutput.description'], { ns: 'tools' })}
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{[...reservedOutputParameters, ...outputParameters].map((item, index) => (
|
||||
<tr
|
||||
key={
|
||||
item.reserved
|
||||
? `reserved-${item.name}`
|
||||
: item.source
|
||||
? `${item.source.nodeId}-${item.source.outputIndex}`
|
||||
: `output-${item.name}-${index}`
|
||||
}
|
||||
className="border-b border-divider-regular last:border-0"
|
||||
>
|
||||
<td className="max-w-39 p-2 pl-3">
|
||||
<WorkflowToolOutputName
|
||||
duplicateSources={duplicateOutputSourceGroups.get(
|
||||
normalizeWorkflowOutputName(item.name),
|
||||
)}
|
||||
item={item}
|
||||
reservedOutputParameters={reservedOutputParameters}
|
||||
/>
|
||||
</td>
|
||||
<td className="w-59 p-2 pl-3 text-text-tertiary">
|
||||
<span className="text-[13px] leading-4.5 font-normal text-text-secondary">
|
||||
{item.description}
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
{/* Tags */}
|
||||
<div>
|
||||
<div className="py-2 system-sm-medium text-text-primary">
|
||||
{t(($) => $['createTool.toolInput.label'], { ns: 'tools' })}
|
||||
</div>
|
||||
<LabelSelector value={labels} onChange={handleLabelSelect} />
|
||||
</div>
|
||||
{/* Privacy Policy */}
|
||||
<Field name="privacy_policy" className="gap-0">
|
||||
<FieldLabel className="py-2 text-text-primary">
|
||||
{t(($) => $['createTool.privacyPolicy'], { ns: 'tools' })}
|
||||
</FieldLabel>
|
||||
<Input
|
||||
className="h-10"
|
||||
value={privacyPolicy}
|
||||
onValueChange={(value) => setPrivacyPolicy(value)}
|
||||
placeholder={t(($) => $['createTool.privacyPolicyPlaceholder'], { ns: 'tools' })}
|
||||
/>
|
||||
</Field>
|
||||
</div>
|
||||
<div
|
||||
className={cn(
|
||||
!isAdd && onRemove ? 'justify-between' : 'justify-end',
|
||||
'mt-2 flex shrink-0 rounded-b-[10px] border-t border-divider-regular bg-background-section-burn px-6 py-4',
|
||||
)}
|
||||
>
|
||||
{!isAdd && onRemove && (
|
||||
<Button variant="primary" tone="destructive" onClick={onRemove}>
|
||||
{t(($) => $['operation.delete'], { ns: 'common' })}
|
||||
</Button>
|
||||
)}
|
||||
<div className="flex space-x-2">
|
||||
<Button onClick={onHide}>{t(($) => $['operation.cancel'], { ns: 'common' })}</Button>
|
||||
<Button variant="primary" type="submit">
|
||||
{t(($) => $['operation.save'], { ns: 'common' })}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</WorkflowToolDrawerFrame>
|
||||
{confirmModalOpen && (
|
||||
<ConfirmModal
|
||||
show={confirmModalOpen}
|
||||
onClose={() => setConfirmModalOpen(false)}
|
||||
onConfirm={onConfirm}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import type { FC } from 'react'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'
|
||||
import { RiArrowDownSLine } from '@remixicon/react'
|
||||
import { useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
type MethodSelectorProps = {
|
||||
value?: string
|
||||
onChange: (v: string) => void
|
||||
}
|
||||
const MethodSelector: FC<MethodSelectorProps> = ({ value, onChange }) => {
|
||||
const { t } = useTranslation(['tools'])
|
||||
const [open, setOpen] = useState(false)
|
||||
const handleSelect = (value: string) => {
|
||||
onChange(value)
|
||||
setOpen(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<div className="relative">
|
||||
<PopoverTrigger
|
||||
nativeButton={false}
|
||||
render={
|
||||
<div
|
||||
className={cn(
|
||||
'flex h-9 min-h-14 cursor-pointer items-center gap-1 bg-transparent px-3 py-2 hover:bg-background-section-burn',
|
||||
'data-popup-open:bg-background-section-burn! data-popup-open:hover:bg-background-section-burn',
|
||||
)}
|
||||
>
|
||||
<div className={cn('grow truncate text-[13px] leading-4.5 text-text-secondary')}>
|
||||
{value === 'llm'
|
||||
? t(($) => $['createTool.toolInput.methodParameter'], { ns: 'tools' })
|
||||
: t(($) => $['createTool.toolInput.methodSetting'], { ns: 'tools' })}
|
||||
</div>
|
||||
<div className="ml-1 shrink-0 text-text-secondary opacity-60">
|
||||
<RiArrowDownSLine className="size-4" />
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
<PopoverContent align="start" sideOffset={4}>
|
||||
<div className="relative w-[320px]">
|
||||
<div className="p-1">
|
||||
<button
|
||||
type="button"
|
||||
className="block w-full cursor-pointer rounded-lg border-none bg-transparent py-2.5 pr-2 pl-3 text-left hover:bg-components-panel-on-panel-item-bg-hover"
|
||||
onClick={() => handleSelect('llm')}
|
||||
>
|
||||
<div className="flex items-center gap-1">
|
||||
<div className="size-4 shrink-0">
|
||||
{value === 'llm' && (
|
||||
<span
|
||||
aria-hidden
|
||||
className="i-custom-vender-line-general-check size-4 shrink-0 text-text-accent"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-[13px] leading-4.5 font-medium text-text-secondary">
|
||||
{t(($) => $['createTool.toolInput.methodParameter'], { ns: 'tools' })}
|
||||
</div>
|
||||
</div>
|
||||
<div className="pl-5 text-[13px] leading-4.5 text-text-tertiary">
|
||||
{t(($) => $['createTool.toolInput.methodParameterTip'], { ns: 'tools' })}
|
||||
</div>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="block w-full cursor-pointer rounded-lg border-none bg-transparent py-2.5 pr-2 pl-3 text-left hover:bg-components-panel-on-panel-item-bg-hover"
|
||||
onClick={() => handleSelect('form')}
|
||||
>
|
||||
<div className="flex items-center gap-1">
|
||||
<div className="size-4 shrink-0">
|
||||
{value === 'form' && (
|
||||
<span
|
||||
aria-hidden
|
||||
className="i-custom-vender-line-general-check size-4 shrink-0 text-text-accent"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-[13px] leading-4.5 font-medium text-text-secondary">
|
||||
{t(($) => $['createTool.toolInput.methodSetting'], { ns: 'tools' })}
|
||||
</div>
|
||||
</div>
|
||||
<div className="pl-5 text-[13px] leading-4.5 text-text-tertiary">
|
||||
{t(($) => $['createTool.toolInput.methodSettingTip'], { ns: 'tools' })}
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</div>
|
||||
</Popover>
|
||||
)
|
||||
}
|
||||
|
||||
export default MethodSelector
|
||||
@@ -0,0 +1,99 @@
|
||||
import type {
|
||||
WorkflowToolOutputSource,
|
||||
WorkflowToolProviderOutputParameter,
|
||||
WorkflowToolProviderOutputSchema,
|
||||
} from '../types'
|
||||
import { VarType } from '@/app/components/workflow/types'
|
||||
import { normalizeWorkflowOutputName } from '@/app/components/workflow/utils/variable'
|
||||
|
||||
const validVarTypes = new Set<string>(Object.values(VarType))
|
||||
|
||||
const normalizeVarType = (type?: string): VarType | undefined => {
|
||||
if (!type) return undefined
|
||||
|
||||
return validVarTypes.has(type) ? (type as VarType) : undefined
|
||||
}
|
||||
|
||||
export const getUniqueWorkflowOutputSources = (
|
||||
outputParameters: readonly WorkflowToolProviderOutputParameter[],
|
||||
): WorkflowToolOutputSource[] => {
|
||||
const sources: WorkflowToolOutputSource[] = []
|
||||
const sourceNodeIds = new Set<string>()
|
||||
|
||||
for (const output of outputParameters) {
|
||||
const source = output.source
|
||||
if (!source || sourceNodeIds.has(source.nodeId)) continue
|
||||
|
||||
sourceNodeIds.add(source.nodeId)
|
||||
sources.push(source)
|
||||
}
|
||||
|
||||
return sources
|
||||
}
|
||||
|
||||
export const getSourceNodeDisplayName = (
|
||||
source: WorkflowToolOutputSource,
|
||||
duplicateSources: readonly WorkflowToolOutputSource[],
|
||||
) => {
|
||||
const title = source.nodeTitle || source.nodeId
|
||||
if (!source.nodeTitle) return title
|
||||
|
||||
let sameTitleSourceCount = 0
|
||||
let sourceIndex = -1
|
||||
|
||||
for (const candidate of duplicateSources) {
|
||||
if (candidate.nodeTitle !== source.nodeTitle) continue
|
||||
|
||||
if (candidate.nodeId === source.nodeId) sourceIndex = sameTitleSourceCount
|
||||
sameTitleSourceCount += 1
|
||||
}
|
||||
|
||||
if (sameTitleSourceCount < 2 || sourceIndex < 0) return title
|
||||
|
||||
return `${title} (${sourceIndex + 1}/${sameTitleSourceCount})`
|
||||
}
|
||||
|
||||
export const getDuplicateWorkflowOutputGroups = (
|
||||
outputParameters: WorkflowToolProviderOutputParameter[],
|
||||
) => {
|
||||
const groups = new Map<string, WorkflowToolProviderOutputParameter[]>()
|
||||
|
||||
for (const item of outputParameters) {
|
||||
const name = normalizeWorkflowOutputName(item.name)
|
||||
if (!name) continue
|
||||
|
||||
const group = groups.get(name) || []
|
||||
group.push(item)
|
||||
groups.set(name, group)
|
||||
}
|
||||
|
||||
return new Map([...groups].filter(([, items]) => items.length > 1))
|
||||
}
|
||||
|
||||
export const buildWorkflowOutputParameters = (
|
||||
outputParameters: WorkflowToolProviderOutputParameter[] | null | undefined,
|
||||
outputSchema?: WorkflowToolProviderOutputSchema | null,
|
||||
): WorkflowToolProviderOutputParameter[] => {
|
||||
const schemaProperties = outputSchema?.properties
|
||||
|
||||
if (Array.isArray(outputParameters) && outputParameters.length > 0) {
|
||||
if (!schemaProperties) return outputParameters
|
||||
|
||||
return outputParameters.map((item) => {
|
||||
const schema = schemaProperties[item.name]
|
||||
return {
|
||||
...item,
|
||||
description: item.description || schema?.description || '',
|
||||
type: normalizeVarType(item.type || schema?.type),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
if (!schemaProperties) return []
|
||||
|
||||
return Object.entries(schemaProperties).map(([name, schema]) => ({
|
||||
name,
|
||||
description: schema.description || '',
|
||||
type: normalizeVarType(schema.type),
|
||||
}))
|
||||
}
|
||||
Reference in new issue
Block a user