Initial commit

This commit is contained in:
2025-10-14 14:17:21 +08:00
commit ac715a8b88
35011 changed files with 3834178 additions and 0 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

@@ -0,0 +1,69 @@
'use client'
import { useRef } from 'react'
import { useTranslation } from 'react-i18next'
import { useContext } from 'use-context-selector'
import { useMount } from 'ahooks'
import cn from '@/utils/classnames'
import { Apps02 } from '@/app/components/base/icons/src/vender/line/others'
import I18n from '@/context/i18n'
import { getLanguage } from '@/i18n/language'
import { useStore as useLabelStore } from '@/app/components/tools/labels/store'
import { fetchLabelList } from '@/service/tools'
type Props = {
value: string
onSelect: (type: string) => void
}
const Icon = ({ svgString, active }: { svgString: string; active: boolean }) => {
const svgRef = useRef<SVGSVGElement | null>(null)
const SVGParser = (svg: string) => {
if (!svg)
return null
const parser = new DOMParser()
const doc = parser.parseFromString(svg, 'image/svg+xml')
return doc.documentElement
}
useMount(() => {
const svgElement = SVGParser(svgString)
if (svgRef.current && svgElement)
svgRef.current.appendChild(svgElement)
})
return <svg className={cn('w-4 h-4 text-gray-700', active && '!text-primary-600')} ref={svgRef} />
}
const Category = ({
value,
onSelect,
}: Props) => {
const { t } = useTranslation()
const { locale } = useContext(I18n)
const language = getLanguage(locale)
const labelList = useLabelStore(s => s.labelList)
const setLabelList = useLabelStore(s => s.setLabelList)
useMount(() => {
fetchLabelList().then((res) => {
setLabelList(res)
})
})
return (
<div className='mb-3'>
<div className='px-3 py-0.5 text-gray-500 text-xs leading-[18px] font-medium'>{t('tools.addToolModal.category').toLocaleUpperCase()}</div>
<div className={cn('mb-0.5 p-1 pl-3 flex items-center cursor-pointer text-gray-700 text-sm leading-5 rounded-lg hover:bg-white', value === '' && '!bg-white !text-primary-600 font-medium')} onClick={() => onSelect('')}>
<Apps02 className='shrink-0 w-4 h-4 mr-2' />
{t('tools.type.all')}
</div>
{labelList.map(label => (
<div key={label.name} title={label.label[language]} className={cn('mb-0.5 p-1 pl-3 flex items-center cursor-pointer text-gray-700 text-sm leading-5 rounded-lg hover:bg-white truncate overflow-hidden', value === label.name && '!bg-white !text-primary-600 font-medium')} onClick={() => onSelect(label.name)}>
<div className='shrink-0 w-4 h-4 mr-2'>
<Icon active={value === label.name} svgString={label.icon} />
</div>
{label.label[language]}
</div>
))}
</div>
)
}
export default Category

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

View File

@@ -0,0 +1,21 @@
'use client'
import { useSearchParams } from 'next/navigation'
import { useTranslation } from 'react-i18next'
const Empty = () => {
const { t } = useTranslation()
const searchParams = useSearchParams()
return (
<div className='flex flex-col items-center'>
<div className="shrink-0 w-[163px] h-[149px] bg-cover bg-no-repeat bg-[url('~@/app/components/tools/add-tool-modal/empty.png')]"></div>
<div className='mb-1 text-[13px] font-medium text-text-primary leading-[18px]'>
{t(`tools.addToolModal.${searchParams.get('category') === 'workflow' ? 'emptyTitle' : 'emptyTitleCustom'}`)}
</div>
<div className='text-[13px] text-text-tertiary leading-[18px]'>
{t(`tools.addToolModal.${searchParams.get('category') === 'workflow' ? 'emptyTip' : 'emptyTipCustom'}`)}
</div>
</div>
)
}
export default Empty

View File

@@ -0,0 +1,250 @@
'use client'
import type { FC } from 'react'
import React, { useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useContext } from 'use-context-selector'
import produce from 'immer'
import {
RiAddLine,
RiCloseLine,
} from '@remixicon/react'
import { useMount } from 'ahooks'
import type { Collection, CustomCollectionBackend, Tool } from '../types'
import Type from './type'
import Category from './category'
import Tools from './tools'
import cn from '@/utils/classnames'
import I18n from '@/context/i18n'
import Drawer from '@/app/components/base/drawer'
import Button from '@/app/components/base/button'
import Loading from '@/app/components/base/loading'
import Input from '@/app/components/base/input'
import EditCustomToolModal from '@/app/components/tools/edit-custom-collection-modal'
import ConfigCredential from '@/app/components/tools/setting/build-in/config-credentials'
import {
createCustomCollection,
fetchAllBuiltInTools,
fetchAllCustomTools,
fetchAllWorkflowTools,
removeBuiltInToolCredential,
updateBuiltInToolCredential,
} from '@/service/tools'
import type { ToolWithProvider } from '@/app/components/workflow/types'
import Toast from '@/app/components/base/toast'
import ConfigContext from '@/context/debug-configuration'
import type { ModelConfig } from '@/models/debug'
type Props = {
onHide: () => void
}
// Add and Edit
const AddToolModal: FC<Props> = ({
onHide,
}) => {
const { t } = useTranslation()
const { locale } = useContext(I18n)
const [currentType, setCurrentType] = useState('builtin')
const [currentCategory, setCurrentCategory] = useState('')
const [keywords, setKeywords] = useState<string>('')
const handleKeywordsChange = (value: string) => {
setKeywords(value)
}
const isMatchingKeywords = (text: string, keywords: string) => {
return text.toLowerCase().includes(keywords.toLowerCase())
}
const [toolList, setToolList] = useState<ToolWithProvider[]>([])
const [listLoading, setListLoading] = useState(true)
const getAllTools = async () => {
setListLoading(true)
const buildInTools = await fetchAllBuiltInTools()
const customTools = await fetchAllCustomTools()
const workflowTools = await fetchAllWorkflowTools()
const mergedToolList = [
...buildInTools,
...customTools,
...workflowTools.filter((toolWithProvider) => {
return !toolWithProvider.tools.some((tool) => {
return !!tool.parameters.find(item => item.name === '__image')
})
}),
]
setToolList(mergedToolList)
setListLoading(false)
}
const filteredList = useMemo(() => {
return toolList.filter((toolWithProvider) => {
if (currentType === 'all')
return true
else
return toolWithProvider.type === currentType
}).filter((toolWithProvider) => {
if (!currentCategory)
return true
else
return toolWithProvider.labels.includes(currentCategory)
}).filter((toolWithProvider) => {
return (
isMatchingKeywords(toolWithProvider.name, keywords)
|| toolWithProvider.tools.some((tool) => {
return Object.values(tool.label).some((label) => {
return isMatchingKeywords(label, keywords)
})
})
)
})
}, [currentType, currentCategory, toolList, keywords])
const {
modelConfig,
setModelConfig,
} = useContext(ConfigContext)
const [isShowEditCollectionToolModal, setIsShowEditCustomCollectionModal] = useState(false)
const doCreateCustomToolCollection = async (data: CustomCollectionBackend) => {
await createCustomCollection(data)
Toast.notify({
type: 'success',
message: t('common.api.actionSuccess'),
})
setIsShowEditCustomCollectionModal(false)
getAllTools()
}
const [showSettingAuth, setShowSettingAuth] = useState(false)
const [collection, setCollection] = useState<Collection>()
const toolSelectHandle = (collection: Collection, tool: Tool) => {
const parameters: Record<string, string> = {}
if (tool.parameters) {
tool.parameters.forEach((item) => {
parameters[item.name] = ''
})
}
const nexModelConfig = produce(modelConfig, (draft: ModelConfig) => {
draft.agentConfig.tools.push({
provider_id: collection.id || collection.name,
provider_type: collection.type,
provider_name: collection.name,
tool_name: tool.name,
tool_label: tool.label[locale] || tool.label[locale.replaceAll('-', '_')],
tool_parameters: parameters,
enabled: true,
})
})
setModelConfig(nexModelConfig)
}
const authSelectHandle = (provider: Collection) => {
setCollection(provider)
setShowSettingAuth(true)
}
const updateBuiltinAuth = async (value: Record<string, any>) => {
if (!collection)
return
await updateBuiltInToolCredential(collection.name, value)
Toast.notify({
type: 'success',
message: t('common.api.actionSuccess'),
})
await getAllTools()
setShowSettingAuth(false)
}
const removeBuiltinAuth = async () => {
if (!collection)
return
await removeBuiltInToolCredential(collection.name)
Toast.notify({
type: 'success',
message: t('common.api.actionSuccess'),
})
await getAllTools()
setShowSettingAuth(false)
}
useMount(() => {
getAllTools()
})
return (
<>
<Drawer
isOpen
mask
clickOutsideNotOpen
onClose={onHide}
footer={null}
panelClassname={cn('mt-16 mx-2 sm:mr-2 mb-3 !p-0 rounded-xl', 'mt-2 !w-[640px]', '!max-w-[640px]')}
>
<div
className='w-full flex bg-white border-[0.5px] border-gray-200 rounded-xl shadow-xl'
style={{
height: 'calc(100vh - 16px)',
}}
>
<div className='relative shrink-0 w-[200px] pb-3 bg-gray-100 rounded-l-xl border-r-[0.5px] border-black/2 overflow-y-auto'>
<div className='sticky top-0 left-0 right-0'>
<div className='sticky top-0 left-0 right-0 px-5 py-3 text-md font-semibold text-gray-900'>{t('tools.addTool')}</div>
<div className='px-3 pt-2 pb-4'>
<Button variant='primary' className='w-[176px]' onClick={() => setIsShowEditCustomCollectionModal(true)}>
<RiAddLine className='w-4 h-4 mr-1' />
{t('tools.createCustomTool')}
</Button>
</div>
</div>
<div className='px-2 py-1'>
<Type value={currentType} onSelect={setCurrentType} />
<Category value={currentCategory} onSelect={setCurrentCategory} />
</div>
</div>
<div className='relative grow bg-white rounded-r-xl overflow-y-auto'>
<div className='z-10 sticky top-0 left-0 right-0 p-2 flex items-center gap-1 bg-white'>
<div className='grow'>
<Input
showLeftIcon
showClearIcon
value={keywords}
onChange={e => handleKeywordsChange(e.target.value)}
onClear={() => handleKeywordsChange('')}
/>
</div>
<div className='ml-2 mr-1 w-[1px] h-4 bg-gray-200'></div>
<div className='p-2 cursor-pointer' onClick={onHide}>
<RiCloseLine className='w-4 h-4 text-gray-500' />
</div>
</div>
{listLoading && (
<div className='flex h-[200px] items-center justify-center bg-white'>
<Loading />
</div>
)}
{!listLoading && (
<Tools
showWorkflowEmpty={currentType === 'workflow'}
tools={filteredList}
addedTools={(modelConfig?.agentConfig?.tools as any) || []}
onSelect={toolSelectHandle}
onAuthSetup={authSelectHandle}
/>
)}
</div>
</div>
</Drawer>
{isShowEditCollectionToolModal && (
<EditCustomToolModal
positionLeft
payload={null}
onHide={() => setIsShowEditCustomCollectionModal(false)}
onAdd={doCreateCustomToolCollection}
/>
)}
{showSettingAuth && collection && (
<ConfigCredential
collection={collection}
onCancel={() => setShowSettingAuth(false)}
onSaved={updateBuiltinAuth}
onRemove={removeBuiltinAuth}
/>
)}
</>
)
}
export default React.memo(AddToolModal)

View File

