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.

13.3 KB
Raw Blame
import type { Shape as HooksStoreShape } from '../../hooks-store/store'
import type { RunFile } from '../../types'
import type { FileUpload } from '@/app/components/base/features/types'
import type { FileEntity } from '@/app/components/base/file-uploader/types'
import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { TransferMethod } from '@/types/app'
import { createStartNode } from '../../__tests__/fixtures'
import { renderWorkflowFlowComponent } from '../../__tests__/workflow-test-env'
import { InputVarType, WorkflowRunningStatus } from '../../types'
import InputsPanel from '../inputs-panel'

const mockNotify = vi.fn()
const request = vi.hoisted(() => vi.fn<() => Promise<Response>>())

vi.mock('@/service/base', async (importOriginal) => ({
  ...(await importOriginal<typeof import('@/service/base')>()),
  request,
}))

vi.mock('next/navigation', () => ({
  useParams: () => ({}),
  usePathname: () => '/apps',
}))

vi.mock('@/app/notifications', async (importOriginal) => ({
  ...(await importOriginal()),
  toast: {
    success: (message: string) => mockNotify({ type: 'success', message }),
    error: (message: string) => mockNotify({ type: 'error', message }),
    warning: (message: string) => mockNotify({ type: 'warning', message }),
    info: (message: string) => mockNotify({ type: 'info', message }),
  },
}))

const fileSettingsWithImage = {
  enabled: true,
  image: {
    enabled: true,
  },
  allowed_file_upload_methods: [TransferMethod.remote_url],
  number_limits: 3,
  image_file_size_limit: 10,
} satisfies FileUpload & { image_file_size_limit: number }

const uploadedRunFile = {
  transfer_method: TransferMethod.remote_url,
  upload_file_id: 'file-2',
} as unknown as RunFile

const uploadingRunFile = {
  transfer_method: TransferMethod.local_file,
} as unknown as RunFile

const createHooksStoreProps = (
  overrides: Partial<HooksStoreShape> = {},
): Partial<HooksStoreShape> => ({
  handleRun: vi.fn(),
  fileSettings: fileSettingsWithImage,
  ...overrides,
})

const renderInputsPanel = (
  startNode: ReturnType<typeof createStartNode>,
  options?: Omit<Parameters<typeof renderWorkflowFlowComponent>[1], 'nodes' | 'edges'>,
  onRun = vi.fn(),
) =>
  renderWorkflowFlowComponent(<InputsPanel onRun={onRun} />, {
    nodes: [startNode],
    edges: [],
    ...options,
  })

