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.

test(web): exercise inspector, credential and workflow state owners (#44733)

Stephen Zhouf763ab94679c
diff --git a/web/app/components/plugins/plugin-auth/__tests__/plugin-auth.spec.tsx b/web/app/components/plugins/plugin-auth/__tests__/plugin-auth.spec.tsx
index 64a4c70a0fb..95a763eb22f 100644
--- a/web/app/components/plugins/plugin-auth/__tests__/plugin-auth.spec.tsx
+++ b/web/app/components/plugins/plugin-auth/__tests__/plugin-auth.spec.tsx
@@ -1,157 +1,109 @@
+import type { Credential } from '../types'
+import type { ConsoleQueryTestOptions } from '@/test/console/query-data'
import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
-import { render as renderWithoutUrlState } from '@/test/console/render'
-import { createNuqsTestRenderer } from '@/test/nuqs-testing'
+import { NuqsTestingAdapter } from 'nuqs/adapters/testing'
+import { renderWithConsoleQuery } from '@/test/console/query-data'
import PluginAuth from '../plugin-auth'
-import { AuthCategory } from '../types'
+import { AuthCategory, CredentialTypeEnum } from '../types'
-const mockUsePluginAuth = vi.fn()
-const mockConsoleState = vi.hoisted(() => ({
- workspacePermissionKeys: ['credential.use', 'credential.create', 'credential.manage'] as string[],
+const requests = vi.hoisted(() => ({ credentials: vi.fn() }))
+vi.mock('@/service/base', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/service/base')>()),
+ get: requests.credentials,
}))
-vi.mock('../hooks/use-plugin-auth', () => ({
- usePluginAuth: (...args: unknown[]) => mockUsePluginAuth(...args),
-}))
-
-vi.mock('../authorized', () => ({
- default: ({ pluginPayload }: { pluginPayload: { provider: string } }) => (
- <div data-testid="authorized">
- Authorized:
- {pluginPayload.provider}
- </div>
- ),
-}))
-
-vi.mock('@/context/permission-state', async () => {
- const { createPermissionStateModuleMock } = await import('@/test/console/state-fixture')
- return createPermissionStateModuleMock(() => ({
- workspacePermissionKeys: mockConsoleState.workspacePermissionKeys,
- }))
-})
-
-const defaultPayload = {
- category: AuthCategory.tool,
+const defaultPayload = { category: AuthCategory.tool, provider: 'test-provider' }
+const credential: Credential = {
+ id: 'key-1',
+ name: 'Production key',
provider: 'test-provider',
+ credential_type: CredentialTypeEnum.API_KEY,
+ is_default: true,
+ credentials: { api_key: 'masked-secret' },
}
-
+const credentialInfo = (credentials: Credential[] = [], allowCustomToken = true) => ({
+ credentials,
+ supported_credential_types: [CredentialTypeEnum.API_KEY],
+ allow_custom_token: allowCustomToken,
+ is_oauth_custom_client_enabled: false,
+})
const onUrlUpdate = vi.fn()
-const render = createNuqsTestRenderer(renderWithoutUrlState, () => ({ onUrlUpdate }))
-
-describe('PluginAuth', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- mockConsoleState.workspacePermissionKeys = [
- 'credential.use',
- 'credential.create',
- 'credential.manage',
- ]
- })
-
- it('renders Authorize component when not authorized', () => {
- mockUsePluginAuth.mockReturnValue({
- isAuthorized: false,
- canOAuth: false,
- canApiKey: true,
- credentials: [],
- invalidPluginCredentialInfo: vi.fn(),
- notAllowCustomCredential: false,
- })
-
- render(<PluginAuth pluginPayload={defaultPayload} />)
- expect(mockUsePluginAuth).toHaveBeenCalledWith(defaultPayload, true)
- expect(screen.getByRole('button', { name: 'plugin.auth.useApiAuth' })).toBeEnabled()
- expect(screen.queryByText('plugin.auth.permissionHint.title')).not.toBeInTheDocument()
- expect(screen.queryByTestId('authorized')).not.toBeInTheDocument()
- })
-
- it('renders Authorized component when authorized and no children', () => {
- mockUsePluginAuth.mockReturnValue({
- isAuthorized: true,
- canOAuth: true,
- canApiKey: true,
- credentials: [{ id: '1', name: 'key', is_default: true, provider: 'test' }],
- invalidPluginCredentialInfo: vi.fn(),
- notAllowCustomCredential: false,
- })
-
- render(<PluginAuth pluginPayload={defaultPayload} />)
- expect(screen.getByTestId('authorized')).toBeInTheDocument()
- expect(screen.queryByRole('button', { name: 'plugin.auth.useApiAuth' })).not.toBeInTheDocument()
- })
-
- it('renders children when authorized and children provided', () => {
- mockUsePluginAuth.mockReturnValue({
- isAuthorized: true,
- canOAuth: false,
- canApiKey: true,
- credentials: [{ id: '1', name: 'key', is_default: true, provider: 'test' }],
- invalidPluginCredentialInfo: vi.fn(),
- notAllowCustomCredential: false,
- })
-
- render(
- <PluginAuth pluginPayload={defaultPayload}>
- <div data-testid="custom-children">Custom Content</div>
- </PluginAuth>,
- )
- expect(screen.getByTestId('custom-children')).toBeInTheDocument()
- expect(screen.queryByTestId('authorized')).not.toBeInTheDocument()
- })
-
- it('disables authorization without credential.create and links to members settings', async () => {
- const user = userEvent.setup()
- mockConsoleState.workspacePermissionKeys = ['credential.use']
- mockUsePluginAuth.mockReturnValue({
- isAuthorized: false,
- canOAuth: false,
- canApiKey: true,
- credentials: [],
- invalidPluginCredentialInfo: vi.fn(),
- notAllowCustomCredential: false,
- })
-
- render(<PluginAuth pluginPayload={defaultPayload} />)
-
- expect(screen.getByRole('button', { name: 'plugin.auth.useApiAuth' })).toBeDisabled()
- expect(screen.getByText('plugin.auth.permissionHint.title')).toBeInTheDocument()
- expect(screen.getByText('plugin.auth.permissionHint.description')).toBeInTheDocument()
- await user.click(screen.getByRole('button', { name: 'plugin.auth.permissionHint.action' }))
- await waitFor(() =>
- expect(onUrlUpdate.mock.lastCall?.[0].searchParams.get('settings')).toBe('members'),
- )
- })
+const renderAuth = (
+ options: ConsoleQueryTestOptions = {},
+ props: Partial<React.ComponentProps<typeof PluginAuth>> = {},
+) =>
+ renderWithConsoleQuery(
+ <NuqsTestingAdapter onUrlUpdate={onUrlUpdate}>
+ <PluginAuth pluginPayload={defaultPayload} {...props} />
+ </NuqsTestingAdapter>,
+ {
+ workspacePermissionKeys: ['credential.use', 'credential.create', 'credential.manage'],
+ systemFeatures: { rbac_enabled: true },
+ ...options,
+ },
+ )
+
+beforeEach(() => {
+ requests.credentials.mockResolvedValue(credentialInfo())
+})
- it('does not render permission hint for datasource authorization', () => {
- mockConsoleState.workspacePermissionKeys = ['credential.use']
- mockUsePluginAuth.mockReturnValue({
- isAuthorized: false,
- canOAuth: false,
- canApiKey: true,
- credentials: [],
- invalidPluginCredentialInfo: vi.fn(),
- notAllowCustomCredential: false,
- })
+it('offers API authorization when the provider has no saved credentials', async () => {
+ renderAuth()
+ expect(await screen.findByRole('button', { name: 'plugin.auth.useApiAuth' })).toBeEnabled()
+ expect(requests.credentials).toHaveBeenCalledWith(
+ '/workspaces/current/tool-provider/builtin/test-provider/credential/info',
+ )
+ expect(screen.queryByText('plugin.auth.permissionHint.title')).not.toBeInTheDocument()
+ expect(
+ screen.queryByRole('button', { name: /plugin.auth.authorization$/ }),
+ ).not.toBeInTheDocument()
+})
- render(<PluginAuth pluginPayload={{ ...defaultPayload, category: AuthCategory.datasource }} />)
+it('opens the saved credentials when the provider is authorized', async () => {
+ const user = userEvent.setup()
+ requests.credentials.mockResolvedValue(credentialInfo([credential]))
+ renderAuth()
+ const trigger = await screen.findByRole('button', { name: /1.*plugin.auth.authorization/ })
+ expect(screen.queryByRole('button', { name: 'plugin.auth.useApiAuth' })).not.toBeInTheDocument()
+ await user.click(trigger)
+ expect(await screen.findByText('Production key')).toBeVisible()
+})
- expect(screen.queryByText('plugin.auth.permissionHint.title')).not.toBeInTheDocument()
- })
+it('renders the caller content when the provider is authorized', async () => {
+ requests.credentials.mockResolvedValue(credentialInfo([credential]))
+ renderAuth({}, { children: <div>Custom Content</div> })
+ expect(await screen.findByText('Custom Content')).toBeVisible()
+ expect(
+ screen.queryByRole('button', { name: /plugin.auth.authorization$/ }),
+ ).not.toBeInTheDocument()
+})
- it('does not render permission hint when custom credentials are unavailable', () => {
- mockConsoleState.workspacePermissionKeys = ['credential.use']
- mockUsePluginAuth.mockReturnValue({
- isAuthorized: false,
- canOAuth: false,
- canApiKey: true,
- credentials: [],
- invalidPluginCredentialInfo: vi.fn(),
- notAllowCustomCredential: true,
- })
+it('disables authorization without credential.create and links to members settings', async () => {
+ const user = userEvent.setup()
+ renderAuth({ workspacePermissionKeys: ['credential.use'] })
+ expect(await screen.findByRole('button', { name: 'plugin.auth.useApiAuth' })).toBeDisabled()
+ expect(screen.getByText('plugin.auth.permissionHint.title')).toBeVisible()
+ expect(screen.getByText('plugin.auth.permissionHint.description')).toBeVisible()
+ await user.click(screen.getByRole('button', { name: 'plugin.auth.permissionHint.action' }))
+ await waitFor(() =>
+ expect(onUrlUpdate.mock.lastCall?.[0].searchParams.get('settings')).toBe('members'),
+ )
+})
- render(<PluginAuth pluginPayload={defaultPayload} />)
+it('does not offer tool credential permissions for a datasource', () => {
+ renderAuth(
+ { workspacePermissionKeys: ['credential.use'] },
+ { pluginPayload: { ...defaultPayload, category: AuthCategory.datasource } },
+ )
+ expect(screen.queryByText('plugin.auth.permissionHint.title')).not.toBeInTheDocument()
+ expect(screen.queryByRole('button', { name: 'plugin.auth.useApiAuth' })).not.toBeInTheDocument()
+ expect(requests.credentials).not.toHaveBeenCalled()
+})
- expect(screen.queryByText('plugin.auth.permissionHint.title')).not.toBeInTheDocument()
- })
+it('disables custom credentials without a permission hint when the provider forbids them', async () => {
+ requests.credentials.mockResolvedValue(credentialInfo([], false))
+ renderAuth({ workspacePermissionKeys: ['credential.use'] })
+ expect(await screen.findByRole('button', { name: 'plugin.auth.useApiAuth' })).toBeDisabled()
+ expect(screen.queryByText('plugin.auth.permissionHint.title')).not.toBeInTheDocument()
})
diff --git a/web/app/components/workflow/hooks/__tests__/use-workflow-comment.spec.ts b/web/app/components/workflow/hooks/__tests__/use-workflow-comment.spec.ts
index 32c5d6d2e14..9d7a7d53b2c 100644
--- a/web/app/components/workflow/hooks/__tests__/use-workflow-comment.spec.ts
+++ b/web/app/components/workflow/hooks/__tests__/use-workflow-comment.spec.ts
@@ -3,18 +3,14 @@ import type {
WorkflowCommentDetail,
} from '@dify/contracts/api/console/apps/types.gen'
import { act, waitFor } from '@testing-library/react'
+import { useReactFlow } from 'reactflow'
import { seedAccountProfileQuery } from '@/test/console/account-profile'
import { createConsoleQueryClient, seedSystemFeatures } from '@/test/console/query-data'
-import { renderWorkflowHook } from '../../__tests__/workflow-test-env'
+import { createNode } from '../../__tests__/fixtures'
+import { renderWorkflowFlowHook } from '../../__tests__/workflow-test-env'
import { ControlMode } from '../../types'
import { useWorkflowComment } from '../use-workflow-comment'
-const mockScreenToFlowPosition = vi.hoisted(() =>
- vi.fn(({ x, y }: { x: number; y: number }) => ({ x: x - 90, y: y - 180 })),
-)
-const mockSetCenter = vi.hoisted(() => vi.fn())
-const mockGetNodes = vi.hoisted(() => vi.fn(() => []))
-
const mockCreateWorkflowComment = vi.hoisted(() => vi.fn())
const mockCreateWorkflowCommentReply = vi.hoisted(() => vi.fn())
const mockDeleteWorkflowComment = vi.hoisted(() => vi.fn())
@@ -43,14 +39,6 @@ const mockConsoleState = vi.hoisted(() => ({
},
}))
-vi.mock('reactflow', () => ({
- useReactFlow: () => ({
- screenToFlowPosition: mockScreenToFlowPosition,
- setCenter: mockSetCenter,
- getNodes: mockGetNodes,
- }),
-}))
-
vi.mock('@/service/console', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/service/console')>()
const { withConsoleClientResponses } = await import('@/test/console/service-responses')
@@ -130,6 +118,14 @@ const createSeededQueryClient = () => {
return queryClient
}
+const useCommentCanvas = () => ({ ...useWorkflowComment(), flow: useReactFlow() })
+
+const renderWorkflowHook: typeof renderWorkflowFlowHook = (hook, options) =>
+ renderWorkflowFlowHook(hook, {
+ ...options,
+ reactFlowProps: { fitView: false, defaultViewport: { x: 80, y: 160, zoom: 2 } },
+ })
+
describe('useWorkflowComment', () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -143,7 +139,6 @@ describe('useWorkflowComment', () => {
created_at: 1700000000,
})
mockUpdateWorkflowComment.mockResolvedValue({})
- mockGetNodes.mockReturnValue([])
mockCreateWorkflowCommentReply.mockResolvedValue({})
mockUpdateWorkflowCommentReply.mockResolvedValue({})
mockDeleteWorkflowCommentReply.mockResolvedValue({})
@@ -151,11 +146,13 @@ describe('useWorkflowComment', () => {
mockDeleteWorkflowComment.mockResolvedValue({})
})
+ afterEach(() => vi.unstubAllGlobals())
+
it('loads comment list on mount when collaboration is enabled', async () => {
const comment = baseComment()
mockFetchWorkflowComments.mockResolvedValue({ data: [comment] })
- const { store } = renderWorkflowHook(() => useWorkflowComment(), {
+ const { store } = renderWorkflowHook(useCommentCanvas, {
queryClient: createSeededQueryClient(),
})
@@ -172,7 +169,7 @@ describe('useWorkflowComment', () => {
it('does not load comment list when collaboration is disabled', async () => {
globalFeatureState.enableCollaboration = false
- renderWorkflowHook(() => useWorkflowComment(), {
+ renderWorkflowHook(useCommentCanvas, {
queryClient: createSeededQueryClient(),
})
@@ -182,11 +179,11 @@ describe('useWorkflowComment', () => {
})
it('creates a comment, updates local cache, and emits collaboration sync', async () => {
- const { result, store } = renderWorkflowHook(() => useWorkflowComment(), {
+ const { result, store } = renderWorkflowHook(useCommentCanvas, {
queryClient: createSeededQueryClient(),
initialStoreState: {
comments: [],
- pendingComment: { pageX: 100, pageY: 200, elementX: 10, elementY: 20 },
+ pendingComment: { pageX: 100, pageY: 200, elementX: 100, elementY: 200 },
isCommentQuickAdd: true,
mentionableUsersCache: {
'app-1': [
@@ -242,11 +239,11 @@ describe('useWorkflowComment', () => {
created_at: '1700001234',
})
- const { result, store } = renderWorkflowHook(() => useWorkflowComment(), {
+ const { result, store } = renderWorkflowHook(useCommentCanvas, {
queryClient: createSeededQueryClient(),
initialStoreState: {
comments: [],
- pendingComment: { pageX: 100, pageY: 200, elementX: 10, elementY: 20 },
+ pendingComment: { pageX: 100, pageY: 200, elementX: 100, elementY: 200 },
isCommentQuickAdd: true,
},
})
@@ -269,11 +266,11 @@ describe('useWorkflowComment', () => {
created_at: createdAt,
})
- const { result, store } = renderWorkflowHook(() => useWorkflowComment(), {
+ const { result, store } = renderWorkflowHook(useCommentCanvas, {
queryClient: createSeededQueryClient(),
initialStoreState: {
comments: [],
- pendingComment: { pageX: 100, pageY: 200, elementX: 10, elementY: 20 },
+ pendingComment: { pageX: 100, pageY: 200, elementX: 100, elementY: 200 },
isCommentQuickAdd: true,
mentionableUsersCache: {
'app-1': [
@@ -320,7 +317,7 @@ describe('useWorkflowComment', () => {
const commentDetail = baseCommentDetail()
mockUpdateWorkflowComment.mockRejectedValue(new Error('update failed'))
- const { result, store } = renderWorkflowHook(() => useWorkflowComment(), {
+ const { result, store } = renderWorkflowHook(useCommentCanvas, {
queryClient: createSeededQueryClient(),
initialStoreState: {
comments: [comment],
@@ -364,7 +361,7 @@ describe('useWorkflowComment', () => {
mockFetchWorkflowComments.mockResolvedValue({ data: [comment] })
mockFetchWorkflowComment.mockResolvedValue(detail)
- const { unmount, result } = renderWorkflowHook(() => useWorkflowComment(), {
+ const { unmount, result } = renderWorkflowHook(useCommentCanvas, {
queryClient: createSeededQueryClient(),
initialStoreState: {
activeCommentId: comment.id,
@@ -394,6 +391,7 @@ describe('useWorkflowComment', () => {
})
it('focuses comment thread, loads detail, and updates navigation/create/close states', async () => {
+ vi.stubGlobal('innerWidth', 1600)
const commentA = baseComment()
const commentB: WorkflowCommentBasic = {
...baseComment(),
@@ -402,7 +400,6 @@ describe('useWorkflowComment', () => {
position_x: 50,
position_y: 80,
}
- mockGetNodes.mockReturnValue([{ id: 'node-1', data: { selected: true } }] as never)
mockFetchWorkflowComment.mockResolvedValue({
...baseCommentDetail(),
id: commentB.id,
@@ -411,14 +408,15 @@ describe('useWorkflowComment', () => {
position_y: commentB.position_y,
})
- const { result, store } = renderWorkflowHook(() => useWorkflowComment(), {
+ const { result, store } = renderWorkflowHook(useCommentCanvas, {
queryClient: createSeededQueryClient(),
+ nodes: [createNode({ id: 'node-1', data: { selected: true } })],
initialStoreState: {
comments: [commentA, commentB],
commentDetailCache: {
[commentA.id]: baseCommentDetail(),
},
- rightPanelWidth: 800,
+ rightPanelWidth: 0,
nodePanelWidth: 300,
controlMode: ControlMode.Comment,
activeCommentId: commentA.id,
@@ -433,7 +431,10 @@ describe('useWorkflowComment', () => {
await waitFor(() => {
expect(store.getState().activeCommentId).toBe(commentB.id)
})
- expect(mockSetCenter).toHaveBeenCalledWith(502, 80, { zoom: 1, duration: 600 })
+ await waitFor(() =>
+ expect(result.current.flow.getViewport()).toEqual({ x: -380, y: 170, zoom: 1 }),
+ )
+ expect(result.current.activeComment?.content).toBe('second detail')
act(() => {
result.current.handleCreateComment({
@@ -476,7 +477,7 @@ describe('useWorkflowComment', () => {
position_y: commentB.position_y,
})
- const { result, store } = renderWorkflowHook(() => useWorkflowComment(), {
+ const { result, store } = renderWorkflowHook(useCommentCanvas, {
queryClient: createSeededQueryClient(),
initialStoreState: {
comments: [commentA, commentB],
@@ -532,7 +533,7 @@ describe('useWorkflowComment', () => {
})
it('does not update a reply when the content is blank', async () => {
- const { result } = renderWorkflowHook(() => useWorkflowComment(), {
+ const { result } = renderWorkflowHook(useCommentCanvas, {
queryClient: createSeededQueryClient(),
})
@@ -558,7 +559,7 @@ describe('useWorkflowComment', () => {
rejectRequest = reject
}),
)
- const { result } = renderWorkflowHook(() => useWorkflowComment(), {
+ const { result } = renderWorkflowHook(useCommentCanvas, {
queryClient: createSeededQueryClient(),
})
await waitFor(() => expect(result.current.loading).toBe(false))
@@ -610,7 +611,7 @@ describe('useWorkflowComment', () => {
resolveSecond = resolve
}),
)
- const { result } = renderWorkflowHook(() => useWorkflowComment(), {
+ const { result } = renderWorkflowHook(useCommentCanvas, {
queryClient: createSeededQueryClient(),
})
let firstRequest!: Promise<void>
@@ -635,8 +636,8 @@ describe('useWorkflowComment', () => {
expect(result.current.activeCommentLoading).toBe(false)
})
- it('ignores navigation when no active comment or active comment is absent from the list', () => {
- const { result } = renderWorkflowHook(() => useWorkflowComment(), {
+ it('ignores navigation when no active comment or active comment is absent from the list', async () => {
+ const { result } = renderWorkflowHook(useCommentCanvas, {
queryClient: createSeededQueryClient(),
initialStoreState: {
comments: [baseComment()],
@@ -647,23 +648,25 @@ describe('useWorkflowComment', () => {
result.current.handleCommentNavigate('next')
})
- expect(mockSetCenter).not.toHaveBeenCalled()
+ expect(result.current.flow.getViewport()).toEqual({ x: 80, y: 160, zoom: 2 })
- act(() => {
- result.current.handleCommentIconClick({ ...baseComment(), id: 'missing-comment' })
+ await act(async () => {
+ await result.current.handleCommentIconClick({ ...baseComment(), id: 'missing-comment' })
})
-
- mockSetCenter.mockClear()
+ await waitFor(() =>
+ expect(result.current.flow.getViewport()).toEqual({ x: 20, y: 230, zoom: 1 }),
+ )
+ const viewport = result.current.flow.getViewport()
act(() => {
result.current.handleCommentNavigate('next')
})
- expect(mockSetCenter).not.toHaveBeenCalled()
+ expect(result.current.flow.getViewport()).toEqual(viewport)
})
it('clears a pending comment when comment mode is left outside quick add', () => {
- const { store } = renderWorkflowHook(() => useWorkflowComment(), {
+ const { store } = renderWorkflowHook(useCommentCanvas, {
queryClient: createSeededQueryClient(),
initialStoreState: {
controlMode: ControlMode.Pointer,
@@ -696,7 +699,7 @@ describe('useWorkflowComment', () => {
data: [{ ...commentA, resolved: true }, commentB],
})
- const { result, store } = renderWorkflowHook(() => useWorkflowComment(), {
+ const { result, store } = renderWorkflowHook(useCommentCanvas, {
queryClient: createSeededQueryClient(),
initialStoreState: {
comments: [commentA, commentB],
@@ -722,12 +725,16 @@ describe('useWorkflowComment', () => {
content: 'refreshed content',
})
- const { result, store } = renderWorkflowHook(() => useWorkflowComment(), {
+ const { result, store } = renderWorkflowHook(useCommentCanvas, {
queryClient: createSeededQueryClient(),
initialStoreState: {
comments: [commentA],
activeCommentId: commentA.id,
- activeCommentDetail: { ...baseCommentDetail(), id: commentA.id, content: 'stale content' },
+ activeCommentDetail: {
+ ...baseCommentDetail(),
+ id: commentA.id,
+ content: 'stale content',
+ },
},
})
diff --git a/web/app/components/workflow/hooks/__tests__/use-workflow-update.spec.tsx b/web/app/components/workflow/hooks/__tests__/use-workflow-update.spec.tsx
index 99c6d006da6..a5c39b2ad29 100644
--- a/web/app/components/workflow/hooks/__tests__/use-workflow-update.spec.tsx
+++ b/web/app/components/workflow/hooks/__tests__/use-workflow-update.spec.tsx
@@ -1,59 +1,59 @@
-import { act } from '@testing-library/react'
-import { createNode } from '../../__tests__/fixtures'
-import { renderWorkflowHook } from '../../__tests__/workflow-test-env'
+import { act, waitFor } from '@testing-library/react'
+import { useState } from 'react'
+import { useReactFlow } from 'reactflow'
+import { useEventEmitterContextContext } from '@/context/event-emitter'
+import { EventEmitterContextProvider } from '@/context/event-emitter-provider'
+import { createEdge, createNode } from '../../__tests__/fixtures'
+import { renderWorkflowFlowComponent } from '../../__tests__/workflow-test-env'
+import { WORKFLOW_DATA_UPDATE } from '../../constants'
import { useWorkflowUpdate } from '../use-workflow-update'
-const mockSetViewport = vi.hoisted(() => vi.fn())
-const mockEventEmit = vi.hoisted(() => vi.fn())
-
-// Viewport animation is a browser boundary; graph initialization stays real.
-vi.mock('reactflow', async (importOriginal) => ({
- ...(await importOriginal<typeof import('reactflow')>()),
- useReactFlow: () => ({ setViewport: mockSetViewport }),
-}))
+function useUpdateProbe() {
+ const [graph, setGraph] = useState<unknown>()
+ const { eventEmitter } = useEventEmitterContextContext()
+ eventEmitter?.useSubscription((event) => {
+ if (typeof event === 'object' && event.type === WORKFLOW_DATA_UPDATE) setGraph(event.payload)
+ })
+ return { ...useWorkflowUpdate(), flow: useReactFlow(), graph }
+}
-vi.mock('@/context/event-emitter', () => ({
- useEventEmitterContextContext: () => ({
- eventEmitter: {
- emit: (...args: unknown[]) => mockEventEmit(...args),
+it('publishes initialized graph data and applies the supplied viewport', async () => {
+ const result = {} as { current: ReturnType<typeof useUpdateProbe> }
+ function Probe() {
+ result.current = useUpdateProbe()
+ return null
+ }
+ renderWorkflowFlowComponent(
+ <EventEmitterContextProvider>
+ <Probe />
+ </EventEmitterContextProvider>,
+ {
+ reactFlowProps: { fitView: false, defaultViewport: { x: 80, y: 40, zoom: 1.5 } },
},
- }),
-}))
-
-describe('useWorkflowUpdate', () => {
- it('emits initialized data and only sets a valid viewport', () => {
- const { result } = renderWorkflowHook(() => useWorkflowUpdate())
-
- act(() => {
- result.current.handleUpdateWorkflowCanvas({
- nodes: [createNode({ id: 'n1' })],
- edges: [],
- viewport: { x: 10, y: 20, zoom: 0.5 },
- })
- result.current.handleUpdateWorkflowCanvas({
- nodes: [],
- edges: [],
- viewport: { x: 'bad' } as never,
- })
- })
+ )
+ await waitFor(() => expect(result.current.flow.viewportInitialized).toBe(true))
- expect(mockEventEmit).toHaveBeenCalledWith(
- expect.objectContaining({
- type: 'WORKFLOW_DATA_UPDATE',
- payload: expect.objectContaining({
- nodes: [
- expect.objectContaining({
- id: 'n1',
- data: expect.objectContaining({
- _connectedSourceHandleIds: [],
- _connectedTargetHandleIds: [],
- }),
- }),
- ],
- }),
- }),
- )
- expect(mockSetViewport).toHaveBeenCalledTimes(1)
- expect(mockSetViewport).toHaveBeenCalledWith({ x: 10, y: 20, zoom: 0.5 })
+ act(() =>
+ result.current.handleUpdateWorkflowCanvas({
+ nodes: [createNode({ id: 'source' }), createNode({ id: 'target' })],
+ edges: [createEdge({ id: 'edge', source: 'source', target: 'target' })],
+ viewport: { x: 10, y: 20, zoom: 0.5 },
+ }),
+ )
+ await waitFor(() =>
+ expect(result.current.flow.getViewport()).toEqual({ x: 10, y: 20, zoom: 0.5 }),
+ )
+ expect(result.current.graph).toMatchObject({
+ nodes: [
+ {
+ id: 'source',
+ data: { _connectedSourceHandleIds: ['source'], _connectedTargetHandleIds: [] },
+ },
+ {
+ id: 'target',
+ data: { _connectedSourceHandleIds: [], _connectedTargetHandleIds: ['target'] },
+ },
+ ],
+ edges: [{ id: 'edge', source: 'source', target: 'target' }],
})
})
diff --git a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/misc.spec.ts b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/misc.spec.ts
index a8b3d8a50bd..c1062af7ac4 100644
--- a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/misc.spec.ts
+++ b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/misc.spec.ts
@@ -1,6 +1,8 @@
import type { ChatItemInTree } from '@/app/components/base/chat/types'
import { act } from '@testing-library/react'
-import { renderWorkflowHook as renderHook } from '@/app/components/workflow/__tests__/workflow-test-env'
+import { createNode } from '@/app/components/workflow/__tests__/fixtures'
+import { renderWorkflowCanvasHook } from '@/app/components/workflow/__tests__/workflow-test-env'
+import { BlockEnum } from '@/app/components/workflow/types'
import { useChat } from '../../hooks'
const mockHandleRun = vi.fn()
@@ -9,7 +11,6 @@ const mockFetchInspectVars = vi.fn()
const mockInvalidAllLastRun = vi.fn()
const mockSubmitHumanInputForm = vi.fn()
const mockSseGet = vi.fn()
-const mockGetNodes = vi.fn((): { id: string; type: string; data: Record<string, unknown> }[] => [])
vi.mock('@/service/base', () => ({
sseGet: (...args: unknown[]) => mockSseGet(...args),
@@ -32,21 +33,13 @@ vi.mock('@/app/notifications', () => ({
},
}))
-vi.mock('reactflow', () => ({
- useStoreApi: () => ({
- getState: () => ({
- getNodes: mockGetNodes,
- }),
- }),
-}))
-
-vi.mock('../../../../hooks/use-workflow-run', () => ({
- useWorkflowRun: () => ({ handleRun: mockHandleRun }),
-}))
-
-vi.mock('../../../../hooks/use-set-workflow-vars-with-value', () => ({
- useSetWorkflowVarsWithValue: () => ({ fetchInspectVars: mockFetchInspectVars }),
-}))
+// Run transport and inspector loading are supplied by the owning application through
+// the real hooks store; useChat and its facade hooks stay mounted.
+const renderHook: typeof renderWorkflowCanvasHook = (hook, options) =>
+ renderWorkflowCanvasHook(hook, {
+ ...options,
+ hooksStoreProps: { handleRun: mockHandleRun, fetchInspectVars: mockFetchInspectVars },
+ })
const resetMocksAndWorkflowState = () => {
vi.clearAllMocks()
@@ -235,27 +228,25 @@ describe('useChat – handleSubmitHumanInputForm', () => {
describe('useChat – getHumanInputNodeData', () => {
beforeEach(() => {
resetMocksAndWorkflowState()
- mockGetNodes.mockReturnValue([])
})
it('should return the custom node matching the given nodeID', () => {
- const mockNode = { id: 'node-1', type: 'custom', data: { title: 'Human Input' } }
- mockGetNodes.mockReturnValue([
- mockNode,
- { id: 'node-2', type: 'custom', data: { title: 'Other' } },
- ])
+ const mockNode = createNode({
+ id: 'node-1',
+ data: { type: BlockEnum.HumanInput, title: 'Human Input' },
+ })
const { result } = renderHook(() => useChat({}), {
+ nodes: [mockNode, createNode({ id: 'node-2', data: { title: 'Other' } })],
resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },
})
const node = result.current.getHumanInputNodeData('node-1')
- expect(node).toEqual(mockNode)
+ expect(node).toMatchObject(mockNode)
})
it('should return undefined when no matching node', () => {
- mockGetNodes.mockReturnValue([{ id: 'node-2', type: 'custom', data: {} }])
-
const { result } = renderHook(() => useChat({}), {
+ nodes: [createNode({ id: 'node-2' })],
resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },
})
const node = result.current.getHumanInputNodeData('nonexistent')
@@ -263,16 +254,16 @@ describe('useChat – getHumanInputNodeData', () => {
})
it('should filter out non-custom nodes', () => {
- mockGetNodes.mockReturnValue([
- { id: 'node-1', type: 'default', data: {} },
- { id: 'node-1', type: 'custom', data: { found: true } },
- ])
-
+ const customNode = createNode({
+ id: 'custom-node',
+ data: { type: BlockEnum.HumanInput, title: 'Human Input' },
+ })
const { result } = renderHook(() => useChat({}), {
+ nodes: [createNode({ id: 'default-node', type: 'default' }), customNode],
resource: { kind: 'app', appId: 'app-1', mode: 'workflow' },
})
- const node = result.current.getHumanInputNodeData('node-1')
- expect(node).toEqual({ id: 'node-1', type: 'custom', data: { found: true } })
+ expect(result.current.getHumanInputNodeData('default-node')).toBeUndefined()
+ expect(result.current.getHumanInputNodeData('custom-node')).toMatchObject(customNode)
})
})
diff --git a/web/app/components/workflow/variable-inspect/__tests__/right.spec.tsx b/web/app/components/workflow/variable-inspect/__tests__/right.spec.tsx
index 635c1fb8fb9..b782b9031da 100644
--- a/web/app/components/workflow/variable-inspect/__tests__/right.spec.tsx
+++ b/web/app/components/workflow/variable-inspect/__tests__/right.spec.tsx
@@ -1,9 +1,17 @@
import type { currentVarType } from '../panel'
import type { VarInInspect } from '@/types/workflow'
-import { screen } from '@testing-library/react'
+import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { consoleQuery } from '@/service/console'
+import { seedModelProviderQueries } from '@/test/console/model-provider'
+import { createConsoleQueryWrapper, seedAppDslVersion } from '@/test/console/query-data'
import { VarInInspectType } from '@/types/workflow'
+import { createNode } from '../../__tests__/fixtures'
import { renderWorkflowFlowComponent } from '../../__tests__/workflow-test-env'
+import { HooksStoreContextProvider } from '../../hooks-store/provider'
+import useCurrentVars from '../../hooks/use-inspect-vars-crud'
+import { useInspectVarsCrudCommon } from '../../hooks/use-inspect-vars-crud-common'
+import { useStore } from '../../store'
import { BlockEnum, VarType } from '../../types'
import Right from '../right'
const createVariable = (overrides: Partial<VarInInspect> = {}): VarInInspect => ({
@@ -24,28 +32,58 @@ const createVariable = (overrides: Partial<VarInInspect> = {}): VarInInspect =>
...overrides,
})
-const { mockResetConversationVar, mockResetToLastRunVar } = vi.hoisted(() => ({
- mockResetConversationVar: vi.fn(),
- mockResetToLastRunVar: vi.fn(),
-}))
-
-vi.mock('../../hooks/use-inspect-vars-crud', () => ({
- default: () => ({
- editInspectVarValue: vi.fn(),
- resetConversationVar: mockResetConversationVar,
- resetToLastRunVar: mockResetToLastRunVar,
- }),
-}))
-
-vi.mock('../../hooks/use-nodes-interactions', () => ({
- useNodesInteractions: () => ({
- handleNodeSelect: vi.fn(),
- }),
-}))
-
-vi.mock('../../hooks/use-tool-icon', () => ({
- useToolIcon: () => '',
-}))
+const requests = vi.hoisted(() => ({ reset: vi.fn(), conversation: vi.fn() }))
+vi.mock('@/service/console', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/console')>()
+ const { withConsoleResponses, withConsoleClientResponses } =
+ await import('@/test/console/service-responses')
+ return {
+ ...actual,
+ consoleClient: withConsoleClientResponses(actual.consoleClient, {
+ 'workspaces.current.triggers.get': async () => [],
+ 'apps.byAppId.workflows.draft.variables.byVariableId.reset.put': requests.reset,
+ }),
+ consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'apps.byAppId.workflows.draft.conversationVariables.get': requests.conversation,
+ 'apps.byAppId.workflows.draft.systemVariables.get': async () => ({ items: [] }),
+ 'workspaces.current.tools.builtin.get': async () => [],
+ 'workspaces.current.tools.api.get': async () => [],
+ 'workspaces.current.tools.workflow.get': async () => [],
+ 'workspaces.current.tools.mcp.get': async () => [],
+ }),
+ }
+})
+
+function LiveRight({
+ initial,
+ handleOpenMenu,
+}: {
+ initial: currentVarType
+ handleOpenMenu: () => void
+}) {
+ const nodeVars = useStore((s) => s.nodesWithInspectVars)
+ const { conversationVars } = useCurrentVars()
+ const variable =
+ initial.var.type === VarInInspectType.conversation
+ ? conversationVars.find((v) => v.id === initial.var.id)
+ : nodeVars.find((n) => n.nodeId === initial.nodeId)?.vars.find((v) => v.id === initial.var.id)
+ return (
+ <Right
+ nodeId={initial.nodeId}
+ currentNodeVar={variable ? { ...initial, var: variable } : undefined}
+ handleOpenMenu={handleOpenMenu}
+ />
+ )
+}
+
+function InspectOwner(props: { initial: currentVarType; handleOpenMenu: () => void }) {
+ const owner = useInspectVarsCrudCommon()
+ return (
+ <HooksStoreContextProvider {...owner}>
+ <LiveRight {...props} />
+ </HooksStoreContextProvider>
+ )
+}
const createCurrentNodeVar = (overrides: Partial<VarInInspect> = {}): currentVarType => ({
nodeId: 'node-1',
@@ -64,13 +102,40 @@ const renderRight = (
options: { bottomPanelWidth?: number; handleOpenMenu?: () => void } = {},
) => {
const handleOpenMenu = options.handleOpenMenu ?? vi.fn()
+ const { queryClient } = createConsoleQueryWrapper()
+ seedModelProviderQueries(queryClient)
+ seedAppDslVersion(queryClient)
+ queryClient.setQueryData(
+ consoleQuery.apps.byAppId.workflows.draft.conversationVariables.get.queryKey({
+ input: { params: { app_id: 'app-1' } },
+ }),
+ {
+ items:
+ currentNodeVar.var.type === VarInInspectType.conversation
+ ? [{ ...currentNodeVar.var, value: currentNodeVar.var.value ?? null, full_content: null }]
+ : [],
+ },
+ )
const result = renderWorkflowFlowComponent(
- <Right nodeId="node-1" currentNodeVar={currentNodeVar} handleOpenMenu={handleOpenMenu} />,
+ <InspectOwner initial={currentNodeVar} handleOpenMenu={handleOpenMenu} />,
{
- nodes: [],
+ queryClient,
+ nodes: [createNode({ id: 'node-1', data: { type: BlockEnum.Code, title: 'Code' } })],
edges: [],
initialStoreState: {
bottomPanelWidth: options.bottomPanelWidth ?? 560,
+ nodesWithInspectVars:
+ currentNodeVar.var.type === VarInInspectType.conversation
+ ? []
+ : [
+ {
+ nodeId: currentNodeVar.nodeId,
+ nodeType: BlockEnum.Code,
+ title: 'Code',
+ nodePayload: currentNodeVar.nodeData,
+ vars: [currentNodeVar.var],
+ },
+ ],
},
},
)
@@ -80,7 +145,11 @@ const renderRight = (
describe('VariableInspect Right', () => {
beforeEach(() => {
- vi.clearAllMocks()
+ requests.conversation.mockResolvedValue({ items: [] })
+ requests.reset.mockResolvedValue({
+ ...createVariable({ value: 'last run value' }),
+ full_content: null,
+ })
})
it('opens the variable menu from the named narrow-panel command', async () => {
@@ -113,24 +182,49 @@ describe('VariableInspect Right', () => {
it('resets an edited node variable from its named command', async () => {
const user = userEvent.setup()
- renderRight(createCurrentNodeVar({ edited: true }))
+ const { store } = renderRight(createCurrentNodeVar({ edited: true }))
+ expect(screen.getByRole('textbox')).toHaveValue('value')
await user.click(
screen.getByRole('button', { name: 'workflowDebug.debug.variableInspect.reset' }),
)
- expect(mockResetToLastRunVar).toHaveBeenCalledWith('node-1', 'var-1')
+ await waitFor(() => expect(screen.getByRole('textbox')).toHaveValue('last run value'))
+ expect(
+ screen.queryByRole('button', { name: 'workflowDebug.debug.variableInspect.reset' }),
+ ).not.toBeInTheDocument()
+ expect(store.getState().nodesWithInspectVars[0]?.vars[0]).toMatchObject({
+ id: 'var-1',
+ value: 'last run value',
+ edited: false,
+ })
+ expect(requests.reset).toHaveBeenCalledExactlyOnceWith({
+ params: { app_id: 'app-1', variable_id: 'var-1' },
+ })
})
it('resets an edited conversation variable from its named command', async () => {
const user = userEvent.setup()
- renderRight(
- createCurrentNodeVar({
- type: VarInInspectType.conversation,
- edited: true,
- }),
- )
+ const variable = createVariable({
+ type: VarInInspectType.conversation,
+ selector: ['conversation', 'result'],
+ edited: true,
+ })
+ requests.conversation.mockResolvedValue({ items: [variable] })
+ requests.reset.mockImplementation(async () => {
+ requests.conversation.mockResolvedValue({
+ items: [{ ...variable, value: 'conversation default', edited: false, full_content: null }],
+ })
+ return { ...variable, value: 'conversation default', edited: false, full_content: null }
+ })
+ renderRight({
+ ...createCurrentNodeVar(),
+ nodeId: 'conversation',
+ nodeType: VarInInspectType.conversation,
+ var: variable,
+ })
+ await waitFor(() => expect(screen.getByRole('textbox')).toHaveValue('value'))
await user.click(
screen.getByRole('button', {
@@ -138,6 +232,14 @@ describe('VariableInspect Right', () => {
}),
)
- expect(mockResetConversationVar).toHaveBeenCalledWith('var-1')
+ await waitFor(() => expect(screen.getByRole('textbox')).toHaveValue('conversation default'))
+ expect(
+ screen.queryByRole('button', {
+ name: 'workflowDebug.debug.variableInspect.resetConversationVar',
+ }),
+ ).not.toBeInTheDocument()
+ expect(requests.reset).toHaveBeenCalledExactlyOnceWith({
+ params: { app_id: 'app-1', variable_id: 'var-1' },
+ })
})
})