@@ -0,0 +1,149 @@
import {
memo,
useCallback,
} from 'react'
import { useTranslation } from 'react-i18next'
import {
RiAddLine,
} from '@remixicon/react'
import cn from '@/utils/classnames'
import { ArrowUpRight } from '@/app/components/base/icons/src/vender/line/arrows'
import { Check } from '@/app/components/base/icons/src/vender/line/general'
import { Tag01 } from '@/app/components/base/icons/src/vender/line/financeAndECommerce'
import type { ToolWithProvider } from '@/app/components/workflow/types'
import { BlockEnum } from '@/app/components/workflow/types'
import BlockIcon from '@/app/components/workflow/block-icon'
import Tooltip from '@/app/components/base/tooltip'
import Button from '@/app/components/base/button'
import { useGetLanguage } from '@/context/i18n'
import { useStore as useLabelStore } from '@/app/components/tools/labels/store'
import Empty from '@/app/components/tools/add-tool-modal/empty'
import type { Tool } from '@/app/components/tools/types'
import { CollectionType } from '@/app/components/tools/types'
import type { AgentTool } from '@/types/app'
import { MAX_TOOLS_NUM } from '@/config'
type ToolsProps = {
showWorkflowEmpty: boolean
tools: ToolWithProvider[]
addedTools: AgentTool[]
onSelect: (provider: ToolWithProvider, tool: Tool) => void
onAuthSetup: (provider: ToolWithProvider) => void
}
const Blocks = ({
showWorkflowEmpty,
tools,
addedTools,
onSelect,
onAuthSetup,
}: ToolsProps) => {
const { t } = useTranslation()
const language = useGetLanguage()
const labelList = useLabelStore(s => s.labelList)
const addable = addedTools.length < MAX_TOOLS_NUM
const renderGroup = useCallback((toolWithProvider: ToolWithProvider) => {
const list = toolWithProvider.tools
const needAuth = toolWithProvider.allow_delete && !toolWithProvider.is_team_authorization && toolWithProvider.type === CollectionType.builtIn
return (
<div
key={toolWithProvider.id}
className='group mb-1 last-of-type:mb-0'
>
<div className='flex items-center justify-between w-full pl-3 pr-1 h-[22px] text-xs font-medium text-gray-500'>
{toolWithProvider.label[language]}
<a className='hidden cursor-pointer items-center group-hover:flex' href={`/tools?category=${toolWithProvider.type}`} target='_blank'>{t('tools.addToolModal.manageInTools')}<ArrowUpRight className='ml-0.5 w-3 h-3' /></a>
</div>
{list.map((tool) => {
const labelContent = (() => {
if (!tool.labels)
return ''
return tool.labels.map((name) => {
const label = labelList.find(item => item.name === name)
return label?.label[language]
}).filter(Boolean).join(', ')
})()
const added = !!addedTools?.find(v => v.provider_id === toolWithProvider.id && v.provider_type === toolWithProvider.type && v.tool_name === tool.name)
return (
<Tooltip
key={tool.name}
position='bottom'
popupClassName='!p-0 !px-3 !py-2.5 !w-[210px] !leading-[18px] !text-xs !text-gray-700 !border-[0.5px] !border-black/5 !bg-transparent !rounded-xl !shadow-lg translate-x-[108px]'
popupContent={(
<div>
<BlockIcon
size='md'
className='mb-2'
type={BlockEnum.Tool}
toolIcon={toolWithProvider.icon}
/>
<div className='mb-1 text-sm leading-5 text-gray-900'>{tool.label[language]}</div>
<div className='text-xs text-gray-700 leading-[18px]'>{tool.description[language]}</div>
{tool.labels?.length > 0 && (
<div className='flex items-center shrink-0 mt-1'>
<div className='relative w-full flex items-center gap-1 py-1 rounded-md text-gray-500' title={labelContent}>
<Tag01 className='shrink-0 w-3 h-3 text-gray-500' />
<div className='grow text-xs text-start leading-[18px] font-normal truncate'>{labelContent}</div>
</div>
</div>
)}
</div>
)}
>
<div className='group/item flex items-center w-full pl-3 pr-1 h-8 rounded-lg hover:bg-gray-50 cursor-pointer'>
<BlockIcon
className={cn('mr-2 shrink-0', needAuth && 'opacity-30')}
type={BlockEnum.Tool}
toolIcon={toolWithProvider.icon}
/>
<div className={cn('grow text-sm text-gray-900 truncate', needAuth && 'opacity-30')}>{tool.label[language]}</div>
{!needAuth && added && (
<div className='flex items-center gap-1 rounded-[6px] border border-gray-100 px-2 py-[3px] bg-white text-gray-300 text-xs font-medium leading-[18px]'>
<Check className='w-3 h-3' />
{t('tools.addToolModal.added').toLocaleUpperCase()}
</div>
)}
{!needAuth && !added && addable && (
<Button
variant='secondary-accent'
size='small'
className={cn('hidden shrink-0 items-center group-hover/item:flex')}
onClick={() => onSelect(toolWithProvider, tool)}
>
<RiAddLine className='w-3 h-3' />
{t('tools.addToolModal.add').toLocaleUpperCase()}
</Button>
)}
{needAuth && (
<Button
variant='secondary-accent'
size='small'
className={cn('hidden shrink-0 group-hover/item:flex')}
onClick={() => onAuthSetup(toolWithProvider)}
>{t('tools.auth.setup')}</Button>
)}
</div>
</Tooltip>
)
})}
</div>
)
}, [addable, language, t, labelList, addedTools, onAuthSetup, onSelect])
return (
<div className='p-1 pb-6 max-w-[440px]'>
{!tools.length && !showWorkflowEmpty && (
<div className='flex items-center px-3 h-[22px] text-xs font-medium text-gray-500'>{t('workflow.tabs.noResult')}</div>
)}
{!tools.length && showWorkflowEmpty && (
<div className='pt-[280px]'>
<Empty />
</div>
)}
{!!tools.length && tools.map(renderGroup)}
</div>
)
}
export default memo(Blocks)

View File

@@ -0,0 +1,34 @@
'use client'
import { useTranslation } from 'react-i18next'
import cn from '@/utils/classnames'
import { Exchange02, FileCode } from '@/app/components/base/icons/src/vender/line/others'
type Props = {
value: string
onSelect: (type: string) => void
}
const Types = ({
value,
onSelect,
}: Props) => {
const { t } = useTranslation()
return (
<div className='mb-3'>
<div className={cn('mb-0.5 p-1 pl-3 flex items-center cursor-pointer text-sm leading-5 rounded-lg hover:bg-white', value === 'builtin' && '!bg-white font-medium')} onClick={() => onSelect('builtin')}>
<div className="shrink-0 w-4 h-4 mr-2 bg-cover bg-no-repeat bg-[url('~@/app/components/tools/add-tool-modal/D.png')]" />
<span className={cn('text-gray-700', value === 'builtin' && '!text-primary-600')}>{t('tools.type.builtIn')}</span>
</div>
<div className={cn('mb-0.5 p-1 pl-3 flex items-center cursor-pointer text-gray-700 text-sm leading-5 rounded-lg hover:bg-white', value === 'api' && '!bg-white !text-primary-600 font-medium')} onClick={() => onSelect('api')}>
<FileCode className='shrink-0 w-4 h-4 mr-2' />
{t('tools.type.custom')}
</div>
<div className={cn('mb-0.5 p-1 pl-3 flex items-center cursor-pointer text-gray-700 text-sm leading-5 rounded-lg hover:bg-white', value === 'workflow' && '!bg-white !text-primary-600 font-medium')} onClick={() => onSelect('workflow')}>
<Exchange02 className='shrink-0 w-4 h-4 mr-2' />
{t('tools.type.workflow')}
</div>
</div>
)
}
export default Types

View File

@@ -0,0 +1,152 @@
'use client'
import type { FC } from 'react'
import React from 'react'
import { useTranslation } from 'react-i18next'
import Tooltip from '@/app/components/base/tooltip'
import cn from '@/utils/classnames'
import type { Credential } from '@/app/components/tools/types'
import Drawer from '@/app/components/base/drawer-plus'
import Button from '@/app/components/base/button'
import Radio from '@/app/components/base/radio/ui'
import { AuthHeaderPrefix, AuthType } from '@/app/components/tools/types'
type Props = {
positionCenter?: boolean
credential: Credential
onChange: (credential: Credential) => void
onHide: () => void
}
const keyClassNames = 'py-2 leading-5 text-sm font-medium text-gray-900'
type ItemProps = {
text: string
value: AuthType | AuthHeaderPrefix
isChecked: boolean
onClick: (value: AuthType | AuthHeaderPrefix) => void
}
const SelectItem: FC<ItemProps> = ({ text, value, isChecked, onClick }) => {
return (
<div
className={cn(isChecked ? 'border-[2px] border-indigo-600 shadow-sm bg-white' : 'border border-gray-100', 'mb-2 flex items-center h-9 pl-3 w-[150px] rounded-xl bg-gray-25 hover:bg-gray-50 cursor-pointer space-x-2')}
onClick={() => onClick(value)}
>
<Radio isChecked={isChecked} />
<div className='text-sm font-normal text-gray-900'>{text}</div>
</div>
)
}
const ConfigCredential: FC<Props> = ({
positionCenter,
credential,
onChange,
onHide,
}) => {
const { t } = useTranslation()
const [tempCredential, setTempCredential] = React.useState<Credential>(credential)
return (
<Drawer
isShow
positionCenter={positionCenter}
onHide={onHide}
title={t('tools.createTool.authMethod.title')!}
panelClassName='mt-2 !w-[520px] h-fit'
maxWidthClassName='!max-w-[520px]'
height={'fit-content'}
headerClassName='!border-b-black/5'
body={
<div className='pt-2 px-6'>
<div className='space-y-4'>
<div>
<div className={keyClassNames}>{t('tools.createTool.authMethod.type')}</div>
<div className='flex space-x-3'>
<SelectItem
text={t('tools.createTool.authMethod.types.none')}
value={AuthType.none}
isChecked={tempCredential.auth_type === AuthType.none}
onClick={value => setTempCredential({ ...tempCredential, auth_type: value as AuthType })}
/>
<SelectItem
text={t('tools.createTool.authMethod.types.api_key')}
value={AuthType.apiKey}
isChecked={tempCredential.auth_type === AuthType.apiKey}
onClick={value => setTempCredential({
...tempCredential,
auth_type: value as AuthType,
api_key_header: tempCredential.api_key_header || 'Authorization',
api_key_value: tempCredential.api_key_value || '',
api_key_header_prefix: tempCredential.api_key_header_prefix || AuthHeaderPrefix.custom,
})}
/>
</div>
</div>
{tempCredential.auth_type === AuthType.apiKey && (
<>
<div className={keyClassNames}>{t('tools.createTool.authHeaderPrefix.title')}</div>
<div className='flex space-x-3'>
<SelectItem
text={t('tools.createTool.authHeaderPrefix.types.basic')}
value={AuthHeaderPrefix.basic}
isChecked={tempCredential.api_key_header_prefix === AuthHeaderPrefix.basic}
onClick={value => setTempCredential({ ...tempCredential, api_key_header_prefix: value as AuthHeaderPrefix })}
/>
<SelectItem
text={t('tools.createTool.authHeaderPrefix.types.bearer')}
value={AuthHeaderPrefix.bearer}
isChecked={tempCredential.api_key_header_prefix === AuthHeaderPrefix.bearer}
onClick={value => setTempCredential({ ...tempCredential, api_key_header_prefix: value as AuthHeaderPrefix })}
/>
<SelectItem
text={t('tools.createTool.authHeaderPrefix.types.custom')}
value={AuthHeaderPrefix.custom}
isChecked={tempCredential.api_key_header_prefix === AuthHeaderPrefix.custom}
onClick={value => setTempCredential({ ...tempCredential, api_key_header_prefix: value as AuthHeaderPrefix })}
/>
</div>
<div>
<div className='flex items-center h-8 text-[13px] font-medium text-gray-900'>
{t('tools.createTool.authMethod.key')}
<Tooltip
popupContent={
<div className='w-[261px] text-gray-500'>
{t('tools.createTool.authMethod.keyTooltip')}
</div>
}
triggerClassName='ml-0.5 w-4 h-4'
/>
</div>
<input
value={tempCredential.api_key_header}
onChange={e => setTempCredential({ ...tempCredential, api_key_header: e.target.value })}
className='w-full h-10 px-3 text-sm font-normal border border-transparent bg-gray-100 rounded-lg grow outline-none focus:bg-components-input-bg-active focus:border-components-input-border-active focus:shadow-xs'
placeholder={t('tools.createTool.authMethod.types.apiKeyPlaceholder')!}
/>
</div>
<div>
<div className={keyClassNames}>{t('tools.createTool.authMethod.value')}</div>
<input
value={tempCredential.api_key_value}
onChange={e => setTempCredential({ ...tempCredential, api_key_value: e.target.value })}
className='w-full h-10 px-3 text-sm font-normal border border-transparent bg-gray-100 rounded-lg grow outline-none focus:bg-components-input-bg-active focus:border-components-input-border-active focus:shadow-xs'
placeholder={t('tools.createTool.authMethod.types.apiValuePlaceholder')!}
/>
</div>
</>)}
</div>
<div className='mt-4 shrink-0 flex justify-end space-x-2 py-4'>
<Button onClick={onHide}>{t('common.operation.cancel')}</Button>
<Button variant='primary' onClick={() => {
onChange(tempCredential)
onHide()
}}>{t('common.operation.save')}</Button>
</div>
</div>
}
/>
)
}
export default React.memo(ConfigCredential)

View File

@@ -0,0 +1,181 @@
const examples = [
{
key: 'json',
content: `{
"openapi": "3.1.0",
"info": {
"title": "Get weather data",
"description": "Retrieves current weather data for a location.",
"version": "v1.0.0"
},
"servers": [
{
"url": "https://weather.example.com"
}
],
"paths": {
"/location": {
"get": {
"description": "Get temperature for a specific location",
"operationId": "GetCurrentWeather",
"parameters": [
{
"name": "location",
"in": "query",
"description": "The city and state to retrieve the weather for",
"required": true,
"schema": {
"type": "string"
}
}
],
"deprecated": false
}
}
},
"components": {
"schemas": {}
}
}`,
},
{
key: 'yaml',
content: `# Taken from https://github.com/OAI/OpenAPI-Specification/blob/main/examples/v3.0/petstore.yaml
openapi: "3.0.0"
info:
version: 1.0.0
title: Swagger Petstore
license:
name: MIT
servers:
- url: https://petstore.swagger.io/v1
paths:
/pets:
get:
summary: List all pets
operationId: listPets
tags:
- pets
parameters:
- name: limit
in: query
description: How many items to return at one time (max 100)
required: false
schema:
type: integer
maximum: 100
format: int32
responses:
'200':
description: A paged array of pets
headers:
x-next:
description: A link to the next page of responses
schema:
type: string
content:
application/json:
schema:
$ref: "#/components/schemas/Pets"
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
post:
summary: Create a pet
operationId: createPets
tags:
- pets
responses:
'201':
description: Null response
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
/pets/{petId}:
get:
summary: Info for a specific pet
operationId: showPetById
tags:
- pets
parameters:
- name: petId
in: path
required: true
description: The id of the pet to retrieve
schema:
type: string
responses:
'200':
description: Expected response to a valid request
content:
application/json:
schema:
$ref: "#/components/schemas/Pet"
default:
description: unexpected error
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
components:
schemas:
Pet:
type: object
required:
- id
- name
properties:
id:
type: integer
format: int64
name:
type: string
tag:
type: string
Pets:
type: array
maxItems: 100
items:
$ref: "#/components/schemas/Pet"
Error:
type: object
required:
- code
- message
properties:
code:
type: integer
format: int32
message:
type: string`,
},
{
key: 'blankTemplate',
content: `{
"openapi": "3.1.0",
"info": {
"title": "Untitled",
"description": "Your OpenAPI specification",
"version": "v1.0.0"
},
"servers": [
{
"url": ""
}
],
"paths": {},
"components": {
"schemas": {}
}
}`,
},
]
export default examples

View File

