Skip to content

armgit / dify

Public Imported from GitHub
0

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

refactor(workflow): use route identity and Console Query for webhook URLs (#44135)

yyhe389b86319cb
diff --git a/oxlint-suppressions.json b/oxlint-suppressions.json
index 07a243395ce..84afe06531e 100644
--- a/oxlint-suppressions.json
+++ b/oxlint-suppressions.json
@@ -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
@@ -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
@@ -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
diff --git a/web/app/components/workflow/hooks/__tests__/use-auto-generate-webhook-url.spec.ts b/web/app/components/workflow/hooks/__tests__/use-auto-generate-webhook-url.spec.ts
index 1e536ae0e37..6de78fb9557 100644
--- a/web/app/components/workflow/hooks/__tests__/use-auto-generate-webhook-url.spec.ts
+++ b/web/app/components/workflow/hooks/__tests__/use-auto-generate-webhook-url.spec.ts
@@ -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', () => {
@@ -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',
})
@@ -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
@@ -74,6 +82,32 @@ 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()
@@ -81,7 +115,7 @@ describe('useAutoGenerateWebhookUrl', () => {
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
@@ -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 () => {
@@ -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()
diff --git a/web/app/components/workflow/hooks/use-auto-generate-webhook-url.ts b/web/app/components/workflow/hooks/use-auto-generate-webhook-url.ts
index 7794ab3260b..5b2fe32e56a 100644
--- a/web/app/components/workflow/hooks/use-auto-generate-webhook-url.ts
+++ b/web/app/components/workflow/hooks/use-auto-generate-webhook-url.ts
@@ -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()
@@ -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) => {
@@ -40,6 +48,6 @@ export const useAutoGenerateWebhookUrl = () => {
console.error('Failed to auto-generate webhook URL:', error)
}
},
- [collaborativeWorkflow],
+ [appId, collaborativeWorkflow, queryClient],
)
}
diff --git a/web/app/components/workflow/nodes/agent-v2/__tests__/node.spec.tsx b/web/app/components/workflow/nodes/agent-v2/__tests__/node.spec.tsx
index 034ef3935d3..28b2fa4f5fd 100644
--- a/web/app/components/workflow/nodes/agent-v2/__tests__/node.spec.tsx
+++ b/web/app/components/workflow/nodes/agent-v2/__tests__/node.spec.tsx
@@ -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,
diff --git a/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-output-routes-history.spec.tsx b/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-output-routes-history.spec.tsx
index ce0477b676a..ea9090f1c51 100644
--- a/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-output-routes-history.spec.tsx
+++ b/web/app/components/workflow/nodes/agent-v2/components/__tests__/agent-output-routes-history.spec.tsx
@@ -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: [] }),
}))
diff --git a/web/app/components/workflow/nodes/trigger-webhook/__tests__/use-config.spec.tsx b/web/app/components/workflow/nodes/trigger-webhook/__tests__/use-config.spec.tsx
index afd7c069518..0cbe43f7829 100644
--- a/web/app/components/workflow/nodes/trigger-webhook/__tests__/use-config.spec.tsx
+++ b/web/app/components/workflow/nodes/trigger-webhook/__tests__/use-config.spec.tsx
@@ -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'
@@ -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 = (
@@ -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)
})
@@ -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')
@@ -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 }])
@@ -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',
@@ -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()
})
})
diff --git a/web/app/components/workflow/nodes/trigger-webhook/use-config.ts b/web/app/components/workflow/nodes/trigger-webhook/use-config.ts
index c1e7509d857..fa6c011a6fc 100644
--- a/web/app/components/workflow/nodes/trigger-webhook/use-config.ts
+++ b/web/app/components/workflow/nodes/trigger-webhook/use-config.ts
@@ -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,
@@ -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(
@@ -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,
diff --git a/web/models/app.ts b/web/models/app.ts
index 80d8d7f78c1..542b07de050 100644
--- a/web/models/app.ts
+++ b/web/models/app.ts
@@ -61,12 +61,3 @@ export type TracingConfig = {
| AliyunConfig
| TencentConfig
}
-
-export type WebhookTriggerResponse = {
- id: string
- webhook_id: string
- webhook_url: string
- webhook_debug_url: string
- node_id: string
- created_at: string
-}
diff --git a/web/service/apps.ts b/web/service/apps.ts
index ceaf120fa79..ffd82e1efaa 100644
--- a/web/service/apps.ts
+++ b/web/service/apps.ts
@@ -1,5 +1,5 @@
import type { TracingProvider } from '@/app/(commonLayout)/app/(appDetailLayout)/[appId]/overview/tracing/type'
-import type { TracingConfig, TracingStatus, WebhookTriggerResponse } from '@/models/app'
+import type { TracingConfig, TracingStatus } from '@/models/app'
import type { CommonResponse } from '@/models/common'
import { del, get, patch, post } from './base'
@@ -18,21 +18,6 @@ export const updateTracingStatus = ({
return post<CommonResponse>(`/apps/${appId}/trace`, { body })
}
-// Webhook Trigger
-export const fetchWebhookUrl = ({
- appId,
- nodeId,
-}: {
- appId: string
- nodeId: string
-}): Promise<WebhookTriggerResponse> => {
- return get<WebhookTriggerResponse>(
- `apps/${appId}/workflows/triggers/webhook`,
- { params: { node_id: nodeId } },
- { silent: true },
- )
-}
-
export const fetchTracingConfig = ({
appId,
provider,