Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 0 additions & 15 deletions oxlint-suppressions.json
Original file line number Diff line number Diff line change
Expand Up @@ -2613,11 +2613,6 @@
"count": 1
}
},
"web/app/components/workflow/hooks/use-auto-generate-webhook-url.ts": {
"dify/no-app-store-imports": {
"count": 1
}
},
"web/app/components/workflow/hooks/use-checklist.ts": {
"dify/no-app-store-imports": {
"count": 1
Expand Down Expand Up @@ -3505,11 +3500,6 @@
"count": 4
}
},
"web/app/components/workflow/nodes/trigger-webhook/__tests__/use-config.spec.tsx": {
"dify/no-app-store-imports": {
"count": 1
}
},
"web/app/components/workflow/nodes/trigger-webhook/components/generic-table.tsx": {
"dify/require-disable-directive-description": {
"count": 1
Expand All @@ -3520,11 +3510,6 @@
"count": 1
}
},
"web/app/components/workflow/nodes/trigger-webhook/use-config.ts": {
"dify/no-app-store-imports": {
"count": 1
}
},
"web/app/components/workflow/nodes/utils.ts": {
"typescript/no-explicit-any": {
"count": 1
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,16 @@ type WebhookFlowNode = Node & {
}
}

vi.mock('@/app/components/app/store', async () =>
(await import('../../__tests__/service-mock-factory')).createAppStoreMock({ appId: 'app-123' }),
)
const routeParams = vi.hoisted(() => ({ appId: 'app-123' as string | undefined }))
const mockRequest = vi.hoisted(() => vi.fn())

const mockFetchWebhookUrl = vi.fn()
vi.mock('@/service/apps', () => ({
fetchWebhookUrl: (...args: unknown[]) => mockFetchWebhookUrl(...args),
vi.mock('@/next/navigation', async (importOriginal) => ({
...(await importOriginal<typeof import('@/next/navigation')>()),
useParams: () => routeParams,
}))

vi.mock('@/service/console/browser', () => ({
consoleBrowserLink: { call: mockRequest },
}))

describe('useAutoGenerateWebhookUrl', () => {
Expand Down Expand Up @@ -48,11 +51,12 @@ describe('useAutoGenerateWebhookUrl', () => {
)

beforeEach(() => {
vi.clearAllMocks()
routeParams.appId = 'app-123'
mockRequest.mockReset()
})

it('should fetch and set webhook URL for a webhook trigger node', async () => {
mockFetchWebhookUrl.mockResolvedValue({
mockRequest.mockResolvedValue({
webhook_url: 'https://example.com/webhook',
webhook_debug_url: 'https://example.com/webhook-debug',
})
Expand All @@ -63,7 +67,11 @@ describe('useAutoGenerateWebhookUrl', () => {
await result.current.autoGenerateWebhookUrl('webhook-1')
})

expect(mockFetchWebhookUrl).toHaveBeenCalledWith({ appId: 'app-123', nodeId: 'webhook-1' })
expect(mockRequest).toHaveBeenCalledWith(
['apps', 'byAppId', 'workflows', 'triggers', 'webhook', 'get'],
{ params: { app_id: 'app-123' }, query: { node_id: 'webhook-1' } },
expect.any(Object),
)

await waitFor(() => {
const webhookNode = result.current.nodes.find((node) => node.id === 'webhook-1') as
Expand All @@ -74,14 +82,40 @@ describe('useAutoGenerateWebhookUrl', () => {
})
})

it('uses the current route after switching apps and skips routes without an app', async () => {
routeParams.appId = undefined
const { result, rerender } = renderAutoGenerateWebhookUrlHook()

await act(async () => {
await result.current.autoGenerateWebhookUrl('webhook-1')
})
expect(mockRequest).not.toHaveBeenCalled()

routeParams.appId = 'app-456'
rerender()
mockRequest.mockResolvedValue({
webhook_url: 'https://example.com/other-webhook',
webhook_debug_url: 'https://example.com/other-debug',
})
await act(async () => {
await result.current.autoGenerateWebhookUrl('webhook-1')
})

expect(mockRequest).toHaveBeenCalledWith(
['apps', 'byAppId', 'workflows', 'triggers', 'webhook', 'get'],
{ params: { app_id: 'app-456' }, query: { node_id: 'webhook-1' } },
expect.any(Object),
)
})

it('should not fetch when node is not a webhook trigger', async () => {
const { result } = renderAutoGenerateWebhookUrlHook()

await act(async () => {
await result.current.autoGenerateWebhookUrl('code-1')
})

expect(mockFetchWebhookUrl).not.toHaveBeenCalled()
expect(mockRequest).not.toHaveBeenCalled()

const codeNode = result.current.nodes.find((node) => node.id === 'code-1') as
| WebhookFlowNode
Expand All @@ -96,7 +130,7 @@ describe('useAutoGenerateWebhookUrl', () => {
await result.current.autoGenerateWebhookUrl('nonexistent')
})

expect(mockFetchWebhookUrl).not.toHaveBeenCalled()
expect(mockRequest).not.toHaveBeenCalled()
})

it('should not fetch when webhook_url already exists', async () => {
Expand All @@ -122,12 +156,12 @@ describe('useAutoGenerateWebhookUrl', () => {
await result.current.autoGenerateWebhookUrl('webhook-1')
})

expect(mockFetchWebhookUrl).not.toHaveBeenCalled()
expect(mockRequest).not.toHaveBeenCalled()
})

it('should handle API errors gracefully', async () => {
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
mockFetchWebhookUrl.mockRejectedValue(new Error('network error'))
mockRequest.mockRejectedValue(new Error('network error'))

const { result } = renderAutoGenerateWebhookUrlHook()

Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
import { useQueryClient } from '@tanstack/react-query'
import { produce } from 'immer'
import { useCallback } from 'react'
import { useStore as useAppStore } from '@/app/components/app/store'
import { BlockEnum } from '@/app/components/workflow/types'
import { fetchWebhookUrl } from '@/service/apps'
import { useParams } from '@/next/navigation'
import { consoleQuery } from '@/service/console'
import { useCollaborativeWorkflow } from './use-collaborative-workflow'

export const useAutoGenerateWebhookUrl = () => {
const { appId } = useParams<{ appId?: string }>()
const queryClient = useQueryClient()
const collaborativeWorkflow = useCollaborativeWorkflow()

return useCallback(
async (nodeId: string) => {
const appId = useAppStore.getState().appDetail?.id
if (!appId) return

const { nodes } = collaborativeWorkflow.getState()
Expand All @@ -20,7 +22,13 @@ export const useAutoGenerateWebhookUrl = () => {
if (node.data.webhook_url && node.data.webhook_url.length > 0) return

try {
const response = await fetchWebhookUrl({ appId, nodeId })
const response = await queryClient.query(
consoleQuery.apps.byAppId.workflows.triggers.webhook.get.queryOptions({
input: { params: { app_id: appId }, query: { node_id: nodeId } },
staleTime: 0,
retry: false,
}),
)
const { nodes: latestNodes, setNodes } = collaborativeWorkflow.getState()
let hasUpdated = false
const updatedNodes = produce(latestNodes, (draft) => {
Expand All @@ -40,6 +48,6 @@ export const useAutoGenerateWebhookUrl = () => {
console.error('Failed to auto-generate webhook URL:', error)
}
},
[collaborativeWorkflow],
[appId, collaborativeWorkflow, queryClient],
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ const { mockUseAgentRosterDetail, mockUseWorkflowInlineAgentDetail } = vi.hoiste
mockUseWorkflowInlineAgentDetail: vi.fn(),
}))

vi.mock('@/next/navigation', async (importOriginal) => ({
...(await importOriginal<typeof import('@/next/navigation')>()),
useParams: () => ({ appId: 'app-1' }),
}))

vi.mock('../../_base/components/setting-item', () => ({
SettingItem: ({
label,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@ import { useNodesInteractions } from '@/app/components/workflow/hooks/use-nodes-
import { BlockEnum } from '@/app/components/workflow/types'
import { AgentOutputRoutes } from '../agent-output-routes'

vi.mock('@/next/navigation', async (importOriginal) => ({
...(await importOriginal<typeof import('@/next/navigation')>()),
useParams: () => ({ appId: 'app-1' }),
}))

vi.mock('../../../_base/hooks/use-available-var-list', () => ({
default: () => ({ availableVars: [], availableNodesWithParent: [] }),
}))
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import type { WebhookTriggerNodeType } from '../types'
import { renderHook } from '@testing-library/react'
import { useStore as useAppStore } from '@/app/components/app/store'
import { BlockEnum, VarType } from '@/app/components/workflow/types'
import { toast } from '@/app/notifications'
import { fetchWebhookUrl } from '@/service/apps'
import { renderHookWithConsoleQuery } from '@/test/console/query-data'
import { createNodeCrudModuleMock } from '../../__tests__/use-config-test-utils'
import { useConfig } from '../use-config'

Expand Down Expand Up @@ -45,11 +43,17 @@ vi.mock('@/app/components/workflow/nodes/_base/hooks/use-node-crud', () => ({
...createNodeCrudModuleMock<WebhookTriggerNodeType>(mockSetInputs),
}))

vi.mock('@/service/apps', () => ({
fetchWebhookUrl: vi.fn(),
const routeParams = vi.hoisted(() => ({ appId: 'app-1' as string | undefined }))
const mockRequest = vi.hoisted(() => vi.fn())

vi.mock('@/next/navigation', async (importOriginal) => ({
...(await importOriginal<typeof import('@/next/navigation')>()),
useParams: () => routeParams,
}))

const mockedFetchWebhookUrl = vi.mocked(fetchWebhookUrl)
vi.mock('@/service/console/browser', () => ({
consoleBrowserLink: { call: mockRequest },
}))
const mockedToastError = vi.mocked(toast.error)

const createPayload = (
Expand All @@ -73,9 +77,8 @@ const createPayload = (
describe('useConfig', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.spyOn(useAppStore, 'getState').mockReturnValue({
appDetail: { id: 'app-1' },
} as never)
routeParams.appId = 'app-1'
mockRequest.mockReset()
mockUseNodesReadOnly.mockReturnValue({ nodesReadOnly: false })
mockIsVarUsedInNodes.mockReturnValue(false)
})
Expand All @@ -102,7 +105,7 @@ describe('useConfig', () => {
],
})
mockIsVarUsedInNodes.mockImplementation(([_, variable]) => variable === 'payload')
const { result } = renderHook(() => useConfig('webhook-node', payload))
const { result } = renderHookWithConsoleQuery(() => useConfig('webhook-node', payload))

result.current.handleMethodChange('GET')
result.current.handleContentTypeChange('text/plain')
Expand Down Expand Up @@ -145,7 +148,7 @@ describe('useConfig', () => {
},
],
})
const { result } = renderHook(() => useConfig('webhook-node', payload))
const { result } = renderHookWithConsoleQuery(() => useConfig('webhook-node', payload))

result.current.handleParamsChange([{ name: 'page', type: VarType.number, required: true }])
result.current.handleHeadersChange([{ name: 'x-request-id', required: false }])
Expand Down Expand Up @@ -192,20 +195,27 @@ describe('useConfig', () => {
})

it('should generate webhook urls once and fall back to empty url on request failure', async () => {
mockedFetchWebhookUrl.mockResolvedValueOnce({
mockRequest.mockResolvedValueOnce({
webhook_url: 'https://example.com/hook',
webhook_debug_url: 'https://example.com/debug',
} as never)
mockedFetchWebhookUrl.mockRejectedValueOnce(new Error('boom'))
mockRequest.mockRejectedValueOnce(new Error('boom'))

const { result, rerender } = renderHook(({ payload }) => useConfig('webhook-node', payload), {
initialProps: {
payload: createPayload(),
const { result, rerender } = renderHookWithConsoleQuery(
({ payload }) => useConfig('webhook-node', payload),
{
initialProps: {
payload: createPayload(),
},
},
})
)

await result.current.generateWebhookUrl()
expect(mockedFetchWebhookUrl).toHaveBeenCalledWith({ appId: 'app-1', nodeId: 'webhook-node' })
expect(mockRequest).toHaveBeenCalledWith(
['apps', 'byAppId', 'workflows', 'triggers', 'webhook', 'get'],
{ params: { app_id: 'app-1' }, query: { node_id: 'webhook-node' } },
expect.any(Object),
)
expect(mockSetInputs).toHaveBeenCalledWith(
expect.objectContaining({
webhook_url: 'https://example.com/hook',
Expand All @@ -227,22 +237,20 @@ describe('useConfig', () => {
payload: createPayload({ webhook_url: 'https://already-exists' }),
})
await result.current.generateWebhookUrl()
expect(mockedFetchWebhookUrl).toHaveBeenCalledTimes(2)
expect(mockRequest).toHaveBeenCalledTimes(2)
})

it('should expose readonly state and skip url generation without app id', async () => {
mockUseNodesReadOnly.mockReturnValue({ nodesReadOnly: true })
vi.spyOn(useAppStore, 'getState').mockReturnValue({
appDetail: undefined,
} as never)
routeParams.appId = undefined

const { result } = renderHook(() => useConfig('webhook-node', createPayload()))
const { result } = renderHookWithConsoleQuery(() => useConfig('webhook-node', createPayload()))

expect(result.current.readOnly).toBe(true)

await result.current.generateWebhookUrl()

expect(mockedFetchWebhookUrl).not.toHaveBeenCalled()
expect(mockRequest).not.toHaveBeenCalled()
expect(mockSetInputs).not.toHaveBeenCalled()
})
})
18 changes: 13 additions & 5 deletions web/app/components/workflow/nodes/trigger-webhook/use-config.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import type { SelectorParam } from 'i18next'
import type { HttpMethod, WebhookHeader, WebhookParameter, WebhookTriggerNodeType } from './types'
import { useQueryClient } from '@tanstack/react-query'
import { useCallback } from 'react'
import { useTranslation } from 'react-i18next'
import { useStore as useAppStore } from '@/app/components/app/store'
import useNodeCrud from '@/app/components/workflow/nodes/_base/hooks/use-node-crud'
import { toast } from '@/app/notifications'
import { fetchWebhookUrl } from '@/service/apps'
import { useParams } from '@/next/navigation'
import { consoleQuery } from '@/service/console'
import { useNodesReadOnly, useWorkflow } from '../../hooks/use-workflow'
import {
updateContentType,
Expand Down Expand Up @@ -34,7 +35,8 @@ export const useConfig = (id: string, payload: WebhookTriggerNodeType) => {
const { t } = useTranslation(['appDebug'])
const { nodesReadOnly: readOnly } = useNodesReadOnly()
const { inputs, setInputs } = useNodeCrud<WebhookTriggerNodeType>(id, payload)
const appId = useAppStore.getState().appDetail?.id
const { appId } = useParams<{ appId?: string }>()
const queryClient = useQueryClient()
const { isVarUsedInNodes, removeUsedVarInNodes } = useWorkflow()

const notifyVarError = useCallback(
Expand Down Expand Up @@ -153,13 +155,19 @@ export const useConfig = (id: string, payload: WebhookTriggerNodeType) => {
if (!appId) return

try {
const response = await fetchWebhookUrl({ appId, nodeId: id })
const response = await queryClient.query(
consoleQuery.apps.byAppId.workflows.triggers.webhook.get.queryOptions({
input: { params: { app_id: appId }, query: { node_id: id } },
staleTime: 0,
retry: false,
}),
)
setInputs(updateWebhookUrls(inputs, response.webhook_url, response.webhook_debug_url))
} catch (error: unknown) {
console.error('Failed to generate webhook URL:', error)
setInputs(updateWebhookUrls(inputs, ''))
}
}, [appId, id, inputs, setInputs])
}, [appId, id, inputs, setInputs, queryClient])

return {
readOnly,
Expand Down
Loading
Loading