@@ -0,0 +1,122 @@
'use client'
import type { FC } from 'react'
import React, { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useClickAway } from 'ahooks'
import {
RiAddLine,
RiArrowDownSLine,
} from '@remixicon/react'
import Toast from '../../base/toast'
import examples from './examples'
import Button from '@/app/components/base/button'
import { importSchemaFromURL } from '@/service/tools'
type Props = {
onChange: (value: string) => void
}
const GetSchema: FC<Props> = ({
onChange,
}) => {
const { t } = useTranslation()
const [showImportFromUrl, setShowImportFromUrl] = useState(false)
const [importUrl, setImportUrl] = useState('')
const [isParsing, setIsParsing] = useState(false)
const handleImportFromUrl = async () => {
if (!importUrl.startsWith('http://') && !importUrl.startsWith('https://')) {
Toast.notify({
type: 'error',
message: t('tools.createTool.urlError'),
})
return
}
setIsParsing(true)
try {
const { schema } = await importSchemaFromURL(importUrl) as any
setImportUrl('')
onChange(schema)
}
finally {
setIsParsing(false)
setShowImportFromUrl(false)
}
}
const importURLRef = React.useRef(null)
useClickAway(() => {
setShowImportFromUrl(false)
}, importURLRef)
const [showExamples, setShowExamples] = useState(false)
const showExamplesRef = React.useRef(null)
useClickAway(() => {
setShowExamples(false)
}, showExamplesRef)
return (
<div className='flex space-x-1 justify-end relative w-[224px]'>
<div ref={importURLRef}>
<Button
size='small'
className='space-x-1 '
onClick={() => { setShowImportFromUrl(!showImportFromUrl) }}
>
<RiAddLine className='w-3 h-3' />
<div className='text-xs font-medium text-gray-700'>{t('tools.createTool.importFromUrl')}</div>
</Button>
{showImportFromUrl && (
<div className=' absolute left-[-35px] top-[26px] p-2 rounded-lg border border-gray-200 bg-white shadow-lg'>
<div className='relative'>
<input
type='text'
className='w-[244px] h-8 pl-1.5 pr-[44px] overflow-x-auto border border-gray-200 rounded-lg text-[13px] focus:outline-none focus:border-components-input-border-active'
placeholder={t('tools.createTool.importFromUrlPlaceHolder')!}
value={importUrl}
onChange={e => setImportUrl(e.target.value)}
/>
<Button
className='absolute top-1 right-1'
size='small'
variant='primary'
disabled={!importUrl}
onClick={handleImportFromUrl}
loading={isParsing}
>
{isParsing ? '' : t('common.operation.ok')}
</Button>
</div>
</div>
)}
</div>
<div className='relative -mt-0.5' ref={showExamplesRef}>
<Button
size='small'
className='space-x-1'
onClick={() => { setShowExamples(!showExamples) }}
>
<div className='text-xs font-medium text-gray-700'>{t('tools.createTool.examples')}</div>
<RiArrowDownSLine className='w-3 h-3' />
</Button>
{showExamples && (
<div className='absolute top-7 right-0 p-1 rounded-lg bg-white shadow-sm'>
{examples.map(item => (
<div
key={item.key}
onClick={() => {
onChange(item.content)
setShowExamples(false)
}}
className='px-3 py-1.5 rounded-lg hover:bg-gray-50 leading-5 text-sm font-normal text-gray-700 cursor-pointer whitespace-nowrap'
>
{t(`tools.createTool.exampleOptions.${item.key}`)}
</div>
))}
</div>
)}
</div>
</div>
)
}
export default React.memo(GetSchema)

View File

