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.

7.0 KB
Raw Blame
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,
  }
}