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.

9.6 KB
Raw Blame
'use client'
import type { FC } from 'react'
import type {
  Credential,
  CustomCollectionBackend,
  CustomParamSchema,
} from '@/app/components/tools/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 { IconButton } from '@langgenius/dify-ui/icon-button'
import { Input } from '@langgenius/dify-ui/input'
import { RiSettings2Line } from '@remixicon/react'
import * as React from 'react'
import { useId, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useLocale } from '#i18n'
import { AuthType } from '@/app/components/tools/types'
import { getPluginLanguage } from '@/i18n/metadata'
import { testAPIAvailable } from '@/service/tools'
import ConfigCredentials from './config-credentials'

type Props = Readonly<{
  positionCenter?: boolean
  customCollection: CustomCollectionBackend
  tool: CustomParamSchema
  onHide: () => void
}>

const TestApi: FC<Props> = ({ positionCenter, customCollection, tool, onHide }) => {
  const { t } = useTranslation(['common', 'tools'])
  const parameterId = useId()
  const locale = useLocale()
  const language = getPluginLanguage(locale)
  const [credentialsModalShow, setCredentialsModalShow] = useState(false)
  const [tempCredential, setTempCredential] = React.useState<Credential>(
    customCollection.credentials,
  )
  const [testing, setTesting] = useState(false)
  const [result, setResult] = useState<string>('')
  const { operation_id: toolName, parameters } = tool
  const [parametersValue, setParametersValue] = useState<Record<string, string>>({})
  const handleTest = async () => {
    if (testing) return
    setTesting(true)
    // clone test schema
    const credentials = JSON.parse(JSON.stringify(tempCredential)) as Credential
    if (credentials.auth_type === AuthType.none) {
      delete credentials.api_key_header_prefix
      delete credentials.api_key_header
      delete credentials.api_key_value
    }
    const data = {
      provider_name: customCollection.provider,
      tool_name: toolName,
      credentials,
      schema_type: customCollection.schema_type,
      schema: customCollection.schema,
      parameters: parametersValue,
    }
    const res = (await testAPIAvailable(data)) as any
    setResult(res.error || res.result)
    setTesting(false)
  }

  return (
    <>
      <Drawer
        open
        modal
        disablePointerDismissal
        swipeDirection="right"
        onOpenChange={(open) => {
          if (!open) onHide()
        }}
      >
        <DrawerPortal>
          <DrawerBackdrop forceRender />
          <DrawerViewport>
            <DrawerPopup
              className={cn(
                'data-[swipe-direction=right]:top-2 data-[swipe-direction=right]:bottom-2 data-[swipe-direction=right]:h-auto data-[swipe-direction=right]:w-150 data-[swipe-direction=right]:max-w-[calc(100vw-1rem)] data-[swipe-direction=right]:rounded-xl data-[swipe-direction=right]:ring-divider-subtle',
                positionCenter
                  ? 'data-[swipe-direction=right]:right-[max(0.5rem,calc(50%-300px))]'
                  : 'data-[swipe-direction=right]:right-2',
              )}
            >
              <DrawerContent>
                <div className="shrink-0 border-b border-divider-regular 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">
                      {`${t(($) => $['test.title'], { ns: 'tools' })}  ${toolName}`}
                    </DrawerTitle>
                    <DrawerClose
                      render={
                        <IconButton
                          aria-label={t(($) => $['operation.close'], { ns: 'common' })}
                          size="md"
                        >
                          <span aria-hidden="true" className="i-ri-close-line size-4" />
                        </IconButton>
                      }
                    />
                  </div>
                </div>
                <form
                  className="min-h-0 flex-1 overflow-y-auto px-6 pt-2"
                  onSubmit={(event) => {
                    event.preventDefault()
                    void handleTest()
                  }}
                >
                  <div className="space-y-4">
                    <div>
                      <div className="py-2 system-sm-medium text-text-primary">
                        {t(($) => $['createTool.authMethod.title'], { ns: 'tools' })}
                      </div>
                      <button
                        type="button"
                        className="flex h-9 w-full cursor-pointer items-center justify-between rounded-lg bg-components-input-bg-normal px-2.5 outline-hidden focus-visible:ring-2 focus-visible:ring-state-accent-solid"
                        onClick={() => setCredentialsModalShow(true)}
                      >
                        <span className="system-xs-regular text-text-primary">
                          {t(($) => $[`createTool.authMethod.types.${tempCredential.auth_type}`], {
                            ns: 'tools',
                          })}
                        </span>
                        <RiSettings2Line aria-hidden className="size-4 text-text-secondary" />
                      </button>
                    </div>

                    <div>
                      <div className="py-2 system-sm-medium text-text-primary">
                        {t(($) => $['test.parametersValue'], { ns: 'tools' })}
                      </div>
                      <div className="rounded-lg border border-divider-regular">
                        <table className="w-full body-xs-regular text-text-secondary">
                          <thead className="text-text-tertiary uppercase">
                            <tr className="border-b border-divider-regular">
                              <th className="p-2 ps-3 font-medium">
                                {t(($) => $['test.parameters'], { ns: 'tools' })}
                              </th>
                              <th className="p-2 ps-3 font-medium">
                                {t(($) => $['test.value'], { ns: 'tools' })}
                              </th>
                            </tr>
                          </thead>
                          <tbody>
                            {parameters.map((item, index) => (
                              <tr
                                key={index}
                                className="border-b border-divider-regular last:border-0"
                              >
                                <td className="py-2 ps-3 pe-2.5">
                                  <label htmlFor={`${parameterId}-${item.name}`}>
                                    {item.label[language]}
                                  </label>
                                </td>
                                <td className="">
                                  <Input
                                    id={`${parameterId}-${item.name}`}
                                    name={item.name}
                                    value={parametersValue[item.name] || ''}
                                    onValueChange={(value) =>
                                      setParametersValue({
                                        ...parametersValue,
                                        [item.name]: value,
                                      })
                                    }
                                    type="text"
                                    className="bg-transparent"
                                  />
                                </td>
                              </tr>
                            ))}
                          </tbody>
                        </table>
                      </div>
                    </div>
                  </div>
                  <Button
                    variant="primary"
                    className="mt-4 h-10 w-full"
                    loading={testing}
                    type="submit"
                  >
                    {t(($) => $['test.title'], { ns: 'tools' })}
                  </Button>
                  <div className="mt-6">
                    <div className="flex items-center space-x-3">
                      <div className="system-xs-semibold text-text-tertiary">
                        {t(($) => $['test.testResult'], { ns: 'tools' })}
                      </div>
                      <div className="h-px w-0 grow"></div>
                    </div>
                    <div
                      role="status"
                      className="mt-2 h-50 overflow-x-hidden overflow-y-auto rounded-lg bg-components-input-bg-normal px-3 py-2 system-xs-regular text-text-secondary"
                    >
                      {result || (
                        <span className="text-text-quaternary">
                          {t(($) => $['test.testResultPlaceholder'], { ns: 'tools' })}
                        </span>
                      )}
                    </div>
                  </div>
                </form>
              </DrawerContent>
            </DrawerPopup>
          </DrawerViewport>
        </DrawerPortal>
      </Drawer>
      {credentialsModalShow && (
        <ConfigCredentials
          positionCenter={positionCenter}
          credential={tempCredential}
          onChange={setTempCredential}
          onHide={() => setCredentialsModalShow(false)}
        />
      )}
    </>
  )
}
export default React.memo(TestApi)