@@ -0,0 +1,366 @@
'use client'
import type { FC } from 'react'
import React, { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useDebounce, useGetState } from 'ahooks'
import produce from 'immer'
import { LinkExternal02, Settings01 } from '../../base/icons/src/vender/line/general'
import type { Credential, CustomCollectionBackend, CustomParamSchema, Emoji } from '../types'
import { AuthHeaderPrefix, AuthType } from '../types'
import GetSchema from './get-schema'
import ConfigCredentials from './config-credentials'
import TestApi from './test-api'
import cn from '@/utils/classnames'
import Drawer from '@/app/components/base/drawer-plus'
import Button from '@/app/components/base/button'
import Input from '@/app/components/base/input'
import Textarea from '@/app/components/base/textarea'
import EmojiPicker from '@/app/components/base/emoji-picker'
import AppIcon from '@/app/components/base/app-icon'
import { parseParamsSchema } from '@/service/tools'
import LabelSelector from '@/app/components/tools/labels/selector'
import Toast from '@/app/components/base/toast'
const fieldNameClassNames = 'py-2 leading-5 text-sm font-medium text-gray-900'
type Props = {
positionLeft?: boolean
payload: any
onHide: () => void
onAdd?: (payload: CustomCollectionBackend) => void
onRemove?: () => void
onEdit?: (payload: CustomCollectionBackend) => void
}
// Add and Edit
const EditCustomCollectionModal: FC<Props> = ({
positionLeft,
payload,
onHide,
onAdd,
onEdit,
onRemove,
}) => {
const { t } = useTranslation()
const isAdd = !payload
const isEdit = !!payload
const [editFirst, setEditFirst] = useState(!isAdd)
const [paramsSchemas, setParamsSchemas] = useState<CustomParamSchema[]>(payload?.tools || [])
const [customCollection, setCustomCollection, getCustomCollection] = useGetState<CustomCollectionBackend>(isAdd
? {
provider: '',
credentials: {
auth_type: AuthType.none,
api_key_header: 'Authorization',
api_key_header_prefix: AuthHeaderPrefix.basic,
},
icon: {
content: '🕵️',
background: '#FEF7C3',
},
schema_type: '',
schema: '',
}
: payload)
const originalProvider = isEdit ? payload.provider : ''
const [showEmojiPicker, setShowEmojiPicker] = useState(false)
const emoji = customCollection.icon
const setEmoji = (emoji: Emoji) => {
const newCollection = produce(customCollection, (draft) => {
draft.icon = emoji
})
setCustomCollection(newCollection)
}
const schema = customCollection.schema
const debouncedSchema = useDebounce(schema, { wait: 500 })
const setSchema = (schema: any) => {
const newCollection = produce(customCollection, (draft) => {
draft.schema = schema
})
setCustomCollection(newCollection)
}
useEffect(() => {
if (!debouncedSchema)
return
if (isEdit && editFirst) {
setEditFirst(false)
return
}
(async () => {
try {
const { parameters_schema, schema_type } = await parseParamsSchema(debouncedSchema)
const customCollection = getCustomCollection()
const newCollection = produce(customCollection, (draft) => {
draft.schema_type = schema_type
})
setCustomCollection(newCollection)
setParamsSchemas(parameters_schema)
}
catch (e) {
const customCollection = getCustomCollection()
const newCollection = produce(customCollection, (draft) => {
draft.schema_type = ''
})
setCustomCollection(newCollection)
setParamsSchemas([])
}
})()
}, [debouncedSchema])
const [credentialsModalShow, setCredentialsModalShow] = useState(false)
const credential = customCollection.credentials
const setCredential = (credential: Credential) => {
const newCollection = produce(customCollection, (draft) => {
draft.credentials = credential
})
setCustomCollection(newCollection)
}
const [currTool, setCurrTool] = useState<CustomParamSchema | null>(null)
const [isShowTestApi, setIsShowTestApi] = useState(false)
const [labels, setLabels] = useState<string[]>(payload?.labels || [])
const handleLabelSelect = (value: string[]) => {
setLabels(value)
}
const handleSave = () => {
// const postData = clone(customCollection)
const postData = produce(customCollection, (draft) => {
delete draft.tools
if (draft.credentials.auth_type === AuthType.none) {
delete draft.credentials.api_key_header
delete draft.credentials.api_key_header_prefix
delete draft.credentials.api_key_value
}
draft.labels = labels
})
let errorMessage = ''
if (!postData.provider)
errorMessage = t('common.errorMsg.fieldRequired', { field: t('tools.createTool.name') })
if (!postData.schema)
errorMessage = t('common.errorMsg.fieldRequired', { field: t('tools.createTool.schema') })
if (errorMessage) {
Toast.notify({
type: 'error',
message: errorMessage,
})
return
}
if (isAdd) {
onAdd?.(postData)
return
}
onEdit?.({
...postData,
original_provider: originalProvider,
})
}
const getPath = (url: string) => {
if (!url)
return ''
try {
const path = decodeURI(new URL(url).pathname)
return path || ''
}
catch (e) {
return url
}
}
return (
<>
<Drawer
isShow
positionCenter={isAdd && !positionLeft}
onHide={onHide}
title={t(`tools.createTool.${isAdd ? 'title' : 'editTitle'}`)!}
panelClassName='mt-2 !w-[640px]'
maxWidthClassName='!max-w-[640px]'
height='calc(100vh - 16px)'
headerClassName='!border-b-black/5'
body={
<div className='flex flex-col h-full'>
<div className='grow h-0 overflow-y-auto px-6 py-3 space-y-4'>
<div>
<div className={fieldNameClassNames}>{t('tools.createTool.name')} <span className='ml-1 text-red-500'>*</span></div>
<div className='flex items-center justify-between gap-3'>
<AppIcon size='large' onClick={() => { setShowEmojiPicker(true) }} className='cursor-pointer' icon={emoji.content} background={emoji.background} />
<Input
className='h-10 grow' placeholder={t('tools.createTool.toolNamePlaceHolder')!}
value={customCollection.provider}
onChange={(e) => {
const newCollection = produce(customCollection, (draft) => {
draft.provider = e.target.value
})
setCustomCollection(newCollection)
}}
/>
</div>
</div>
{/* Schema */}
<div className='select-none'>
<div className='flex justify-between items-center'>
<div className='flex items-center'>
<div className={fieldNameClassNames}>{t('tools.createTool.schema')}<span className='ml-1 text-red-500'>*</span></div>
<div className='mx-2 w-px h-3 bg-black/5'></div>
<a
href="https://swagger.io/specification/"
target='_blank' rel='noopener noreferrer'
className='flex items-center h-[18px] space-x-1 text-[#155EEF]'
>
<div className='text-xs font-normal'>{t('tools.createTool.viewSchemaSpec')}</div>
<LinkExternal02 className='w-3 h-3' />
</a>
</div>
<GetSchema onChange={setSchema} />
</div>
<Textarea
className='h-[240px] resize-none'
value={schema}
onChange={e => setSchema(e.target.value)}
placeholder={t('tools.createTool.schemaPlaceHolder')!}
/>
</div>
{/* Available Tools */}
<div>
<div className={fieldNameClassNames}>{t('tools.createTool.availableTools.title')}</div>
<div className='rounded-lg border border-gray-200 w-full overflow-x-auto'>
<table className='w-full leading-[18px] text-xs text-gray-700 font-normal'>
<thead className='text-gray-500 uppercase'>
<tr className={cn(paramsSchemas.length > 0 && 'border-b', 'border-gray-200')}>
<th className="p-2 pl-3 font-medium">{t('tools.createTool.availableTools.name')}</th>
<th className="p-2 pl-3 font-medium w-[236px]">{t('tools.createTool.availableTools.description')}</th>
<th className="p-2 pl-3 font-medium">{t('tools.createTool.availableTools.method')}</th>
<th className="p-2 pl-3 font-medium">{t('tools.createTool.availableTools.path')}</th>
<th className="p-2 pl-3 font-medium w-[54px]">{t('tools.createTool.availableTools.action')}</th>
</tr>
</thead>
<tbody>
{paramsSchemas.map((item, index) => (
<tr key={index} className='border-b last:border-0 border-gray-200'>
<td className="p-2 pl-3">{item.operation_id}</td>
<td className="p-2 pl-3 text-gray-500 w-[236px]">{item.summary}</td>
<td className="p-2 pl-3">{item.method}</td>
<td className="p-2 pl-3">{getPath(item.server_url)}</td>
<td className="p-2 pl-3 w-[62px]">
<Button
size='small'
onClick={() => {
setCurrTool(item)
setIsShowTestApi(true)
}}
>
{t('tools.createTool.availableTools.test')}
</Button>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
{/* Authorization method */}
<div>
<div className={fieldNameClassNames}>{t('tools.createTool.authMethod.title')}</div>
<div className='flex items-center h-9 justify-between px-2.5 bg-gray-100 rounded-lg cursor-pointer' onClick={() => setCredentialsModalShow(true)}>
<div className='text-sm font-normal text-gray-900'>{t(`tools.createTool.authMethod.types.${credential.auth_type}`)}</div>
<Settings01 className='w-4 h-4 text-gray-700 opacity-60' />
</div>
</div>
{/* Labels */}
<div>
<div className='py-2 leading-5 text-sm font-medium text-gray-900'>{t('tools.createTool.toolInput.label')}</div>
<LabelSelector value={labels} onChange={handleLabelSelect} />
</div>
{/* Privacy Policy */}
<div>
<div className={fieldNameClassNames}>{t('tools.createTool.privacyPolicy')}</div>
<Input
value={customCollection.privacy_policy}
onChange={(e) => {
const newCollection = produce(customCollection, (draft) => {
draft.privacy_policy = e.target.value
})
setCustomCollection(newCollection)
}}
className='h-10 grow' placeholder={t('tools.createTool.privacyPolicyPlaceholder') || ''} />
</div>
<div>
<div className={fieldNameClassNames}>{t('tools.createTool.customDisclaimer')}</div>
<Input
value={customCollection.custom_disclaimer}
onChange={(e) => {
const newCollection = produce(customCollection, (draft) => {
draft.custom_disclaimer = e.target.value
})
setCustomCollection(newCollection)
}}
className='h-10 grow' placeholder={t('tools.createTool.customDisclaimerPlaceholder') || ''} />
</div>
</div>
<div className={cn(isEdit ? 'justify-between' : 'justify-end', 'mt-2 shrink-0 flex py-4 px-6 rounded-b-[10px] bg-gray-50 border-t border-black/5')} >
{
isEdit && (
<Button onClick={onRemove} className='text-red-500 border-red-50 hover:border-red-500'>{t('common.operation.delete')}</Button>
)
}
<div className='flex space-x-2 '>
<Button onClick={onHide}>{t('common.operation.cancel')}</Button>
<Button variant='primary' onClick={handleSave}>{t('common.operation.save')}</Button>
</div>
</div>
{showEmojiPicker && <EmojiPicker
onSelect={(icon, icon_background) => {
setEmoji({ content: icon, background: icon_background })
setShowEmojiPicker(false)
}}
onClose={() => {
setShowEmojiPicker(false)
}}
/>}
{credentialsModalShow && (
<ConfigCredentials
positionCenter={isAdd}
credential={credential}
onChange={setCredential}
onHide={() => setCredentialsModalShow(false)}
/>)
}
{isShowTestApi && (
<TestApi
positionCenter={isAdd}
tool={currTool as CustomParamSchema}
customCollection={customCollection}
onHide={() => setIsShowTestApi(false)}
/>
)}
</div>
}
isShowMask={true}
clickOutsideNotOpen={true}
/>
</>
)
}
export default React.memo(EditCustomCollectionModal)

View File

@@ -0,0 +1,134 @@
'use client'
import type { FC } from 'react'
import React, { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useContext } from 'use-context-selector'
import { Settings01 } from '../../base/icons/src/vender/line/general'
import ConfigCredentials from './config-credentials'
import { AuthType, type Credential, type CustomCollectionBackend, type CustomParamSchema } from '@/app/components/tools/types'
import Button from '@/app/components/base/button'
import Drawer from '@/app/components/base/drawer-plus'
import I18n from '@/context/i18n'
import { testAPIAvailable } from '@/service/tools'
import { getLanguage } from '@/i18n/language'
type Props = {
positionCenter?: boolean
customCollection: CustomCollectionBackend
tool: CustomParamSchema
onHide: () => void
}
const keyClassNames = 'py-2 leading-5 text-sm font-medium text-gray-900'
const TestApi: FC<Props> = ({
positionCenter,
customCollection,
tool,
onHide,
}) => {
const { t } = useTranslation()
const { locale } = useContext(I18n)
const language = getLanguage(locale)
const [credentialsModalShow, setCredentialsModalShow] = useState(false)
const [tempCredential, setTempCredential] = React.useState<Credential>(customCollection.credentials)
const [result, setResult] = useState<string>('')
const { operation_id: toolName, parameters } = tool
const [parametersValue, setParametersValue] = useState<Record<string, string>>({})
const handleTest = async () => {
// 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)
}
return (
<>
<Drawer
isShow
positionCenter={positionCenter}
onHide={onHide}
title={`${t('tools.test.title')} ${toolName}`}
panelClassName='mt-2 !w-[600px]'
maxWidthClassName='!max-w-[600px]'
height='calc(100vh - 16px)'
headerClassName='!border-b-black/5'
body={
<div className='pt-2 px-6 overflow-y-auto'>
<div className='space-y-4'>
<div>
<div className={keyClassNames}>{t('tools.createTool.authMethod.title')}</div>
<div className='flex items-center h-9 justify-between px-2.5 bg-gray-100 rounded-lg cursor-pointer' onClick={() => setCredentialsModalShow(true)}>
<div className='text-sm font-normal text-gray-900'>{t(`tools.createTool.authMethod.types.${tempCredential.auth_type}`)}</div>
<Settings01 className='w-4 h-4 text-gray-700 opacity-60' />
</div>
</div>
<div>
<div className={keyClassNames}>{t('tools.test.parametersValue')}</div>
<div className='rounded-lg border border-gray-200'>
<table className='w-full leading-[18px] text-xs text-gray-700 font-normal'>
<thead className='text-gray-500 uppercase'>
<tr className='border-b border-gray-200'>
<th className="p-2 pl-3 font-medium">{t('tools.test.parameters')}</th>
<th className="p-2 pl-3 font-medium">{t('tools.test.value')}</th>
</tr>
</thead>
<tbody>
{parameters.map((item, index) => (
<tr key={index} className='border-b last:border-0 border-gray-200'>
<td className="py-2 pl-3 pr-2.5">
{item.label[language]}
</td>
<td className="">
<input
value={parametersValue[item.name] || ''}
onChange={e => setParametersValue({ ...parametersValue, [item.name]: e.target.value })}
type='text' className='px-3 h-[34px] w-full outline-none focus:bg-gray-100' ></input>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</div>
<Button variant='primary' className=' mt-4 w-full h-10' onClick={handleTest}>{t('tools.test.title')}</Button>
<div className='mt-6'>
<div className='flex items-center space-x-3'>
<div className='leading-[18px] text-xs font-semibold text-gray-500'>{t('tools.test.testResult')}</div>
<div className='grow w-0 h-px bg-[rgb(243, 244, 246)]'></div>
</div>
<div className='mt-2 px-3 py-2 h-[200px] overflow-y-auto overflow-x-hidden rounded-lg bg-gray-100 leading-4 text-xs font-normal text-gray-700'>
{result || <span className='text-gray-400'>{t('tools.test.testResultPlaceholder')}</span>}
</div>
</div>
</div>
}
/>
{credentialsModalShow && (
<ConfigCredentials
positionCenter={positionCenter}
credential={tempCredential}
onChange={setTempCredential}
onHide={() => setCredentialsModalShow(false)}
/>)
}
</>
)
}
export default React.memo(TestApi)

View File

@@ -0,0 +1,6 @@
import type { TypeWithI18N } from '@/app/components/header/account-setting/model-provider-page/declarations'
export type Label = {
name: string
icon: string
label: TypeWithI18N
}

View File

@@ -0,0 +1,150 @@
import type { FC } from 'react'
import { useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useContext } from 'use-context-selector'
import { useDebounceFn, useMount } from 'ahooks'
import { RiArrowDownSLine } from '@remixicon/react'
import { useStore as useLabelStore } from './store'
import cn from '@/utils/classnames'
import {
PortalToFollowElem,
PortalToFollowElemContent,
PortalToFollowElemTrigger,
} from '@/app/components/base/portal-to-follow-elem'
import Input from '@/app/components/base/input'
import { Tag01, Tag03 } from '@/app/components/base/icons/src/vender/line/financeAndECommerce'
import { Check } from '@/app/components/base/icons/src/vender/line/general'
import { XCircle } from '@/app/components/base/icons/src/vender/solid/general'
import type { Label } from '@/app/components/tools/labels/constant'
import { fetchLabelList } from '@/service/tools'
import I18n from '@/context/i18n'
import { getLanguage } from '@/i18n/language'
type LabelFilterProps = {
value: string[]
onChange: (v: string[]) => void
}
const LabelFilter: FC<LabelFilterProps> = ({
value,
onChange,
}) => {
const { t } = useTranslation()
const { locale } = useContext(I18n)
const language = getLanguage(locale)
const [open, setOpen] = useState(false)
const labelList = useLabelStore(s => s.labelList)
const setLabelList = useLabelStore(s => s.setLabelList)
const [keywords, setKeywords] = useState('')
const [searchKeywords, setSearchKeywords] = useState('')
const { run: handleSearch } = useDebounceFn(() => {
setSearchKeywords(keywords)
}, { wait: 500 })
const handleKeywordsChange = (value: string) => {
setKeywords(value)
handleSearch()
}
const filteredLabelList = useMemo(() => {
return labelList.filter(label => label.name.includes(searchKeywords))
}, [labelList, searchKeywords])
const currentLabel = useMemo(() => {
return labelList.find(label => label.name === value[0])
}, [value, labelList])
const selectLabel = (label: Label) => {
if (value.includes(label.name))
onChange(value.filter(v => v !== label.name))
else
onChange([...value, label.name])
}
useMount(() => {
fetchLabelList().then((res) => {
setLabelList(res)
})
})
return (
<PortalToFollowElem
open={open}
onOpenChange={setOpen}
placement='bottom-start'
offset={4}
>
<div className='relative'>
<PortalToFollowElemTrigger
onClick={() => setOpen(v => !v)}
className='block'
>
<div className={cn(
'flex items-center gap-1 px-2 h-8 rounded-lg border-[0.5px] border-transparent bg-gray-200 cursor-pointer hover:bg-gray-300',
open && !value.length && '!bg-gray-300 hover:bg-gray-300',
!open && !!value.length && '!bg-white/80 shadow-xs !border-black/5 hover:!bg-gray-200',
open && !!value.length && '!bg-gray-200 !border-black/5 shadow-xs hover:!bg-gray-200',
)}>
<div className='p-[1px]'>
<Tag01 className='h-3.5 w-3.5 text-gray-700' />
</div>
<div className='text-[13px] leading-[18px] text-gray-700'>
{!value.length && t('common.tag.placeholder')}
{!!value.length && currentLabel?.label[language]}
</div>
{value.length > 1 && (
<div className='text-xs font-medium leading-[18px] text-gray-500'>{`+${value.length - 1}`}</div>
)}
{!value.length && (
<div className='p-[1px]'>
<RiArrowDownSLine className='h-3.5 w-3.5 text-gray-700' />
</div>
)}
{!!value.length && (
<div className='p-[1px] cursor-pointer group/clear' onClick={(e) => {
e.stopPropagation()
onChange([])
}}>
<XCircle className='h-3.5 w-3.5 text-gray-400 group-hover/clear:text-gray-600' />
</div>
)}
</div>
</PortalToFollowElemTrigger>
<PortalToFollowElemContent className='z-[1002]'>
<div className='relative w-[240px] bg-white rounded-lg border-[0.5px] border-gray-200 shadow-lg'>
<div className='p-2 border-b-[0.5px] border-black/5'>
<Input
showLeftIcon
showClearIcon
value={keywords}
onChange={e => handleKeywordsChange(e.target.value)}
onClear={() => handleKeywordsChange('')}
/>
</div>
<div className='p-1'>
{filteredLabelList.map(label => (
<div
key={label.name}
className='flex items-center gap-2 pl-3 py-[6px] pr-2 rounded-lg cursor-pointer hover:bg-gray-100'
onClick={() => selectLabel(label)}
>
<div title={label.label[language]} className='grow text-sm text-gray-700 leading-5 truncate'>{label.label[language]}</div>
{value.includes(label.name) && <Check className='shrink-0 w-4 h-4 text-primary-600' />}
</div>
))}
{!filteredLabelList.length && (
<div className='p-3 flex flex-col items-center gap-1'>
<Tag03 className='h-6 w-6 text-gray-300' />
<div className='text-gray-500 text-xs leading-[14px]'>{t('common.tag.noTag')}</div>
</div>
)}
</div>
</div>
</PortalToFollowElemContent>
</div>
</PortalToFollowElem>
)
}
export default LabelFilter

View File

@@ -0,0 +1,134 @@
import type { FC } from 'react'
import { useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useContext } from 'use-context-selector'
import { useDebounceFn, useMount } from 'ahooks'
import { RiArrowDownSLine } from '@remixicon/react'
import { useStore as useLabelStore } from './store'
import cn from '@/utils/classnames'
import {
PortalToFollowElem,
PortalToFollowElemContent,
PortalToFollowElemTrigger,
} from '@/app/components/base/portal-to-follow-elem'
import Input from '@/app/components/base/input'
import { Tag03 } from '@/app/components/base/icons/src/vender/line/financeAndECommerce'
import Checkbox from '@/app/components/base/checkbox'
import type { Label } from '@/app/components/tools/labels/constant'
import { fetchLabelList } from '@/service/tools'
import I18n from '@/context/i18n'
import { getLanguage } from '@/i18n/language'
type LabelSelectorProps = {
value: string[]
onChange: (v: string[]) => void
}
const LabelSelector: FC<LabelSelectorProps> = ({
value,
onChange,
}) => {
const { t } = useTranslation()
const { locale } = useContext(I18n)
const language = getLanguage(locale)
const [open, setOpen] = useState(false)
const labelList = useLabelStore(s => s.labelList)
const setLabelList = useLabelStore(s => s.setLabelList)
const [keywords, setKeywords] = useState('')
const [searchKeywords, setSearchKeywords] = useState('')
const { run: handleSearch } = useDebounceFn(() => {
setSearchKeywords(keywords)
}, { wait: 500 })
const handleKeywordsChange = (value: string) => {
setKeywords(value)
handleSearch()
}
const filteredLabelList = useMemo(() => {
return labelList.filter(label => label.name.includes(searchKeywords))
}, [labelList, searchKeywords])
const selectedLabels = useMemo(() => {
return value.map(v => labelList.find(l => l.name === v)?.label[language]).join(', ')
}, [value, labelList, language])
const selectLabel = (label: Label) => {
if (value.includes(label.name))
onChange(value.filter(v => v !== label.name))
else
onChange([...value, label.name])
}
useMount(() => {
fetchLabelList().then((res) => {
setLabelList(res)
})
})
return (
<PortalToFollowElem
open={open}
onOpenChange={setOpen}
placement='bottom-start'
offset={4}
>
<div className='relative'>
<PortalToFollowElemTrigger
onClick={() => setOpen(v => !v)}
className='block'
>
<div className={cn(
'flex items-center gap-1 px-3 h-10 rounded-lg border-[0.5px] border-transparent bg-gray-100 cursor-pointer hover:bg-gray-200',
open && '!bg-gray-200 hover:bg-gray-200',
)}>
<div title={value.length > 0 ? selectedLabels : ''} className={cn('grow text-[13px] leading-[18px] text-gray-700 truncate', !value.length && '!text-gray-400')}>
{!value.length && t('tools.createTool.toolInput.labelPlaceholder')}
{!!value.length && selectedLabels}
</div>
<div className='shrink-0 ml-1 text-gray-700 opacity-60'>
<RiArrowDownSLine className='h-4 w-4' />
</div>
</div>
</PortalToFollowElemTrigger>
<PortalToFollowElemContent className='z-[1040]'>
<div className='relative w-[591px] bg-white rounded-lg border-[0.5px] border-gray-200 shadow-lg'>
<div className='p-2 border-b-[0.5px] border-black/5'>
<Input
showLeftIcon
showClearIcon
value={keywords}
onChange={e => handleKeywordsChange(e.target.value)}
onClear={() => handleKeywordsChange('')}
/>
</div>
<div className='p-1 max-h-[264px] overflow-y-auto'>
{filteredLabelList.map(label => (
<div
key={label.name}
className='flex items-center gap-2 pl-3 py-[6px] pr-2 rounded-lg cursor-pointer hover:bg-gray-100'
onClick={() => selectLabel(label)}
>
<Checkbox
className='shrink-0'
checked={value.includes(label.name)}
onCheck={() => { }}
/>
<div title={label.label[language]} className='grow text-sm text-gray-700 leading-5 truncate'>{label.label[language]}</div>
</div>
))}
{!filteredLabelList.length && (
<div className='p-3 flex flex-col items-center gap-1'>
<Tag03 className='h-6 w-6 text-gray-300' />
<div className='text-gray-500 text-xs leading-[14px]'>{t('common.tag.noTag')}</div>
</div>
)}
</div>
</div>
</PortalToFollowElemContent>
</div>
</PortalToFollowElem>
)
}
export default LabelSelector

View File

@@ -0,0 +1,15 @@
import { create } from 'zustand'
import type { Label } from './constant'
type State = {
labelList: Label[]
}
type Action = {
setLabelList: (labelList?: Label[]) => void
}
export const useStore = create<State & Action>(set => ({
labelList: [],
setLabelList: labelList => set(() => ({ labelList })),
}))

View File

@@ -0,0 +1,125 @@
'use client'
import { useEffect, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { RiCloseLine } from '@remixicon/react'
import type { Collection } from './types'
import cn from '@/utils/classnames'
import { useTabSearchParams } from '@/hooks/use-tab-searchparams'
import TabSliderNew from '@/app/components/base/tab-slider-new'
import LabelFilter from '@/app/components/tools/labels/filter'
import Input from '@/app/components/base/input'
import { DotsGrid } from '@/app/components/base/icons/src/vender/line/general'
import { Colors } from '@/app/components/base/icons/src/vender/line/others'
import { Route } from '@/app/components/base/icons/src/vender/line/mapsAndTravel'
import CustomCreateCard from '@/app/components/tools/provider/custom-create-card'
import ContributeCard from '@/app/components/tools/provider/contribute'
import ProviderCard from '@/app/components/tools/provider/card'
import ProviderDetail from '@/app/components/tools/provider/detail'
import Empty from '@/app/components/tools/add-tool-modal/empty'
import { fetchCollectionList } from '@/service/tools'
const ProviderList = () => {
const { t } = useTranslation()
const [activeTab, setActiveTab] = useTabSearchParams({
defaultTab: 'builtin',
})
const options = [
{ value: 'builtin', text: t('tools.type.builtIn'), icon: <DotsGrid className='w-[14px] h-[14px] mr-1' /> },
{ value: 'api', text: t('tools.type.custom'), icon: <Colors className='w-[14px] h-[14px] mr-1' /> },
{ value: 'workflow', text: t('tools.type.workflow'), icon: <Route className='w-[14px] h-[14px] mr-1' /> },
]
const [tagFilterValue, setTagFilterValue] = useState<string[]>([])
const handleTagsChange = (value: string[]) => {
setTagFilterValue(value)
}
const [keywords, setKeywords] = useState<string>('')
const handleKeywordsChange = (value: string) => {
setKeywords(value)
}
const [collectionList, setCollectionList] = useState<Collection[]>([])
const filteredCollectionList = useMemo(() => {
return collectionList.filter((collection) => {
if (collection.type !== activeTab)
return false
if (tagFilterValue.length > 0 && (!collection.labels || collection.labels.every(label => !tagFilterValue.includes(label))))
return false
if (keywords)
return Object.values(collection.label).some(value => value.toLowerCase().includes(keywords.toLowerCase()))
return true
})
}, [activeTab, tagFilterValue, keywords, collectionList])
const getProviderList = async () => {
const list = await fetchCollectionList()
setCollectionList([...list])
}
useEffect(() => {
getProviderList()
}, [])
const [currentProvider, setCurrentProvider] = useState<Collection | undefined>()
useEffect(() => {
if (currentProvider && collectionList.length > 0) {
const newCurrentProvider = collectionList.find(collection => collection.id === currentProvider.id)
setCurrentProvider(newCurrentProvider)
}
}, [collectionList, currentProvider])
return (
<div className='relative flex overflow-hidden bg-gray-100 shrink-0 h-0 grow'>
<div className='relative flex flex-col overflow-y-auto bg-gray-100 grow'>
<div className={cn(
'sticky top-0 flex justify-between items-center pt-4 px-12 pb-2 leading-[56px] bg-gray-100 z-20 flex-wrap gap-y-2',
currentProvider && 'pr-6',
)}>
<TabSliderNew
value={activeTab}
onChange={(state) => {
setActiveTab(state)
if (state !== activeTab)
setCurrentProvider(undefined)
}}
options={options}
/>
<div className='flex items-center gap-2'>
<LabelFilter value={tagFilterValue} onChange={handleTagsChange} />
<Input
showLeftIcon
showClearIcon
wrapperClassName='w-[200px]'
value={keywords}
onChange={e => handleKeywordsChange(e.target.value)}
onClear={() => handleKeywordsChange('')}
/>
</div>
</div>
<div className={cn(
'relative grid content-start grid-cols-1 gap-4 px-12 pt-2 pb-4 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 grow shrink-0',
currentProvider && 'pr-6 sm:grid-cols-1 md:grid-cols-2 lg:grid-cols-3',
)}>
{activeTab === 'builtin' && <ContributeCard />}
{activeTab === 'api' && <CustomCreateCard onRefreshData={getProviderList} />}
{filteredCollectionList.map(collection => (
<ProviderCard
active={currentProvider?.id === collection.id}
onSelect={() => setCurrentProvider(collection)}
key={collection.id}
collection={collection}
/>
))}
{!filteredCollectionList.length && <div className='absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2'><Empty /></div>}
</div>
</div>
<div className={cn(
'shrink-0 w-0 border-l-[0.5px] border-black/8 overflow-y-auto transition-all duration-200 ease-in-out',
currentProvider && 'w-[420px]',
)}>
{currentProvider && <ProviderDetail collection={currentProvider} onRefreshData={getProviderList} />}
</div>
<div className='absolute top-5 right-5 p-1 cursor-pointer' onClick={() => setCurrentProvider(undefined)}><RiCloseLine className='w-4 h-4' /></div>
</div>
)
}
ProviderList.displayName = 'ToolProviderList'
export default ProviderList

View File

@@ -0,0 +1,83 @@
'use client'
import { useMemo } from 'react'
import { useContext } from 'use-context-selector'
import { useTranslation } from 'react-i18next'
import type { Collection } from '../types'
import cn from '@/utils/classnames'
import AppIcon from '@/app/components/base/app-icon'
import { Tag01 } from '@/app/components/base/icons/src/vender/line/financeAndECommerce'
import I18n from '@/context/i18n'
import { getLanguage } from '@/i18n/language'
import { useStore as useLabelStore } from '@/app/components/tools/labels/store'
type Props = {
active: boolean
collection: Collection
onSelect: () => void
}
const ProviderCard = ({
active,
collection,
onSelect,
}: Props) => {
const { t } = useTranslation()
const { locale } = useContext(I18n)
const language = getLanguage(locale)
const labelList = useLabelStore(s => s.labelList)
const labelContent = useMemo(() => {
if (!collection.labels)
return ''
return collection.labels.map((name) => {
const label = labelList.find(item => item.name === name)
return label?.label[language]
}).filter(Boolean).join(', ')
}, [collection.labels, labelList, language])
return (
<div className={cn('group col-span-1 bg-white border-2 border-solid border-transparent rounded-xl shadow-sm min-h-[160px] flex flex-col transition-all duration-200 ease-in-out cursor-pointer hover:shadow-lg', active && '!border-primary-400')} onClick={onSelect}>
<div className='flex pt-[14px] px-[14px] pb-3 h-[66px] items-center gap-3 grow-0 shrink-0'>
<div className='relative shrink-0'>
{typeof collection.icon === 'string' && (
<div className='w-10 h-10 bg-center bg-cover bg-no-repeat rounded-md' style={{ backgroundImage: `url(${collection.icon})` }} />
)}
{typeof collection.icon !== 'string' && (
<AppIcon
size='large'
icon={collection.icon.content}
background={collection.icon.background}
/>
)}
</div>
<div className='grow w-0 py-[1px]'>
<div className='flex items-center text-sm leading-5 font-semibold text-gray-800'>
<div className='truncate' title={collection.label[language]}>{collection.label[language]}</div>
</div>
<div className='flex items-center text-[10px] leading-[18px] text-gray-500 font-medium'>
<div className='truncate'>{t('tools.author')}&nbsp;{collection.author}</div>
</div>
</div>
</div>
<div
className={cn(
'grow mb-2 px-[14px] max-h-[72px] text-xs leading-normal text-gray-500',
collection.labels?.length ? 'line-clamp-2' : 'line-clamp-4',
collection.labels?.length > 0 && 'group-hover:line-clamp-2 group-hover:max-h-[36px]',
)}
title={collection.description[language]}
>
{collection.description[language]}
</div>
{collection.labels?.length > 0 && (
<div className='flex items-center shrink-0 mt-1 pt-1 pl-[14px] pr-[6px] pb-[6px] h-[42px]'>
<div className='relative w-full flex items-center gap-1 py-[7px] rounded-md text-gray-500' title={labelContent}>
<Tag01 className='shrink-0 w-3 h-3' />
<div className='grow text-xs text-start leading-[18px] font-normal truncate'>{labelContent}</div>
</div>
</div>
)}
</div>
)
}
export default ProviderCard

View File

@@ -0,0 +1,40 @@
'use client'
import type { FC } from 'react'
import React from 'react'
import { useTranslation } from 'react-i18next'
import {
RiHammerFill,
} from '@remixicon/react'
import { Heart02 } from '@/app/components/base/icons/src/vender/solid/education'
import { BookOpen01 } from '@/app/components/base/icons/src/vender/line/education'
import { ArrowUpRight } from '@/app/components/base/icons/src/vender/line/arrows'
const Contribute: FC = () => {
const { t } = useTranslation()
return (
<a
href='https://github.com/langgenius/dify/blob/main/api/core/tools/README.md'
target='_blank'
rel='noopener noreferrer'
className="group flex col-span-1 bg-white bg-cover bg-no-repeat bg-[url('~@/app/components/tools/provider/grid_bg.svg')] border-2 border-solid border-transparent rounded-xl shadow-sm min-h-[160px] flex-col transition-all duration-200 ease-in-out cursor-pointer hover:shadow-lg"
>
<div className='flex pt-[14px] px-[14px] pb-3 h-[66px] items-center gap-3 grow-0 shrink-0'>
<div className='relative shrink-0 flex items-center'>
<div className='z-10 flex p-3 rounded-[10px] bg-white border-[0.5px] border-primary-100 shadow-md'><RiHammerFill className='w-4 h-4 text-primary-600'/></div>
<div className='-translate-x-2 flex p-3 rounded-[10px] bg-[#FEF6FB] border-[0.5px] border-[#FCE7F6] shadow-md'><Heart02 className='w-4 h-4 text-[#EE46BC]'/></div>
</div>
</div>
<div className='mb-3 px-[14px] text-[15px] leading-5 font-semibold'>
<div className='text-gradient'>{t('tools.contribute.line1')}</div>
<div className='text-gradient'>{t('tools.contribute.line2')}</div>
</div>
<div className='px-4 py-3 border-t-[0.5px] border-black/5 flex items-center space-x-1 text-[#155EEF]'>
<BookOpen01 className='w-3 h-3' />
<div className='grow leading-[18px] text-xs font-normal'>{t('tools.contribute.viewGuide')}</div>
<ArrowUpRight className='w-3 h-3' />
</div>
</a>
)
}
export default React.memo(Contribute)

View File

@@ -0,0 +1,76 @@
'use client'
import { useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useContext } from 'use-context-selector'
import {
RiAddLine,
} from '@remixicon/react'
import type { CustomCollectionBackend } from '../types'
import I18n from '@/context/i18n'
import { getLanguage } from '@/i18n/language'
import { BookOpen01 } from '@/app/components/base/icons/src/vender/line/education'
import { ArrowUpRight } from '@/app/components/base/icons/src/vender/line/arrows'
import EditCustomToolModal from '@/app/components/tools/edit-custom-collection-modal'
import { createCustomCollection } from '@/service/tools'
import Toast from '@/app/components/base/toast'
import { useAppContext } from '@/context/app-context'
type Props = {
onRefreshData: () => void
}
const Contribute = ({ onRefreshData }: Props) => {
const { t } = useTranslation()
const { locale } = useContext(I18n)
const language = getLanguage(locale)
const { isCurrentWorkspaceManager } = useAppContext()
const linkUrl = useMemo(() => {
if (language.startsWith('zh_'))
return 'https://docs.dify.ai/zh-hans/guides/tools#ru-he-chuang-jian-zi-ding-yi-gong-ju'
return 'https://docs.dify.ai/guides/tools#how-to-create-custom-tools'
}, [language])
const [isShowEditCollectionToolModal, setIsShowEditCustomCollectionModal] = useState(false)
const doCreateCustomToolCollection = async (data: CustomCollectionBackend) => {
await createCustomCollection(data)
Toast.notify({
type: 'success',
message: t('common.api.actionSuccess'),
})
setIsShowEditCustomCollectionModal(false)
onRefreshData()
}
return (
<>
{isCurrentWorkspaceManager && (
<div className='flex flex-col col-span-1 bg-gray-200 border-[0.5px] border-black/5 rounded-xl min-h-[160px] transition-all duration-200 ease-in-out cursor-pointer hover:bg-gray-50 hover:shadow-lg'>
<div className='group grow rounded-t-xl hover:bg-white' onClick={() => setIsShowEditCustomCollectionModal(true)}>
<div className='shrink-0 flex items-center p-4 pb-3'>
<div className='w-10 h-10 flex items-center justify-center border border-gray-200 bg-gray-100 rounded-lg group-hover:border-primary-100 group-hover:bg-primary-50'>
<RiAddLine className='w-4 h-4 text-gray-500 group-hover:text-primary-600'/>
</div>
<div className='ml-3 text-sm font-semibold leading-5 text-gray-800 group-hover:text-primary-600'>{t('tools.createCustomTool')}</div>
</div>
</div>
<div className='px-4 py-3 rounded-b-xl border-t-[0.5px] border-black/5 text-gray-500 hover:text-[#155EEF] hover:bg-white'>
<a href={linkUrl} target='_blank' rel='noopener noreferrer' className='flex items-center space-x-1'>
<BookOpen01 className='shrink-0 w-3 h-3' />
<div className='grow leading-[18px] text-xs font-normal truncate' title={t('tools.customToolTip') || ''}>{t('tools.customToolTip')}</div>
<ArrowUpRight className='shrink-0 w-3 h-3' />
</a>
</div>
</div>
)}
{isShowEditCollectionToolModal && (
<EditCustomToolModal
payload={null}
onHide={() => setIsShowEditCustomCollectionModal(false)}
onAdd={doCreateCustomToolCollection}
/>
)}
</>
)
}
export default Contribute

View File

@@ -0,0 +1,376 @@
'use client'
import React, { useCallback, useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useContext } from 'use-context-selector'
import { AuthHeaderPrefix, AuthType, CollectionType } from '../types'
import type { Collection, CustomCollectionBackend, Tool, WorkflowToolProviderRequest, WorkflowToolProviderResponse } from '../types'
import ToolItem from './tool-item'
import cn from '@/utils/classnames'
import I18n from '@/context/i18n'
import { getLanguage } from '@/i18n/language'
import Confirm from '@/app/components/base/confirm'
import AppIcon from '@/app/components/base/app-icon'
import Button from '@/app/components/base/button'
import Indicator from '@/app/components/header/indicator'
import { LinkExternal02, Settings01 } from '@/app/components/base/icons/src/vender/line/general'
import ConfigCredential from '@/app/components/tools/setting/build-in/config-credentials'
import EditCustomToolModal from '@/app/components/tools/edit-custom-collection-modal'
import WorkflowToolModal from '@/app/components/tools/workflow-tool'
import Toast from '@/app/components/base/toast'
import {
deleteWorkflowTool,
fetchBuiltInToolList,
fetchCustomCollection,
fetchCustomToolList,
fetchModelToolList,
fetchWorkflowToolDetail,
removeBuiltInToolCredential,
removeCustomCollection,
saveWorkflowToolProvider,
updateBuiltInToolCredential,
updateCustomCollection,
} from '@/service/tools'
import { useModalContext } from '@/context/modal-context'
import { useProviderContext } from '@/context/provider-context'
import { ConfigurationMethodEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
import Loading from '@/app/components/base/loading'
import { useAppContext } from '@/context/app-context'
type Props = {
collection: Collection
onRefreshData: () => void
}
const ProviderDetail = ({
collection,
onRefreshData,
}: Props) => {
const { t } = useTranslation()
const { locale } = useContext(I18n)
const language = getLanguage(locale)
const needAuth = collection.allow_delete || collection.type === CollectionType.model
const isAuthed = collection.is_team_authorization
const isBuiltIn = collection.type === CollectionType.builtIn
const isModel = collection.type === CollectionType.model
const { isCurrentWorkspaceManager } = useAppContext()
const [isDetailLoading, setIsDetailLoading] = useState(false)
// built in provider
const [showSettingAuth, setShowSettingAuth] = useState(false)
const { setShowModelModal } = useModalContext()
const { modelProviders: providers } = useProviderContext()
const showSettingAuthModal = () => {
if (isModel) {
const provider = providers.find(item => item.provider === collection?.id)
if (provider) {
setShowModelModal({
payload: {
currentProvider: provider,
currentConfigurationMethod: ConfigurationMethodEnum.predefinedModel,
currentCustomConfigurationModelFixedFields: undefined,
},
onSaveCallback: () => {
onRefreshData()
},
})
}
}
else {
setShowSettingAuth(true)
}
}
// custom provider
const [customCollection, setCustomCollection] = useState<CustomCollectionBackend | WorkflowToolProviderResponse | null>(null)
const [isShowEditCollectionToolModal, setIsShowEditCustomCollectionModal] = useState(false)
const [showConfirmDelete, setShowConfirmDelete] = useState(false)
const [deleteAction, setDeleteAction] = useState('')
const doUpdateCustomToolCollection = async (data: CustomCollectionBackend) => {
await updateCustomCollection(data)
onRefreshData()
Toast.notify({
type: 'success',
message: t('common.api.actionSuccess'),
})
setIsShowEditCustomCollectionModal(false)
}
const doRemoveCustomToolCollection = async () => {
await removeCustomCollection(collection?.name as string)
onRefreshData()
Toast.notify({
type: 'success',
message: t('common.api.actionSuccess'),
})
setIsShowEditCustomCollectionModal(false)
}
const getCustomProvider = useCallback(async () => {
setIsDetailLoading(true)
const res = await fetchCustomCollection(collection.name)
if (res.credentials.auth_type === AuthType.apiKey && !res.credentials.api_key_header_prefix) {
if (res.credentials.api_key_value)
res.credentials.api_key_header_prefix = AuthHeaderPrefix.custom
}
setCustomCollection({
...res,
labels: collection.labels,
provider: collection.name,
})
setIsDetailLoading(false)
}, [collection.labels, collection.name])
// workflow provider
const [isShowEditWorkflowToolModal, setIsShowEditWorkflowToolModal] = useState(false)
const getWorkflowToolProvider = useCallback(async () => {
setIsDetailLoading(true)
const res = await fetchWorkflowToolDetail(collection.id)
const payload = {
...res,
parameters: res.tool?.parameters.map((item) => {
return {
name: item.name,
description: item.llm_description,
form: item.form,
required: item.required,
type: item.type,
}
}) || [],
labels: res.tool?.labels || [],
}
setCustomCollection(payload)
setIsDetailLoading(false)
}, [collection.id])
const removeWorkflowToolProvider = async () => {
await deleteWorkflowTool(collection.id)
onRefreshData()
Toast.notify({
type: 'success',
message: t('common.api.actionSuccess'),
})
setIsShowEditWorkflowToolModal(false)
}
const updateWorkflowToolProvider = async (data: WorkflowToolProviderRequest & Partial<{
workflow_app_id: string
workflow_tool_id: string
}>) => {
await saveWorkflowToolProvider(data)
onRefreshData()
getWorkflowToolProvider()
Toast.notify({
type: 'success',
message: t('common.api.actionSuccess'),
})
setIsShowEditWorkflowToolModal(false)
}
const onClickCustomToolDelete = () => {
setDeleteAction('customTool')
setShowConfirmDelete(true)
}
const onClickWorkflowToolDelete = () => {
setDeleteAction('workflowTool')
setShowConfirmDelete(true)
}
const handleConfirmDelete = () => {
if (deleteAction === 'customTool')
doRemoveCustomToolCollection()
else if (deleteAction === 'workflowTool')
removeWorkflowToolProvider()
setShowConfirmDelete(false)
}
// ToolList
const [toolList, setToolList] = useState<Tool[]>([])
const getProviderToolList = useCallback(async () => {
setIsDetailLoading(true)
try {
if (collection.type === CollectionType.builtIn) {
const list = await fetchBuiltInToolList(collection.name)
setToolList(list)
}
else if (collection.type === CollectionType.model) {
const list = await fetchModelToolList(collection.name)
setToolList(list)
}
else if (collection.type === CollectionType.workflow) {
setToolList([])
}
else {
const list = await fetchCustomToolList(collection.name)
setToolList(list)
}
}
catch (e) { }
setIsDetailLoading(false)
}, [collection.name, collection.type])
useEffect(() => {
if (collection.type === CollectionType.custom)
getCustomProvider()
if (collection.type === CollectionType.workflow)
getWorkflowToolProvider()
getProviderToolList()
}, [collection.name, collection.type, getCustomProvider, getProviderToolList, getWorkflowToolProvider])
return (
<div className='px-6 py-3'>
<div className='flex items-center py-1 gap-2'>
<div className='relative shrink-0'>
{typeof collection.icon === 'string' && (
<div className='w-8 h-8 bg-center bg-cover bg-no-repeat rounded-md' style={{ backgroundImage: `url(${collection.icon})` }} />
)}
{typeof collection.icon !== 'string' && (
<AppIcon
size='small'
icon={collection.icon.content}
background={collection.icon.background}
/>
)}
</div>
<div className='grow w-0 py-[1px]'>
<div className='flex items-center text-md leading-6 font-semibold text-gray-900'>
<div className='truncate' title={collection.label[language]}>{collection.label[language]}</div>
</div>
</div>
</div>
<div className='mt-2 min-h-[36px] text-gray-500 text-sm leading-[18px]'>{collection.description[language]}</div>
<div className='flex gap-1 border-b-[0.5px] border-black/5'>
{(collection.type === CollectionType.builtIn) && needAuth && (
<Button
variant={isAuthed ? 'secondary' : 'primary'}
className={cn('shrink-0 my-3 w-full', isAuthed && 'bg-white')}
onClick={() => {
if (collection.type === CollectionType.builtIn || collection.type === CollectionType.model)
showSettingAuthModal()
}}
disabled={!isCurrentWorkspaceManager}
>
{isAuthed && <Indicator className='mr-2' color={'green'} />}
<div className={cn('text-white leading-[18px] text-[13px] font-medium', isAuthed && '!text-gray-700')}>
{isAuthed ? t('tools.auth.authorized') : t('tools.auth.unauthorized')}
</div>
</Button>
)}
{collection.type === CollectionType.custom && !isDetailLoading && (
<Button
className={cn('shrink-0 my-3 w-full')}
onClick={() => setIsShowEditCustomCollectionModal(true)}
>
<Settings01 className='mr-1 w-4 h-4 text-gray-500' />
<div className='leading-5 text-sm font-medium text-gray-700'>{t('tools.createTool.editAction')}</div>
</Button>
)}
{collection.type === CollectionType.workflow && !isDetailLoading && customCollection && (
<>
<Button
variant='primary'
className={cn('shrink-0 my-3 w-[183px]')}
>
<a className='flex items-center text-white' href={`/app/${(customCollection as WorkflowToolProviderResponse).workflow_app_id}/workflow`} rel='noreferrer' target='_blank'>
<div className='leading-5 text-sm font-medium'>{t('tools.openInStudio')}</div>
<LinkExternal02 className='ml-1 w-4 h-4' />
</a>
</Button>
<Button
className={cn('shrink-0 my-3 w-[183px]')}
onClick={() => setIsShowEditWorkflowToolModal(true)}
disabled={!isCurrentWorkspaceManager}
>
<div className='leading-5 text-sm font-medium text-gray-700'>{t('tools.createTool.editAction')}</div>
</Button>
</>
)}
</div>
{/* Tools */}
<div className='pt-3'>
{isDetailLoading && <div className='flex h-[200px]'><Loading type='app' /></div>}
{!isDetailLoading && (
<div className='text-xs font-medium leading-6 text-gray-500'>
{collection.type === CollectionType.workflow && <span className=''>{t('tools.createTool.toolInput.title').toLocaleUpperCase()}</span>}
{collection.type !== CollectionType.workflow && <span className=''>{t('tools.includeToolNum', { num: toolList.length }).toLocaleUpperCase()}</span>}
{needAuth && (isBuiltIn || isModel) && !isAuthed && (
<>
<span className='px-1'>·</span>
<span className='text-[#DC6803]'>{t('tools.auth.setup').toLocaleUpperCase()}</span>
</>
)}
</div>
)}
{!isDetailLoading && (
<div className='mt-1'>
{collection.type !== CollectionType.workflow && toolList.map(tool => (
<ToolItem
key={tool.name}
disabled={needAuth && (isBuiltIn || isModel) && !isAuthed}
collection={collection}
tool={tool}
isBuiltIn={isBuiltIn}
isModel={isModel}
/>
))}
{collection.type === CollectionType.workflow && (customCollection as WorkflowToolProviderResponse)?.tool?.parameters.map(item => (
<div key={item.name} className='mb-2 px-4 py-3 rounded-xl bg-gray-25 border-[0.5px] border-gray-200'>
<div className='flex items-center gap-2'>
<span className='font-medium text-sm text-gray-900'>{item.name}</span>
<span className='text-xs leading-[18px] text-gray-500'>{item.type}</span>
<span className='font-medium text-xs leading-[18px] text-[#ec4a0a]'>{item.required ? t('tools.createTool.toolInput.required') : ''}</span>
</div>
<div className='h-[18px] leading-[18px] text-gray-500 text-xs'>{item.llm_description}</div>
</div>
))}
</div>
)}
</div>
{showSettingAuth && (
<ConfigCredential
collection={collection}
onCancel={() => setShowSettingAuth(false)}
onSaved={async (value) => {
await updateBuiltInToolCredential(collection.name, value)
Toast.notify({
type: 'success',
message: t('common.api.actionSuccess'),
})
await onRefreshData()
setShowSettingAuth(false)
}}
onRemove={async () => {
await removeBuiltInToolCredential(collection.name)
Toast.notify({
type: 'success',
message: t('common.api.actionSuccess'),
})
await onRefreshData()
setShowSettingAuth(false)
}}
/>
)}
{isShowEditCollectionToolModal && (
<EditCustomToolModal
payload={customCollection}
onHide={() => setIsShowEditCustomCollectionModal(false)}
onEdit={doUpdateCustomToolCollection}
onRemove={onClickCustomToolDelete}
/>
)}
{isShowEditWorkflowToolModal && (
<WorkflowToolModal
payload={customCollection}
onHide={() => setIsShowEditWorkflowToolModal(false)}
onRemove={onClickWorkflowToolDelete}
onSave={updateWorkflowToolProvider}
/>
)}
{showConfirmDelete && (
<Confirm
title={t('tools.createTool.deleteToolConfirmTitle')}
content={t('tools.createTool.deleteToolConfirmContent')}
isShow={showConfirmDelete}
onConfirm={handleConfirmDelete}
onCancel={() => setShowConfirmDelete(false)}
/>
)}
</div>
)
}
export default ProviderDetail

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 13 KiB

View File

@@ -0,0 +1,53 @@
'use client'
import React, { useState } from 'react'
import { useContext } from 'use-context-selector'
import type { Collection, Tool } from '../types'
import cn from '@/utils/classnames'
import I18n from '@/context/i18n'
import { getLanguage } from '@/i18n/language'
import SettingBuiltInTool from '@/app/components/app/configuration/config/agent/agent-tools/setting-built-in-tool'
type Props = {
disabled?: boolean
collection: Collection
tool: Tool
isBuiltIn: boolean
isModel: boolean
}
const ToolItem = ({
disabled,
collection,
tool,
isBuiltIn,
isModel,
}: Props) => {
const { locale } = useContext(I18n)
const language = getLanguage(locale)
const [showDetail, setShowDetail] = useState(false)
return (
<>
<div
className={cn('mb-2 px-4 py-3 rounded-xl bg-gray-25 border-[0.5px] border-gary-200 shadow-xs cursor-pointer', disabled && 'opacity-50 !cursor-not-allowed')}
onClick={() => !disabled && setShowDetail(true)}
>
<div className='text-gray-800 font-semibold text-sm leading-5'>{tool.label[language]}</div>
<div className='mt-0.5 text-xs leading-[18px] text-gray-500 line-clamp-2' title={tool.description[language]}>{tool.description[language]}</div>
</div>
{showDetail && (
<SettingBuiltInTool
collection={collection}
toolName={tool.name}
readonly
onHide={() => {
setShowDetail(false)
}}
isBuiltIn={isBuiltIn}
isModel={isModel}
/>
)}
</>
)
}
export default ToolItem

View File

@@ -0,0 +1,119 @@
'use client'
import type { FC } from 'react'
import React, { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { addDefaultValue, toolCredentialToFormSchemas } from '../../utils/to-form-schema'
import type { Collection } from '../../types'
import cn from '@/utils/classnames'
import Drawer from '@/app/components/base/drawer-plus'
import Button from '@/app/components/base/button'
import Toast from '@/app/components/base/toast'
import { fetchBuiltInToolCredential, fetchBuiltInToolCredentialSchema } from '@/service/tools'
import Loading from '@/app/components/base/loading'
import Form from '@/app/components/header/account-setting/model-provider-page/model-modal/Form'
import { LinkExternal02 } from '@/app/components/base/icons/src/vender/line/general'
import { useLanguage } from '@/app/components/header/account-setting/model-provider-page/hooks'
type Props = {
collection: Collection
onCancel: () => void
onSaved: (value: Record<string, any>) => void
isHideRemoveBtn?: boolean
onRemove?: () => void
}
const ConfigCredential: FC<Props> = ({
collection,
onCancel,
onSaved,
isHideRemoveBtn,
onRemove = () => { },
}) => {
const { t } = useTranslation()
const language = useLanguage()
const [credentialSchema, setCredentialSchema] = useState<any>(null)
const { name: collectionName } = collection
const [tempCredential, setTempCredential] = React.useState<any>({})
useEffect(() => {
fetchBuiltInToolCredentialSchema(collectionName).then(async (res) => {
const toolCredentialSchemas = toolCredentialToFormSchemas(res)
const credentialValue = await fetchBuiltInToolCredential(collectionName)
setTempCredential(credentialValue)
const defaultCredentials = addDefaultValue(credentialValue, toolCredentialSchemas)
setCredentialSchema(toolCredentialSchemas)
setTempCredential(defaultCredentials)
})
}, [])
const handleSave = () => {
for (const field of credentialSchema) {
if (field.required && !tempCredential[field.name]) {
Toast.notify({ type: 'error', message: t('common.errorMsg.fieldRequired', { field: field.label[language] || field.label.en_US }) })
return
}
}
onSaved(tempCredential)
}
return (
<Drawer
isShow
onHide={onCancel}
title={t('tools.auth.setupModalTitle') as string}
titleDescription={t('tools.auth.setupModalTitleDescription') as string}
panelClassName='mt-2 !w-[405px]'
maxWidthClassName='!max-w-[405px]'
height='calc(100vh - 16px)'
contentClassName='!bg-gray-100'
headerClassName='!border-b-black/5'
body={
<div className='px-6 py-3 h-full'>
{!credentialSchema
? <Loading type='app' />
: (
<>
<Form
value={tempCredential}
onChange={(v) => {
setTempCredential(v)
}}
formSchemas={credentialSchema}
isEditMode={true}
showOnVariableMap={{}}
validating={false}
inputClassName='!bg-gray-50'
fieldMoreInfo={item => item.url
? (<a
href={item.url}
target='_blank' rel='noopener noreferrer'
className='inline-flex items-center text-xs text-primary-600'
>
{t('tools.howToGet')}
<LinkExternal02 className='ml-1 w-3 h-3' />
</a>)
: null}
/>
<div className={cn((collection.is_team_authorization && !isHideRemoveBtn) ? 'justify-between' : 'justify-end', 'mt-2 flex ')} >
{
(collection.is_team_authorization && !isHideRemoveBtn) && (
<Button onClick={onRemove}>{t('common.operation.remove')}</Button>
)
}
< div className='flex space-x-2'>
<Button onClick={onCancel}>{t('common.operation.cancel')}</Button>
<Button variant='primary' onClick={handleSave}>{t('common.operation.save')}</Button>
</div>
</div>
</>
)
}
</div >
}
isShowMask={true}
clickOutsideNotOpen={false}
/>
)
}
export default React.memo(ConfigCredential)

View File

@@ -0,0 +1,165 @@
import type { TypeWithI18N } from '../header/account-setting/model-provider-page/declarations'
export enum LOC {
tools = 'tools',
app = 'app',
}
export enum AuthType {
none = 'none',
apiKey = 'api_key',
}
export enum AuthHeaderPrefix {
basic = 'basic',
bearer = 'bearer',
custom = 'custom',
}
export type Credential = {
'auth_type': AuthType
'api_key_header'?: string
'api_key_value'?: string
'api_key_header_prefix'?: AuthHeaderPrefix
}
export enum CollectionType {
all = 'all',
builtIn = 'builtin',
custom = 'api',
model = 'model',
workflow = 'workflow',
}
export type Emoji = {
background: string
content: string
}
export type Collection = {
id: string
name: string
author: string
description: TypeWithI18N
icon: string | Emoji
label: TypeWithI18N
type: CollectionType
team_credentials: Record<string, any>
is_team_authorization: boolean
allow_delete: boolean
labels: string[]
}
export type ToolParameter = {
name: string
label: TypeWithI18N
human_description: TypeWithI18N
type: string
form: string
llm_description: string
required: boolean
default: string
options?: {
label: TypeWithI18N
value: string
}[]
min?: number
max?: number
}
export type Tool = {
name: string
author: string
label: TypeWithI18N
description: any
parameters: ToolParameter[]
labels: string[]
}
export type ToolCredential = {
name: string
label: TypeWithI18N
help: TypeWithI18N
placeholder: TypeWithI18N
type: string
required: boolean
default: string
options?: {
label: TypeWithI18N
value: string
}[]
}
export type CustomCollectionBackend = {
provider: string
original_provider?: string
credentials: Credential
icon: Emoji
schema_type: string
schema: string
privacy_policy: string
custom_disclaimer: string
tools?: ParamItem[]
id: string
labels: string[]
}
export type ParamItem = {
name: string
label: TypeWithI18N
human_description: TypeWithI18N
llm_description: string
type: string
form: string
required: boolean
default: string
min?: number
max?: number
options?: {
label: TypeWithI18N
value: string
}[]
}
export type CustomParamSchema = {
operation_id: string // name
summary: string
server_url: string
method: string
parameters: ParamItem[]
}
export type WorkflowToolProviderParameter = {
name: string
form: string
description: string
required?: boolean
type?: string
}
export type WorkflowToolProviderRequest = {
name: string
icon: Emoji
description: string
parameters: WorkflowToolProviderParameter[]
labels: string[]
privacy_policy: string
}
export type WorkflowToolProviderResponse = {
workflow_app_id: string
workflow_tool_id: string
label: string
name: string
icon: Emoji
description: string
synced: boolean
tool: {
author: string
name: string
label: TypeWithI18N
description: TypeWithI18N
labels: string[]
parameters: ParamItem[]
}
privacy_policy: string
}

View File

@@ -0,0 +1,27 @@
import type { ThoughtItem } from '@/app/components/base/chat/chat/type'
import type { FileEntity } from '@/app/components/base/file-uploader/types'
import type { VisionFile } from '@/types/app'
export const sortAgentSorts = (list: ThoughtItem[]) => {
if (!list)
return list
if (list.some(item => item.position === undefined))
return list
const temp = [...list]
temp.sort((a, b) => a.position - b.position)
return temp
}
export const addFileInfos = (list: ThoughtItem[], messageFiles: (FileEntity | VisionFile)[]) => {
if (!list || !messageFiles)
return list
return list.map((item) => {
if (item.files && item.files?.length > 0) {
return {
...item,
message_files: item.files.map(fileId => messageFiles.find(file => file.id === fileId)) as FileEntity[],
}
}
return item
})
}

View File

@@ -0,0 +1,65 @@
import type { ToolCredential, ToolParameter } from '../types'
const toType = (type: string) => {
switch (type) {
case 'string':
return 'text-input'
case 'number':
return 'number-input'
default:
return type
}
}
export const toolParametersToFormSchemas = (parameters: ToolParameter[]) => {
if (!parameters)
return []
const formSchemas = parameters.map((parameter) => {
return {
...parameter,
variable: parameter.name,
type: toType(parameter.type),
_type: parameter.type,
show_on: [],
options: parameter.options?.map((option) => {
return {
...option,
show_on: [],
}
}),
tooltip: parameter.human_description,
}
})
return formSchemas
}
export const toolCredentialToFormSchemas = (parameters: ToolCredential[]) => {
if (!parameters)
return []
const formSchemas = parameters.map((parameter) => {
return {
...parameter,
variable: parameter.name,
label: parameter.label,
tooltip: parameter.help,
show_on: [],
options: parameter.options?.map((option) => {
return {
...option,
show_on: [],
}
}),
}
})
return formSchemas
}
export const addDefaultValue = (value: Record<string, any>, formSchemas: { variable: string; default?: any }[]) => {
const newValues = { ...value }
formSchemas.forEach((formSchema) => {
const itemValue = value[formSchema.variable]
if ((formSchema.default !== undefined) && (value === undefined || itemValue === null || itemValue === '' || itemValue === undefined))
newValues[formSchema.variable] = formSchema.default
})
return newValues
}

View File

@@ -0,0 +1,240 @@
'use client'
import React, { useCallback, useEffect, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useRouter } from 'next/navigation'
import cn from '@/utils/classnames'
import Button from '@/app/components/base/button'
import { ArrowUpRight } from '@/app/components/base/icons/src/vender/line/arrows'
import { Tools } from '@/app/components/base/icons/src/vender/line/others'
import Indicator from '@/app/components/header/indicator'
import WorkflowToolModal from '@/app/components/tools/workflow-tool'
import Loading from '@/app/components/base/loading'
import Toast from '@/app/components/base/toast'
import { createWorkflowToolProvider, fetchWorkflowToolDetailByAppID, saveWorkflowToolProvider } from '@/service/tools'
import type { Emoji, WorkflowToolProviderParameter, WorkflowToolProviderRequest, WorkflowToolProviderResponse } from '@/app/components/tools/types'
import type { InputVar } from '@/app/components/workflow/types'
import { useAppContext } from '@/context/app-context'
type Props = {
disabled: boolean
published: boolean
detailNeedUpdate: boolean
workflowAppId: string
icon: Emoji
name: string
description: string
inputs?: InputVar[]
handlePublish: () => void
onRefreshData?: () => void
}
const WorkflowToolConfigureButton = ({
disabled,
published,
detailNeedUpdate,
workflowAppId,
icon,
name,
description,
inputs,
handlePublish,
onRefreshData,
}: Props) => {
const { t } = useTranslation()
const router = useRouter()
const [showModal, setShowModal] = useState(false)
const [isLoading, setIsLoading] = useState(false)
const [detail, setDetail] = useState<WorkflowToolProviderResponse>()
const { isCurrentWorkspaceManager } = useAppContext()
const outdated = useMemo(() => {
if (!detail)
return false
if (detail.tool.parameters.length !== inputs?.length) {
return true
}
else {
for (const item of inputs || []) {
const param = detail.tool.parameters.find(toolParam => toolParam.name === item.variable)
if (!param) {
return true
}
else if (param.required !== item.required) {
return true
}
else {
if (item.type === 'paragraph' && param.type !== 'string')
return true
if (item.type === 'text-input' && param.type !== 'string')
return true
}
}
}
return false
}, [detail, inputs])
const payload = useMemo(() => {
let parameters: WorkflowToolProviderParameter[] = []
if (!published) {
parameters = (inputs || []).map((item) => {
return {
name: item.variable,
description: '',
form: 'llm',
required: item.required,
type: item.type,
}
})
}
else if (detail && detail.tool) {
parameters = (inputs || []).map((item) => {
return {
name: item.variable,
required: item.required,
type: item.type === 'paragraph' ? 'string' : item.type,
description: detail.tool.parameters.find(param => param.name === item.variable)?.llm_description || '',
form: detail.tool.parameters.find(param => param.name === item.variable)?.form || 'llm',
}
})
}
return {
icon: detail?.icon || icon,
label: detail?.label || name,
name: detail?.name || '',
description: detail?.description || description,
parameters,
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])
const getDetail = useCallback(async (workflowAppId: string) => {
setIsLoading(true)
const res = await fetchWorkflowToolDetailByAppID(workflowAppId)
setDetail(res)
setIsLoading(false)
}, [])
useEffect(() => {
if (published)
getDetail(workflowAppId)
}, [getDetail, published, workflowAppId])
useEffect(() => {
if (detailNeedUpdate)
getDetail(workflowAppId)
}, [detailNeedUpdate, getDetail, workflowAppId])
const createHandle = async (data: WorkflowToolProviderRequest & { workflow_app_id: string }) => {
try {
await createWorkflowToolProvider(data)
onRefreshData?.()
getDetail(workflowAppId)
Toast.notify({
type: 'success',
message: t('common.api.actionSuccess'),
})
setShowModal(false)
}
catch (e) {
Toast.notify({ type: 'error', message: (e as Error).message })
}
}
const updateWorkflowToolProvider = async (data: WorkflowToolProviderRequest & Partial<{
workflow_app_id: string
workflow_tool_id: string
}>) => {
try {
await handlePublish()
await saveWorkflowToolProvider(data)
onRefreshData?.()
getDetail(workflowAppId)
Toast.notify({
type: 'success',
message: t('common.api.actionSuccess'),
})
setShowModal(false)
}
catch (e) {
Toast.notify({ type: 'error', message: (e as Error).message })
}
}
return (
<>
<div className='mt-2 pt-2 border-t-[0.5px] border-t-black/5'>
{(!published || !isLoading) && (
<div className={cn(
'group bg-gray-100 rounded-lg transition-colors',
disabled ? 'shadow-xs opacity-30 cursor-not-allowed' : 'cursor-pointer',
!published && 'hover:bg-primary-50',
)}>
{isCurrentWorkspaceManager
? (
<div
className='flex justify-start items-center gap-2 px-2.5 py-2'
onClick={() => !published && setShowModal(true)}
>
<Tools className={cn('relative w-4 h-4', !published && 'group-hover:text-primary-600')} />
<div title={t('workflow.common.workflowAsTool') || ''} className={cn('grow shrink basis-0 text-[13px] font-medium leading-[18px] truncate', !published && 'group-hover:text-primary-600')}>{t('workflow.common.workflowAsTool')}</div>
{!published && (
<span className='shrink-0 px-1 border border-black/8 rounded-[5px] bg-white text-[10px] font-medium leading-[18px] text-gray-500'>{t('workflow.common.configureRequired').toLocaleUpperCase()}</span>
)}
</div>)
: (
<div
className='flex justify-start items-center gap-2 px-2.5 py-2'
>
<Tools className='w-4 h-4 text-gray-500' />
<div title={t('workflow.common.workflowAsTool') || ''} className='grow shrink basis-0 text-[13px] font-medium leading-[18px] truncate text-gray-500'>{t('workflow.common.workflowAsTool')}</div>
</div>
)}
{published && (
<div className='px-2.5 py-2 border-t-[0.5px] border-black/5'>
<div className='flex justify-between'>
<Button
size='small'
className='w-[140px]'
onClick={() => setShowModal(true)}
disabled={!isCurrentWorkspaceManager}
>
{t('workflow.common.configure')}
{outdated && <Indicator className='ml-1' color={'yellow'} />}
</Button>
<Button
size='small'
className='w-[140px]'
onClick={() => router.push('/tools?category=workflow')}
>
{t('workflow.common.manageInTools')}
<ArrowUpRight className='ml-1' />
</Button>
</div>
{outdated && <div className='mt-1 text-xs leading-[18px] text-[#dc6803]'>{t('workflow.common.workflowAsToolTip')}</div>}
</div>
)}
</div>
)}
{published && isLoading && <div className='pt-2'><Loading type='app' /></div>}
</div>
{showModal && (
<WorkflowToolModal
isAdd={!published}
payload={payload}
onHide={() => setShowModal(false)}
onCreate={createHandle}
onSave={updateWorkflowToolProvider}
/>
)}
</>
)
}
export default WorkflowToolConfigureButton

View File

@@ -0,0 +1,46 @@
'use client'
import { useTranslation } from 'react-i18next'
import { RiCloseLine } from '@remixicon/react'
import s from './style.module.css'
import cn from '@/utils/classnames'
import Button from '@/app/components/base/button'
import Modal from '@/app/components/base/modal'
import { AlertTriangle } from '@/app/components/base/icons/src/vender/solid/alertsAndFeedback'
type ConfirmModalProps = {
show: boolean
onConfirm?: () => void
onClose: () => void
}
const ConfirmModal = ({ show, onConfirm, onClose }: ConfirmModalProps) => {
const { t } = useTranslation()
return (
<Modal
className={cn('p-8 max-w-[600px] w-[600px]', s.bg)}
isShow={show}
onClose={() => { }}
>
<div className='absolute right-4 top-4 p-2 cursor-pointer' onClick={onClose}>
<RiCloseLine className='w-4 h-4 text-gray-500' />
</div>
<div className='w-12 h-12 p-3 bg-white rounded-xl border-[0.5px] border-gray-100 shadow-xl'>
<AlertTriangle className='w-6 h-6 text-[rgb(247,144,9)]' />
</div>
<div className='relative mt-3 text-xl font-semibold leading-[30px] text-gray-900'>{t('tools.createTool.confirmTitle')}</div>
<div className='my-1 text-gray-500 text-sm leading-5'>
{t('tools.createTool.confirmTip')}
</div>
<div className='pt-6 flex justify-end items-center'>
<div className='flex items-center'>
<Button className='mr-2' onClick={onClose}>{t('common.operation.cancel')}</Button>
<Button className='border-red-700' variant="warning" onClick={onConfirm}>{t('common.operation.confirm')}</Button>
</div>
</div>
</Modal>
)
}
export default ConfirmModal

View File

@@ -0,0 +1,3 @@
.bg {
background: linear-gradient(180deg, rgba(247, 144, 9, 0.05) 0%, rgba(247, 144, 9, 0.00) 24.41%), #F9FAFB;
}

View File

@@ -0,0 +1,282 @@
'use client'
import type { FC } from 'react'
import React, { useState } from 'react'
import { useTranslation } from 'react-i18next'
import produce from 'immer'
import type { Emoji, WorkflowToolProviderParameter, WorkflowToolProviderRequest } from '../types'
import cn from '@/utils/classnames'
import Drawer from '@/app/components/base/drawer-plus'
import Input from '@/app/components/base/input'
import Textarea from '@/app/components/base/textarea'
import Button from '@/app/components/base/button'
import Toast from '@/app/components/base/toast'
import EmojiPicker from '@/app/components/base/emoji-picker'
import AppIcon from '@/app/components/base/app-icon'
import MethodSelector from '@/app/components/tools/workflow-tool/method-selector'
import LabelSelector from '@/app/components/tools/labels/selector'
import ConfirmModal from '@/app/components/tools/workflow-tool/confirm-modal'
import Tooltip from '@/app/components/base/tooltip'
type Props = {
isAdd?: boolean
payload: any
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
}
// Add and Edit
const WorkflowToolAsModal: FC<Props> = ({
isAdd,
payload,
onHide,
onRemove,
onSave,
onCreate,
}) => {
const { t } = useTranslation()
const [showEmojiPicker, setShowEmojiPicker] = useState<Boolean>(false)
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 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 [showModal, setShowModal] = useState(false)
const isNameValid = (name: string) => {
// when the user has not input anything, no need for a warning
if (name === '')
return true
return /^[a-zA-Z0-9_]+$/.test(name)
}
const onConfirm = () => {
let errorMessage = ''
if (!label)
errorMessage = t('common.errorMsg.fieldRequired', { field: t('tools.createTool.name') })
if (!name)
errorMessage = t('common.errorMsg.fieldRequired', { field: t('tools.createTool.nameForToolCall') })
if (!isNameValid(name))
errorMessage = t('tools.createTool.nameForToolCall') + t('tools.createTool.nameForToolCallTip')
if (errorMessage) {
Toast.notify({
type: 'error',
message: errorMessage,
})
return
}
const requestParams = {
name,
description,
icon: emoji,
label,
parameters: parameters.map(item => ({
name: item.name,
description: item.description,
form: item.form,
})),
labels,
privacy_policy: privacyPolicy,
}
if (!isAdd) {
onSave?.({
...requestParams,
workflow_tool_id: payload.workflow_tool_id,
})
}
else {
onCreate?.({
...requestParams,
workflow_app_id: payload.workflow_app_id,
})
}
}
return (
<>
<Drawer
isShow
onHide={onHide}
title={t('workflow.common.workflowAsTool')!}
panelClassName='mt-2 !w-[640px]'
maxWidthClassName='!max-w-[640px]'
height='calc(100vh - 16px)'
headerClassName='!border-b-black/5'
body={
<div className='flex flex-col h-full'>
<div className='grow h-0 overflow-y-auto px-6 py-3 space-y-4'>
{/* name & icon */}
<div>
<div className='py-2 leading-5 text-sm font-medium text-gray-900'>{t('tools.createTool.name')} <span className='ml-1 text-red-500'>*</span></div>
<div className='flex items-center justify-between gap-3'>
<AppIcon size='large' onClick={() => { setShowEmojiPicker(true) }} className='cursor-pointer' iconType='emoji' icon={emoji.content} background={emoji.background} />
<Input
className='grow h-10'
placeholder={t('tools.createTool.toolNamePlaceHolder')!}
value={label}
onChange={e => setLabel(e.target.value)}
/>
</div>
</div>
{/* name for tool call */}
<div>
<div className='flex items-center py-2 leading-5 text-sm font-medium text-gray-900'>
{t('tools.createTool.nameForToolCall')} <span className='ml-1 text-red-500'>*</span>
<Tooltip
popupContent={
<div className='w-[180px]'>
{t('tools.createTool.nameForToolCallPlaceHolder')}
</div>
}
/>
</div>
<Input
className='h-10'
placeholder={t('tools.createTool.nameForToolCallPlaceHolder')!}
value={name}
onChange={e => setName(e.target.value)}
/>
{!isNameValid(name) && (
<div className='text-xs leading-[18px] text-red-500'>{t('tools.createTool.nameForToolCallTip')}</div>
)}
</div>
{/* description */}
<div>
<div className='py-2 leading-5 text-sm font-medium text-gray-900'>{t('tools.createTool.description')}</div>
<Textarea
placeholder={t('tools.createTool.descriptionPlaceholder') || ''}
value={description}
onChange={e => setDescription(e.target.value)}
/>
</div>
{/* Tool Input */}
<div>
<div className='py-2 leading-5 text-sm font-medium text-gray-900'>{t('tools.createTool.toolInput.title')}</div>
<div className='rounded-lg border border-gray-200 w-full overflow-x-auto'>
<table className='w-full leading-[18px] text-xs text-gray-700 font-normal'>
<thead className='text-gray-500 uppercase'>
<tr className='border-b border-gray-200'>
<th className="p-2 pl-3 font-medium w-[156px]">{t('tools.createTool.toolInput.name')}</th>
<th className="p-2 pl-3 font-medium w-[102px]">{t('tools.createTool.toolInput.method')}</th>
<th className="p-2 pl-3 font-medium">{t('tools.createTool.toolInput.description')}</th>
</tr>
</thead>
<tbody>
{parameters.map((item, index) => (
<tr key={index} className='border-b last:border-0 border-gray-200'>
<td className="p-2 pl-3 max-w-[156px]">
<div className='text-[13px] leading-[18px]'>
<div title={item.name} className='flex'>
<span className='font-medium text-gray-900 truncate'>{item.name}</span>
<span className='shrink-0 pl-1 text-[#ec4a0a] text-xs leading-[18px]'>{item.required ? t('tools.createTool.toolInput.required') : ''}</span>
</div>
<div className='text-gray-500'>{item.type}</div>
</div>
</td>
<td>
{item.name === '__image' && (
<div className={cn(
'flex items-center gap-1 min-h-[56px] px-3 py-2 h-9 bg-white cursor-default',
)}>
<div className={cn('grow text-[13px] leading-[18px] text-gray-700 truncate')}>
{t('tools.createTool.toolInput.methodParameter')}
</div>
</div>
)}
{item.name !== '__image' && (
<MethodSelector value={item.form} onChange={value => handleParameterChange('form', value, index)} />
)}
</td>
<td className="p-2 pl-3 text-gray-500 w-[236px]">
<input
type='text'
className='grow text-gray-700 text-[13px] leading-[18px] font-normal bg-white outline-none appearance-none caret-primary-600 placeholder:text-gray-300'
placeholder={t('tools.createTool.toolInput.descriptionPlaceholder')!}
value={item.description}
onChange={e => handleParameterChange('description', e.target.value, index)}
/>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
{/* Tags */}
<div>
<div className='py-2 leading-5 text-sm font-medium text-gray-900'>{t('tools.createTool.toolInput.label')}</div>
<LabelSelector value={labels} onChange={handleLabelSelect} />
</div>
{/* Privacy Policy */}
<div>
<div className='py-2 leading-5 text-sm font-medium text-gray-900'>{t('tools.createTool.privacyPolicy')}</div>
<Input
className='h-10'
value={privacyPolicy}
onChange={e => setPrivacyPolicy(e.target.value)}
placeholder={t('tools.createTool.privacyPolicyPlaceholder') || ''} />
</div>
</div>
<div className={cn((!isAdd && onRemove) ? 'justify-between' : 'justify-end', 'mt-2 shrink-0 flex py-4 px-6 rounded-b-[10px] bg-gray-50 border-t border-black/5')} >
{!isAdd && onRemove && (
<Button onClick={onRemove} className='text-red-500 border-red-50 hover:border-red-500'>{t('common.operation.delete')}</Button>
)}
<div className='flex space-x-2 '>
<Button onClick={onHide}>{t('common.operation.cancel')}</Button>
<Button variant='primary' onClick={() => {
if (isAdd)
onConfirm()
else
setShowModal(true)
}}>{t('common.operation.save')}</Button>
</div>
</div>
</div>
}
isShowMask={true}
clickOutsideNotOpen={true}
/>
{showEmojiPicker && <EmojiPicker
onSelect={(icon, icon_background) => {
setEmoji({ content: icon, background: icon_background })
setShowEmojiPicker(false)
}}
onClose={() => {
setShowEmojiPicker(false)
}}
/>}
{showModal && (
<ConfirmModal
show={showModal}
onClose={() => setShowModal(false)}
onConfirm={onConfirm}
/>
)}
</>
)
}
export default React.memo(WorkflowToolAsModal)

View File

@@ -0,0 +1,77 @@
import type { FC } from 'react'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { RiArrowDownSLine } from '@remixicon/react'
import cn from '@/utils/classnames'
import {
PortalToFollowElem,
PortalToFollowElemContent,
PortalToFollowElemTrigger,
} from '@/app/components/base/portal-to-follow-elem'
import { Check } from '@/app/components/base/icons/src/vender/line/general'
type MethodSelectorProps = {
value?: string
onChange: (v: string) => void
}
const MethodSelector: FC<MethodSelectorProps> = ({
value,
onChange,
}) => {
const { t } = useTranslation()
const [open, setOpen] = useState(false)
return (
<PortalToFollowElem
open={open}
onOpenChange={setOpen}
placement='bottom-start'
offset={4}
>
<div className='relative'>
<PortalToFollowElemTrigger
onClick={() => setOpen(v => !v)}
className='block'
>
<div className={cn(
'flex items-center gap-1 min-h-[56px] px-3 py-2 h-9 bg-white cursor-pointer hover:bg-gray-100',
open && '!bg-gray-100 hover:bg-gray-100',
)}>
<div className={cn('grow text-[13px] leading-[18px] text-gray-700 truncate')}>
{value === 'llm' ? t('tools.createTool.toolInput.methodParameter') : t('tools.createTool.toolInput.methodSetting')}
</div>
<div className='shrink-0 ml-1 text-gray-700 opacity-60'>
<RiArrowDownSLine className='h-4 w-4' />
</div>
</div>
</PortalToFollowElemTrigger>
<PortalToFollowElemContent className='z-[1040]'>
<div className='relative w-[320px] bg-white rounded-lg border-[0.5px] border-gray-200 shadow-lg'>
<div className='p-1'>
<div className='pl-3 pr-2 py-2.5 rounded-lg hover:bg-gray-50 cursor-pointer' onClick={() => onChange('llm')}>
<div className='flex item-center gap-1'>
<div className='shrink-0 w-4 h-4'>
{value === 'llm' && <Check className='shrink-0 w-4 h-4 text-primary-600' />}
</div>
<div className='text-[13px] text-gray-700 font-medium leading-[18px]'>{t('tools.createTool.toolInput.methodParameter')}</div>
</div>
<div className='pl-5 text-gray-500 text-[13px] leading-[18px]'>{t('tools.createTool.toolInput.methodParameterTip')}</div>
</div>
<div className='pl-3 pr-2 py-2.5 rounded-lg hover:bg-gray-50 cursor-pointer' onClick={() => onChange('form')}>
<div className='flex item-center gap-1'>
<div className='shrink-0 w-4 h-4'>
{value === 'form' && <Check className='shrink-0 w-4 h-4 text-primary-600' />}
</div>
<div className='text-[13px] text-gray-700 font-medium leading-[18px]'>{t('tools.createTool.toolInput.methodSetting')}</div>
</div>
<div className='pl-5 text-gray-500 text-[13px] leading-[18px]'>{t('tools.createTool.toolInput.methodSettingTip')}</div>
</div>
</div>
</div>
</PortalToFollowElemContent>
</div>
</PortalToFollowElem>
)
}
export default MethodSelector