describe('InputsPanel', () => {
  beforeEach(() => {
    vi.clearAllMocks()
    request.mockReset()
  })

  describe('Rendering', () => {
    it('should render current inputs, defaults, and the image uploader from the start node', () => {
      renderInputsPanel(
        createStartNode({
          data: {
            variables: [
              {
                type: InputVarType.textInput,
                variable: 'question',
                label: 'Question',
                required: true,
                default: 'default question',
              },
              {
                type: InputVarType.number,
                variable: 'count',
                label: 'Count',
                required: false,
                default: '2',
              },
            ],
          },
        }),
        {
          initialStoreState: {
            inputs: {
              question: 'overridden question',
            },
          },
          hooksStoreProps: createHooksStoreProps(),
        },
      )

      expect(screen.getByDisplayValue('overridden question')).toHaveFocus()
      expect(screen.getByRole('textbox', { name: 'Count' })).toHaveValue('2')
      expect(screen.getByText('common.imageUploader.pasteImageLink')).toBeInTheDocument()
    })
  })

  describe('User Interactions', () => {
    it('should update workflow inputs and image files when users edit the form', async () => {
      const user = userEvent.setup()
      const { store } = renderInputsPanel(
        createStartNode({
          data: {
            variables: [
              {
                type: InputVarType.textInput,
                variable: 'question',
                label: 'Question',
                required: true,
              },
            ],
          },
        }),
        {
          hooksStoreProps: createHooksStoreProps(),
        },
      )

      await user.type(screen.getByPlaceholderText('Question'), 'changed question')
      expect(store.getState().inputs).toEqual({ question: 'changed question' })

      await user.click(screen.getByText('common.imageUploader.pasteImageLink'))
      await user.type(
        await screen.findByPlaceholderText('common.imageUploader.pasteImageLinkInputPlaceholder'),
        'https://example.com/image.png',
      )
      await user.click(screen.getByRole('button', { name: 'common.operation.ok' }))

      await waitFor(() => {
        expect(store.getState().files).toEqual([
          {
            type: 'image',
            transfer_method: TransferMethod.remote_url,
            url: 'https://example.com/image.png',
            upload_file_id: '',
          },
        ])
      })
    })

    it('should not start a run when input validation fails', async () => {
      const user = userEvent.setup()
      const onRun = vi.fn()
      const handleRun = vi.fn()

      renderInputsPanel(
        createStartNode({
          data: {
            variables: [
              {
                type: InputVarType.textInput,
                variable: 'question',
                label: 'Question',
                required: true,
              },
            ],
          },
        }),
        {
          hooksStoreProps: createHooksStoreProps({ handleRun }),
        },
        onRun,
      )

      await user.click(screen.getByRole('button', { name: 'workflow.singleRun.startRun' }))

      expect(mockNotify).toHaveBeenCalledWith({
        type: 'error',
        message: 'appDebug.errorMessage.valueOfVarRequired:{"key":"Question"}',
      })
      expect(onRun).not.toHaveBeenCalled()
      expect(handleRun).not.toHaveBeenCalled()
    })

    it('should start a run with processed inputs when validation succeeds', async () => {
      const user = userEvent.setup()
      const onRun = vi.fn()
      const handleRun = vi.fn()

      renderInputsPanel(
        createStartNode({
          data: {
            variables: [
              {
                type: InputVarType.textInput,
                variable: 'question',
                label: 'Question',
                required: true,
              },
              {
                type: InputVarType.checkbox,
                variable: 'confirmed',
                label: 'Confirmed',
                required: false,
              },
            ],
          },
        }),
        {
          initialStoreState: {
            inputs: {
              question: 'run this',
              confirmed: 'truthy',
            },
            files: [uploadedRunFile],
          },
          hooksStoreProps: createHooksStoreProps({
            handleRun,
            fileSettings: {
              enabled: false,
            },
          }),
        },
        onRun,
      )

      await user.click(screen.getByRole('button', { name: 'workflow.singleRun.startRun' }))

      expect(onRun).toHaveBeenCalledTimes(1)
      expect(handleRun).toHaveBeenCalledWith({
        inputs: {
          question: 'run this',
          confirmed: true,
        },
        files: [uploadedRunFile],
      })
    })
  })

  it.each([false, true])(
    'submits the selected file and preserves clear semantics (required: %s)',
    async (required) => {
      const user = userEvent.setup()
      const handleRun = vi.fn()
      const defaultFile: FileEntity = {
        id: 'default-file',
        name: 'default.txt',
        size: 10,
        type: 'text/plain',
        progress: 100,
        transferMethod: TransferMethod.local_file,
        supportFileType: 'document',
        uploadedId: 'default-upload',
      }
      renderInputsPanel(
        createStartNode({
          data: {
            variables: [
              {
                type: InputVarType.singleFile,
                variable: 'file',
                label: 'File',
                required,
                default: defaultFile,
                allowed_file_types: ['document'],
                allowed_file_upload_methods: [TransferMethod.remote_url],
              },
            ],
          },
        }),
        { hooksStoreProps: createHooksStoreProps({ handleRun, fileSettings: { enabled: false } }) },
      )
      const runButton = screen.getByRole('button', { name: 'workflow.singleRun.startRun' })
      await user.click(runButton)
      expect(handleRun).toHaveBeenLastCalledWith(
        expect.objectContaining({
          inputs: {
            file: {
              type: 'document',
              transfer_method: 'local_file',
              url: '',
              upload_file_id: 'default-upload',
            },
          },
        }),
      )

      await user.click(screen.getByRole('button', { name: /remove.*default.txt/ }))
      expect(screen.queryByText('default.txt')).not.toBeInTheDocument()
      handleRun.mockClear()
      await user.click(runButton)
      if (required) {
        expect(handleRun).not.toHaveBeenCalled()
        expect(mockNotify).toHaveBeenCalledWith({
          type: 'error',
          message: 'appDebug.errorMessage.valueOfVarRequired:{"key":"File"}',
        })
      } else {
        expect(handleRun).toHaveBeenCalledWith(expect.objectContaining({ inputs: { file: '' } }))
      }

      const replacementUrl = 'https://example.com/replacement.txt'
      request.mockResolvedValue(
        Response.json({
          id: 'replacement-upload',
          name: 'replacement.txt',
          mime_type: 'text/plain',
          size: 10,
          url: replacementUrl,
        }),
      )
      await user.click(screen.getByRole('button', { name: /fileUploader.pasteFileLink/ }))
      await user.type(screen.getByPlaceholderText(/pasteFileLinkInputPlaceholder/), replacementUrl)
      await user.click(screen.getByRole('button', { name: 'common.operation.ok' }))
      await waitFor(() => expect(screen.queryByRole('progressbar')).not.toBeInTheDocument())
      await user.keyboard('{Escape}')
      await user.click(runButton)
      expect(handleRun).toHaveBeenLastCalledWith(
        expect.objectContaining({
          inputs: {
            file: {
              type: 'document',
              transfer_method: 'remote_url',
              url: replacementUrl,
              upload_file_id: 'replacement-upload',
            },
          },
        }),
      )
    },
  )

  it.each([false, true])(
    'accepts a zero default or explicit numeric override (%s)',
    async (override) => {
      const user = userEvent.setup()
      const handleRun = vi.fn()
      renderInputsPanel(
        createStartNode({
          data: {
            variables: [
              {
                type: InputVarType.number,
                variable: 'count',
                label: 'Count',
                required: true,
                default: override ? 5 : 0,
              },
            ],
          },
        }),
        {
          initialStoreState: { inputs: override ? { count: 0 } : {} },
          hooksStoreProps: createHooksStoreProps({ handleRun, fileSettings: { enabled: false } }),
        },
      )

      await user.click(screen.getByRole('button', { name: 'workflow.singleRun.startRun' }))

      expect(mockNotify).not.toHaveBeenCalled()
      expect(handleRun).toHaveBeenCalledWith(expect.objectContaining({ inputs: { count: 0 } }))
    },
  )

  describe('Disabled States', () => {
    it('should disable the run button while a local file is still uploading', () => {
      renderInputsPanel(createStartNode(), {
        initialStoreState: {
          files: [uploadingRunFile],
        },
        hooksStoreProps: createHooksStoreProps({
          fileSettings: {
            enabled: false,
          },
        }),
      })

      expect(screen.getByRole('button', { name: 'workflow.singleRun.startRun' })).toBeDisabled()
    })

    it('should disable the run button while the workflow is already running', () => {
      renderInputsPanel(createStartNode(), {
        initialStoreState: {
          workflowRunningData: {
            result: {
              status: WorkflowRunningStatus.Running,
              inputs_truncated: false,
              process_data_truncated: false,
              outputs_truncated: false,
            },
            tracing: [],
          },
        },
        hooksStoreProps: createHooksStoreProps(),
      })

      expect(screen.getByRole('button', { name: 'workflow.singleRun.startRun' })).toBeDisabled()
    })

    it('should disable the run button and skip execution when test/run permission is missing', async () => {
      const user = userEvent.setup()
      const onRun = vi.fn()
      const handleRun = vi.fn()

      renderInputsPanel(
        createStartNode(),
        {
          hooksStoreProps: createHooksStoreProps({
            handleRun,
            accessControl: {
              canEdit: true,
              canRun: false,
              canImportExportDSL: true,
              canReleaseAndVersion: true,
            },
          }),
        },
        onRun,
      )

      await user.click(screen.getByRole('button', { name: 'workflow.singleRun.startRun' }))

      expect(screen.getByRole('button', { name: 'workflow.singleRun.startRun' })).toBeDisabled()
      expect(mockNotify).not.toHaveBeenCalled()
      expect(onRun).not.toHaveBeenCalled()
      expect(handleRun).not.toHaveBeenCalled()
    })
  })
})