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.

23.6 KB
Raw Blame
'use client'
import type {
  Emoji,
  WorkflowToolOutputSource,
  WorkflowToolProviderOutputParameter,
  WorkflowToolProviderOutputSchema,
  WorkflowToolProviderParameter,
  WorkflowToolProviderRequest,
} from '../types'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import {
  Drawer,
  DrawerBackdrop,
  DrawerClose,
  DrawerContent,
  DrawerPopup,
  DrawerPortal,
  DrawerTitle,
  DrawerViewport,
} from '@langgenius/dify-ui/drawer'
import { Field, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { Infotip, InfotipContent, InfotipTrigger } from '@langgenius/dify-ui/infotip'
import { Input } from '@langgenius/dify-ui/input'
import { Textarea } from '@langgenius/dify-ui/textarea'
import { produce } from 'immer'
import * as React from 'react'
import { useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import {
  IconPicker,
  IconPickerContent,
  IconPickerIcon,
  IconPickerTrigger,
} from '@/app/components/base/icon-picker'
import LabelSelector from '@/app/components/tools/labels/selector'
import ConfirmModal from '@/app/components/tools/workflow-tool/confirm-modal'
import MethodSelector from '@/app/components/tools/workflow-tool/method-selector'
import { normalizeWorkflowOutputName } from '@/app/components/workflow/utils/variable'
import { toast } from '@/app/notifications'
import {
  buildWorkflowToolRequestPayload,
  getReservedWorkflowOutputParameters,
  getWorkflowOutputParameters,
  hasReservedWorkflowOutputConflict,
  isWorkflowToolNameValid,
} from './helpers'
import {
  getDuplicateWorkflowOutputGroups,
  getSourceNodeDisplayName,
  getUniqueWorkflowOutputSources,
} from './utils'

export type WorkflowToolDrawerPayload = {
  icon: Emoji
  label: string
  name: string
  description: string
  parameters: WorkflowToolProviderParameter[]
  outputParameters?: WorkflowToolProviderOutputParameter[]
  labels: string[]
  privacy_policy: string
  tool?: {
    output_schema?: WorkflowToolProviderOutputSchema
  }
  workflow_tool_id?: string
  workflow_app_id?: string
}

export type WorkflowToolDrawerProps = {
  isAdd?: boolean
  payload: WorkflowToolDrawerPayload
  onHide: () => void
  onRemove?: () => void
  onCreate?: (payload: WorkflowToolProviderRequest & { workflow_app_id: string }) => void
  onSave?: (
    payload: WorkflowToolProviderRequest &
      Partial<{
        workflow_app_id: string
        workflow_tool_id: string
      }>,
  ) => void
}

type WorkflowToolDrawerFrameProps = {
  title: string
  closeLabel: string
  onHide: () => void
  children: React.ReactNode
}

const WorkflowToolDrawerFrame = ({
  title,
  closeLabel,
  onHide,
  children,
}: WorkflowToolDrawerFrameProps) => {
  const handleOpenChange = React.useCallback(
    (open: boolean) => {
      if (!open) onHide()
    },
    [onHide],
  )

  return (
    <Drawer
      open
      modal
      disablePointerDismissal
      swipeDirection="right"
      onOpenChange={handleOpenChange}
    >
      <DrawerPortal>
        <DrawerBackdrop />
        <DrawerViewport>
          <DrawerPopup
            className={cn(
              'data-[swipe-direction=right]:top-2 data-[swipe-direction=right]:right-2 data-[swipe-direction=right]:bottom-2 data-[swipe-direction=right]:h-[calc(100dvh-16px)] data-[swipe-direction=right]:w-160 data-[swipe-direction=right]:max-w-[calc(100vw-16px)]',
              'data-[swipe-direction=right]:rounded-xl data-[swipe-direction=right]:ring-divider-subtle',
            )}
          >
            <DrawerContent className="overflow-hidden">
              <div className="shrink-0 border-b border-divider-subtle py-4">
                <div className="flex h-6 items-center justify-between ps-6 pe-5">
                  <DrawerTitle className="min-w-0 truncate system-xl-semibold text-text-primary">
                    {title}
                  </DrawerTitle>
                  <DrawerClose
                    render={
                      <IconButton aria-label={closeLabel} size="md">
                        <span aria-hidden="true" className="i-ri-close-line size-4" />
                      </IconButton>
                    }
                  />
                </div>
              </div>
              <div className="grow overflow-hidden">{children}</div>
            </DrawerContent>
          </DrawerPopup>
        </DrawerViewport>
      </DrawerPortal>
    </Drawer>
  )
}

const WorkflowToolOutputName = React.memo(
  ({
    duplicateSources,
    item,
    reservedOutputParameters,
  }: {
    duplicateSources?: WorkflowToolOutputSource[]
    item: WorkflowToolProviderOutputParameter
    reservedOutputParameters: WorkflowToolProviderOutputParameter[]
  }) => {
    const outputNameId = React.useId()

    const { t } = useTranslation(['tools', 'workflow'])
    const reservedOutputDuplicateTip = t(
      ($) => $['createTool.toolOutput.reservedParameterDuplicateTip'],
      { ns: 'tools' },
    )
    const sourceNodeLabel = t(($) => $['createTool.toolOutput.sourceNode'], { ns: 'tools' })
    const duplicateOutputTip = t(($) => $['errorMsg.duplicateOutputVariable'], {
      ns: 'workflow',
      variable: normalizeWorkflowOutputName(item.name),
    })
    const hasReservedNameConflict =
      !item.reserved && hasReservedWorkflowOutputConflict(reservedOutputParameters, item.name)
    const hasDuplicateNameConflict = !item.reserved && !!duplicateSources
    const sources = duplicateSources || []

    return (
      <div className="text-[13px] leading-4.5">
        <div className="flex min-w-0 items-center gap-x-1">
          <span id={outputNameId} className="truncate font-medium text-text-primary">
            {item.name}
          </span>
          {item.reserved && (
            <span className="shrink-0 text-xs leading-4.5 text-[#ec4a0a]">
              {t(($) => $['createTool.toolOutput.reserved'], { ns: 'tools' })}
            </span>
          )}
          {hasReservedNameConflict || hasDuplicateNameConflict ? (
            <Infotip>
              <InfotipTrigger
                aria-labelledby={outputNameId}
                className="text-text-warning-secondary"
                iconSize="small"
                iconVariant="warning"
              />
              <InfotipContent
                aria-labelledby={outputNameId}
                className={hasDuplicateNameConflict ? 'w-60' : 'w-45'}
              >
                <div className="space-y-2">
                  {hasReservedNameConflict ? <p>{reservedOutputDuplicateTip}</p> : null}
                  {hasDuplicateNameConflict ? (
                    <div className="space-y-1.5">
                      <p>{duplicateOutputTip}</p>
                      {sources.length > 0 ? (
                        <ul className="space-y-1">
                          {sources.map((source) => {
                            const sourceTitle = getSourceNodeDisplayName(source, sources)
                            return (
                              <li key={source.nodeId}>
                                {sourceNodeLabel}: <span translate="no">{sourceTitle}</span>
                              </li>
                            )
                          })}
                        </ul>
                      ) : null}
                    </div>
                  ) : null}
                </div>
              </InfotipContent>
            </Infotip>
          ) : null}
        </div>
        <div className="text-text-tertiary">{item.type}</div>
        {hasDuplicateNameConflict && item.source ? (
          <div className="system-xs-regular wrap-break-word text-text-tertiary">
            {sourceNodeLabel} ·{' '}
            <span translate="no">{getSourceNodeDisplayName(item.source, sources)}</span>
          </div>
        ) : null}
      </div>
    )
  },
)

export function WorkflowToolDrawer({
  isAdd,
  payload,
  onHide,
  onRemove,
  onSave,
  onCreate,
}: WorkflowToolDrawerProps) {
  const { t } = useTranslation(['workflow', 'common', 'tools', 'navigation'])
  const parameterId = React.useId()
  const toolNameLabelId = React.useId()

  const [emoji, setEmoji] = useState<Emoji>(payload.icon)
  const [label, setLabel] = useState<string>(payload.label)
  const [name, setName] = useState(payload.name)
  const [description, setDescription] = useState(payload.description)
  const [parameters, setParameters] = useState<WorkflowToolProviderParameter[]>(payload.parameters)
  const rawOutputParameters = payload.outputParameters
  const outputSchema = payload.tool?.output_schema
  const outputParameters = useMemo<WorkflowToolProviderOutputParameter[]>(
    () => getWorkflowOutputParameters(rawOutputParameters, outputSchema),
    [rawOutputParameters, outputSchema],
  )
  const reservedOutputParameters = useMemo(() => getReservedWorkflowOutputParameters(t), [t])
  const duplicateOutputSourceGroups = useMemo(() => {
    const groups = getDuplicateWorkflowOutputGroups(outputParameters)
    const sourceGroups = new Map<string, WorkflowToolOutputSource[]>()

    for (const [name, outputs] of groups)
      sourceGroups.set(name, getUniqueWorkflowOutputSources(outputs))

    return sourceGroups
  }, [outputParameters])

  const handleParameterChange = (key: string, value: string, index: number) => {
    const newData = produce(parameters, (draft: WorkflowToolProviderParameter[]) => {
      if (key === 'description') draft[index]!.description = value
      else draft[index]!.form = value
    })
    setParameters(newData)
  }
  const [labels, setLabels] = useState<string[]>(payload.labels)
  const handleLabelSelect = (value: string[]) => {
    setLabels(value)
  }
  const [privacyPolicy, setPrivacyPolicy] = useState(payload.privacy_policy)
  const [confirmModalOpen, setConfirmModalOpen] = useState(false)

  const onConfirm = () => {
    let errorMessage = ''
    if (!label)
      errorMessage = t(($) => $['errorMsg.fieldRequired'], {
        ns: 'common',
        field: t(($) => $['createTool.name'], { ns: 'tools' }),
      })

    if (!name)
      errorMessage = t(($) => $['errorMsg.fieldRequired'], {
        ns: 'common',
        field: t(($) => $['createTool.nameForToolCall'], { ns: 'tools' }),
      })

    if (!isWorkflowToolNameValid(name))
      errorMessage =
        t(($) => $['createTool.nameForToolCall'], { ns: 'tools' }) +
        t(($) => $['createTool.nameForToolCallTip'], { ns: 'tools' })

    if (errorMessage) {
      toast.error(errorMessage)
      return
    }

    const requestParams = buildWorkflowToolRequestPayload({
      name,
      description,
      emoji,
      label,
      parameters,
      labels,
      privacyPolicy,
    })
    if (!isAdd) {
      onSave?.({
        ...requestParams,
        workflow_tool_id: payload.workflow_tool_id!,
      })
    } else {
      onCreate?.({
        ...requestParams,
        workflow_app_id: payload.workflow_app_id!,
      })
    }
  }

  return (
    <>
      <WorkflowToolDrawerFrame
        onHide={onHide}
        title={t(($) => $['common.workflowAsTool'], { ns: 'navigation' })!}
        closeLabel={t(($) => $['operation.close'], { ns: 'common' })!}
      >
        <form
          className="flex h-full flex-col"
          onSubmit={(event) => {
            event.preventDefault()
            if (isAdd) onConfirm()
            else setConfirmModalOpen(true)
          }}
        >
          <div className="h-0 grow space-y-4 overflow-y-auto px-6 py-3">
            {/* name & icon */}
            <IconPicker
              value={{
                type: 'emoji',
                icon: emoji.content,
                background: emoji.background,
              }}
              onValueChange={(payload) => {
                if (payload.type === 'emoji')
                  setEmoji({ content: payload.icon, background: payload.background })
              }}
            >
              <Field name="label" className="gap-0">
                <FieldLabel className="py-2 text-text-primary">
                  {t(($) => $['createTool.name'], { ns: 'tools' })}{' '}
                  <span aria-hidden className="ms-1 text-text-destructive">
                    *
                  </span>
                </FieldLabel>
                <div className="flex items-center justify-between gap-3">
                  <IconPickerTrigger
                    aria-label={t(($) => $['createTool.changeIcon'], { ns: 'tools' })}
                    className="shrink-0 cursor-pointer rounded-[10px]"
                  >
                    <IconPickerIcon size="large" />
                  </IconPickerTrigger>
                  <Input
                    className="h-10 min-w-0 flex-1"
                    placeholder={t(($) => $['createTool.toolNamePlaceHolder'], { ns: 'tools' })!}
                    value={label}
                    onValueChange={(value) => setLabel(value)}
                  />
                </div>
              </Field>
              <IconPickerContent enableImageUpload={false} />
            </IconPicker>
            {/* name for tool call */}
            <Field name="name" className="gap-0" invalid={!isWorkflowToolNameValid(name)}>
              <div className="flex items-center py-2 system-sm-medium text-text-primary">
                <FieldLabel id={toolNameLabelId} className="py-0 text-text-primary">
                  {t(($) => $['createTool.nameForToolCall'], { ns: 'tools' })}
                </FieldLabel>
                <span aria-hidden className="ms-1 text-text-destructive">
                  *
                </span>
                <Infotip>
                  <InfotipTrigger aria-labelledby={toolNameLabelId} className="ms-1 size-3.5" />
                  <InfotipContent aria-labelledby={toolNameLabelId} className="w-45">
                    {t(($) => $['createTool.nameForToolCallPlaceHolder'], { ns: 'tools' })}
                  </InfotipContent>
                </Infotip>
              </div>
              <Input
                className="h-10"
                placeholder={t(($) => $['createTool.nameForToolCallPlaceHolder'], { ns: 'tools' })!}
                value={name}
                onValueChange={(value) => setName(value)}
              />
              {!isWorkflowToolNameValid(name) && (
                <FieldError match className="py-0 text-xs leading-4.5">
                  {t(($) => $['createTool.nameForToolCallTip'], { ns: 'tools' })}
                </FieldError>
              )}
            </Field>
            {/* description */}
            <Field name="description" className="gap-0">
              <FieldLabel className="py-2 text-text-primary">
                {t(($) => $['createTool.description'], { ns: 'tools' })}
              </FieldLabel>
              <Textarea
                placeholder={t(($) => $['createTool.descriptionPlaceholder'], { ns: 'tools' })}
                value={description}
                onValueChange={(value) => setDescription(value)}
              />
            </Field>
            {/* Tool Input  */}
            <div>
              <div className="py-2 system-sm-medium text-text-primary">
                {t(($) => $['createTool.toolInput.title'], { ns: 'tools' })}
              </div>
              <div className="w-full overflow-x-auto rounded-lg border border-divider-regular">
                <table className="w-full text-xs leading-4.5 font-normal text-text-secondary">
                  <thead className="text-text-tertiary uppercase">
                    <tr className="border-b border-divider-regular">
                      <th className="w-39 p-2 ps-3 font-medium">
                        {t(($) => $['createTool.toolInput.name'], { ns: 'tools' })}
                      </th>
                      <th className="w-25.5 p-2 ps-3 font-medium">
                        {t(($) => $['createTool.toolInput.method'], { ns: 'tools' })}
                      </th>
                      <th id={`${parameterId}-description`} className="p-2 ps-3 font-medium">
                        {t(($) => $['createTool.toolInput.description'], { ns: 'tools' })}
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    {parameters.map((item, index) => (
                      <tr key={index} className="border-b border-divider-regular last:border-0">
                        <td className="max-w-39 p-2 ps-3">
                          <div className="text-[13px] leading-4.5">
                            <div className="flex">
                              <span
                                id={`${parameterId}-${index}-name`}
                                className="truncate font-medium text-text-primary"
                              >
                                {item.name}
                              </span>
                              <span className="shrink-0 ps-1 text-xs leading-4.5 text-[#ec4a0a]">
                                {item.required
                                  ? t(($) => $['createTool.toolInput.required'], { ns: 'tools' })
                                  : ''}
                              </span>
                            </div>
                            <div className="text-text-tertiary">{item.type}</div>
                          </div>
                        </td>
                        <td>
                          {item.name === '__image' && (
                            <div
                              className={cn(
                                'flex h-9 min-h-14 cursor-default items-center gap-1 bg-transparent px-3 py-2',
                              )}
                            >
                              <div
                                className={cn(
                                  'grow truncate text-[13px] leading-4.5 text-text-secondary',
                                )}
                              >
                                {t(($) => $['createTool.toolInput.methodParameter'], {
                                  ns: 'tools',
                                })}
                              </div>
                            </div>
                          )}
                          {item.name !== '__image' && (
                            <MethodSelector
                              value={item.form}
                              onChange={(value) => handleParameterChange('form', value, index)}
                            />
                          )}
                        </td>
                        <td className="w-59 p-2 ps-3 text-text-tertiary">
                          <input
                            type="text"
                            aria-labelledby={`${parameterId}-${index}-name ${parameterId}-description`}
                            className="w-full appearance-none rounded-sm bg-transparent text-[13px] leading-4.5 font-normal text-text-secondary caret-primary-600 outline-hidden placeholder:text-text-quaternary focus-visible:ring-2 focus-visible:ring-state-accent-solid"
                            placeholder={t(
                              ($) => $['createTool.toolInput.descriptionPlaceholder'],
                              {
                                ns: 'tools',
                              },
                            )!}
                            value={item.description}
                            onChange={(e) =>
                              handleParameterChange('description', e.target.value, index)
                            }
                          />
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
            {/* Tool Output  */}
            <div>
              <div className="py-2 system-sm-medium text-text-primary">
                {t(($) => $['createTool.toolOutput.title'], { ns: 'tools' })}
              </div>
              <div className="w-full overflow-x-auto rounded-lg border border-divider-regular">
                <table className="w-full text-xs leading-4.5 font-normal text-text-secondary">
                  <thead className="text-text-tertiary uppercase">
                    <tr className="border-b border-divider-regular">
                      <th className="w-39 p-2 ps-3 font-medium">
                        {t(($) => $['createTool.name'], { ns: 'tools' })}
                      </th>
                      <th className="p-2 ps-3 font-medium">
                        {t(($) => $['createTool.toolOutput.description'], { ns: 'tools' })}
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    {[...reservedOutputParameters, ...outputParameters].map((item, index) => (
                      <tr
                        key={
                          item.reserved
                            ? `reserved-${item.name}`
                            : item.source
                              ? `${item.source.nodeId}-${item.source.outputIndex}`
                              : `output-${item.name}-${index}`
                        }
                        className="border-b border-divider-regular last:border-0"
                      >
                        <td className="max-w-39 p-2 ps-3">
                          <WorkflowToolOutputName
                            duplicateSources={duplicateOutputSourceGroups.get(
                              normalizeWorkflowOutputName(item.name),
                            )}
                            item={item}
                            reservedOutputParameters={reservedOutputParameters}
                          />
                        </td>
                        <td className="w-59 p-2 ps-3 text-text-tertiary">
                          <span className="text-[13px] leading-4.5 font-normal text-text-secondary">
                            {item.description}
                          </span>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
            {/* Tags */}
            <div>
              <div className="py-2 system-sm-medium text-text-primary">
                {t(($) => $['createTool.toolInput.label'], { ns: 'tools' })}
              </div>
              <LabelSelector value={labels} onChange={handleLabelSelect} />
            </div>
            {/* Privacy Policy */}
            <Field name="privacy_policy" className="gap-0">
              <FieldLabel className="py-2 text-text-primary">
                {t(($) => $['createTool.privacyPolicy'], { ns: 'tools' })}
              </FieldLabel>
              <Input
                className="h-10"
                value={privacyPolicy}
                onValueChange={(value) => setPrivacyPolicy(value)}
                placeholder={t(($) => $['createTool.privacyPolicyPlaceholder'], { ns: 'tools' })}
              />
            </Field>
          </div>
          <div
            className={cn(
              !isAdd && onRemove ? 'justify-between' : 'justify-end',
              'mt-2 flex shrink-0 rounded-b-[10px] border-t border-divider-regular bg-background-section-burn px-6 py-4',
            )}
          >
            {!isAdd && onRemove && (
              <Button variant="primary" tone="destructive" onClick={onRemove}>
                {t(($) => $['operation.delete'], { ns: 'common' })}
              </Button>
            )}
            <div className="flex space-x-2">
              <Button onClick={onHide}>{t(($) => $['operation.cancel'], { ns: 'common' })}</Button>
              <Button variant="primary" type="submit">
                {t(($) => $['operation.save'], { ns: 'common' })}
              </Button>
            </div>
          </div>
        </form>
      </WorkflowToolDrawerFrame>
      {confirmModalOpen && (
        <ConfirmModal
          show={confirmModalOpen}
          onClose={() => setConfirmModalOpen(false)}
          onConfirm={onConfirm}
        />
      )}
    </>
  )
}