This commit is contained in:
Joel
2024-11-15 16:13:40 +08:00
47 changed files with 937 additions and 101 deletions

View File

@ -3,8 +3,9 @@ import type { FC } from 'react'
import Modal from '@/app/components/base/modal'
import React, { useCallback, useState } from 'react'
import { InstallStep } from '../../types'
import type { Dependency } from '../../types'
import type { Dependency, Plugin } from '../../types'
import Install from './steps/install'
import Installed from './steps/installed'
import { useTranslation } from 'react-i18next'
const i18nPrefix = 'plugin.installModal'
@ -29,7 +30,8 @@ const InstallBundle: FC<Props> = ({
}) => {
const { t } = useTranslation()
const [step, setStep] = useState<InstallStep>(installType === InstallType.fromMarketplace ? InstallStep.readyToInstall : InstallStep.uploading)
const [installedPlugins, setInstalledPlugins] = useState<Plugin[]>([])
const [installStatus, setInstallStatus] = useState<{ success: boolean }[]>([])
const getTitle = useCallback(() => {
if (step === InstallStep.uploadFailed)
return t(`${i18nPrefix}.uploadFailed`)
@ -41,6 +43,12 @@ const InstallBundle: FC<Props> = ({
return t(`${i18nPrefix}.installPlugin`)
}, [step, t])
const handleInstalled = useCallback((plugins: Plugin[], installStatus: { success: boolean }[]) => {
setInstallStatus(installStatus)
setInstalledPlugins(plugins)
setStep(InstallStep.installed)
}, [])
return (
<Modal
isShow={true}
@ -57,6 +65,14 @@ const InstallBundle: FC<Props> = ({
<Install
fromDSLPayload={fromDSLPayload}
onCancel={onClose}
onInstalled={handleInstalled}
/>
)}
{step === InstallStep.installed && (
<Installed
list={installedPlugins}
installStatus={installStatus}
onCancel={onClose}
/>
)}
</Modal>

View File

@ -29,7 +29,10 @@ const Item: FC<Props> = ({
const [payload, setPayload] = React.useState<Plugin | null>(null)
useEffect(() => {
if (data) {
const payload = pluginManifestToCardPluginProps(data.manifest)
const payload = {
...pluginManifestToCardPluginProps(data.manifest),
plugin_id: data.unique_identifier,
}
onFetchedPayload(payload)
setPayload(payload)
}

View File

@ -5,6 +5,7 @@ import type { Plugin } from '../../../types'
import Card from '../../../card'
import Checkbox from '@/app/components/base/checkbox'
import Badge, { BadgeState } from '@/app/components/base/badge/index'
import useGetIcon from '../../base/use-get-icon'
type Props = {
checked: boolean
@ -17,6 +18,7 @@ const LoadedItem: FC<Props> = ({
onCheckedChange,
payload,
}) => {
const { getIconUrl } = useGetIcon()
return (
<div className='flex items-center space-x-2'>
<Checkbox
@ -26,7 +28,10 @@ const LoadedItem: FC<Props> = ({
/>
<Card
className='grow'
payload={payload}
payload={{
...payload,
icon: getIconUrl(payload.icon),
}}
titleLeft={payload.version ? <Badge className='mx-1' size="s" state={BadgeState.Default}>{payload.version}</Badge> : null}
/>
</div>

View File

@ -26,9 +26,12 @@ const InstallByDSLList: FC<Props> = ({
const [plugins, setPlugins, getPlugins] = useGetState<Plugin[]>([])
const handlePlugInFetched = useCallback((index: number) => {
return (p: Plugin) => {
setPlugins(plugins.map((item, i) => i === index ? p : item))
const nextPlugins = produce(getPlugins(), (draft) => {
draft[index] = p
})
setPlugins(nextPlugins)
}
}, [plugins])
}, [getPlugins, setPlugins])
const marketPlaceInDSLIndex = useMemo(() => {
const res: number[] = []

View File

@ -7,23 +7,25 @@ import { RiLoader2Line } from '@remixicon/react'
import { useTranslation } from 'react-i18next'
import InstallByDSLList from './install-by-dsl-list'
import { useInstallFromMarketplaceAndGitHub } from '@/service/use-plugins'
import { useInvalidateInstalledPluginList } from '@/service/use-plugins'
const i18nPrefix = 'plugin.installModal'
type Props = {
fromDSLPayload: Dependency[]
onInstalled: (plugins: Plugin[], installStatus: { success: boolean }[]) => void
onCancel: () => void
}
const Install: FC<Props> = ({
fromDSLPayload,
onInstalled,
onCancel,
}) => {
const { t } = useTranslation()
const [selectedPlugins, setSelectedPlugins] = React.useState<Plugin[]>([])
const [selectedIndexes, setSelectedIndexes] = React.useState<number[]>([])
const selectedPluginsNum = selectedPlugins.length
const invalidateInstalledPluginList = useInvalidateInstalledPluginList()
const handleSelect = (plugin: Plugin, selectedIndex: number) => {
const isSelected = !!selectedPlugins.find(p => p.plugin_id === plugin.plugin_id)
let nextSelectedPlugins
@ -35,18 +37,21 @@ const Install: FC<Props> = ({
const nextSelectedIndexes = isSelected ? selectedIndexes.filter(i => i !== selectedIndex) : [...selectedIndexes, selectedIndex]
setSelectedIndexes(nextSelectedIndexes)
}
const [canInstall, setCanInstall] = React.useState(false)
const handleLoadedAllPlugin = useCallback(() => {
setCanInstall(true)
}, [selectedPlugins, selectedIndexes])
}, [])
// Install from marketplace and github
const { mutate: installFromMarketplaceAndGitHub, isPending: isInstalling } = useInstallFromMarketplaceAndGitHub({
onSuccess: () => {
console.log('success!')
onSuccess: (res: { success: boolean }[]) => {
onInstalled(selectedPlugins, res)
const hasInstallSuccess = res.some(r => r.success)
if (hasInstallSuccess)
invalidateInstalledPluginList()
},
})
console.log(canInstall, !isInstalling, selectedPlugins.length === 0)
const handleInstall = () => {
installFromMarketplaceAndGitHub(fromDSLPayload.filter((_d, index) => selectedIndexes.includes(index)))
}

View File

@ -0,0 +1,60 @@
'use client'
import type { FC } from 'react'
import React from 'react'
import type { Plugin } from '../../../types'
import Card from '@/app/components/plugins/card'
import Button from '@/app/components/base/button'
import { useTranslation } from 'react-i18next'
import Badge, { BadgeState } from '@/app/components/base/badge/index'
import useGetIcon from '../../base/use-get-icon'
type Props = {
list: Plugin[]
installStatus: { success: boolean }[]
onCancel: () => void
}
const Installed: FC<Props> = ({
list,
installStatus,
onCancel,
}) => {
const { t } = useTranslation()
const { getIconUrl } = useGetIcon()
return (
<>
<div className='flex flex-col px-6 py-3 justify-center items-start gap-4 self-stretch'>
{/* <p className='text-text-secondary system-md-regular'>{(isFailed && errMsg) ? errMsg : t(`plugin.installModal.${isFailed ? 'installFailedDesc' : 'installedSuccessfullyDesc'}`)}</p> */}
<div className='flex p-2 items-start content-start gap-1 self-stretch flex-wrap rounded-2xl bg-background-section-burn space-y-1'>
{list.map((plugin, index) => {
return (
<Card
key={plugin.plugin_id}
className='w-full'
payload={{
...plugin,
icon: getIconUrl(plugin.icon),
}}
installed={installStatus[index].success}
installFailed={!installStatus[index].success}
titleLeft={plugin.version ? <Badge className='mx-1' size="s" state={BadgeState.Default}>{plugin.version}</Badge> : null}
/>
)
})}
</div>
</div>
{/* Action Buttons */}
<div className='flex p-6 pt-5 justify-end items-center gap-2 self-stretch'>
<Button
variant='primary'
className='min-w-[72px]'
onClick={onCancel}
>
{t('common.operation.close')}
</Button>
</div>
</>
)
}
export default React.memo(Installed)

View File

@ -2,7 +2,7 @@
import React from 'react'
import Button from '@/app/components/base/button'
import type { PluginDeclaration, UpdateFromGitHubPayload } from '../../../types'
import type { PluginDeclaration, PluginType, UpdateFromGitHubPayload } from '../../../types'
import Card from '../../../card'
import Badge, { BadgeState } from '@/app/components/base/badge/index'
import { pluginManifestToCardPluginProps } from '../../utils'
@ -13,6 +13,7 @@ import { RiLoader2Line } from '@remixicon/react'
import { usePluginTaskList } from '@/service/use-plugins'
import checkTaskStatus from '../../base/check-task-status'
import { parseGitHubUrl } from '../../utils'
import { useCategories } from '../../../hooks'
type LoadedProps = {
updatePayload: UpdateFromGitHubPayload
@ -40,6 +41,7 @@ const Loaded: React.FC<LoadedProps> = ({
onFailed,
}) => {
const { t } = useTranslation()
const { categoriesMap } = useCategories()
const [isInstalling, setIsInstalling] = React.useState(false)
const { mutateAsync: installPackageFromGitHub } = useInstallPackageFromGitHub()
const { handleRefetch } = usePluginTaskList()
@ -115,7 +117,7 @@ const Loaded: React.FC<LoadedProps> = ({
<div className='flex p-2 items-start content-start gap-1 self-stretch flex-wrap rounded-2xl bg-background-section-burn'>
<Card
className='w-full'
payload={pluginManifestToCardPluginProps(payload)}
payload={{ ...pluginManifestToCardPluginProps(payload), type: categoriesMap[payload.category].label as PluginType }}
titleLeft={<Badge className='mx-1' size="s" state={BadgeState.Default}>{payload.version}</Badge>}
/>
</div>

View File

@ -52,7 +52,10 @@ const TagsFilter = ({
open={open}
onOpenChange={setOpen}
>
<PortalToFollowElemTrigger onClick={() => setOpen(v => !v)}>
<PortalToFollowElemTrigger
className='shrink-0'
onClick={() => setOpen(v => !v)}
>
<div className={cn(
'flex items-center text-text-tertiary rounded-lg hover:bg-state-base-hover cursor-pointer',
size === 'large' && 'px-2 py-1 h-8',

View File

@ -0,0 +1,125 @@
import { useCallback } from 'react'
import { useTranslation } from 'react-i18next'
import Input from '@/app/components/base/input'
import Textarea from '@/app/components/base/textarea'
import { PortalSelect } from '@/app/components/base/select'
import { InputVarType } from '@/app/components/workflow/types'
import { FileUploaderInAttachmentWrapper } from '@/app/components/base/file-uploader'
type Props = {
inputsForms: any[]
inputs: Record<string, any>
inputsRef: any
onFormChange: (value: Record<string, any>) => void
}
const AppInputsForm = ({
inputsForms,
inputs,
inputsRef,
onFormChange,
}: Props) => {
const { t } = useTranslation()
const handleFormChange = useCallback((variable: string, value: any) => {
onFormChange({
...inputsRef.current,
[variable]: value,
})
}, [onFormChange, inputsRef])
const renderField = (form: any) => {
const {
label,
variable,
options,
} = form
if (form.type === InputVarType.textInput) {
return (
<Input
value={inputs[variable] || ''}
onChange={e => handleFormChange(variable, e.target.value)}
placeholder={label}
/>
)
}
if (form.type === InputVarType.number) {
return (
<Input
type="number"
value={inputs[variable] || ''}
onChange={e => handleFormChange(variable, e.target.value)}
placeholder={label}
/>
)
}
if (form.type === InputVarType.paragraph) {
return (
<Textarea
value={inputs[variable] || ''}
onChange={e => handleFormChange(variable, e.target.value)}
placeholder={label}
/>
)
}
if (form.type === InputVarType.select) {
return (
<PortalSelect
popupClassName="w-[356px] z-[1050]"
value={inputs[variable] || ''}
items={options.map((option: string) => ({ value: option, name: option }))}
onSelect={item => handleFormChange(variable, item.value as string)}
placeholder={label}
/>
)
}
if (form.type === InputVarType.singleFile) {
return (
<FileUploaderInAttachmentWrapper
value={inputs[variable] ? [inputs[variable]] : []}
onChange={files => handleFormChange(variable, files[0])}
fileConfig={{
allowed_file_types: form.allowed_file_types,
allowed_file_extensions: form.allowed_file_extensions,
allowed_file_upload_methods: form.allowed_file_upload_methods,
number_limits: 1,
fileUploadConfig: (form as any).fileUploadConfig,
}}
/>
)
}
if (form.type === InputVarType.multiFiles) {
return (
<FileUploaderInAttachmentWrapper
value={inputs[variable]}
onChange={files => handleFormChange(variable, files)}
fileConfig={{
allowed_file_types: form.allowed_file_types,
allowed_file_extensions: form.allowed_file_extensions,
allowed_file_upload_methods: form.allowed_file_upload_methods,
number_limits: form.max_length,
fileUploadConfig: (form as any).fileUploadConfig,
}}
/>
)
}
}
if (!inputsForms.length)
return null
return (
<div className='px-4 py-2 flex flex-col gap-4'>
{inputsForms.map(form => (
<div key={form.variable}>
<div className='h-6 mb-1 flex items-center gap-1 text-text-secondary system-sm-semibold'>
<div className='truncate'>{form.label}</div>
{!form.required && <span className='text-text-tertiary system-xs-regular'>{t('workflow.panel.optional')}</span>}
</div>
{renderField(form)}
</div>
))}
</div>
)
}
export default AppInputsForm

View File

@ -0,0 +1,180 @@
'use client'
import React, { useMemo, useRef } from 'react'
import { useTranslation } from 'react-i18next'
import Loading from '@/app/components/base/loading'
import AppInputsForm from '@/app/components/plugins/plugin-detail-panel/app-selector/app-inputs-form'
import { useAppDetail } from '@/service/use-apps'
import { useAppWorkflow } from '@/service/use-workflow'
import { useFileUploadConfig } from '@/service/use-common'
import { Resolution } from '@/types/app'
import { FILE_EXTS } from '@/app/components/base/prompt-editor/constants'
import type { App } from '@/types/app'
import type { FileUpload } from '@/app/components/base/features/types'
import { BlockEnum, InputVarType, SupportUploadFileTypes } from '@/app/components/workflow/types'
import cn from '@/utils/classnames'
type Props = {
value?: {
app_id: string
inputs: Record<string, any>
}
appDetail: App
onFormChange: (value: Record<string, any>) => void
}
const AppInputsPanel = ({
value,
appDetail,
onFormChange,
}: Props) => {
const { t } = useTranslation()
const inputsRef = useRef<any>(value?.inputs || {})
const isBasicApp = appDetail.mode !== 'advanced-chat' && appDetail.mode !== 'workflow'
const { data: fileUploadConfig } = useFileUploadConfig()
const { data: currentApp, isFetching: isAppLoading } = useAppDetail(appDetail.id)
const { data: currentWorkflow, isFetching: isWorkflowLoading } = useAppWorkflow(isBasicApp ? 'empty' : appDetail.id)
const isLoading = isAppLoading || isWorkflowLoading
const basicAppFileConfig = useMemo(() => {
let fileConfig: FileUpload
if (isBasicApp)
fileConfig = currentApp?.model_config?.file_upload as FileUpload
else
fileConfig = currentWorkflow?.features?.file_upload as FileUpload
return {
image: {
detail: fileConfig?.image?.detail || Resolution.high,
enabled: !!fileConfig?.image?.enabled,
number_limits: fileConfig?.image?.number_limits || 3,
transfer_methods: fileConfig?.image?.transfer_methods || ['local_file', 'remote_url'],
},
enabled: !!(fileConfig?.enabled || fileConfig?.image?.enabled),
allowed_file_types: fileConfig?.allowed_file_types || [SupportUploadFileTypes.image],
allowed_file_extensions: fileConfig?.allowed_file_extensions || [...FILE_EXTS[SupportUploadFileTypes.image]].map(ext => `.${ext}`),
allowed_file_upload_methods: fileConfig?.allowed_file_upload_methods || fileConfig?.image?.transfer_methods || ['local_file', 'remote_url'],
number_limits: fileConfig?.number_limits || fileConfig?.image?.number_limits || 3,
}
}, [currentApp?.model_config?.file_upload, currentWorkflow?.features?.file_upload, isBasicApp])
const inputFormSchema = useMemo(() => {
if (!currentApp)
return []
let inputFormSchema = []
if (isBasicApp) {
inputFormSchema = currentApp.model_config.user_input_form.filter((item: any) => !item.external_data_tool).map((item: any) => {
if (item.paragraph) {
return {
...item.paragraph,
type: 'paragraph',
required: false,
}
}
if (item.number) {
return {
...item.number,
type: 'number',
required: false,
}
}
if (item.select) {
return {
...item.select,
type: 'select',
required: false,
}
}
if (item['file-list']) {
return {
...item['file-list'],
type: 'file-list',
required: false,
fileUploadConfig,
}
}
if (item.file) {
return {
...item.file,
type: 'file',
required: false,
fileUploadConfig,
}
}
return {
...item['text-input'],
type: 'text-input',
required: false,
}
})
}
else {
const startNode = currentWorkflow?.graph.nodes.find(node => node.data.type === BlockEnum.Start) as any
inputFormSchema = startNode?.data.variables.map((variable: any) => {
if (variable.type === InputVarType.multiFiles) {
return {
...variable,
required: false,
fileUploadConfig,
}
}
if (variable.type === InputVarType.singleFile) {
return {
...variable,
required: false,
fileUploadConfig,
}
}
return {
...variable,
required: false,
}
})
}
if ((currentApp.mode === 'completion' || currentApp.mode === 'workflow') && basicAppFileConfig.enabled) {
inputFormSchema.push({
label: 'Image Upload',
variable: '#image#',
type: InputVarType.singleFile,
required: false,
...basicAppFileConfig,
fileUploadConfig,
})
}
return inputFormSchema
}, [basicAppFileConfig, currentApp, currentWorkflow, fileUploadConfig, isBasicApp])
const handleFormChange = (value: Record<string, any>) => {
inputsRef.current = value
onFormChange(value)
}
return (
<div className={cn('max-h-[240px] flex flex-col pb-4 rounded-b-2xl border-t border-divider-subtle')}>
{isLoading && <div className='pt-3'><Loading type='app' /></div>}
{!isLoading && (
<div className='shrink-0 mt-3 mb-2 px-4 h-6 flex items-center system-sm-semibold text-text-secondary'>{t('app.appSelector.params')}</div>
)}
{!isLoading && !inputFormSchema.length && (
<div className='h-16 flex flex-col justify-center items-center'>
<div className='text-text-tertiary system-sm-regular'>{t('app.appSelector.noParams')}</div>
</div>
)}
{!isLoading && !!inputFormSchema.length && (
<div className='grow overflow-y-auto'>
<AppInputsForm
inputs={value?.inputs || {}}
inputsRef={inputsRef}
inputsForms={inputFormSchema}
onFormChange={handleFormChange}
/>
</div>
)}
</div>
)
}
export default AppInputsPanel

View File

@ -0,0 +1,113 @@
'use client'
import type { FC } from 'react'
import React, { useMemo } from 'react'
import { useState } from 'react'
import {
PortalToFollowElem,
PortalToFollowElemContent,
PortalToFollowElemTrigger,
} from '@/app/components/base/portal-to-follow-elem'
import type {
OffsetOptions,
Placement,
} from '@floating-ui/react'
import Input from '@/app/components/base/input'
import AppIcon from '@/app/components/base/app-icon'
import type { App } from '@/types/app'
type Props = {
appList: App[]
disabled: boolean
trigger: React.ReactNode
placement?: Placement
offset?: OffsetOptions
isShow: boolean
onShowChange: (isShow: boolean) => void
onSelect: (app: App) => void
}
const AppPicker: FC<Props> = ({
appList,
disabled,
trigger,
placement = 'right-start',
offset = 0,
isShow,
onShowChange,
onSelect,
}) => {
const [searchText, setSearchText] = useState('')
const filteredAppList = useMemo(() => {
return (appList || []).filter(app => app.name.toLowerCase().includes(searchText.toLowerCase())).filter(app => (app.mode !== 'advanced-chat' && app.mode !== 'workflow') || !!app.workflow)
}, [appList, searchText])
const getAppType = (app: App) => {
switch (app.mode) {
case 'advanced-chat':
return 'chatflow'
case 'agent-chat':
return 'agent'
case 'chat':
return 'chat'
case 'completion':
return 'completion'
case 'workflow':
return 'workflow'
}
}
const handleTriggerClick = () => {
if (disabled) return
onShowChange(true)
}
return (
<PortalToFollowElem
placement={placement}
offset={offset}
open={isShow}
onOpenChange={onShowChange}
>
<PortalToFollowElemTrigger
onClick={handleTriggerClick}
>
{trigger}
</PortalToFollowElemTrigger>
<PortalToFollowElemContent className='z-[1000]'>
<div className="relative w-[356px] min-h-20 rounded-xl bg-components-panel-bg-blur border-[0.5px] border-components-panel-border shadow-lg">
<div className='p-2 pb-1'>
<Input
showLeftIcon
showClearIcon
value={searchText}
onChange={e => setSearchText(e.target.value)}
onClear={() => setSearchText('')}
/>
</div>
<div className='p-1'>
{filteredAppList.map(app => (
<div
key={app.id}
className='flex items-center gap-3 py-1 pl-2 pr-3 rounded-lg hover:bg-state-base-hover cursor-pointer'
onClick={() => onSelect(app)}
>
<AppIcon
className='shrink-0'
size='xs'
iconType={app.icon_type}
icon={app.icon}
background={app.icon_background}
imageUrl={app.icon_url}
/>
<div title={app.name} className='grow system-sm-medium text-components-input-text-filled'>{app.name}</div>
<div className='shrink-0 text-text-tertiary system-2xs-medium-uppercase'>{getAppType(app)}</div>
</div>
))}
</div>
</div>
</PortalToFollowElemContent>
</PortalToFollowElem>
)
}
export default React.memo(AppPicker)

View File

@ -0,0 +1,48 @@
'use client'
import React from 'react'
import { useTranslation } from 'react-i18next'
import {
RiArrowDownSLine,
} from '@remixicon/react'
import AppIcon from '@/app/components/base/app-icon'
import type { App } from '@/types/app'
import cn from '@/utils/classnames'
type Props = {
open: boolean
appDetail?: App
}
const AppTrigger = ({
open,
appDetail,
}: Props) => {
const { t } = useTranslation()
return (
<div className={cn(
'group flex items-center p-2 pl-3 bg-components-input-bg-normal rounded-lg cursor-pointer hover:bg-state-base-hover-alt',
open && 'bg-state-base-hover-alt',
appDetail && 'pl-1.5 py-1.5',
)}>
{appDetail && (
<AppIcon
className='mr-2'
size='xs'
iconType={appDetail.icon_type}
icon={appDetail.icon}
background={appDetail.icon_background}
imageUrl={appDetail.icon_url}
/>
)}
{appDetail && (
<div title={appDetail.name} className='grow system-sm-medium text-components-input-text-filled'>{appDetail.name}</div>
)}
{!appDetail && (
<div className='grow text-components-input-text-placeholder system-sm-regular truncate'>{t('app.appSelector.placeholder')}</div>
)}
<RiArrowDownSLine className={cn('shrink-0 ml-0.5 w-4 h-4 text-text-quaternary group-hover:text-text-secondary', open && 'text-text-secondary')} />
</div>
)
}
export default AppTrigger

View File

@ -0,0 +1,139 @@
'use client'
import type { FC } from 'react'
import React, { useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import {
PortalToFollowElem,
PortalToFollowElemContent,
PortalToFollowElemTrigger,
} from '@/app/components/base/portal-to-follow-elem'
import AppTrigger from '@/app/components/plugins/plugin-detail-panel/app-selector/app-trigger'
import AppPicker from '@/app/components/plugins/plugin-detail-panel/app-selector/app-picker'
import AppInputsPanel from '@/app/components/plugins/plugin-detail-panel/app-selector/app-inputs-panel'
import { useAppFullList } from '@/service/use-apps'
import type { App } from '@/types/app'
import type {
OffsetOptions,
Placement,
} from '@floating-ui/react'
type Props = {
value?: {
app_id: string
inputs: Record<string, any>
files?: any[]
}
disabled?: boolean
placement?: Placement
offset?: OffsetOptions
onSelect: (app: {
app_id: string
inputs: Record<string, any>
files?: any[]
}) => void
supportAddCustomTool?: boolean
}
const AppSelector: FC<Props> = ({
value,
disabled,
placement = 'bottom',
offset = 4,
onSelect,
}) => {
const { t } = useTranslation()
const [isShow, onShowChange] = useState(false)
const handleTriggerClick = () => {
if (disabled) return
onShowChange(true)
}
const { data: appList } = useAppFullList()
const currentAppInfo = useMemo(() => {
if (!appList?.data || !value)
return undefined
return appList.data.find(app => app.id === value.app_id)
}, [appList?.data, value])
const [isShowChooseApp, setIsShowChooseApp] = useState(false)
const handleSelectApp = (app: App) => {
const clearValue = app.id !== value?.app_id
const appValue = {
app_id: app.id,
inputs: clearValue ? {} : value?.inputs || {},
files: clearValue ? [] : value?.files || [],
}
onSelect(appValue)
setIsShowChooseApp(false)
}
const handleFormChange = (inputs: Record<string, any>) => {
const newFiles = inputs['#image#']
delete inputs['#image#']
const newValue = {
app_id: value?.app_id || '',
inputs,
files: newFiles ? [newFiles] : value?.files || [],
}
onSelect(newValue)
}
const formattedValue = useMemo(() => {
return {
app_id: value?.app_id || '',
inputs: {
...value?.inputs,
...(value?.files?.length ? { '#image#': value.files[0] } : {}),
},
}
}, [value])
return (
<>
<PortalToFollowElem
placement={placement}
offset={offset}
open={isShow}
onOpenChange={onShowChange}
>
<PortalToFollowElemTrigger
className='w-full'
onClick={handleTriggerClick}
>
<AppTrigger
open={isShow}
appDetail={currentAppInfo}
/>
</PortalToFollowElemTrigger>
<PortalToFollowElemContent className='z-[1000]'>
<div className="relative w-[389px] min-h-20 rounded-xl bg-components-panel-bg-blur border-[0.5px] border-components-panel-border shadow-lg">
<div className='px-4 py-3 flex flex-col gap-1'>
<div className='h-6 flex items-center system-sm-semibold text-text-secondary'>{t('app.appSelector.label')}</div>
<AppPicker
placement='bottom'
offset={offset}
trigger={
<AppTrigger
open={isShowChooseApp}
appDetail={currentAppInfo}
/>
}
isShow={isShowChooseApp}
onShowChange={setIsShowChooseApp}
disabled={false}
appList={appList?.data || []}
onSelect={handleSelectApp}
/>
</div>
{/* app inputs config panel */}
{currentAppInfo && (
<AppInputsPanel
value={formattedValue}
appDetail={currentAppInfo}
onFormChange={handleFormChange}
/>
)}
</div>
</PortalToFollowElemContent>
</PortalToFollowElem>
</>
)
}
export default React.memo(AppSelector)

View File

@ -69,7 +69,7 @@ const EndpointModal: FC<Props> = ({
isEditMode={true}
showOnVariableMap={{}}
validating={false}
inputClassName='bg-components-input-bg-normal hover:bg-state-base-hover-alt'
inputClassName='bg-components-input-bg-normal hover:bg-components-input-bg-hover'
fieldMoreInfo={item => item.url
? (<a
href={item.url}

View File

@ -0,0 +1,183 @@
'use client'
import type { FC } from 'react'
import React, { useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import {
PortalToFollowElem,
PortalToFollowElemContent,
PortalToFollowElemTrigger,
} from '@/app/components/base/portal-to-follow-elem'
import ToolTrigger from '@/app/components/plugins/plugin-detail-panel/tool-selector/tool-trigger'
import ToolPicker from '@/app/components/workflow/block-selector/tool-picker'
import Button from '@/app/components/base/button'
import Indicator from '@/app/components/header/indicator'
import ToolCredentialForm from '@/app/components/plugins/plugin-detail-panel/tool-selector/tool-credentials-form'
import Toast from '@/app/components/base/toast'
import { useAppContext } from '@/context/app-context'
import {
useAllBuiltInTools,
useAllCustomTools,
useAllWorkflowTools,
useInvalidateAllBuiltInTools,
useUpdateProviderCredentials,
} from '@/service/use-tools'
import { CollectionType } from '@/app/components/tools/types'
import type { ToolDefaultValue } from '@/app/components/workflow/block-selector/types'
import type {
OffsetOptions,
Placement,
} from '@floating-ui/react'
import cn from '@/utils/classnames'
type Props = {
value?: {
provider: string
tool_name: string
}
disabled?: boolean
placement?: Placement
offset?: OffsetOptions
onSelect: (tool: {
provider: string
tool_name: string
}) => void
supportAddCustomTool?: boolean
}
const ToolSelector: FC<Props> = ({
value,
disabled,
placement = 'bottom',
offset = 4,
onSelect,
}) => {
const { t } = useTranslation()
const [isShow, onShowChange] = useState(false)
const handleTriggerClick = () => {
if (disabled) return
onShowChange(true)
}
const { data: buildInTools } = useAllBuiltInTools()
const { data: customTools } = useAllCustomTools()
const { data: workflowTools } = useAllWorkflowTools()
const invalidateAllBuiltinTools = useInvalidateAllBuiltInTools()
const currentProvider = useMemo(() => {
const mergedTools = [...(buildInTools || []), ...(customTools || []), ...(workflowTools || [])]
return mergedTools.find((toolWithProvider) => {
return toolWithProvider.id === value?.provider && toolWithProvider.tools.some(tool => tool.name === value?.tool_name)
})
}, [value, buildInTools, customTools, workflowTools])
const [isShowChooseTool, setIsShowChooseTool] = useState(false)
const handleSelectTool = (tool: ToolDefaultValue) => {
const toolValue = {
provider: tool.provider_id,
tool_name: tool.tool_name,
}
onSelect(toolValue)
setIsShowChooseTool(false)
if (tool.provider_type === CollectionType.builtIn && tool.is_team_authorization)
onShowChange(false)
}
const { isCurrentWorkspaceManager } = useAppContext()
const [isShowSettingAuth, setShowSettingAuth] = useState(false)
const handleCredentialSettingUpdate = () => {
invalidateAllBuiltinTools()
Toast.notify({
type: 'success',
message: t('common.api.actionSuccess'),
})
setShowSettingAuth(false)
onShowChange(false)
}
const { mutate: updatePermission } = useUpdateProviderCredentials({
onSuccess: handleCredentialSettingUpdate,
})
return (
<>
<PortalToFollowElem
placement={placement}
offset={offset}
open={isShow}
onOpenChange={onShowChange}
>
<PortalToFollowElemTrigger
className='w-full'
onClick={handleTriggerClick}
>
<ToolTrigger
open={isShow}
value={value}
provider={currentProvider}
/>
</PortalToFollowElemTrigger>
<PortalToFollowElemContent className='z-[1000]'>
<div className="relative w-[389px] min-h-20 rounded-xl bg-components-panel-bg-blur border-[0.5px] border-components-panel-border shadow-lg">
<div className='px-4 py-3 flex flex-col gap-1'>
<div className='h-6 flex items-center system-sm-semibold text-text-secondary'>{t('tools.toolSelector.label')}</div>
<ToolPicker
placement='bottom'
offset={offset}
trigger={
<ToolTrigger
open={isShowChooseTool}
value={value}
provider={currentProvider}
/>
}
isShow={isShowChooseTool}
onShowChange={setIsShowChooseTool}
disabled={false}
supportAddCustomTool
onSelect={handleSelectTool}
/>
</div>
{/* authorization panel */}
{isShowSettingAuth && currentProvider && (
<div className='px-4 pb-4 border-t border-divider-subtle'>
<ToolCredentialForm
collection={currentProvider}
onCancel={() => setShowSettingAuth(false)}
onSaved={async value => updatePermission({
providerName: currentProvider.name,
credentials: value,
})}
/>
</div>
)}
{!isShowSettingAuth && currentProvider && currentProvider.type === CollectionType.builtIn && currentProvider.is_team_authorization && currentProvider.allow_delete && (
<div className='px-4 py-3 flex items-center border-t border-divider-subtle'>
<div className='grow mr-3 h-6 flex items-center system-sm-semibold text-text-secondary'>{t('tools.toolSelector.auth')}</div>
{isCurrentWorkspaceManager && (
<Button
variant='secondary'
size='small'
onClick={() => {}}
>
<Indicator className='mr-2' color={'green'} />
{t('tools.auth.authorized')}
</Button>
)}
</div>
)}
{!isShowSettingAuth && currentProvider && currentProvider.type === CollectionType.builtIn && !currentProvider.is_team_authorization && currentProvider.allow_delete && (
<div className='px-4 py-3 flex items-center border-t border-divider-subtle'>
<Button
variant='primary'
className={cn('shrink-0 w-full')}
onClick={() => setShowSettingAuth(true)}
disabled={!isCurrentWorkspaceManager}
>
{t('tools.auth.unauthorized')}
</Button>
</div>
)}
</div>
</PortalToFollowElemContent>
</PortalToFollowElem>
</>
)
}
export default React.memo(ToolSelector)

View File

@ -0,0 +1,95 @@
'use client'
import type { FC } from 'react'
import React, { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import {
RiArrowRightUpLine,
} from '@remixicon/react'
import { addDefaultValue, toolCredentialToFormSchemas } from '@/app/components/tools/utils/to-form-schema'
import type { Collection } from '@/app/components/tools/types'
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 { useLanguage } from '@/app/components/header/account-setting/model-provider-page/hooks'
import cn from '@/utils/classnames'
type Props = {
collection: Collection
onCancel: () => void
onSaved: (value: Record<string, any>) => void
}
const ToolCredentialForm: FC<Props> = ({
collection,
onCancel,
onSaved,
}) => {
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 (
<div className='h-full'>
{!credentialSchema
? <div className='pt-3'><Loading type='app' /></div>
: (
<>
<Form
value={tempCredential}
onChange={(v) => {
setTempCredential(v)
}}
formSchemas={credentialSchema}
isEditMode={true}
showOnVariableMap={{}}
validating={false}
inputClassName='bg-components-input-bg-normal hover:bg-components-input-bg-hover'
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')}
<RiArrowRightUpLine className='ml-1 w-3 h-3' />
</a>)
: null}
/>
<div className={cn('mt-1 flex justify-end')} >
<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 >
)
}
export default React.memo(ToolCredentialForm)

View File

@ -0,0 +1,53 @@
'use client'
import React from 'react'
import { useTranslation } from 'react-i18next'
import {
RiArrowDownSLine,
} from '@remixicon/react'
import BlockIcon from '@/app/components/workflow/block-icon'
import { BlockEnum } from '@/app/components/workflow/types'
import type { ToolWithProvider } from '@/app/components/workflow/types'
import cn from '@/utils/classnames'
type Props = {
open: boolean
provider?: ToolWithProvider
value?: {
provider: string
tool_name: string
}
}
const ToolTrigger = ({
open,
provider,
value,
}: Props) => {
const { t } = useTranslation()
return (
<div className={cn(
'group flex items-center p-2 pl-3 bg-components-input-bg-normal rounded-lg cursor-pointer hover:bg-state-base-hover-alt',
open && 'bg-state-base-hover-alt',
value && 'pl-1.5 py-1.5',
)}>
{value && provider && (
<div className='shrink-0 mr-1 p-px rounded-lg bg-components-panel-bg border border-components-panel-border'>
<BlockIcon
className='!w-4 !h-4'
type={BlockEnum.Tool}
toolIcon={provider.icon}
/>
</div>
)}
{value && (
<div className='grow system-sm-medium text-components-input-text-filled'>{value.tool_name}</div>
)}
{!value && (
<div className='grow text-components-input-text-placeholder system-sm-regular'>{t('tools.toolSelector.placeholder')}</div>
)}
<RiArrowDownSLine className={cn('shrink-0 ml-0.5 w-4 h-4 text-text-quaternary group-hover:text-text-secondary', open && 'text-text-secondary')} />
</div>
)
}
export default ToolTrigger

View File

@ -11,7 +11,7 @@ export const usePluginTaskStatus = () => {
pluginTasks,
} = usePluginTaskList()
const { mutate } = useMutationClearTaskPlugin()
const allPlugins = pluginTasks.map(task => task.plugins.map((plugin) => {
const allPlugins = pluginTasks.filter(task => task.status !== TaskStatus.success).map(task => task.plugins.map((plugin) => {
return {
...plugin,
taskId: task.id,

View File

@ -34,11 +34,14 @@ const PluginTasks = () => {
handleClearErrorPlugin,
} = usePluginTaskStatus()
const { getIconUrl } = useGetIcon()
const runningPluginsLength = runningPlugins.length
const errorPluginsLength = errorPlugins.length
const successPluginsLength = successPlugins.length
const isInstalling = runningPlugins.length > 0 && errorPlugins.length === 0 && successPlugins.length === 0
const isInstallingWithError = errorPlugins.length > 0 && errorPlugins.length < totalPluginsLength
const isSuccess = successPlugins.length === totalPluginsLength && totalPluginsLength > 0
const isFailed = errorPlugins.length === totalPluginsLength && totalPluginsLength > 0
const isInstalling = runningPluginsLength > 0 && errorPluginsLength === 0
const isInstallingWithError = runningPluginsLength > 0 && errorPluginsLength > 0
const isSuccess = successPluginsLength === totalPluginsLength && totalPluginsLength > 0
const isFailed = runningPluginsLength === 0 && (errorPluginsLength + successPluginsLength) === totalPluginsLength && totalPluginsLength > 0
const tip = useMemo(() => {
if (isInstalling)
@ -51,6 +54,9 @@ const PluginTasks = () => {
return t('plugin.task.installError', { errorLength: errorPlugins.length })
}, [isInstalling, isInstallingWithError, isFailed, errorPlugins, runningPlugins, totalPluginsLength, t])
if (!totalPluginsLength)
return null
return (
<div className='flex items-center'>
<PortalToFollowElem
@ -72,7 +78,7 @@ const PluginTasks = () => {
<div
className={cn(
'relative flex items-center justify-center w-8 h-8 rounded-lg border-[0.5px] border-components-button-secondary-border bg-components-button-secondary-bg shadow-xs hover:bg-components-button-secondary-bg-hover',
(isInstallingWithError || isFailed) && 'border-components-button-destructive-secondary-border-hover bg-state-destructive-hover hover:bg-state-destructive-hover-alt',
(isInstallingWithError || isFailed) && 'border-components-button-destructive-secondary-border-hover bg-state-destructive-hover hover:bg-state-destructive-hover-alt cursor-pointer',
)}
>
<RiInstallLine
@ -115,7 +121,9 @@ const PluginTasks = () => {
</PortalToFollowElemTrigger>
<PortalToFollowElemContent className='z-10'>
<div className='p-1 pb-2 w-[320px] rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur shadow-lg'>
<div className='flex items-center px-2 pt-1 h-7 system-sm-semibold-uppercase'>{t('plugin.task.installedError')}</div>
<div className='flex items-center px-2 pt-1 h-7 system-sm-semibold-uppercase'>
{t('plugin.task.installedError', { errorLength: errorPlugins.length })}
</div>
{
errorPlugins.map(errorPlugin => (
<div