This commit is contained in:
2025-12-01 17:21:38 +08:00
parent 32fee2b8ab
commit fab8c13cb3
7511 changed files with 996300 additions and 0 deletions

View File

@@ -0,0 +1,52 @@
import React, { useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import ToolItem from '@/app/components/tools/provider/tool-item'
import {
useAllToolProviders,
useBuiltinTools,
} from '@/service/use-tools'
import type { PluginDetail } from '@/app/components/plugins/types'
type Props = {
detail: PluginDetail
}
const ActionList = ({
detail,
}: Props) => {
const { t } = useTranslation()
const providerBriefInfo = detail.declaration?.tool?.identity
const providerKey = providerBriefInfo ? `${detail.plugin_id}/${providerBriefInfo.name}` : ''
const { data: collectionList = [] } = useAllToolProviders()
const provider = useMemo(() => {
return collectionList.find(collection => collection.name === providerKey)
}, [collectionList, providerKey])
const { data } = useBuiltinTools(providerKey)
if (!providerKey || !data || !provider)
return null
return (
<div className='px-4 pb-4 pt-2'>
<div className='mb-1 py-1'>
<div className='system-sm-semibold-uppercase mb-1 flex h-6 items-center justify-between text-text-secondary'>
{t('plugin.detailPanel.actionNum', { num: data.length, action: data.length > 1 ? 'actions' : 'action' })}
</div>
</div>
<div className='flex flex-col gap-2'>
{data.map(tool => (
<ToolItem
key={`${detail.plugin_id}${tool.name}`}
disabled={false}
collection={provider}
tool={tool}
isBuiltIn={true}
isModel={false}
/>
))}
</div>
</div>
)
}
export default ActionList

View File

@@ -0,0 +1,58 @@
import React, { useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import StrategyItem from '@/app/components/plugins/plugin-detail-panel/strategy-item'
import {
useStrategyProviderDetail,
} from '@/service/use-strategy'
import type { PluginDetail } from '@/app/components/plugins/types'
type Props = {
detail: PluginDetail
}
const AgentStrategyList = ({
detail,
}: Props) => {
const { t } = useTranslation()
const providerBriefInfo = detail.declaration.agent_strategy.identity
const providerKey = `${detail.plugin_id}/${providerBriefInfo.name}`
const { data: strategyProviderDetail } = useStrategyProviderDetail(providerKey)
const providerDetail = useMemo(() => {
return {
...strategyProviderDetail?.declaration.identity,
tenant_id: detail.tenant_id,
}
}, [detail.tenant_id, strategyProviderDetail?.declaration.identity])
const strategyList = useMemo(() => {
if (!strategyProviderDetail)
return []
return strategyProviderDetail.declaration.strategies
}, [strategyProviderDetail])
if (!strategyProviderDetail)
return null
return (
<div className='px-4 pb-4 pt-2'>
<div className='mb-1 py-1'>
<div className='system-sm-semibold-uppercase mb-1 flex h-6 items-center justify-between text-text-secondary'>
{t('plugin.detailPanel.strategyNum', { num: strategyList.length, strategy: strategyList.length > 1 ? 'strategies' : 'strategy' })}
</div>
</div>
<div className='flex flex-col gap-2'>
{strategyList.map(strategyDetail => (
<StrategyItem
key={`${strategyDetail.identity.provider}${strategyDetail.identity.name}`}
provider={providerDetail as any}
detail={strategyDetail}
/>
))}
</div>
</div>
)
}
export default AgentStrategyList

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='flex flex-col gap-4 px-4 py-2'>
{inputsForms.map(form => (
<div key={form.variable}>
<div className='system-sm-semibold mb-1 flex h-6 items-center gap-1 text-text-secondary'>
<div className='truncate'>{form.label}</div>
{!form.required && <span className='system-xs-regular text-text-tertiary'>{t('workflow.panel.optional')}</span>}
</div>
{renderField(form)}
</div>
))}
</div>
)
}
export default AppInputsForm

View File

@@ -0,0 +1,194 @@
'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 { AppModeEnum, 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 !== AppModeEnum.ADVANCED_CHAT && appDetail.mode !== AppModeEnum.WORKFLOW
const { data: fileUploadConfig } = useFileUploadConfig()
const { data: currentApp, isFetching: isAppLoading } = useAppDetail(appDetail.id)
const { data: currentWorkflow, isFetching: isWorkflowLoading } = useAppWorkflow(isBasicApp ? '' : 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.checkbox) {
return {
...item.checkbox,
type: 'checkbox',
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,
}
}
if (item.json_object) {
return {
...item.json_object,
type: 'json_object',
}
}
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 === AppModeEnum.COMPLETION || currentApp.mode === AppModeEnum.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('flex max-h-[240px] flex-col rounded-b-2xl border-t border-divider-subtle pb-4')}>
{isLoading && <div className='pt-3'><Loading type='app' /></div>}
{!isLoading && (
<div className='system-sm-semibold mb-2 mt-3 flex h-6 shrink-0 items-center px-4 text-text-secondary'>{t('app.appSelector.params')}</div>
)}
{!isLoading && !inputFormSchema.length && (
<div className='flex h-16 flex-col items-center justify-center'>
<div className='system-sm-regular text-text-tertiary'>{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,196 @@
'use client'
import type { FC } from 'react'
import React, { useCallback, useEffect, useRef } 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, AppModeEnum } from '@/types/app'
import { useTranslation } from 'react-i18next'
type Props = {
scope: string
disabled: boolean
trigger: React.ReactNode
placement?: Placement
offset?: OffsetOptions
isShow: boolean
onShowChange: (isShow: boolean) => void
onSelect: (app: App) => void
apps: App[]
isLoading: boolean
hasMore: boolean
onLoadMore: () => void
searchText: string
onSearchChange: (text: string) => void
}
const AppPicker: FC<Props> = ({
scope: _scope,
disabled,
trigger,
placement = 'right-start',
offset = 0,
isShow,
onShowChange,
onSelect,
apps,
isLoading,
hasMore,
onLoadMore,
searchText,
onSearchChange,
}) => {
const { t } = useTranslation()
const observerTarget = useRef<HTMLDivElement>(null)
const observerRef = useRef<IntersectionObserver | null>(null)
const loadingRef = useRef(false)
const handleIntersection = useCallback((entries: IntersectionObserverEntry[]) => {
const target = entries[0]
if (!target.isIntersecting || loadingRef.current || !hasMore || isLoading) return
loadingRef.current = true
onLoadMore()
// Reset loading state
setTimeout(() => {
loadingRef.current = false
}, 500)
}, [hasMore, isLoading, onLoadMore])
useEffect(() => {
if (!isShow) {
if (observerRef.current) {
observerRef.current.disconnect()
observerRef.current = null
}
return
}
let mutationObserver: MutationObserver | null = null
const setupIntersectionObserver = () => {
if (!observerTarget.current) return
// Create new observer
observerRef.current = new IntersectionObserver(handleIntersection, {
root: null,
rootMargin: '100px',
threshold: 0.1,
})
observerRef.current.observe(observerTarget.current)
}
// Set up MutationObserver to watch DOM changes
mutationObserver = new MutationObserver((_mutations) => {
if (observerTarget.current) {
setupIntersectionObserver()
mutationObserver?.disconnect()
}
})
// Watch body changes since Portal adds content to body
mutationObserver.observe(document.body, {
childList: true,
subtree: true,
})
// If element exists, set up IntersectionObserver directly
if (observerTarget.current)
setupIntersectionObserver()
return () => {
if (observerRef.current) {
observerRef.current.disconnect()
observerRef.current = null
}
mutationObserver?.disconnect()
}
}, [isShow, handleIntersection])
const getAppType = (app: App) => {
switch (app.mode) {
case AppModeEnum.ADVANCED_CHAT:
return 'chatflow'
case AppModeEnum.AGENT_CHAT:
return 'agent'
case AppModeEnum.CHAT:
return 'chat'
case AppModeEnum.COMPLETION:
return 'completion'
case AppModeEnum.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 flex max-h-[400px] min-h-20 w-[356px] flex-col rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur shadow-lg backdrop-blur-sm">
<div className='p-2 pb-1'>
<Input
showLeftIcon
showClearIcon
value={searchText}
onChange={e => onSearchChange(e.target.value)}
onClear={() => onSearchChange('')}
/>
</div>
<div className='min-h-0 flex-1 overflow-y-auto p-1'>
{apps.map(app => (
<div
key={app.id}
className='flex cursor-pointer items-center gap-3 rounded-lg py-1 pl-2 pr-3 hover:bg-state-base-hover'
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='system-sm-medium grow text-components-input-text-filled'>{app.name}</div>
<div className='system-2xs-medium-uppercase shrink-0 text-text-tertiary'>{getAppType(app)}</div>
</div>
))}
<div ref={observerTarget} className='h-4 w-full'>
{isLoading && (
<div className='flex justify-center py-2'>
<div className='text-sm text-gray-500'>{t('common.loading')}</div>
</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 cursor-pointer items-center rounded-lg bg-components-input-bg-normal p-2 pl-3 hover:bg-state-base-hover-alt',
open && 'bg-state-base-hover-alt',
appDetail && 'py-1.5 pl-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='system-sm-medium grow text-components-input-text-filled'>{appDetail.name}</div>
)}
{!appDetail && (
<div className='system-sm-regular grow truncate text-components-input-text-placeholder'>{t('app.appSelector.placeholder')}</div>
)}
<RiArrowDownSLine className={cn('ml-0.5 h-4 w-4 shrink-0 text-text-quaternary group-hover:text-text-secondary', open && 'text-text-secondary')} />
</div>
)
}
export default AppTrigger

View File

@@ -0,0 +1,210 @@
'use client'
import type { FC } from 'react'
import React, { useCallback, 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 type { App } from '@/types/app'
import type {
OffsetOptions,
Placement,
} from '@floating-ui/react'
import useSWRInfinite from 'swr/infinite'
import { fetchAppList } from '@/service/apps'
import type { AppListResponse } from '@/models/app'
const PAGE_SIZE = 20
const getKey = (
pageIndex: number,
previousPageData: AppListResponse,
searchText: string,
) => {
if (pageIndex === 0 || (previousPageData && previousPageData.has_more)) {
const params: any = {
url: 'apps',
params: {
page: pageIndex + 1,
limit: PAGE_SIZE,
name: searchText,
},
}
return params
}
return null
}
type Props = {
value?: {
app_id: string
inputs: Record<string, any>
files?: any[]
}
scope?: string
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,
scope,
disabled,
placement = 'bottom',
offset = 4,
onSelect,
}) => {
const { t } = useTranslation()
const [isShow, onShowChange] = useState(false)
const [searchText, setSearchText] = useState('')
const [isLoadingMore, setIsLoadingMore] = useState(false)
const { data, isLoading, setSize } = useSWRInfinite(
(pageIndex: number, previousPageData: AppListResponse) => getKey(pageIndex, previousPageData, searchText),
fetchAppList,
{
revalidateFirstPage: true,
shouldRetryOnError: false,
dedupingInterval: 500,
errorRetryCount: 3,
},
)
const displayedApps = useMemo(() => {
if (!data) return []
return data.flatMap(({ data: apps }) => apps)
}, [data])
const hasMore = data?.at(-1)?.has_more ?? true
const handleLoadMore = useCallback(async () => {
if (isLoadingMore || !hasMore) return
setIsLoadingMore(true)
try {
await setSize((size: number) => size + 1)
}
finally {
// Add a small delay to ensure state updates are complete
setTimeout(() => {
setIsLoadingMore(false)
}, 300)
}
}, [isLoadingMore, hasMore, setSize])
const handleTriggerClick = () => {
if (disabled) return
onShowChange(true)
}
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])
const currentAppInfo = useMemo(() => {
if (!displayedApps || !value)
return undefined
return displayedApps.find(app => app.id === value.app_id)
}, [displayedApps, 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 min-h-20 w-[389px] rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur shadow-lg backdrop-blur-sm">
<div className='flex flex-col gap-1 px-4 py-3'>
<div className='system-sm-semibold flex h-6 items-center 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}
onSelect={handleSelectApp}
scope={scope || 'all'}
apps={displayedApps}
isLoading={isLoading || isLoadingMore}
hasMore={hasMore}
onLoadMore={handleLoadMore}
searchText={searchText}
onSearchChange={setSearchText}
/>
</div>
{/* app inputs config panel */}
{currentAppInfo && (
<AppInputsPanel
value={formattedValue}
appDetail={currentAppInfo}
onFormChange={handleFormChange}
/>
)}
</div>
</PortalToFollowElemContent>
</PortalToFollowElem>
</>
)
}
export default React.memo(AppSelector)

View File

@@ -0,0 +1,109 @@
import React, { useMemo } from 'react'
import { useTranslation } from 'react-i18next'
// import { useAppContext } from '@/context/app-context'
// import Button from '@/app/components/base/button'
// import Toast from '@/app/components/base/toast'
// import Indicator from '@/app/components/header/indicator'
// import ToolItem from '@/app/components/tools/provider/tool-item'
// import ConfigCredential from '@/app/components/tools/setting/build-in/config-credentials'
import type { PluginDetail } from '@/app/components/plugins/types'
import { useDataSourceList } from '@/service/use-pipeline'
import { transformDataSourceToTool } from '@/app/components/workflow/block-selector/utils'
type Props = {
detail: PluginDetail
}
const ActionList = ({
detail,
}: Props) => {
const { t } = useTranslation()
// const { isCurrentWorkspaceManager } = useAppContext()
// const providerBriefInfo = detail.declaration.datasource?.identity
// const providerKey = `${detail.plugin_id}/${providerBriefInfo?.name}`
const { data: dataSourceList } = useDataSourceList(true)
const provider = useMemo(() => {
const result = dataSourceList?.find(collection => collection.plugin_id === detail.plugin_id)
if (result)
return transformDataSourceToTool(result)
}, [detail.plugin_id, dataSourceList])
const data: any = []
// const { data } = useBuiltinTools(providerKey)
// const [showSettingAuth, setShowSettingAuth] = useState(false)
// const handleCredentialSettingUpdate = () => {
// Toast.notify({
// type: 'success',
// message: t('common.api.actionSuccess'),
// })
// setShowSettingAuth(false)
// }
// const { mutate: updatePermission, isPending } = useUpdateProviderCredentials({
// onSuccess: handleCredentialSettingUpdate,
// })
// const { mutate: removePermission } = useRemoveProviderCredentials({
// onSuccess: handleCredentialSettingUpdate,
// })
if (!data || !provider)
return null
return (
<div className='px-4 pb-4 pt-2'>
<div className='mb-1 py-1'>
<div className='system-sm-semibold-uppercase mb-1 flex h-6 items-center justify-between text-text-secondary'>
{t('plugin.detailPanel.actionNum', { num: data.length, action: data.length > 1 ? 'actions' : 'action' })}
{/* {provider.is_team_authorization && provider.allow_delete && (
<Button
variant='secondary'
size='small'
onClick={() => setShowSettingAuth(true)}
disabled={!isCurrentWorkspaceManager}
>
<Indicator className='mr-2' color={'green'} />
{t('tools.auth.authorized')}
</Button>
)} */}
</div>
{/* {!provider.is_team_authorization && provider.allow_delete && (
<Button
variant='primary'
className='w-full'
onClick={() => setShowSettingAuth(true)}
disabled={!isCurrentWorkspaceManager}
>{t('workflow.nodes.tool.authorize')}</Button>
)} */}
</div>
{/* <div className='flex flex-col gap-2'>
{data.map(tool => (
<ToolItem
key={`${detail.plugin_id}${tool.name}`}
disabled={false}
collection={provider}
tool={tool}
isBuiltIn={true}
isModel={false}
/>
))}
</div>
{showSettingAuth && (
<ConfigCredential
collection={provider}
onCancel={() => setShowSettingAuth(false)}
onSaved={async value => updatePermission({
providerName: provider.name,
credentials: value,
})}
onRemove={async () => removePermission(provider.name)}
isSaving={isPending}
/>
)} */}
</div>
)
}
export default ActionList

View File

@@ -0,0 +1,392 @@
import ActionButton from '@/app/components/base/action-button'
import Badge from '@/app/components/base/badge'
import Button from '@/app/components/base/button'
import Confirm from '@/app/components/base/confirm'
import { Github } from '@/app/components/base/icons/src/public/common'
import { BoxSparkleFill } from '@/app/components/base/icons/src/vender/plugin'
import Toast from '@/app/components/base/toast'
import Tooltip from '@/app/components/base/tooltip'
import { AuthCategory, PluginAuth } from '@/app/components/plugins/plugin-auth'
import OperationDropdown from '@/app/components/plugins/plugin-detail-panel/operation-dropdown'
import PluginInfo from '@/app/components/plugins/plugin-page/plugin-info'
import UpdateFromMarketplace from '@/app/components/plugins/update-plugin/from-market-place'
import PluginVersionPicker from '@/app/components/plugins/update-plugin/plugin-version-picker'
import { API_PREFIX } from '@/config'
import { useAppContext } from '@/context/app-context'
import { useGlobalPublicStore } from '@/context/global-public-context'
import { useGetLanguage, useI18N } from '@/context/i18n'
import { useModalContext } from '@/context/modal-context'
import { useProviderContext } from '@/context/provider-context'
import { uninstallPlugin } from '@/service/plugins'
import { useAllToolProviders, useInvalidateAllToolProviders } from '@/service/use-tools'
import cn from '@/utils/classnames'
import { getMarketplaceUrl } from '@/utils/var'
import {
RiArrowLeftRightLine,
RiBugLine,
RiCloseLine,
RiHardDrive3Line,
} from '@remixicon/react'
import { useBoolean } from 'ahooks'
import { useTheme } from 'next-themes'
import React, { useCallback, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import Verified from '../base/badges/verified'
import { AutoUpdateLine } from '../../base/icons/src/vender/system'
import DeprecationNotice from '../base/deprecation-notice'
import Icon from '../card/base/card-icon'
import Description from '../card/base/description'
import OrgInfo from '../card/base/org-info'
import Title from '../card/base/title'
import { useGitHubReleases } from '../install-plugin/hooks'
import useReferenceSetting from '../plugin-page/use-reference-setting'
import { AUTO_UPDATE_MODE } from '../reference-setting-modal/auto-update-setting/types'
import { convertUTCDaySecondsToLocalSeconds, timeOfDayToDayjs } from '../reference-setting-modal/auto-update-setting/utils'
import type { PluginDetail } from '../types'
import { PluginCategoryEnum, PluginSource } from '../types'
const i18nPrefix = 'plugin.action'
type Props = {
detail: PluginDetail
isReadmeView?: boolean
onHide?: () => void
onUpdate?: (isDelete?: boolean) => void
}
const DetailHeader = ({
detail,
isReadmeView = false,
onHide,
onUpdate,
}: Props) => {
const { t } = useTranslation()
const { userProfile: { timezone } } = useAppContext()
const { theme } = useTheme()
const locale = useGetLanguage()
const { locale: currentLocale } = useI18N()
const { checkForUpdates, fetchReleases } = useGitHubReleases()
const { setShowUpdatePluginModal } = useModalContext()
const { refreshModelProviders } = useProviderContext()
const invalidateAllToolProviders = useInvalidateAllToolProviders()
const { enable_marketplace } = useGlobalPublicStore(s => s.systemFeatures)
const {
id,
source,
tenant_id,
version,
latest_unique_identifier,
latest_version,
meta,
plugin_id,
status,
deprecated_reason,
alternative_plugin_id,
} = detail
const { author, category, name, label, description, icon, verified, tool } = detail.declaration || detail
const isTool = category === PluginCategoryEnum.tool
const providerBriefInfo = tool?.identity
const providerKey = `${plugin_id}/${providerBriefInfo?.name}`
const { data: collectionList = [] } = useAllToolProviders(isTool)
const provider = useMemo(() => {
return collectionList.find(collection => collection.name === providerKey)
}, [collectionList, providerKey])
const isFromGitHub = source === PluginSource.github
const isFromMarketplace = source === PluginSource.marketplace
const [isShow, setIsShow] = useState(false)
const [targetVersion, setTargetVersion] = useState({
version: latest_version,
unique_identifier: latest_unique_identifier,
})
const hasNewVersion = useMemo(() => {
if (isFromMarketplace)
return !!latest_version && latest_version !== version
return false
}, [isFromMarketplace, latest_version, version])
const detailUrl = useMemo(() => {
if (isFromGitHub)
return `https://github.com/${meta!.repo}`
if (isFromMarketplace)
return getMarketplaceUrl(`/plugins/${author}/${name}`, { language: currentLocale, theme })
return ''
}, [author, isFromGitHub, isFromMarketplace, meta, name, theme])
const [isShowUpdateModal, {
setTrue: showUpdateModal,
setFalse: hideUpdateModal,
}] = useBoolean(false)
const { referenceSetting } = useReferenceSetting()
const { auto_upgrade: autoUpgradeInfo } = referenceSetting || {}
const isAutoUpgradeEnabled = useMemo(() => {
if (!enable_marketplace)
return false
if (!autoUpgradeInfo || !isFromMarketplace)
return false
if (autoUpgradeInfo.strategy_setting === 'disabled')
return false
if (autoUpgradeInfo.upgrade_mode === AUTO_UPDATE_MODE.update_all)
return true
if (autoUpgradeInfo.upgrade_mode === AUTO_UPDATE_MODE.partial && autoUpgradeInfo.include_plugins.includes(plugin_id))
return true
if (autoUpgradeInfo.upgrade_mode === AUTO_UPDATE_MODE.exclude && !autoUpgradeInfo.exclude_plugins.includes(plugin_id))
return true
return false
}, [autoUpgradeInfo, plugin_id, isFromMarketplace])
const [isDowngrade, setIsDowngrade] = useState(false)
const handleUpdate = async (isDowngrade?: boolean) => {
if (isFromMarketplace) {
setIsDowngrade(!!isDowngrade)
showUpdateModal()
return
}
const owner = meta!.repo.split('/')[0] || author
const repo = meta!.repo.split('/')[1] || name
const fetchedReleases = await fetchReleases(owner, repo)
if (fetchedReleases.length === 0) return
const { needUpdate, toastProps } = checkForUpdates(fetchedReleases, meta!.version)
Toast.notify(toastProps)
if (needUpdate) {
setShowUpdatePluginModal({
onSaveCallback: () => {
onUpdate?.()
},
payload: {
type: PluginSource.github,
category: detail.declaration.category,
github: {
originalPackageInfo: {
id: detail.plugin_unique_identifier,
repo: meta!.repo,
version: meta!.version,
package: meta!.package,
releases: fetchedReleases,
},
},
},
})
}
}
const handleUpdatedFromMarketplace = () => {
onUpdate?.()
hideUpdateModal()
}
const [isShowPluginInfo, {
setTrue: showPluginInfo,
setFalse: hidePluginInfo,
}] = useBoolean(false)
const [isShowDeleteConfirm, {
setTrue: showDeleteConfirm,
setFalse: hideDeleteConfirm,
}] = useBoolean(false)
const [deleting, {
setTrue: showDeleting,
setFalse: hideDeleting,
}] = useBoolean(false)
const handleDelete = useCallback(async () => {
showDeleting()
const res = await uninstallPlugin(id)
hideDeleting()
if (res.success) {
hideDeleteConfirm()
onUpdate?.(true)
if (PluginCategoryEnum.model.includes(category))
refreshModelProviders()
if (PluginCategoryEnum.tool.includes(category))
invalidateAllToolProviders()
}
}, [showDeleting, id, hideDeleting, hideDeleteConfirm, onUpdate, category, refreshModelProviders, invalidateAllToolProviders])
return (
<div className={cn('shrink-0 border-b border-divider-subtle bg-components-panel-bg p-4 pb-3', isReadmeView && 'border-b-0 bg-transparent p-0')}>
<div className="flex">
<div className={cn('overflow-hidden rounded-xl border border-components-panel-border-subtle', isReadmeView && 'bg-components-panel-bg')}>
<Icon src={icon.startsWith('http') ? icon : `${API_PREFIX}/workspaces/current/plugin/icon?tenant_id=${tenant_id}&filename=${icon}`} />
</div>
<div className="ml-3 w-0 grow">
<div className="flex h-5 items-center">
<Title title={label[locale]} />
{verified && !isReadmeView && <Verified className='ml-0.5 h-4 w-4' text={t('plugin.marketplace.verifiedTip')} />}
{version && <PluginVersionPicker
disabled={!isFromMarketplace || isReadmeView}
isShow={isShow}
onShowChange={setIsShow}
pluginID={plugin_id}
currentVersion={version}
onSelect={(state) => {
setTargetVersion(state)
handleUpdate(state.isDowngrade)
}}
trigger={
<Badge
className={cn(
'mx-1',
isShow && 'bg-state-base-hover',
(isShow || isFromMarketplace) && 'hover:bg-state-base-hover',
)}
uppercase={false}
text={
<>
<div>{isFromGitHub ? meta!.version : version}</div>
{isFromMarketplace && !isReadmeView && <RiArrowLeftRightLine className='ml-1 h-3 w-3 text-text-tertiary' />}
</>
}
hasRedCornerMark={hasNewVersion}
/>
}
/>}
{/* Auto update info */}
{isAutoUpgradeEnabled && !isReadmeView && (
<Tooltip popupContent={t('plugin.autoUpdate.nextUpdateTime', { time: timeOfDayToDayjs(convertUTCDaySecondsToLocalSeconds(autoUpgradeInfo?.upgrade_time_of_day || 0, timezone!)).format('hh:mm A') })}>
{/* add a a div to fix tooltip hover not show problem */}
<div>
<Badge className='mr-1 cursor-pointer px-1'>
<AutoUpdateLine className='size-3' />
</Badge>
</div>
</Tooltip>
)}
{(hasNewVersion || isFromGitHub) && (
<Button variant='secondary-accent' size='small' className='!h-5' onClick={() => {
if (isFromMarketplace) {
setTargetVersion({
version: latest_version,
unique_identifier: latest_unique_identifier,
})
}
handleUpdate()
}}>{t('plugin.detailPanel.operation.update')}</Button>
)}
</div>
<div className='mb-1 flex h-4 items-center justify-between'>
<div className='mt-0.5 flex items-center'>
<OrgInfo
packageNameClassName='w-auto'
orgName={author}
packageName={name?.includes('/') ? (name.split('/').pop() || '') : name}
/>
{source && <>
<div className='system-xs-regular ml-1 mr-0.5 text-text-quaternary'>·</div>
{source === PluginSource.marketplace && (
<Tooltip popupContent={t('plugin.detailPanel.categoryTip.marketplace')} >
<div><BoxSparkleFill className='h-3.5 w-3.5 text-text-tertiary hover:text-text-accent' /></div>
</Tooltip>
)}
{source === PluginSource.github && (
<Tooltip popupContent={t('plugin.detailPanel.categoryTip.github')} >
<div><Github className='h-3.5 w-3.5 text-text-secondary hover:text-text-primary' /></div>
</Tooltip>
)}
{source === PluginSource.local && (
<Tooltip popupContent={t('plugin.detailPanel.categoryTip.local')} >
<div><RiHardDrive3Line className='h-3.5 w-3.5 text-text-tertiary' /></div>
</Tooltip>
)}
{source === PluginSource.debugging && (
<Tooltip popupContent={t('plugin.detailPanel.categoryTip.debugging')} >
<div><RiBugLine className='h-3.5 w-3.5 text-text-tertiary hover:text-text-warning' /></div>
</Tooltip>
)}
</>}
</div>
</div>
</div>
{!isReadmeView && (
<div className='flex gap-1'>
<OperationDropdown
source={source}
onInfo={showPluginInfo}
onCheckVersion={handleUpdate}
onRemove={showDeleteConfirm}
detailUrl={detailUrl}
/>
<ActionButton onClick={onHide}>
<RiCloseLine className='h-4 w-4' />
</ActionButton>
</div>)}
</div>
{isFromMarketplace && (
<DeprecationNotice
status={status}
deprecatedReason={deprecated_reason}
alternativePluginId={alternative_plugin_id}
alternativePluginURL={getMarketplaceUrl(`/plugins/${alternative_plugin_id}`, { language: currentLocale, theme })}
className='mt-3'
/>
)}
{!isReadmeView && <Description className='mb-2 mt-3 h-auto' text={description[locale]} descriptionLineRows={2}></Description>}
{
category === PluginCategoryEnum.tool && !isReadmeView && (
<PluginAuth
pluginPayload={{
provider: provider?.name || '',
category: AuthCategory.tool,
providerType: provider?.type || '',
detail,
}}
/>
)
}
{isShowPluginInfo && (
<PluginInfo
repository={isFromGitHub ? meta?.repo : ''}
release={version}
packageName={meta?.package || ''}
onHide={hidePluginInfo}
/>
)}
{isShowDeleteConfirm && (
<Confirm
isShow
title={t(`${i18nPrefix}.delete`)}
content={
<div>
{t(`${i18nPrefix}.deleteContentLeft`)}<span className='system-md-semibold'>{label[locale]}</span>{t(`${i18nPrefix}.deleteContentRight`)}<br />
</div>
}
onCancel={hideDeleteConfirm}
onConfirm={handleDelete}
isLoading={deleting}
isDisabled={deleting}
/>
)}
{
isShowUpdateModal && (
<UpdateFromMarketplace
pluginId={plugin_id}
payload={{
category: detail.declaration.category,
originalPackageInfo: {
id: detail.plugin_unique_identifier,
payload: detail.declaration,
},
targetPackageInfo: {
id: targetVersion.unique_identifier,
version: targetVersion.version,
},
}}
onCancel={hideUpdateModal}
onSave={handleUpdatedFromMarketplace}
isShowDowngradeWarningModal={isDowngrade && isAutoUpgradeEnabled}
/>
)
}
</div>
)
}
export default DetailHeader

View File

@@ -0,0 +1,222 @@
import React, { useEffect, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useBoolean } from 'ahooks'
import copy from 'copy-to-clipboard'
import { RiClipboardLine, RiDeleteBinLine, RiEditLine, RiLoginCircleLine } from '@remixicon/react'
import type { EndpointListItem, PluginDetail } from '../types'
import EndpointModal from './endpoint-modal'
import { NAME_FIELD } from './utils'
import { addDefaultValue, toolCredentialToFormSchemas } from '@/app/components/tools/utils/to-form-schema'
import { CopyCheck } from '@/app/components/base/icons/src/vender/line/files'
import ActionButton from '@/app/components/base/action-button'
import Confirm from '@/app/components/base/confirm'
import Indicator from '@/app/components/header/indicator'
import Switch from '@/app/components/base/switch'
import Toast from '@/app/components/base/toast'
import Tooltip from '@/app/components/base/tooltip'
import {
useDeleteEndpoint,
useDisableEndpoint,
useEnableEndpoint,
useUpdateEndpoint,
} from '@/service/use-endpoints'
type Props = {
pluginDetail: PluginDetail
data: EndpointListItem
handleChange: () => void
}
const EndpointCard = ({
pluginDetail,
data,
handleChange,
}: Props) => {
const { t } = useTranslation()
const [active, setActive] = useState(data.enabled)
const endpointID = data.id
// switch
const [isShowDisableConfirm, {
setTrue: showDisableConfirm,
setFalse: hideDisableConfirm,
}] = useBoolean(false)
const { mutate: enableEndpoint } = useEnableEndpoint({
onSuccess: async () => {
await handleChange()
},
onError: () => {
Toast.notify({ type: 'error', message: t('common.actionMsg.modifiedUnsuccessfully') })
setActive(false)
},
})
const { mutate: disableEndpoint } = useDisableEndpoint({
onSuccess: async () => {
await handleChange()
hideDisableConfirm()
},
onError: () => {
Toast.notify({ type: 'error', message: t('common.actionMsg.modifiedUnsuccessfully') })
setActive(false)
},
})
const handleSwitch = (state: boolean) => {
if (state) {
setActive(true)
enableEndpoint(endpointID)
}
else {
setActive(false)
showDisableConfirm()
}
}
// delete
const [isShowDeleteConfirm, {
setTrue: showDeleteConfirm,
setFalse: hideDeleteConfirm,
}] = useBoolean(false)
const { mutate: deleteEndpoint } = useDeleteEndpoint({
onSuccess: async () => {
await handleChange()
hideDeleteConfirm()
},
onError: () => {
Toast.notify({ type: 'error', message: t('common.actionMsg.modifiedUnsuccessfully') })
},
})
// update
const [isShowEndpointModal, {
setTrue: showEndpointModalConfirm,
setFalse: hideEndpointModalConfirm,
}] = useBoolean(false)
const formSchemas = useMemo(() => {
return toolCredentialToFormSchemas([NAME_FIELD, ...data.declaration.settings])
}, [data.declaration.settings])
const formValue = useMemo(() => {
const formValue = {
name: data.name,
...data.settings,
}
return addDefaultValue(formValue, formSchemas)
}, [data.name, data.settings, formSchemas])
const { mutate: updateEndpoint } = useUpdateEndpoint({
onSuccess: async () => {
await handleChange()
hideEndpointModalConfirm()
},
onError: () => {
Toast.notify({ type: 'error', message: t('common.actionMsg.modifiedUnsuccessfully') })
},
})
const handleUpdate = (state: Record<string, any>) => updateEndpoint({
endpointID,
state,
})
const [isCopied, setIsCopied] = useState(false)
const handleCopy = (value: string) => {
copy(value)
setIsCopied(true)
}
useEffect(() => {
if (isCopied) {
const timer = setTimeout(() => {
setIsCopied(false)
}, 2000)
return () => {
clearTimeout(timer)
}
}
}, [isCopied])
const CopyIcon = isCopied ? CopyCheck : RiClipboardLine
return (
<div className='rounded-xl bg-background-section-burn p-0.5'>
<div className='group rounded-[10px] border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg p-2.5 pl-3'>
<div className='flex items-center'>
<div className='system-md-semibold mb-1 flex h-6 grow items-center gap-1 text-text-secondary'>
<RiLoginCircleLine className='h-4 w-4' />
<div>{data.name}</div>
</div>
<div className='hidden items-center group-hover:flex'>
<ActionButton onClick={showEndpointModalConfirm}>
<RiEditLine className='h-4 w-4' />
</ActionButton>
<ActionButton onClick={showDeleteConfirm} className='text-text-tertiary hover:bg-state-destructive-hover hover:text-text-destructive'>
<RiDeleteBinLine className='h-4 w-4' />
</ActionButton>
</div>
</div>
{data.declaration.endpoints.filter(endpoint => !endpoint.hidden).map((endpoint, index) => (
<div key={index} className='flex h-6 items-center'>
<div className='system-xs-regular w-12 shrink-0 text-text-tertiary'>{endpoint.method}</div>
<div className='group/item system-xs-regular flex grow items-center truncate text-text-secondary'>
<div title={`${data.url}${endpoint.path}`} className='truncate'>{`${data.url}${endpoint.path}`}</div>
<Tooltip popupContent={t(`common.operation.${isCopied ? 'copied' : 'copy'}`)} position='top'>
<ActionButton className='ml-2 hidden shrink-0 group-hover/item:flex' onClick={() => handleCopy(`${data.url}${endpoint.path}`)}>
<CopyIcon className='h-3.5 w-3.5 text-text-tertiary' />
</ActionButton>
</Tooltip>
</div>
</div>
))}
</div>
<div className='flex items-center justify-between p-2 pl-3'>
{active && (
<div className='system-xs-semibold-uppercase flex items-center gap-1 text-util-colors-green-green-600'>
<Indicator color='green' />
{t('plugin.detailPanel.serviceOk')}
</div>
)}
{!active && (
<div className='system-xs-semibold-uppercase flex items-center gap-1 text-text-tertiary'>
<Indicator color='gray' />
{t('plugin.detailPanel.disabled')}
</div>
)}
<Switch
className='ml-3'
defaultValue={active}
onChange={handleSwitch}
size='sm'
/>
</div>
{isShowDisableConfirm && (
<Confirm
isShow
title={t('plugin.detailPanel.endpointDisableTip')}
content={<div>{t('plugin.detailPanel.endpointDisableContent', { name: data.name })}</div>}
onCancel={() => {
hideDisableConfirm()
setActive(true)
}}
onConfirm={() => disableEndpoint(endpointID)}
/>
)}
{isShowDeleteConfirm && (
<Confirm
isShow
title={t('plugin.detailPanel.endpointDeleteTip')}
content={<div>{t('plugin.detailPanel.endpointDeleteContent', { name: data.name })}</div>}
onCancel={hideDeleteConfirm}
onConfirm={() => deleteEndpoint(endpointID)}
/>
)}
{isShowEndpointModal && (
<EndpointModal
formSchemas={formSchemas as any}
defaultValues={formValue}
onCancel={hideEndpointModalConfirm}
onSaved={handleUpdate}
pluginDetail={pluginDetail}
/>
)}
</div>
)
}
export default EndpointCard

View File

@@ -0,0 +1,121 @@
import React, { useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import { useDocLink } from '@/context/i18n'
import { useBoolean } from 'ahooks'
import {
RiAddLine,
RiApps2AddLine,
RiBookOpenLine,
} from '@remixicon/react'
import EndpointModal from './endpoint-modal'
import EndpointCard from './endpoint-card'
import { NAME_FIELD } from './utils'
import { toolCredentialToFormSchemas } from '@/app/components/tools/utils/to-form-schema'
import ActionButton from '@/app/components/base/action-button'
import Tooltip from '@/app/components/base/tooltip'
import Toast from '@/app/components/base/toast'
import {
useCreateEndpoint,
useEndpointList,
useInvalidateEndpointList,
} from '@/service/use-endpoints'
import type { PluginDetail } from '@/app/components/plugins/types'
import cn from '@/utils/classnames'
type Props = {
detail: PluginDetail
}
const EndpointList = ({ detail }: Props) => {
const { t } = useTranslation()
const docLink = useDocLink()
const pluginUniqueID = detail.plugin_unique_identifier
const declaration = detail.declaration.endpoint
const showTopBorder = detail.declaration.tool
const { data } = useEndpointList(detail.plugin_id)
const invalidateEndpointList = useInvalidateEndpointList()
const [isShowEndpointModal, {
setTrue: showEndpointModal,
setFalse: hideEndpointModal,
}] = useBoolean(false)
const formSchemas = useMemo(() => {
return toolCredentialToFormSchemas([NAME_FIELD, ...declaration.settings])
}, [declaration.settings])
const { mutate: createEndpoint } = useCreateEndpoint({
onSuccess: async () => {
await invalidateEndpointList(detail.plugin_id)
hideEndpointModal()
},
onError: () => {
Toast.notify({ type: 'error', message: t('common.actionMsg.modifiedUnsuccessfully') })
},
})
const handleCreate = (state: Record<string, any>) => createEndpoint({
pluginUniqueID,
state,
})
if (!data)
return null
return (
<div className={cn('border-divider-subtle px-4 py-2', showTopBorder && 'border-t')}>
<div className='system-sm-semibold-uppercase mb-1 flex h-6 items-center justify-between text-text-secondary'>
<div className='flex items-center gap-0.5'>
{t('plugin.detailPanel.endpoints')}
<Tooltip
position='right'
popupClassName='w-[240px] p-4 rounded-xl bg-components-panel-bg-blur border-[0.5px] border-components-panel-border'
popupContent={
<div className='flex flex-col gap-2'>
<div className='flex h-8 w-8 items-center justify-center rounded-lg border-[0.5px] border-components-panel-border-subtle bg-background-default-subtle'>
<RiApps2AddLine className='h-4 w-4 text-text-tertiary' />
</div>
<div className='system-xs-regular text-text-tertiary'>{t('plugin.detailPanel.endpointsTip')}</div>
<a
href={docLink('/plugins/schema-definition/endpoint')}
target='_blank'
rel='noopener noreferrer'
>
<div className='system-xs-regular inline-flex cursor-pointer items-center gap-1 text-text-accent'>
<RiBookOpenLine className='h-3 w-3' />
{t('plugin.detailPanel.endpointsDocLink')}
</div>
</a>
</div>
}
/>
</div>
<ActionButton onClick={showEndpointModal}>
<RiAddLine className='h-4 w-4' />
</ActionButton>
</div>
{data.endpoints.length === 0 && (
<div className='system-xs-regular mb-1 flex justify-center rounded-[10px] bg-background-section p-3 text-text-tertiary'>{t('plugin.detailPanel.endpointsEmpty')}</div>
)}
<div className='flex flex-col gap-2'>
{data.endpoints.map((item, index) => (
<EndpointCard
key={index}
data={item}
handleChange={() => invalidateEndpointList(detail.plugin_id)}
pluginDetail={detail}
/>
))}
</div>
{isShowEndpointModal && (
<EndpointModal
formSchemas={formSchemas as any}
onCancel={hideEndpointModal}
onSaved={handleCreate}
pluginDetail={detail}
/>
)}
</div>
)
}
export default EndpointList

View File

@@ -0,0 +1,129 @@
'use client'
import type { FC } from 'react'
import React from 'react'
import { useTranslation } from 'react-i18next'
import { RiArrowRightUpLine, RiCloseLine } from '@remixicon/react'
import ActionButton from '@/app/components/base/action-button'
import Button from '@/app/components/base/button'
import Drawer from '@/app/components/base/drawer'
import Form from '@/app/components/header/account-setting/model-provider-page/model-modal/Form'
import Toast from '@/app/components/base/toast'
import { useRenderI18nObject } from '@/hooks/use-i18n'
import cn from '@/utils/classnames'
import { ReadmeEntrance } from '../readme-panel/entrance'
import type { PluginDetail } from '../types'
import type { FormSchema } from '../../base/form/types'
type Props = {
formSchemas: FormSchema[]
defaultValues?: any
onCancel: () => void
onSaved: (value: Record<string, any>) => void
pluginDetail: PluginDetail
}
const extractDefaultValues = (schemas: any[]) => {
const result: Record<string, any> = {}
for (const field of schemas) {
if (field.default !== undefined)
result[field.name] = field.default
}
return result
}
const EndpointModal: FC<Props> = ({
formSchemas,
defaultValues = {},
onCancel,
onSaved,
pluginDetail,
}) => {
const getValueFromI18nObject = useRenderI18nObject()
const { t } = useTranslation()
const initialValues = Object.keys(defaultValues).length > 0
? defaultValues
: extractDefaultValues(formSchemas)
const [tempCredential, setTempCredential] = React.useState<any>(initialValues)
const handleSave = () => {
for (const field of formSchemas) {
if (field.required && !tempCredential[field.name]) {
Toast.notify({ type: 'error', message: t('common.errorMsg.fieldRequired', { field: typeof field.label === 'string' ? field.label : getValueFromI18nObject(field.label as Record<string, string>) }) })
return
}
}
// Fix: Process boolean fields to ensure they are sent as proper boolean values
const processedCredential = { ...tempCredential }
formSchemas.forEach((field: any) => {
if (field.type === 'boolean' && processedCredential[field.name] !== undefined) {
const value = processedCredential[field.name]
if (typeof value === 'string')
processedCredential[field.name] = value === 'true' || value === '1' || value === 'True'
else if (typeof value === 'number')
processedCredential[field.name] = value === 1
else if (typeof value === 'boolean')
processedCredential[field.name] = value
}
})
onSaved(processedCredential)
}
return (
<Drawer
isOpen
clickOutsideNotOpen={false}
onClose={onCancel}
footer={null}
mask
positionCenter={false}
panelClassName={cn('mb-2 mr-2 mt-[64px] !w-[420px] !max-w-[420px] justify-start rounded-2xl border-[0.5px] border-components-panel-border !bg-components-panel-bg !p-0 shadow-xl')}
>
<>
<div className='p-4 pb-2'>
<div className='flex items-center justify-between'>
<div className='system-xl-semibold text-text-primary'>{t('plugin.detailPanel.endpointModalTitle')}</div>
<ActionButton onClick={onCancel}>
<RiCloseLine className='h-4 w-4' />
</ActionButton>
</div>
<div className='system-xs-regular mt-0.5 text-text-tertiary'>{t('plugin.detailPanel.endpointModalDesc')}</div>
<ReadmeEntrance pluginDetail={pluginDetail} className='px-0 pt-3' />
</div>
<div className='grow overflow-y-auto'>
<div className='px-4 py-2'>
<Form
value={tempCredential}
onChange={(v) => {
setTempCredential(v)
}}
formSchemas={formSchemas as any}
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='body-xs-regular inline-flex items-center text-text-accent-secondary'
>
{t('tools.howToGet')}
<RiArrowRightUpLine className='ml-1 h-3 w-3' />
</a>)
: null}
/>
</div>
<div className={cn('flex justify-end p-4 pt-0')} >
<div className='flex gap-2'>
<Button onClick={onCancel}>{t('common.operation.cancel')}</Button>
<Button variant='primary' onClick={handleSave}>{t('common.operation.save')}</Button>
</div>
</div>
</div>
</>
</Drawer>
)
}
export default React.memo(EndpointModal)

View File

@@ -0,0 +1,88 @@
'use client'
import Drawer from '@/app/components/base/drawer'
import { PluginCategoryEnum, type PluginDetail } from '@/app/components/plugins/types'
import cn from '@/utils/classnames'
import type { FC } from 'react'
import { useCallback, useEffect } from 'react'
import ActionList from './action-list'
import AgentStrategyList from './agent-strategy-list'
import DatasourceActionList from './datasource-action-list'
import DetailHeader from './detail-header'
import EndpointList from './endpoint-list'
import ModelList from './model-list'
import { SubscriptionList } from './subscription-list'
import { usePluginStore } from './store'
import { TriggerEventsList } from './trigger/event-list'
import { ReadmeEntrance } from '../readme-panel/entrance'
type Props = {
detail?: PluginDetail
onUpdate: () => void
onHide: () => void
}
const PluginDetailPanel: FC<Props> = ({
detail,
onUpdate,
onHide,
}) => {
const handleUpdate = useCallback((isDelete = false) => {
if (isDelete)
onHide()
onUpdate()
}, [onHide, onUpdate])
const { setDetail } = usePluginStore()
useEffect(() => {
setDetail(!detail ? undefined : {
plugin_id: detail.plugin_id,
provider: `${detail.plugin_id}/${detail.declaration.name}`,
plugin_unique_identifier: detail.plugin_unique_identifier || '',
declaration: detail.declaration,
name: detail.name,
id: detail.id,
})
}, [detail])
if (!detail)
return null
return (
<Drawer
isOpen={!!detail}
clickOutsideNotOpen={false}
onClose={onHide}
footer={null}
mask={false}
positionCenter={false}
panelClassName={cn('mb-2 mr-2 mt-[64px] !w-[420px] !max-w-[420px] justify-start rounded-2xl border-[0.5px] border-components-panel-border !bg-components-panel-bg !p-0 shadow-xl')}
>
{detail && (
<>
<DetailHeader detail={detail} onUpdate={handleUpdate} onHide={onHide} />
<div className='grow overflow-y-auto'>
<div className='flex min-h-full flex-col'>
<div className='flex-1'>
{detail.declaration.category === PluginCategoryEnum.trigger && (
<>
<SubscriptionList />
<TriggerEventsList />
</>
)}
{!!detail.declaration.tool && <ActionList detail={detail} />}
{!!detail.declaration.agent_strategy && <AgentStrategyList detail={detail} />}
{!!detail.declaration.endpoint && <EndpointList detail={detail} />}
{!!detail.declaration.model && <ModelList detail={detail} />}
{!!detail.declaration.datasource && <DatasourceActionList detail={detail} />}
</div>
<ReadmeEntrance pluginDetail={detail} className='mt-auto' />
</div>
</div>
</>
)}
</Drawer>
)
}
export default PluginDetailPanel

View File

@@ -0,0 +1,46 @@
import React from 'react'
import { useTranslation } from 'react-i18next'
import ModelIcon from '@/app/components/header/account-setting/model-provider-page/model-icon'
import ModelName from '@/app/components/header/account-setting/model-provider-page/model-name'
import { useModelProviderModelList } from '@/service/use-models'
import type { PluginDetail } from '@/app/components/plugins/types'
type Props = {
detail: PluginDetail
}
const ModelList = ({
detail,
}: Props) => {
const { t } = useTranslation()
const { data: res } = useModelProviderModelList(`${detail.plugin_id}/${detail.declaration.model.provider}`)
if (!res)
return null
return (
<div className='px-4 py-2'>
<div className='system-sm-semibold-uppercase mb-1 flex h-6 items-center text-text-secondary'>{t('plugin.detailPanel.modelNum', { num: res.data.length })}</div>
<div className='flex flex-col'>
{res.data.map(model => (
<div key={model.model} className='flex h-6 items-center py-1'>
<ModelIcon
className='mr-2 shrink-0'
provider={(model as any).provider}
modelName={model.model}
/>
<ModelName
className='system-md-regular grow text-text-secondary'
modelItem={model}
showModelType
showMode
showContextSize
/>
</div>
))}
</div>
</div>
)
}
export default ModelList

View File

@@ -0,0 +1,280 @@
import type {
FC,
ReactNode,
} from 'react'
import { useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import type {
DefaultModel,
FormValue,
ModelFeatureEnum,
} from '@/app/components/header/account-setting/model-provider-page/declarations'
import { ModelStatusEnum, ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
import ModelSelector from '@/app/components/header/account-setting/model-provider-page/model-selector'
import {
useModelList,
} from '@/app/components/header/account-setting/model-provider-page/hooks'
import AgentModelTrigger from '@/app/components/header/account-setting/model-provider-page/model-parameter-modal/agent-model-trigger'
import Trigger from '@/app/components/header/account-setting/model-provider-page/model-parameter-modal/trigger'
import type { TriggerProps } from '@/app/components/header/account-setting/model-provider-page/model-parameter-modal/trigger'
import {
PortalToFollowElem,
PortalToFollowElemContent,
PortalToFollowElemTrigger,
} from '@/app/components/base/portal-to-follow-elem'
import LLMParamsPanel from './llm-params-panel'
import TTSParamsPanel from './tts-params-panel'
import { useProviderContext } from '@/context/provider-context'
import cn from '@/utils/classnames'
import Toast from '@/app/components/base/toast'
import { fetchAndMergeValidCompletionParams } from '@/utils/completion-params'
export type ModelParameterModalProps = {
popupClassName?: string
portalToFollowElemContentClassName?: string
isAdvancedMode: boolean
value: any
setModel: (model: any) => void
renderTrigger?: (v: TriggerProps) => ReactNode
readonly?: boolean
isInWorkflow?: boolean
isAgentStrategy?: boolean
scope?: string
}
const ModelParameterModal: FC<ModelParameterModalProps> = ({
popupClassName,
portalToFollowElemContentClassName,
isAdvancedMode,
value,
setModel,
renderTrigger,
readonly,
isInWorkflow,
isAgentStrategy,
scope = ModelTypeEnum.textGeneration,
}) => {
const { t } = useTranslation()
const { isAPIKeySet } = useProviderContext()
const [open, setOpen] = useState(false)
const scopeArray = scope.split('&')
const scopeFeatures = useMemo((): ModelFeatureEnum[] => {
if (scopeArray.includes('all'))
return []
return scopeArray.filter(item => ![
ModelTypeEnum.textGeneration,
ModelTypeEnum.textEmbedding,
ModelTypeEnum.rerank,
ModelTypeEnum.moderation,
ModelTypeEnum.speech2text,
ModelTypeEnum.tts,
].includes(item as ModelTypeEnum)).map(item => item as ModelFeatureEnum)
}, [scopeArray])
const { data: textGenerationList } = useModelList(ModelTypeEnum.textGeneration)
const { data: textEmbeddingList } = useModelList(ModelTypeEnum.textEmbedding)
const { data: rerankList } = useModelList(ModelTypeEnum.rerank)
const { data: moderationList } = useModelList(ModelTypeEnum.moderation)
const { data: sttList } = useModelList(ModelTypeEnum.speech2text)
const { data: ttsList } = useModelList(ModelTypeEnum.tts)
const scopedModelList = useMemo(() => {
const resultList: any[] = []
if (scopeArray.includes('all')) {
return [
...textGenerationList,
...textEmbeddingList,
...rerankList,
...sttList,
...ttsList,
...moderationList,
]
}
if (scopeArray.includes(ModelTypeEnum.textGeneration))
return textGenerationList
if (scopeArray.includes(ModelTypeEnum.textEmbedding))
return textEmbeddingList
if (scopeArray.includes(ModelTypeEnum.rerank))
return rerankList
if (scopeArray.includes(ModelTypeEnum.moderation))
return moderationList
if (scopeArray.includes(ModelTypeEnum.speech2text))
return sttList
if (scopeArray.includes(ModelTypeEnum.tts))
return ttsList
return resultList
}, [scopeArray, textGenerationList, textEmbeddingList, rerankList, sttList, ttsList, moderationList])
const { currentProvider, currentModel } = useMemo(() => {
const currentProvider = scopedModelList.find(item => item.provider === value?.provider)
const currentModel = currentProvider?.models.find((model: { model: string }) => model.model === value?.model)
return {
currentProvider,
currentModel,
}
}, [scopedModelList, value?.provider, value?.model])
const hasDeprecated = useMemo(() => {
return !currentProvider || !currentModel
}, [currentModel, currentProvider])
const modelDisabled = useMemo(() => {
return currentModel?.status !== ModelStatusEnum.active
}, [currentModel?.status])
const disabled = useMemo(() => {
return !isAPIKeySet || hasDeprecated || modelDisabled
}, [hasDeprecated, isAPIKeySet, modelDisabled])
const handleChangeModel = async ({ provider, model }: DefaultModel) => {
const targetProvider = scopedModelList.find(modelItem => modelItem.provider === provider)
const targetModelItem = targetProvider?.models.find((modelItem: { model: string }) => modelItem.model === model)
const model_type = targetModelItem?.model_type as string
let nextCompletionParams: FormValue = {}
if (model_type === ModelTypeEnum.textGeneration) {
try {
const { params: filtered, removedDetails } = await fetchAndMergeValidCompletionParams(
provider,
model,
value?.completion_params,
isAdvancedMode,
)
nextCompletionParams = filtered
const keys = Object.keys(removedDetails || {})
if (keys.length) {
Toast.notify({
type: 'warning',
message: `${t('common.modelProvider.parametersInvalidRemoved')}: ${keys.map(k => `${k} (${removedDetails[k]})`).join(', ')}`,
})
}
}
catch {
Toast.notify({ type: 'error', message: t('common.error') })
}
}
setModel({
provider,
model,
model_type,
...(model_type === ModelTypeEnum.textGeneration ? {
mode: targetModelItem?.model_properties.mode as string,
completion_params: nextCompletionParams,
} : {}),
})
}
const handleLLMParamsChange = (newParams: FormValue) => {
const newValue = {
...value?.completionParams,
completion_params: newParams,
}
setModel({
...value,
...newValue,
})
}
const handleTTSParamsChange = (language: string, voice: string) => {
setModel({
...value,
language,
voice,
})
}
return (
<PortalToFollowElem
open={open}
onOpenChange={setOpen}
placement={isInWorkflow ? 'left' : 'bottom-end'}
offset={4}
>
<div className='relative'>
<PortalToFollowElemTrigger
onClick={() => {
if (readonly)
return
setOpen(v => !v)
}}
className='block'
>
{
renderTrigger
? renderTrigger({
open,
disabled,
modelDisabled,
hasDeprecated,
currentProvider,
currentModel,
providerName: value?.provider,
modelId: value?.model,
})
: (isAgentStrategy
? <AgentModelTrigger
disabled={disabled}
hasDeprecated={hasDeprecated}
currentProvider={currentProvider}
currentModel={currentModel}
providerName={value?.provider}
modelId={value?.model}
scope={scope}
/>
: <Trigger
disabled={disabled}
isInWorkflow={isInWorkflow}
modelDisabled={modelDisabled}
hasDeprecated={hasDeprecated}
currentProvider={currentProvider}
currentModel={currentModel}
providerName={value?.provider}
modelId={value?.model}
/>
)
}
</PortalToFollowElemTrigger>
<PortalToFollowElemContent className={cn('z-50', portalToFollowElemContentClassName)}>
<div className={cn(popupClassName, 'w-[389px] rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg shadow-lg')}>
<div className={cn('max-h-[420px] overflow-y-auto p-4 pt-3')}>
<div className='relative'>
<div className={cn('system-sm-semibold mb-1 flex h-6 items-center text-text-secondary')}>
{t('common.modelProvider.model').toLocaleUpperCase()}
</div>
<ModelSelector
defaultModel={(value?.provider || value?.model) ? { provider: value?.provider, model: value?.model } : undefined}
modelList={scopedModelList}
scopeFeatures={scopeFeatures}
onSelect={handleChangeModel}
/>
</div>
{(currentModel?.model_type === ModelTypeEnum.textGeneration || currentModel?.model_type === ModelTypeEnum.tts) && (
<div className='my-3 h-px bg-divider-subtle' />
)}
{currentModel?.model_type === ModelTypeEnum.textGeneration && (
<LLMParamsPanel
provider={value?.provider}
modelId={value?.model}
completionParams={value?.completion_params || {}}
onCompletionParamsChange={handleLLMParamsChange}
isAdvancedMode={isAdvancedMode}
/>
)}
{currentModel?.model_type === ModelTypeEnum.tts && (
<TTSParamsPanel
currentModel={currentModel}
language={value?.language}
voice={value?.voice}
onChange={handleTTSParamsChange}
/>
)}
</div>
</div>
</PortalToFollowElemContent>
</div>
</PortalToFollowElem>
)
}
export default ModelParameterModal

View File

@@ -0,0 +1,106 @@
import React, { useMemo } from 'react'
import useSWR from 'swr'
import { useTranslation } from 'react-i18next'
import PresetsParameter from '@/app/components/header/account-setting/model-provider-page/model-parameter-modal/presets-parameter'
import ParameterItem from '@/app/components/header/account-setting/model-provider-page/model-parameter-modal/parameter-item'
import Loading from '@/app/components/base/loading'
import type {
FormValue,
ModelParameterRule,
} from '@/app/components/header/account-setting/model-provider-page/declarations'
import type { ParameterValue } from '@/app/components/header/account-setting/model-provider-page/model-parameter-modal/parameter-item'
import { fetchModelParameterRules } from '@/service/common'
import { PROVIDER_WITH_PRESET_TONE, STOP_PARAMETER_RULE, TONE_LIST } from '@/config'
import cn from '@/utils/classnames'
type Props = {
isAdvancedMode: boolean
provider: string
modelId: string
completionParams: FormValue
onCompletionParamsChange: (newParams: FormValue) => void
}
const LLMParamsPanel = ({
isAdvancedMode,
provider,
modelId,
completionParams,
onCompletionParamsChange,
}: Props) => {
const { t } = useTranslation()
const { data: parameterRulesData, isLoading } = useSWR(
(provider && modelId)
? `/workspaces/current/model-providers/${provider}/models/parameter-rules?model=${modelId}`
: null, fetchModelParameterRules,
)
const parameterRules: ModelParameterRule[] = useMemo(() => {
return parameterRulesData?.data || []
}, [parameterRulesData])
const handleSelectPresetParameter = (toneId: number) => {
const tone = TONE_LIST.find(tone => tone.id === toneId)
if (tone) {
onCompletionParamsChange({
...completionParams,
...tone.config,
})
}
}
const handleParamChange = (key: string, value: ParameterValue) => {
onCompletionParamsChange({
...completionParams,
[key]: value,
})
}
const handleSwitch = (key: string, value: boolean, assignValue: ParameterValue) => {
if (!value) {
const newCompletionParams = { ...completionParams }
delete newCompletionParams[key]
onCompletionParamsChange(newCompletionParams)
}
if (value) {
onCompletionParamsChange({
...completionParams,
[key]: assignValue,
})
}
}
if (isLoading) {
return (
<div className='mt-5'><Loading /></div>
)
}
return (
<>
<div className='mb-2 flex items-center justify-between'>
<div className={cn('system-sm-semibold flex h-6 items-center text-text-secondary')}>{t('common.modelProvider.parameters')}</div>
{
PROVIDER_WITH_PRESET_TONE.includes(provider) && (
<PresetsParameter onSelect={handleSelectPresetParameter} />
)
}
</div>
{!!parameterRules.length && (
[
...parameterRules,
...(isAdvancedMode ? [STOP_PARAMETER_RULE] : []),
].map(parameter => (
<ParameterItem
key={`${modelId}-${parameter.name}`}
parameterRule={parameter}
value={completionParams?.[parameter.name]}
onChange={v => handleParamChange(parameter.name, v)}
onSwitch={(checked, assignValue) => handleSwitch(parameter.name, checked, assignValue)}
isInWorkflow
/>
)))}
</>
)
}
export default LLMParamsPanel

View File

@@ -0,0 +1,67 @@
import React, { useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import { languages } from '@/i18n-config/language'
import { PortalSelect } from '@/app/components/base/select'
import cn from '@/utils/classnames'
type Props = {
currentModel: any
language: string
voice: string
onChange: (language: string, voice: string) => void
}
const TTSParamsPanel = ({
currentModel,
language,
voice,
onChange,
}: Props) => {
const { t } = useTranslation()
const voiceList = useMemo(() => {
if (!currentModel)
return []
return currentModel.model_properties.voices.map((item: { mode: any }) => ({
...item,
value: item.mode,
}))
}, [currentModel])
const setLanguage = (language: string) => {
onChange(language, voice)
}
const setVoice = (voice: string) => {
onChange(language, voice)
}
return (
<>
<div className='mb-3'>
<div className='system-sm-semibold mb-1 flex items-center py-1 text-text-secondary'>
{t('appDebug.voice.voiceSettings.language')}
</div>
<PortalSelect
triggerClassName='h-8'
popupClassName={cn('z-[1000]')}
popupInnerClassName={cn('w-[354px]')}
value={language}
items={languages.filter(item => item.supported)}
onSelect={item => setLanguage(item.value as string)}
/>
</div>
<div className='mb-3'>
<div className='system-sm-semibold mb-1 flex items-center py-1 text-text-secondary'>
{t('appDebug.voice.voiceSettings.voice')}
</div>
<PortalSelect
triggerClassName='h-8'
popupClassName={cn('z-[1000]')}
popupInnerClassName={cn('w-[354px]')}
value={voice}
items={voiceList}
onSelect={item => setVoice(item.value as string)}
/>
</div>
</>
)
}
export default TTSParamsPanel

View File

@@ -0,0 +1,197 @@
import React from 'react'
import { useTranslation } from 'react-i18next'
import {
RiAddLine,
RiQuestionLine,
} from '@remixicon/react'
import ToolSelector from '@/app/components/plugins/plugin-detail-panel/tool-selector'
import ActionButton from '@/app/components/base/action-button'
import Tooltip from '@/app/components/base/tooltip'
import Divider from '@/app/components/base/divider'
import type { ToolValue } from '@/app/components/workflow/block-selector/types'
import type { Node } from 'reactflow'
import type { NodeOutPutVar } from '@/app/components/workflow/types'
import cn from '@/utils/classnames'
import { ArrowDownRoundFill } from '@/app/components/base/icons/src/vender/solid/general'
import { useAllMCPTools } from '@/service/use-tools'
type Props = {
disabled?: boolean
value: ToolValue[]
label: string
required?: boolean
tooltip?: any
supportCollapse?: boolean
scope?: string
onChange: (value: ToolValue[]) => void
nodeOutputVars: NodeOutPutVar[],
availableNodes: Node[],
nodeId?: string
canChooseMCPTool?: boolean
}
const MultipleToolSelector = ({
disabled,
value = [],
label,
required,
tooltip,
supportCollapse,
scope,
onChange,
nodeOutputVars,
availableNodes,
nodeId,
canChooseMCPTool,
}: Props) => {
const { t } = useTranslation()
const { data: mcpTools } = useAllMCPTools()
const enabledCount = value.filter((item) => {
const isMCPTool = mcpTools?.find(tool => tool.id === item.provider_name)
if(isMCPTool)
return item.enabled && canChooseMCPTool
return item.enabled
}).length
// collapse control
const [collapse, setCollapse] = React.useState(false)
const handleCollapse = () => {
if (supportCollapse)
setCollapse(!collapse)
}
// add tool
const [open, setOpen] = React.useState(false)
const [panelShowState, setPanelShowState] = React.useState(true)
const handleAdd = (val: ToolValue) => {
const newValue = [...value, val]
// deduplication
const deduplication = newValue.reduce((acc, cur) => {
if (!acc.find(item => item.provider_name === cur.provider_name && item.tool_name === cur.tool_name))
acc.push(cur)
return acc
}, [] as ToolValue[])
// update value
onChange(deduplication)
setOpen(false)
}
const handleAddMultiple = (val: ToolValue[]) => {
const newValue = [...value, ...val]
// deduplication
const deduplication = newValue.reduce((acc, cur) => {
if (!acc.find(item => item.provider_name === cur.provider_name && item.tool_name === cur.tool_name))
acc.push(cur)
return acc
}, [] as ToolValue[])
// update value
onChange(deduplication)
setOpen(false)
}
// delete tool
const handleDelete = (index: number) => {
const newValue = [...value]
newValue.splice(index, 1)
onChange(newValue)
}
// configure tool
const handleConfigure = (val: ToolValue, index: number) => {
const newValue = [...value]
newValue[index] = val
onChange(newValue)
}
return (
<>
<div className='mb-1 flex items-center'>
<div
className={cn('relative flex grow items-center gap-0.5', supportCollapse && 'cursor-pointer')}
onClick={handleCollapse}
>
<div className='system-sm-semibold-uppercase flex h-6 items-center text-text-secondary'>{label}</div>
{required && <div className='text-red-500'>*</div>}
{tooltip && (
<Tooltip
popupContent={tooltip}
>
<div><RiQuestionLine className='h-3.5 w-3.5 text-text-quaternary hover:text-text-tertiary' /></div>
</Tooltip>
)}
{supportCollapse && (
<ArrowDownRoundFill
className={cn(
'h-4 w-4 cursor-pointer text-text-quaternary group-hover/collapse:text-text-secondary',
collapse && 'rotate-[270deg]',
)}
/>
)}
</div>
{value.length > 0 && (
<>
<div className='system-xs-medium flex items-center gap-1 text-text-tertiary'>
<span>{`${enabledCount}/${value.length}`}</span>
<span>{t('appDebug.agent.tools.enabled')}</span>
</div>
<Divider type='vertical' className='ml-3 mr-1 h-3' />
</>
)}
{!disabled && (
<ActionButton className='mx-1' onClick={() => {
setCollapse(false)
setOpen(!open)
setPanelShowState(true)
}}>
<RiAddLine className='h-4 w-4' />
</ActionButton>
)}
</div>
{!collapse && (
<>
{value.length === 0 && (
<div className='system-xs-regular flex justify-center rounded-[10px] bg-background-section p-3 text-text-tertiary'>{t('plugin.detailPanel.toolSelector.empty')}</div>
)}
{value.length > 0 && value.map((item, index) => (
<div className='mb-1' key={index}>
<ToolSelector
nodeId={nodeId}
nodeOutputVars={nodeOutputVars}
availableNodes={availableNodes}
scope={scope}
value={item}
selectedTools={value}
onSelect={item => handleConfigure(item, index)}
onSelectMultiple={handleAddMultiple}
onDelete={() => handleDelete(index)}
supportEnableSwitch
canChooseMCPTool={canChooseMCPTool}
isEdit
/>
</div>
))}
</>
)}
<ToolSelector
nodeId={nodeId}
nodeOutputVars={nodeOutputVars}
availableNodes={availableNodes}
scope={scope}
value={undefined}
selectedTools={value}
onSelect={handleAdd}
controlledState={open}
onControlledStateChange={setOpen}
trigger={
<div className=''></div>
}
panelShowState={panelShowState}
onPanelShowStateChange={setPanelShowState}
isEdit={false}
canChooseMCPTool={canChooseMCPTool}
onSelectMultiple={handleAddMultiple}
/>
</>
)
}
export default MultipleToolSelector

View File

@@ -0,0 +1,104 @@
'use client'
import type { FC } from 'react'
import React, { useCallback, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { PluginSource } from '../types'
import { RiArrowRightUpLine, RiMoreFill } from '@remixicon/react'
import ActionButton from '@/app/components/base/action-button'
// import Button from '@/app/components/base/button'
import {
PortalToFollowElem,
PortalToFollowElemContent,
PortalToFollowElemTrigger,
} from '@/app/components/base/portal-to-follow-elem'
import cn from '@/utils/classnames'
import { useGlobalPublicStore } from '@/context/global-public-context'
type Props = {
source: PluginSource
onInfo: () => void
onCheckVersion: () => void
onRemove: () => void
detailUrl: string
}
const OperationDropdown: FC<Props> = ({
source,
detailUrl,
onInfo,
onCheckVersion,
onRemove,
}) => {
const { t } = useTranslation()
const [open, doSetOpen] = useState(false)
const openRef = useRef(open)
const setOpen = useCallback((v: boolean) => {
doSetOpen(v)
openRef.current = v
}, [doSetOpen])
const handleTrigger = useCallback(() => {
setOpen(!openRef.current)
}, [setOpen])
const { enable_marketplace } = useGlobalPublicStore(s => s.systemFeatures)
return (
<PortalToFollowElem
open={open}
onOpenChange={setOpen}
placement='bottom-end'
offset={{
mainAxis: -12,
crossAxis: 36,
}}
>
<PortalToFollowElemTrigger onClick={handleTrigger}>
<div>
<ActionButton className={cn(open && 'bg-state-base-hover')}>
<RiMoreFill className='h-4 w-4' />
</ActionButton>
</div>
</PortalToFollowElemTrigger>
<PortalToFollowElemContent className='z-50'>
<div className='w-[160px] rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur p-1 shadow-lg'>
{source === PluginSource.github && (
<div
onClick={() => {
onInfo()
handleTrigger()
}}
className='system-md-regular cursor-pointer rounded-lg px-3 py-1.5 text-text-secondary hover:bg-state-base-hover'
>{t('plugin.detailPanel.operation.info')}</div>
)}
{source === PluginSource.github && (
<div
onClick={() => {
onCheckVersion()
handleTrigger()
}}
className='system-md-regular cursor-pointer rounded-lg px-3 py-1.5 text-text-secondary hover:bg-state-base-hover'
>{t('plugin.detailPanel.operation.checkUpdate')}</div>
)}
{(source === PluginSource.marketplace || source === PluginSource.github) && enable_marketplace && (
<a href={detailUrl} target='_blank' className='system-md-regular flex cursor-pointer items-center rounded-lg px-3 py-1.5 text-text-secondary hover:bg-state-base-hover'>
<span className='grow'>{t('plugin.detailPanel.operation.viewDetail')}</span>
<RiArrowRightUpLine className='h-3.5 w-3.5 shrink-0 text-text-tertiary' />
</a>
)}
{(source === PluginSource.marketplace || source === PluginSource.github) && enable_marketplace && (
<div className='my-1 h-px bg-divider-subtle'></div>
)}
<div
onClick={() => {
onRemove()
handleTrigger()
}}
className='system-md-regular cursor-pointer rounded-lg px-3 py-1.5 text-text-secondary hover:bg-state-destructive-hover hover:text-text-destructive'
>{t('plugin.detailPanel.operation.remove')}</div>
</div>
</PortalToFollowElemContent>
</PortalToFollowElem>
)
}
export default React.memo(OperationDropdown)

View File

@@ -0,0 +1,29 @@
import { create } from 'zustand'
import type {
ParametersSchema,
PluginDeclaration,
PluginDetail,
PluginTriggerSubscriptionConstructor,
} from '../types'
type TriggerDeclarationSummary = {
subscription_schema?: ParametersSchema[]
subscription_constructor?: PluginTriggerSubscriptionConstructor | null
}
export type SimpleDetail = Pick<PluginDetail, 'plugin_id' | 'name' | 'plugin_unique_identifier' | 'id'> & {
provider: string
declaration: Partial<Omit<PluginDeclaration, 'trigger'>> & {
trigger?: TriggerDeclarationSummary
}
}
type Shape = {
detail: SimpleDetail | undefined
setDetail: (detail?: SimpleDetail) => void
}
export const usePluginStore = create<Shape>(set => ({
detail: undefined,
setDetail: (detail?: SimpleDetail) => set({ detail }),
}))

View File

@@ -0,0 +1,166 @@
'use client'
import type { FC } from 'react'
import React, { useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import {
RiArrowLeftLine,
RiCloseLine,
} from '@remixicon/react'
import Drawer from '@/app/components/base/drawer'
import ActionButton from '@/app/components/base/action-button'
import Icon from '@/app/components/plugins/card/base/card-icon'
import Description from '@/app/components/plugins/card/base/description'
import Divider from '@/app/components/base/divider'
import type {
StrategyDetail as StrategyDetailType,
} from '@/app/components/plugins/types'
import type { Locale } from '@/i18n-config'
import { useRenderI18nObject } from '@/hooks/use-i18n'
import { API_PREFIX } from '@/config'
import cn from '@/utils/classnames'
type Props = {
provider: {
author: string
name: string
description: Record<Locale, string>
tenant_id: string
icon: string
label: Record<Locale, string>
tags: string[]
}
detail: StrategyDetailType
onHide: () => void
}
const StrategyDetail: FC<Props> = ({
provider,
detail,
onHide,
}) => {
const getValueFromI18nObject = useRenderI18nObject()
const { t } = useTranslation()
const outputSchema = useMemo(() => {
const res: any[] = []
if (!detail.output_schema || !detail.output_schema.properties)
return []
Object.keys(detail.output_schema.properties).forEach((outputKey) => {
const output = detail.output_schema.properties[outputKey]
res.push({
name: outputKey,
type: output.type === 'array'
? `Array[${output.items?.type ? output.items.type.slice(0, 1).toLocaleUpperCase() + output.items.type.slice(1) : 'Unknown'}]`
: `${output.type ? output.type.slice(0, 1).toLocaleUpperCase() + output.type.slice(1) : 'Unknown'}`,
description: output.description,
})
})
return res
}, [detail.output_schema])
const getType = (type: string) => {
if (type === 'number-input')
return t('tools.setBuiltInTools.number')
if (type === 'text-input')
return t('tools.setBuiltInTools.string')
if (type === 'checkbox')
return 'boolean'
if (type === 'file')
return t('tools.setBuiltInTools.file')
if (type === 'array[tools]')
return 'multiple-tool-select'
return type
}
return (
<Drawer
isOpen
clickOutsideNotOpen={false}
onClose={onHide}
footer={null}
mask={false}
positionCenter={false}
panelClassName={cn('mb-2 mr-2 mt-[64px] !w-[420px] !max-w-[420px] justify-start rounded-2xl border-[0.5px] border-components-panel-border !bg-components-panel-bg !p-0 shadow-xl')}
>
<>
{/* header */}
<div className='relative border-b border-divider-subtle p-4 pb-3'>
<div className='absolute right-3 top-3'>
<ActionButton onClick={onHide}>
<RiCloseLine className='h-4 w-4' />
</ActionButton>
</div>
<div
className='system-xs-semibold-uppercase mb-2 flex cursor-pointer items-center gap-1 text-text-accent-secondary'
onClick={onHide}
>
<RiArrowLeftLine className='h-4 w-4' />
BACK
</div>
<div className='flex items-center gap-1'>
<Icon size='tiny' className='h-6 w-6' src={`${API_PREFIX}/workspaces/current/plugin/icon?tenant_id=${provider.tenant_id}&filename=${provider.icon}`} />
<div className=''>{getValueFromI18nObject(provider.label)}</div>
</div>
<div className='system-md-semibold mt-1 text-text-primary'>{getValueFromI18nObject(detail.identity.label)}</div>
<Description className='mt-3' text={getValueFromI18nObject(detail.description)} descriptionLineRows={2}></Description>
</div>
{/* form */}
<div className='h-full'>
<div className='flex h-full flex-col overflow-y-auto'>
<div className='system-sm-semibold-uppercase p-4 pb-1 text-text-primary'>{t('tools.setBuiltInTools.parameters')}</div>
<div className='px-4'>
{detail.parameters.length > 0 && (
<div className='space-y-1 py-2'>
{detail.parameters.map((item: any, index) => (
<div key={index} className='py-1'>
<div className='flex items-center gap-2'>
<div className='code-sm-semibold text-text-secondary'>{getValueFromI18nObject(item.label)}</div>
<div className='system-xs-regular text-text-tertiary'>
{getType(item.type)}
</div>
{item.required && (
<div className='system-xs-medium text-text-warning-secondary'>{t('tools.setBuiltInTools.required')}</div>
)}
</div>
{item.human_description && (
<div className='system-xs-regular mt-0.5 text-text-tertiary'>
{getValueFromI18nObject(item.human_description)}
</div>
)}
</div>
))}
</div>
)}
</div>
{detail.output_schema && (
<>
<div className='px-4'>
<Divider className="!mt-2" />
</div>
<div className='system-sm-semibold-uppercase p-4 pb-1 text-text-primary'>OUTPUT</div>
{outputSchema.length > 0 && (
<div className='space-y-1 px-4 py-2'>
{outputSchema.map((outputItem, index) => (
<div key={index} className='py-1'>
<div className='flex items-center gap-2'>
<div className='code-sm-semibold text-text-secondary'>{outputItem.name}</div>
<div className='system-xs-regular text-text-tertiary'>{outputItem.type}</div>
</div>
{outputItem.description && (
<div className='system-xs-regular mt-0.5 text-text-tertiary'>
{outputItem.description}
</div>
)}
</div>
))}
</div>
)}
</>
)}
</div>
</div>
</>
</Drawer>
)
}
export default StrategyDetail

View File

@@ -0,0 +1,50 @@
'use client'
import React, { useState } from 'react'
import StrategyDetailPanel from './strategy-detail'
import type {
StrategyDetail,
} from '@/app/components/plugins/types'
import type { Locale } from '@/i18n-config'
import { useRenderI18nObject } from '@/hooks/use-i18n'
import cn from '@/utils/classnames'
type Props = {
provider: {
author: string
name: string
description: Record<Locale, string>
tenant_id: string
icon: string
label: Record<Locale, string>
tags: string[]
}
detail: StrategyDetail
}
const StrategyItem = ({
provider,
detail,
}: Props) => {
const getValueFromI18nObject = useRenderI18nObject()
const [showDetail, setShowDetail] = useState(false)
return (
<>
<div
className={cn('bg-components-panel-item-bg mb-2 cursor-pointer rounded-xl border-[0.5px] border-components-panel-border-subtle px-4 py-3 shadow-xs hover:bg-components-panel-on-panel-item-bg-hover')}
onClick={() => setShowDetail(true)}
>
<div className='system-md-semibold pb-0.5 text-text-secondary'>{getValueFromI18nObject(detail.identity.label)}</div>
<div className='system-xs-regular line-clamp-2 text-text-tertiary' title={getValueFromI18nObject(detail.description)}>{getValueFromI18nObject(detail.description)}</div>
</div>
{showDetail && (
<StrategyDetailPanel
provider={provider}
detail={detail}
onHide={() => setShowDetail(false)}
/>
)}
</>
)
}
export default StrategyItem

View File

@@ -0,0 +1,449 @@
'use client'
// import { CopyFeedbackNew } from '@/app/components/base/copy-feedback'
import { EncryptedBottom } from '@/app/components/base/encrypted-bottom'
import { BaseForm } from '@/app/components/base/form/components/base'
import type { FormRefObject } from '@/app/components/base/form/types'
import { FormTypeEnum } from '@/app/components/base/form/types'
import Modal from '@/app/components/base/modal/modal'
import Toast from '@/app/components/base/toast'
import { SupportedCreationMethods } from '@/app/components/plugins/types'
import type { TriggerSubscriptionBuilder } from '@/app/components/workflow/block-selector/types'
import { TriggerCredentialTypeEnum } from '@/app/components/workflow/block-selector/types'
import type { BuildTriggerSubscriptionPayload } from '@/service/use-triggers'
import {
useBuildTriggerSubscription,
useCreateTriggerSubscriptionBuilder,
useTriggerSubscriptionBuilderLogs,
useUpdateTriggerSubscriptionBuilder,
useVerifyTriggerSubscriptionBuilder,
} from '@/service/use-triggers'
import { parsePluginErrorMessage } from '@/utils/error-parser'
import { isPrivateOrLocalAddress } from '@/utils/urlValidation'
import { RiLoader2Line } from '@remixicon/react'
import { debounce } from 'lodash-es'
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import LogViewer from '../log-viewer'
import { usePluginStore } from '../../store'
import { useSubscriptionList } from '../use-subscription-list'
type Props = {
onClose: () => void
createType: SupportedCreationMethods
builder?: TriggerSubscriptionBuilder
}
const CREDENTIAL_TYPE_MAP: Record<SupportedCreationMethods, TriggerCredentialTypeEnum> = {
[SupportedCreationMethods.APIKEY]: TriggerCredentialTypeEnum.ApiKey,
[SupportedCreationMethods.OAUTH]: TriggerCredentialTypeEnum.Oauth2,
[SupportedCreationMethods.MANUAL]: TriggerCredentialTypeEnum.Unauthorized,
}
enum ApiKeyStep {
Verify = 'verify',
Configuration = 'configuration',
}
const defaultFormValues = { values: {}, isCheckValidated: false }
const normalizeFormType = (type: FormTypeEnum | string): FormTypeEnum => {
if (Object.values(FormTypeEnum).includes(type as FormTypeEnum))
return type as FormTypeEnum
switch (type) {
case 'string':
case 'text':
return FormTypeEnum.textInput
case 'password':
case 'secret':
return FormTypeEnum.secretInput
case 'number':
case 'integer':
return FormTypeEnum.textNumber
case 'boolean':
return FormTypeEnum.boolean
default:
return FormTypeEnum.textInput
}
}
const StatusStep = ({ isActive, text }: { isActive: boolean, text: string }) => {
return <div className={`system-2xs-semibold-uppercase flex items-center gap-1 ${isActive
? 'text-state-accent-solid'
: 'text-text-tertiary'}`}>
{/* Active indicator dot */}
{isActive && (
<div className='h-1 w-1 rounded-full bg-state-accent-solid'></div>
)}
{text}
</div>
}
const MultiSteps = ({ currentStep }: { currentStep: ApiKeyStep }) => {
const { t } = useTranslation()
return <div className='mb-6 flex w-1/3 items-center gap-2'>
<StatusStep isActive={currentStep === ApiKeyStep.Verify} text={t('pluginTrigger.modal.steps.verify')} />
<div className='h-px w-3 shrink-0 bg-divider-deep'></div>
<StatusStep isActive={currentStep === ApiKeyStep.Configuration} text={t('pluginTrigger.modal.steps.configuration')} />
</div>
}
export const CommonCreateModal = ({ onClose, createType, builder }: Props) => {
const { t } = useTranslation()
const detail = usePluginStore(state => state.detail)
const { refetch } = useSubscriptionList()
const [currentStep, setCurrentStep] = useState<ApiKeyStep>(createType === SupportedCreationMethods.APIKEY ? ApiKeyStep.Verify : ApiKeyStep.Configuration)
const [subscriptionBuilder, setSubscriptionBuilder] = useState<TriggerSubscriptionBuilder | undefined>(builder)
const isInitializedRef = useRef(false)
const { mutate: verifyCredentials, isPending: isVerifyingCredentials } = useVerifyTriggerSubscriptionBuilder()
const { mutateAsync: createBuilder /* isPending: isCreatingBuilder */ } = useCreateTriggerSubscriptionBuilder()
const { mutate: buildSubscription, isPending: isBuilding } = useBuildTriggerSubscription()
const { mutate: updateBuilder } = useUpdateTriggerSubscriptionBuilder()
const manualPropertiesSchema = detail?.declaration?.trigger?.subscription_schema || [] // manual
const manualPropertiesFormRef = React.useRef<FormRefObject>(null)
const subscriptionFormRef = React.useRef<FormRefObject>(null)
const autoCommonParametersSchema = detail?.declaration.trigger?.subscription_constructor?.parameters || [] // apikey and oauth
const autoCommonParametersFormRef = React.useRef<FormRefObject>(null)
const rawApiKeyCredentialsSchema = detail?.declaration.trigger?.subscription_constructor?.credentials_schema || []
const apiKeyCredentialsSchema = useMemo(() => {
return rawApiKeyCredentialsSchema.map(schema => ({
...schema,
tooltip: schema.help,
}))
}, [rawApiKeyCredentialsSchema])
const apiKeyCredentialsFormRef = React.useRef<FormRefObject>(null)
const { data: logData } = useTriggerSubscriptionBuilderLogs(
detail?.provider || '',
subscriptionBuilder?.id || '',
{
enabled: createType === SupportedCreationMethods.MANUAL,
refetchInterval: 3000,
},
)
useEffect(() => {
const initializeBuilder = async () => {
isInitializedRef.current = true
try {
const response = await createBuilder({
provider: detail?.provider || '',
credential_type: CREDENTIAL_TYPE_MAP[createType],
})
setSubscriptionBuilder(response.subscription_builder)
}
catch (error) {
console.error('createBuilder error:', error)
Toast.notify({
type: 'error',
message: t('pluginTrigger.modal.errors.createFailed'),
})
}
}
if (!isInitializedRef.current && !subscriptionBuilder && detail?.provider)
initializeBuilder()
}, [subscriptionBuilder, detail?.provider, createType, createBuilder, t])
useEffect(() => {
if (subscriptionBuilder?.endpoint && subscriptionFormRef.current && currentStep === ApiKeyStep.Configuration) {
const form = subscriptionFormRef.current.getForm()
if (form)
form.setFieldValue('callback_url', subscriptionBuilder.endpoint)
if (isPrivateOrLocalAddress(subscriptionBuilder.endpoint)) {
console.log('isPrivateOrLocalAddress', isPrivateOrLocalAddress(subscriptionBuilder.endpoint))
subscriptionFormRef.current?.setFields([{
name: 'callback_url',
warnings: [t('pluginTrigger.modal.form.callbackUrl.privateAddressWarning')],
}])
}
else {
subscriptionFormRef.current?.setFields([{
name: 'callback_url',
warnings: [],
}])
}
}
}, [subscriptionBuilder?.endpoint, currentStep, t])
const debouncedUpdate = useMemo(
() => debounce((provider: string, builderId: string, properties: Record<string, any>) => {
updateBuilder(
{
provider,
subscriptionBuilderId: builderId,
properties,
},
{
onError: (error: any) => {
console.error('Failed to update subscription builder:', error)
Toast.notify({
type: 'error',
message: error?.message || t('pluginTrigger.modal.errors.updateFailed'),
})
},
},
)
}, 500),
[updateBuilder, t],
)
const handleManualPropertiesChange = useCallback(() => {
if (!subscriptionBuilder || !detail?.provider)
return
const formValues = manualPropertiesFormRef.current?.getFormValues({ needCheckValidatedValues: false }) || { values: {}, isCheckValidated: true }
debouncedUpdate(detail.provider, subscriptionBuilder.id, formValues.values)
}, [subscriptionBuilder, detail?.provider, debouncedUpdate])
useEffect(() => {
return () => {
debouncedUpdate.cancel()
}
}, [debouncedUpdate])
const handleVerify = () => {
const apiKeyCredentialsFormValues = apiKeyCredentialsFormRef.current?.getFormValues({}) || defaultFormValues
const credentials = apiKeyCredentialsFormValues.values
if (!Object.keys(credentials).length) {
Toast.notify({
type: 'error',
message: 'Please fill in all required credentials',
})
return
}
apiKeyCredentialsFormRef.current?.setFields([{
name: Object.keys(credentials)[0],
errors: [],
}])
verifyCredentials(
{
provider: detail?.provider || '',
subscriptionBuilderId: subscriptionBuilder?.id || '',
credentials,
},
{
onSuccess: () => {
Toast.notify({
type: 'success',
message: t('pluginTrigger.modal.apiKey.verify.success'),
})
setCurrentStep(ApiKeyStep.Configuration)
},
onError: async (error: any) => {
const errorMessage = await parsePluginErrorMessage(error) || t('pluginTrigger.modal.apiKey.verify.error')
apiKeyCredentialsFormRef.current?.setFields([{
name: Object.keys(credentials)[0],
errors: [errorMessage],
}])
},
},
)
}
const handleCreate = () => {
if (!subscriptionBuilder) {
Toast.notify({
type: 'error',
message: 'Subscription builder not found',
})
return
}
const subscriptionFormValues = subscriptionFormRef.current?.getFormValues({})
if (!subscriptionFormValues?.isCheckValidated)
return
const subscriptionNameValue = subscriptionFormValues?.values?.subscription_name as string
const params: BuildTriggerSubscriptionPayload = {
provider: detail?.provider || '',
subscriptionBuilderId: subscriptionBuilder.id,
name: subscriptionNameValue,
}
if (createType !== SupportedCreationMethods.MANUAL) {
if (autoCommonParametersSchema.length > 0) {
const autoCommonParametersFormValues = autoCommonParametersFormRef.current?.getFormValues({}) || defaultFormValues
if (!autoCommonParametersFormValues?.isCheckValidated)
return
params.parameters = autoCommonParametersFormValues.values
}
}
else if (manualPropertiesSchema.length > 0) {
const manualFormValues = manualPropertiesFormRef.current?.getFormValues({}) || defaultFormValues
if (!manualFormValues?.isCheckValidated)
return
}
buildSubscription(
params,
{
onSuccess: () => {
Toast.notify({
type: 'success',
message: t('pluginTrigger.subscription.createSuccess'),
})
onClose()
refetch?.()
},
onError: async (error: any) => {
const errorMessage = await parsePluginErrorMessage(error) || t('pluginTrigger.subscription.createFailed')
Toast.notify({
type: 'error',
message: errorMessage,
})
},
},
)
}
const handleConfirm = () => {
if (currentStep === ApiKeyStep.Verify)
handleVerify()
else
handleCreate()
}
const handleApiKeyCredentialsChange = () => {
apiKeyCredentialsFormRef.current?.setFields([{
name: apiKeyCredentialsSchema[0].name,
errors: [],
}])
}
return (
<Modal
title={t(`pluginTrigger.modal.${createType === SupportedCreationMethods.APIKEY ? 'apiKey' : createType.toLowerCase()}.title`)}
confirmButtonText={
currentStep === ApiKeyStep.Verify
? isVerifyingCredentials ? t('pluginTrigger.modal.common.verifying') : t('pluginTrigger.modal.common.verify')
: isBuilding ? t('pluginTrigger.modal.common.creating') : t('pluginTrigger.modal.common.create')
}
onClose={onClose}
onCancel={onClose}
onConfirm={handleConfirm}
disabled={isVerifyingCredentials || isBuilding}
bottomSlot={currentStep === ApiKeyStep.Verify ? <EncryptedBottom /> : null}
size={createType === SupportedCreationMethods.MANUAL ? 'md' : 'sm'}
containerClassName='min-h-[360px]'
clickOutsideNotClose
>
{createType === SupportedCreationMethods.APIKEY && <MultiSteps currentStep={currentStep} />}
{currentStep === ApiKeyStep.Verify && (
<>
{apiKeyCredentialsSchema.length > 0 && (
<div className='mb-4'>
<BaseForm
formSchemas={apiKeyCredentialsSchema}
ref={apiKeyCredentialsFormRef}
labelClassName='system-sm-medium mb-2 flex items-center gap-1 text-text-primary'
preventDefaultSubmit={true}
formClassName='space-y-4'
onChange={handleApiKeyCredentialsChange}
/>
</div>
)}
</>
)}
{currentStep === ApiKeyStep.Configuration && <div className='max-h-[70vh]'>
<BaseForm
formSchemas={[
{
name: 'subscription_name',
label: t('pluginTrigger.modal.form.subscriptionName.label'),
placeholder: t('pluginTrigger.modal.form.subscriptionName.placeholder'),
type: FormTypeEnum.textInput,
required: true,
},
{
name: 'callback_url',
label: t('pluginTrigger.modal.form.callbackUrl.label'),
placeholder: t('pluginTrigger.modal.form.callbackUrl.placeholder'),
type: FormTypeEnum.textInput,
required: false,
default: subscriptionBuilder?.endpoint || '',
disabled: true,
tooltip: t('pluginTrigger.modal.form.callbackUrl.tooltip'),
showCopy: true,
},
]}
ref={subscriptionFormRef}
labelClassName='system-sm-medium mb-2 flex items-center gap-1 text-text-primary'
formClassName='space-y-4 mb-4'
/>
{/* <div className='system-xs-regular mb-6 mt-[-1rem] text-text-tertiary'>
{t('pluginTrigger.modal.form.callbackUrl.description')}
</div> */}
{createType !== SupportedCreationMethods.MANUAL && autoCommonParametersSchema.length > 0 && (
<BaseForm
formSchemas={autoCommonParametersSchema.map((schema) => {
const normalizedType = normalizeFormType(schema.type as FormTypeEnum | string)
return {
...schema,
tooltip: schema.description,
type: normalizedType,
dynamicSelectParams: normalizedType === FormTypeEnum.dynamicSelect ? {
plugin_id: detail?.plugin_id || '',
provider: detail?.provider || '',
action: 'provider',
parameter: schema.name,
credential_id: subscriptionBuilder?.id || '',
} : undefined,
fieldClassName: schema.type === FormTypeEnum.boolean ? 'flex items-center justify-between' : undefined,
labelClassName: schema.type === FormTypeEnum.boolean ? 'mb-0' : undefined,
}
})}
ref={autoCommonParametersFormRef}
labelClassName='system-sm-medium mb-2 flex items-center gap-1 text-text-primary'
formClassName='space-y-4'
/>
)}
{createType === SupportedCreationMethods.MANUAL && <>
{manualPropertiesSchema.length > 0 && (
<div className='mb-6'>
<BaseForm
formSchemas={manualPropertiesSchema.map(schema => ({
...schema,
tooltip: schema.description,
}))}
ref={manualPropertiesFormRef}
labelClassName='system-sm-medium mb-2 flex items-center gap-1 text-text-primary'
formClassName='space-y-4'
onChange={handleManualPropertiesChange}
/>
</div>
)}
<div className='mb-6'>
<div className='mb-3 flex items-center gap-2'>
<div className='system-xs-medium-uppercase text-text-tertiary'>
{t('pluginTrigger.modal.manual.logs.title')}
</div>
<div className='h-px flex-1 bg-gradient-to-r from-divider-regular to-transparent' />
</div>
<div className='mb-1 flex items-center justify-center gap-1 rounded-lg bg-background-section p-3'>
<div className='h-3.5 w-3.5'>
<RiLoader2Line className='h-full w-full animate-spin' />
</div>
<div className='system-xs-regular text-text-tertiary'>
{t('pluginTrigger.modal.manual.logs.loading', { pluginName: detail?.name || '' })}
</div>
</div>
<LogViewer logs={logData?.logs || []} />
</div>
</>}
</div>}
</Modal>
)
}

View File

@@ -0,0 +1,242 @@
import { ActionButton, ActionButtonState } from '@/app/components/base/action-button'
import Badge from '@/app/components/base/badge'
import { Button } from '@/app/components/base/button'
import type { Option } from '@/app/components/base/select/custom'
import CustomSelect from '@/app/components/base/select/custom'
import Toast from '@/app/components/base/toast'
import Tooltip from '@/app/components/base/tooltip'
import type { TriggerSubscriptionBuilder } from '@/app/components/workflow/block-selector/types'
import { openOAuthPopup } from '@/hooks/use-oauth'
import { useInitiateTriggerOAuth, useTriggerOAuthConfig, useTriggerProviderInfo } from '@/service/use-triggers'
import cn from '@/utils/classnames'
import { RiAddLine, RiEqualizer2Line } from '@remixicon/react'
import { useBoolean } from 'ahooks'
import { useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { SupportedCreationMethods } from '../../../types'
import { usePluginStore } from '../../store'
import { useSubscriptionList } from '../use-subscription-list'
import { CommonCreateModal } from './common-modal'
import { OAuthClientSettingsModal } from './oauth-client'
export enum CreateButtonType {
FULL_BUTTON = 'full-button',
ICON_BUTTON = 'icon-button',
}
type Props = {
className?: string
buttonType?: CreateButtonType
shape?: 'square' | 'circle'
}
const MAX_COUNT = 10
export const DEFAULT_METHOD = 'default'
export const CreateSubscriptionButton = ({ buttonType = CreateButtonType.FULL_BUTTON, shape = 'square' }: Props) => {
const { t } = useTranslation()
const { subscriptions } = useSubscriptionList()
const subscriptionCount = subscriptions?.length || 0
const [selectedCreateInfo, setSelectedCreateInfo] = useState<{ type: SupportedCreationMethods, builder?: TriggerSubscriptionBuilder } | null>(null)
const detail = usePluginStore(state => state.detail)
const { data: providerInfo } = useTriggerProviderInfo(detail?.provider || '')
const supportedMethods = providerInfo?.supported_creation_methods || []
const { data: oauthConfig, refetch: refetchOAuthConfig } = useTriggerOAuthConfig(detail?.provider || '', supportedMethods.includes(SupportedCreationMethods.OAUTH))
const { mutate: initiateOAuth } = useInitiateTriggerOAuth()
const methodType = supportedMethods.length === 1 ? supportedMethods[0] : DEFAULT_METHOD
const [isShowClientSettingsModal, {
setTrue: showClientSettingsModal,
setFalse: hideClientSettingsModal,
}] = useBoolean(false)
const buttonTextMap = useMemo(() => {
return {
[SupportedCreationMethods.OAUTH]: t('pluginTrigger.subscription.createButton.oauth'),
[SupportedCreationMethods.APIKEY]: t('pluginTrigger.subscription.createButton.apiKey'),
[SupportedCreationMethods.MANUAL]: t('pluginTrigger.subscription.createButton.manual'),
[DEFAULT_METHOD]: t('pluginTrigger.subscription.empty.button'),
}
}, [t])
const onClickClientSettings = (e: React.MouseEvent<HTMLDivElement | HTMLButtonElement>) => {
e.stopPropagation()
e.preventDefault()
showClientSettingsModal()
}
const allOptions = useMemo(() => {
const showCustomBadge = oauthConfig?.custom_enabled && oauthConfig?.custom_configured
return [
{
value: SupportedCreationMethods.OAUTH,
label: t('pluginTrigger.subscription.addType.options.oauth.title'),
tag: !showCustomBadge ? null : <Badge className='ml-1 mr-0.5'>
{t('plugin.auth.custom')}
</Badge>,
extra: <Tooltip popupContent={t('pluginTrigger.subscription.addType.options.oauth.clientSettings')}>
<ActionButton onClick={onClickClientSettings}>
<RiEqualizer2Line className='h-4 w-4 text-text-tertiary' />
</ActionButton>
</Tooltip>,
show: supportedMethods.includes(SupportedCreationMethods.OAUTH),
},
{
value: SupportedCreationMethods.APIKEY,
label: t('pluginTrigger.subscription.addType.options.apikey.title'),
show: supportedMethods.includes(SupportedCreationMethods.APIKEY),
},
{
value: SupportedCreationMethods.MANUAL,
label: t('pluginTrigger.subscription.addType.options.manual.description'),
extra: <Tooltip popupContent={t('pluginTrigger.subscription.addType.options.manual.tip')} />,
show: supportedMethods.includes(SupportedCreationMethods.MANUAL),
},
]
}, [t, oauthConfig, supportedMethods, methodType])
const onChooseCreateType = async (type: SupportedCreationMethods) => {
if (type === SupportedCreationMethods.OAUTH) {
if (oauthConfig?.configured) {
initiateOAuth(detail?.provider || '', {
onSuccess: (response) => {
openOAuthPopup(response.authorization_url, (callbackData) => {
if (callbackData) {
Toast.notify({
type: 'success',
message: t('pluginTrigger.modal.oauth.authorization.authSuccess'),
})
setSelectedCreateInfo({ type: SupportedCreationMethods.OAUTH, builder: response.subscription_builder })
}
})
},
onError: () => {
Toast.notify({
type: 'error',
message: t('pluginTrigger.modal.oauth.authorization.authFailed'),
})
},
})
}
else {
showClientSettingsModal()
}
}
else {
setSelectedCreateInfo({ type })
}
}
const onClickCreate = (e: React.MouseEvent<HTMLButtonElement>) => {
if (subscriptionCount >= MAX_COUNT) {
e.stopPropagation()
return
}
if (methodType === DEFAULT_METHOD || (methodType === SupportedCreationMethods.OAUTH && supportedMethods.length === 1))
return
e.stopPropagation()
e.preventDefault()
onChooseCreateType(methodType)
}
if (!supportedMethods.length)
return null
return <>
<CustomSelect<Option & { show: boolean; extra?: React.ReactNode; tag?: React.ReactNode }>
options={allOptions.filter(option => option.show)}
value={methodType}
onChange={value => onChooseCreateType(value as any)}
containerProps={{
open: (methodType === DEFAULT_METHOD || (methodType === SupportedCreationMethods.OAUTH && supportedMethods.length === 1)) ? undefined : false,
placement: 'bottom-start',
offset: 4,
triggerPopupSameWidth: buttonType === CreateButtonType.FULL_BUTTON,
}}
triggerProps={{
className: cn('h-8 bg-transparent px-0 hover:bg-transparent', methodType !== DEFAULT_METHOD && supportedMethods.length > 1 && 'pointer-events-none', buttonType === CreateButtonType.FULL_BUTTON && 'grow'),
}}
popupProps={{
wrapperClassName: 'z-[1000]',
}}
CustomTrigger={() => {
return buttonType === CreateButtonType.FULL_BUTTON ? (
<Button
variant='primary'
size='medium'
className='flex w-full items-center justify-between px-0'
onClick={onClickCreate}
>
<div className='flex flex-1 items-center justify-center'>
<RiAddLine className='mr-2 size-4' />
{buttonTextMap[methodType]}
{methodType === SupportedCreationMethods.OAUTH && oauthConfig?.custom_enabled && oauthConfig?.custom_configured && <Badge
className='ml-1 mr-0.5 border-text-primary-on-surface bg-components-badge-bg-dimm text-text-primary-on-surface'
>
{t('plugin.auth.custom')}
</Badge>}
</div>
{methodType === SupportedCreationMethods.OAUTH
&& <div className='ml-auto flex items-center'>
<div className="h-4 w-px bg-text-primary-on-surface opacity-15" />
<Tooltip popupContent={t('pluginTrigger.subscription.addType.options.oauth.clientSettings')}>
<div onClick={onClickClientSettings} className='p-2'>
<RiEqualizer2Line className='size-4 text-components-button-primary-text' />
</div>
</Tooltip>
</div>
}
</Button>
) : (
<Tooltip
popupContent={subscriptionCount >= MAX_COUNT ? t('pluginTrigger.subscription.maxCount', { num: MAX_COUNT }) : t(`pluginTrigger.subscription.addType.options.${methodType.toLowerCase()}.description`)}
disabled={!(supportedMethods?.length === 1 || subscriptionCount >= MAX_COUNT)}>
<ActionButton
onClick={onClickCreate}
className={cn(
'float-right',
shape === 'circle' && '!rounded-full border-[0.5px] border-components-button-secondary-border-hover bg-components-button-secondary-bg-hover text-components-button-secondary-accent-text shadow-xs hover:border-components-button-secondary-border-disabled hover:bg-components-button-secondary-bg-disabled hover:text-components-button-secondary-accent-text-disabled',
)}
state={subscriptionCount >= MAX_COUNT ? ActionButtonState.Disabled : ActionButtonState.Default}
>
<RiAddLine className='size-4' />
</ActionButton>
</Tooltip>
)
}}
CustomOption={option => (
<>
<div className='mr-8 flex grow items-center gap-1 truncate px-1'>
{option.label}
{option.tag}
</div>
{option.extra}
</>
)}
/>
{selectedCreateInfo && (
<CommonCreateModal
createType={selectedCreateInfo.type}
builder={selectedCreateInfo.builder}
onClose={() => setSelectedCreateInfo(null)}
/>
)}
{isShowClientSettingsModal && (
<OAuthClientSettingsModal
oauthConfig={oauthConfig}
onClose={() => {
hideClientSettingsModal()
refetchOAuthConfig()
}}
showOAuthCreateModal={builder => setSelectedCreateInfo({ type: SupportedCreationMethods.OAUTH, builder })}
/>
)}
</>
}

View File

@@ -0,0 +1,257 @@
'use client'
import Button from '@/app/components/base/button'
import { BaseForm } from '@/app/components/base/form/components/base'
import type { FormRefObject } from '@/app/components/base/form/types'
import Modal from '@/app/components/base/modal/modal'
import Toast from '@/app/components/base/toast'
import type { TriggerOAuthClientParams, TriggerOAuthConfig, TriggerSubscriptionBuilder } from '@/app/components/workflow/block-selector/types'
import OptionCard from '@/app/components/workflow/nodes/_base/components/option-card'
import { openOAuthPopup } from '@/hooks/use-oauth'
import type { ConfigureTriggerOAuthPayload } from '@/service/use-triggers'
import {
useConfigureTriggerOAuth,
useDeleteTriggerOAuth,
useInitiateTriggerOAuth,
useVerifyTriggerSubscriptionBuilder,
} from '@/service/use-triggers'
import {
RiClipboardLine,
RiInformation2Fill,
} from '@remixicon/react'
import React, { useEffect, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { usePluginStore } from '../../store'
type Props = {
oauthConfig?: TriggerOAuthConfig
onClose: () => void
showOAuthCreateModal: (builder: TriggerSubscriptionBuilder) => void
}
enum AuthorizationStatusEnum {
Pending = 'pending',
Success = 'success',
Failed = 'failed',
}
enum ClientTypeEnum {
Default = 'default',
Custom = 'custom',
}
export const OAuthClientSettingsModal = ({ oauthConfig, onClose, showOAuthCreateModal }: Props) => {
const { t } = useTranslation()
const detail = usePluginStore(state => state.detail)
const { system_configured, params, oauth_client_schema } = oauthConfig || {}
const [subscriptionBuilder, setSubscriptionBuilder] = useState<TriggerSubscriptionBuilder | undefined>()
const [authorizationStatus, setAuthorizationStatus] = useState<AuthorizationStatusEnum>()
const [clientType, setClientType] = useState<ClientTypeEnum>(system_configured ? ClientTypeEnum.Default : ClientTypeEnum.Custom)
const clientFormRef = React.useRef<FormRefObject>(null)
const oauthClientSchema = useMemo(() => {
if (oauth_client_schema && oauth_client_schema.length > 0 && params) {
const oauthConfigPramaKeys = Object.keys(params || {})
for (const schema of oauth_client_schema) {
if (oauthConfigPramaKeys.includes(schema.name))
schema.default = params?.[schema.name]
}
return oauth_client_schema
}
return []
}, [oauth_client_schema, params])
const providerName = detail?.provider || ''
const { mutate: initiateOAuth } = useInitiateTriggerOAuth()
const { mutate: verifyBuilder } = useVerifyTriggerSubscriptionBuilder()
const { mutate: configureOAuth } = useConfigureTriggerOAuth()
const { mutate: deleteOAuth } = useDeleteTriggerOAuth()
const handleAuthorization = () => {
setAuthorizationStatus(AuthorizationStatusEnum.Pending)
initiateOAuth(providerName, {
onSuccess: (response) => {
setSubscriptionBuilder(response.subscription_builder)
openOAuthPopup(response.authorization_url, (callbackData) => {
if (callbackData) {
Toast.notify({
type: 'success',
message: t('pluginTrigger.modal.oauth.authorization.authSuccess'),
})
onClose()
showOAuthCreateModal(response.subscription_builder)
}
})
},
onError: () => {
setAuthorizationStatus(AuthorizationStatusEnum.Failed)
Toast.notify({
type: 'error',
message: t('pluginTrigger.modal.oauth.authorization.authFailed'),
})
},
})
}
useEffect(() => {
if (providerName && subscriptionBuilder && authorizationStatus === AuthorizationStatusEnum.Pending) {
const pollInterval = setInterval(() => {
verifyBuilder(
{
provider: providerName,
subscriptionBuilderId: subscriptionBuilder.id,
},
{
onSuccess: (response) => {
if (response.verified) {
setAuthorizationStatus(AuthorizationStatusEnum.Success)
clearInterval(pollInterval)
}
},
onError: () => {
// Continue polling - auth might still be in progress
},
},
)
}, 3000)
return () => clearInterval(pollInterval)
}
}, [subscriptionBuilder, authorizationStatus, verifyBuilder, providerName, t])
const handleRemove = () => {
deleteOAuth(providerName, {
onSuccess: () => {
onClose()
Toast.notify({
type: 'success',
message: t('pluginTrigger.modal.oauth.remove.success'),
})
},
onError: (error: any) => {
Toast.notify({
type: 'error',
message: error?.message || t('pluginTrigger.modal.oauth.remove.failed'),
})
},
})
}
const handleSave = (needAuth: boolean) => {
const isCustom = clientType === ClientTypeEnum.Custom
const params: ConfigureTriggerOAuthPayload = {
provider: providerName,
enabled: isCustom,
}
if (isCustom) {
const clientFormValues = clientFormRef.current?.getFormValues({}) as { values: TriggerOAuthClientParams, isCheckValidated: boolean }
if (!clientFormValues.isCheckValidated)
return
const clientParams = clientFormValues.values
if (clientParams.client_id === oauthConfig?.params.client_id)
clientParams.client_id = '[__HIDDEN__]'
if (clientParams.client_secret === oauthConfig?.params.client_secret)
clientParams.client_secret = '[__HIDDEN__]'
params.client_params = clientParams
}
configureOAuth(params, {
onSuccess: () => {
if (needAuth) {
handleAuthorization()
}
else {
onClose()
Toast.notify({
type: 'success',
message: t('pluginTrigger.modal.oauth.save.success'),
})
}
},
})
}
return (
<Modal
title={t('pluginTrigger.modal.oauth.title')}
confirmButtonText={authorizationStatus === AuthorizationStatusEnum.Pending ? t('pluginTrigger.modal.common.authorizing')
: authorizationStatus === AuthorizationStatusEnum.Success ? t('pluginTrigger.modal.oauth.authorization.waitingJump') : t('plugin.auth.saveAndAuth')}
cancelButtonText={t('plugin.auth.saveOnly')}
extraButtonText={t('common.operation.cancel')}
showExtraButton
clickOutsideNotClose
extraButtonVariant='secondary'
onExtraButtonClick={onClose}
onClose={onClose}
onCancel={() => handleSave(false)}
onConfirm={() => handleSave(true)}
footerSlot={
oauthConfig?.custom_enabled && oauthConfig?.params && clientType === ClientTypeEnum.Custom && (
<div className='grow'>
<Button
variant='secondary'
className='text-components-button-destructive-secondary-text'
// disabled={disabled || doingAction || !editValues}
onClick={handleRemove}
>
{t('common.operation.remove')}
</Button>
</div>
)
}
>
<div className='system-sm-medium mb-2 text-text-secondary'>{t('pluginTrigger.subscription.addType.options.oauth.clientTitle')}</div>
{oauthConfig?.system_configured && <div className='mb-4 flex w-full items-start justify-between gap-2'>
{[ClientTypeEnum.Default, ClientTypeEnum.Custom].map(option => (
<OptionCard
key={option}
title={t(`pluginTrigger.subscription.addType.options.oauth.${option}`)}
onSelect={() => setClientType(option)}
selected={clientType === option}
className="flex-1"
/>
))}
</div>}
{clientType === ClientTypeEnum.Custom && oauthConfig?.redirect_uri && (
<div className='mb-4 flex items-start gap-3 rounded-xl bg-background-section-burn p-4'>
<div className='rounded-lg border-[0.5px] border-components-card-border bg-components-card-bg p-2 shadow-xs shadow-shadow-shadow-3'>
<RiInformation2Fill className='h-5 w-5 shrink-0 text-text-accent' />
</div>
<div className='flex-1 text-text-secondary'>
<div className='system-sm-regular whitespace-pre-wrap leading-4'>
{t('pluginTrigger.modal.oauthRedirectInfo')}
</div>
<div className='system-sm-medium my-1.5 break-all leading-4'>
{oauthConfig.redirect_uri}
</div>
<Button
variant='secondary'
size='small'
onClick={() => {
navigator.clipboard.writeText(oauthConfig.redirect_uri)
Toast.notify({
type: 'success',
message: t('common.actionMsg.copySuccessfully'),
})
}}>
<RiClipboardLine className='mr-1 h-[14px] w-[14px]' />
{t('common.operation.copy')}
</Button>
</div>
</div>
)}
{clientType === ClientTypeEnum.Custom && oauthClientSchema.length > 0 && (
<BaseForm
formSchemas={oauthClientSchema}
ref={clientFormRef}
labelClassName='system-sm-medium mb-2 block text-text-secondary'
formClassName='space-y-4'
/>
)}
</Modal >
)
}

View File

@@ -0,0 +1,75 @@
import Confirm from '@/app/components/base/confirm'
import Input from '@/app/components/base/input'
import Toast from '@/app/components/base/toast'
import { useDeleteTriggerSubscription } from '@/service/use-triggers'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useSubscriptionList } from './use-subscription-list'
type Props = {
onClose: (deleted: boolean) => void
isShow: boolean
currentId: string
currentName: string
workflowsInUse: number
}
const tPrefix = 'pluginTrigger.subscription.list.item.actions.deleteConfirm'
export const DeleteConfirm = (props: Props) => {
const { onClose, isShow, currentId, currentName, workflowsInUse } = props
const { refetch } = useSubscriptionList()
const { mutate: deleteSubscription, isPending: isDeleting } = useDeleteTriggerSubscription()
const { t } = useTranslation()
const [inputName, setInputName] = useState('')
const onConfirm = () => {
if (workflowsInUse > 0 && inputName !== currentName) {
Toast.notify({
type: 'error',
message: t(`${tPrefix}.confirmInputWarning`),
// temporarily
className: 'z-[10000001]',
})
return
}
deleteSubscription(currentId, {
onSuccess: () => {
Toast.notify({
type: 'success',
message: t(`${tPrefix}.success`, { name: currentName }),
className: 'z-[10000001]',
})
refetch?.()
onClose(true)
},
onError: (error: any) => {
Toast.notify({
type: 'error',
message: error?.message || t(`${tPrefix}.error`, { name: currentName }),
className: 'z-[10000001]',
})
},
})
}
return <Confirm
title={t(`${tPrefix}.title`, { name: currentName })}
confirmText={t(`${tPrefix}.confirm`)}
content={workflowsInUse > 0 ? <>
{t(`${tPrefix}.contentWithApps`, { count: workflowsInUse })}
<div className='system-sm-medium mb-2 mt-6 text-text-secondary'>{t(`${tPrefix}.confirmInputTip`, { name: currentName })}</div>
<Input
value={inputName}
onChange={e => setInputName(e.target.value)}
placeholder={t(`${tPrefix}.confirmInputPlaceholder`, { name: currentName })}
/>
</>
: t(`${tPrefix}.content`)}
isShow={isShow}
isLoading={isDeleting}
isDisabled={isDeleting}
onConfirm={onConfirm}
onCancel={() => onClose(false)}
maskClosable={false}
/>
}

View File

@@ -0,0 +1,51 @@
import { withErrorBoundary } from '@/app/components/base/error-boundary'
import Loading from '@/app/components/base/loading'
import { SubscriptionListView } from './list-view'
import { SubscriptionSelectorView } from './selector-view'
import { useSubscriptionList } from './use-subscription-list'
export enum SubscriptionListMode {
PANEL = 'panel',
SELECTOR = 'selector',
}
export type SimpleSubscription = {
id: string,
name: string
}
type SubscriptionListProps = {
mode?: SubscriptionListMode
selectedId?: string
onSelect?: (v: SimpleSubscription, callback?: () => void) => void
}
export { SubscriptionSelectorEntry } from './selector-entry'
export const SubscriptionList = withErrorBoundary(({
mode = SubscriptionListMode.PANEL,
selectedId,
onSelect,
}: SubscriptionListProps) => {
const { isLoading, refetch } = useSubscriptionList()
if (isLoading) {
return (
<div className='flex items-center justify-center py-4'>
<Loading />
</div>
)
}
if (mode === SubscriptionListMode.SELECTOR) {
return (
<SubscriptionSelectorView
selectedId={selectedId}
onSelect={(v) => {
onSelect?.(v, refetch)
}}
/>
)
}
return <SubscriptionListView />
})

View File

@@ -0,0 +1,50 @@
'use client'
import Tooltip from '@/app/components/base/tooltip'
import cn from '@/utils/classnames'
import React from 'react'
import { useTranslation } from 'react-i18next'
import { CreateButtonType, CreateSubscriptionButton } from './create'
import SubscriptionCard from './subscription-card'
import { useSubscriptionList } from './use-subscription-list'
type SubscriptionListViewProps = {
showTopBorder?: boolean
}
export const SubscriptionListView: React.FC<SubscriptionListViewProps> = ({
showTopBorder = false,
}) => {
const { t } = useTranslation()
const { subscriptions } = useSubscriptionList()
const subscriptionCount = subscriptions?.length || 0
return (
<div className={cn('border-divider-subtle px-4 py-2', showTopBorder && 'border-t')}>
<div className='relative flex items-center justify-between'>
{subscriptionCount > 0 && (
<div className='flex h-8 shrink-0 items-center gap-1'>
<span className='system-sm-semibold-uppercase text-text-secondary'>
{t('pluginTrigger.subscription.listNum', { num: subscriptionCount })}
</span>
<Tooltip popupContent={t('pluginTrigger.subscription.list.tip')} />
</div>
)}
<CreateSubscriptionButton
buttonType={subscriptionCount > 0 ? CreateButtonType.ICON_BUTTON : CreateButtonType.FULL_BUTTON}
/>
</div>
{subscriptionCount > 0 && (
<div className='flex flex-col gap-1'>
{subscriptions?.map(subscription => (
<SubscriptionCard
key={subscription.id}
data={subscription}
/>
))}
</div>
)}
</div>
)
}

View File

@@ -0,0 +1,193 @@
'use client'
import React, { useState } from 'react'
import { useTranslation } from 'react-i18next'
import {
RiArrowDownSLine,
RiArrowRightSLine,
RiCheckboxCircleFill,
RiErrorWarningFill,
RiFileCopyLine,
} from '@remixicon/react'
import cn from '@/utils/classnames'
import Toast from '@/app/components/base/toast'
import CodeEditor from '@/app/components/workflow/nodes/_base/components/editor/code-editor'
import { CodeLanguage } from '@/app/components/workflow/nodes/code/types'
import type { TriggerLogEntity } from '@/app/components/workflow/block-selector/types'
import dayjs from 'dayjs'
type Props = {
logs: TriggerLogEntity[]
className?: string
}
enum LogTypeEnum {
REQUEST = 'request',
RESPONSE = 'response',
}
const LogViewer = ({ logs, className }: Props) => {
const { t } = useTranslation()
const [expandedLogs, setExpandedLogs] = useState<Set<string>>(new Set())
const toggleLogExpansion = (logId: string) => {
const newExpanded = new Set(expandedLogs)
if (newExpanded.has(logId))
newExpanded.delete(logId)
else
newExpanded.add(logId)
setExpandedLogs(newExpanded)
}
const parseRequestData = (data: any) => {
if (typeof data === 'string' && data.startsWith('payload=')) {
try {
const urlDecoded = decodeURIComponent(data.substring(8)) // Remove 'payload='
return JSON.parse(urlDecoded)
}
catch {
return data
}
}
if (typeof data === 'object')
return data
try {
return JSON.parse(data)
}
catch {
return data
}
}
const renderJsonContent = (originalData: any, title: LogTypeEnum) => {
const parsedData = title === LogTypeEnum.REQUEST ? { headers: originalData.headers, data: parseRequestData(originalData.data) } : originalData
const isJsonObject = typeof parsedData === 'object'
if (isJsonObject) {
return (
<CodeEditor
readOnly
title={<div className="system-xs-semibold-uppercase text-text-secondary">{title}</div>}
language={CodeLanguage.json}
value={parsedData}
isJSONStringifyBeauty
nodeId=""
/>
)
}
return (
<div className='rounded-md bg-components-input-bg-normal'>
<div className='flex items-center justify-between px-2 py-1'>
<div className='system-xs-semibold-uppercase text-text-secondary'>
{title}
</div>
<button
onClick={(e) => {
e.stopPropagation()
navigator.clipboard.writeText(String(parsedData))
Toast.notify({
type: 'success',
message: t('common.actionMsg.copySuccessfully'),
})
}}
className='rounded-md p-0.5 hover:bg-components-panel-border'
>
<RiFileCopyLine className='h-4 w-4 text-text-tertiary' />
</button>
</div>
<div className='px-2 pb-2 pt-1'>
<pre className='code-xs-regular whitespace-pre-wrap break-all text-text-secondary'>
{String(parsedData)}
</pre>
</div>
</div>
)
}
if (!logs || logs.length === 0)
return null
return (
<div className={cn('flex flex-col gap-1', className)}>
{logs.map((log, index) => {
const logId = log.id || index.toString()
const isExpanded = expandedLogs.has(logId)
const isSuccess = log.response.status_code === 200
const isError = log.response.status_code >= 400
return (
<div
key={logId}
className={cn(
'relative overflow-hidden rounded-lg border bg-components-panel-on-panel-item-bg shadow-sm hover:bg-components-panel-on-panel-item-bg-hover',
isError && 'border-state-destructive-border',
!isError && isExpanded && 'border-components-panel-border',
!isError && !isExpanded && 'border-components-panel-border-subtle',
)}
>
{isError && (
<div className='pointer-events-none absolute left-0 top-0 h-7 w-[179px]'>
<svg xmlns="http://www.w3.org/2000/svg" width="179" height="28" viewBox="0 0 179 28" fill="none" className='h-full w-full'>
<g filter="url(#filter0_f_error_glow)">
<circle cx="27" cy="14" r="32" fill="#F04438" fillOpacity="0.25" />
</g>
<defs>
<filter id="filter0_f_error_glow" x="-125" y="-138" width="304" height="304" filterUnits="userSpaceOnUse" colorInterpolationFilters="sRGB">
<feFlood floodOpacity="0" result="BackgroundImageFix" />
<feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape" />
<feGaussianBlur stdDeviation="60" result="effect1_foregroundBlur" />
</filter>
</defs>
</svg>
</div>
)}
<button
onClick={() => toggleLogExpansion(logId)}
className={cn(
'flex w-full items-center justify-between px-2 py-1.5 text-left',
isExpanded ? 'pb-1 pt-2' : 'min-h-7',
)}
>
<div className='flex items-center gap-0'>
{isExpanded ? (
<RiArrowDownSLine className='h-4 w-4 text-text-tertiary' />
) : (
<RiArrowRightSLine className='h-4 w-4 text-text-tertiary' />
)}
<div className='system-xs-semibold-uppercase text-text-secondary'>
{t(`pluginTrigger.modal.manual.logs.${LogTypeEnum.REQUEST}`)} #{index + 1}
</div>
</div>
<div className='flex items-center gap-1'>
<div className='system-xs-regular text-text-tertiary'>
{dayjs(log.created_at).format('HH:mm:ss')}
</div>
<div className='h-3.5 w-3.5'>
{isSuccess ? (
<RiCheckboxCircleFill className='h-full w-full text-text-success' />
) : (
<RiErrorWarningFill className='h-full w-full text-text-destructive' />
)}
</div>
</div>
</button>
{isExpanded && (
<div className='flex flex-col gap-1 px-1 pb-1'>
{renderJsonContent(log.request, LogTypeEnum.REQUEST)}
{renderJsonContent(log.response, LogTypeEnum.RESPONSE)}
</div>
)}
</div>
)
})}
</div>
)
}
export default LogViewer

View File

@@ -0,0 +1,126 @@
'use client'
import {
PortalToFollowElem,
PortalToFollowElemContent,
PortalToFollowElemTrigger,
} from '@/app/components/base/portal-to-follow-elem'
import type { SimpleSubscription } from '@/app/components/plugins/plugin-detail-panel/subscription-list'
import { SubscriptionList, SubscriptionListMode } from '@/app/components/plugins/plugin-detail-panel/subscription-list'
import cn from '@/utils/classnames'
import { RiArrowDownSLine, RiWebhookLine } from '@remixicon/react'
import { useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useSubscriptionList } from './use-subscription-list'
type SubscriptionTriggerButtonProps = {
selectedId?: string
onClick?: () => void
isOpen?: boolean
className?: string
}
const SubscriptionTriggerButton: React.FC<SubscriptionTriggerButtonProps> = ({
selectedId,
onClick,
isOpen = false,
className,
}) => {
const { t } = useTranslation()
const { subscriptions } = useSubscriptionList()
const statusConfig = useMemo(() => {
if (!selectedId) {
if (isOpen) {
return {
label: t('pluginTrigger.subscription.selectPlaceholder'),
color: 'yellow' as const,
}
}
return {
label: t('pluginTrigger.subscription.noSubscriptionSelected'),
color: 'red' as const,
}
}
if (subscriptions && subscriptions.length > 0) {
const selectedSubscription = subscriptions?.find(sub => sub.id === selectedId)
if (!selectedSubscription) {
return {
label: t('pluginTrigger.subscription.subscriptionRemoved'),
color: 'red' as const,
}
}
return {
label: selectedSubscription.name,
color: 'green' as const,
}
}
return {
label: t('pluginTrigger.subscription.noSubscriptionSelected'),
color: 'red' as const,
}
}, [selectedId, subscriptions, t, isOpen])
return (
<button
className={cn(
'flex h-8 items-center gap-1 rounded-lg px-2 transition-colors',
'hover:bg-state-base-hover-alt',
isOpen && 'bg-state-base-hover-alt',
className,
)}
onClick={onClick}
>
<RiWebhookLine className={cn('h-3.5 w-3.5 shrink-0 text-text-secondary', statusConfig.color === 'red' && 'text-components-button-destructive-secondary-text')} />
<span className={cn('system-xs-medium truncate text-components-button-ghost-text', statusConfig.color === 'red' && 'text-components-button-destructive-secondary-text')}>
{statusConfig.label}
</span>
<RiArrowDownSLine
className={cn(
'ml-auto h-4 w-4 shrink-0 text-text-quaternary transition-transform',
isOpen && 'rotate-180',
statusConfig.color === 'red' && 'text-components-button-destructive-secondary-text',
)}
/>
</button>
)
}
export const SubscriptionSelectorEntry = ({ selectedId, onSelect }: {
selectedId?: string,
onSelect: (v: SimpleSubscription, callback?: () => void) => void
}) => {
const [isOpen, setIsOpen] = useState(false)
return <PortalToFollowElem
placement='bottom-start'
offset={4}
open={isOpen}
onOpenChange={setIsOpen}
>
<PortalToFollowElemTrigger asChild>
<div>
<SubscriptionTriggerButton
selectedId={selectedId}
onClick={() => setIsOpen(!isOpen)}
isOpen={isOpen}
/>
</div>
</PortalToFollowElemTrigger>
<PortalToFollowElemContent className='z-[11]'>
<div className='rounded-xl border border-components-panel-border bg-components-panel-bg shadow-lg'>
<SubscriptionList
mode={SubscriptionListMode.SELECTOR}
selectedId={selectedId}
onSelect={(...args) => {
onSelect(...args)
setIsOpen(false)
}}
/>
</div>
</PortalToFollowElemContent>
</PortalToFollowElem>
}

View File

@@ -0,0 +1,90 @@
'use client'
import ActionButton from '@/app/components/base/action-button'
import Tooltip from '@/app/components/base/tooltip'
import type { TriggerSubscription } from '@/app/components/workflow/block-selector/types'
import cn from '@/utils/classnames'
import { RiCheckLine, RiDeleteBinLine, RiWebhookLine } from '@remixicon/react'
import React, { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { CreateButtonType, CreateSubscriptionButton } from './create'
import { DeleteConfirm } from './delete-confirm'
import { useSubscriptionList } from './use-subscription-list'
type SubscriptionSelectorProps = {
selectedId?: string
onSelect?: ({ id, name }: { id: string, name: string }) => void
}
export const SubscriptionSelectorView: React.FC<SubscriptionSelectorProps> = ({
selectedId,
onSelect,
}) => {
const { t } = useTranslation()
const { subscriptions } = useSubscriptionList()
const [deletedSubscription, setDeletedSubscription] = useState<TriggerSubscription | null>(null)
const subscriptionCount = subscriptions?.length || 0
return (
<div className='w-[320px] p-1'>
{subscriptionCount > 0 && <div className='ml-7 mr-1.5 flex h-8 items-center justify-between'>
<div className='flex shrink-0 items-center gap-1'>
<span className='system-sm-semibold-uppercase text-text-secondary'>
{t('pluginTrigger.subscription.listNum', { num: subscriptionCount })}
</span>
<Tooltip popupContent={t('pluginTrigger.subscription.list.tip')} />
</div>
<CreateSubscriptionButton
buttonType={CreateButtonType.ICON_BUTTON}
shape='circle'
/>
</div>}
<div className='max-h-[320px] overflow-y-auto'>
{subscriptions?.map(subscription => (
<div
key={subscription.id}
className={cn(
'group flex w-full items-center justify-between rounded-lg p-1 text-left transition-colors',
'hover:bg-state-base-hover has-[.subscription-delete-btn:hover]:!bg-state-destructive-hover',
selectedId === subscription.id && 'bg-state-base-hover',
)}
>
<button
type='button'
className='flex flex-1 items-center text-left'
onClick={() => onSelect?.(subscription)}
>
<div className='flex items-center'>
{selectedId === subscription.id && (
<RiCheckLine className='mr-2 h-4 w-4 shrink-0 text-text-accent' />
)}
<RiWebhookLine className={cn('mr-1.5 h-3.5 w-3.5 text-text-secondary', selectedId !== subscription.id && 'ml-6')} />
<span className='system-md-regular leading-6 text-text-secondary'>
{subscription.name}
</span>
</div>
</button>
<ActionButton onClick={(e) => {
e.stopPropagation()
setDeletedSubscription(subscription)
}} className='subscription-delete-btn hidden shrink-0 text-text-tertiary hover:bg-state-destructive-hover hover:text-text-destructive group-hover:flex'>
<RiDeleteBinLine className='size-4' />
</ActionButton>
</div>
))}
</div>
{deletedSubscription && (
<DeleteConfirm
onClose={(deleted) => {
if (deleted)
onSelect?.({ id: '', name: '' })
setDeletedSubscription(null)
}}
isShow={!!deletedSubscription}
currentId={deletedSubscription.id}
currentName={deletedSubscription.name}
workflowsInUse={deletedSubscription.workflows_in_use}
/>
)}
</div>
)
}

View File

@@ -0,0 +1,85 @@
'use client'
import ActionButton from '@/app/components/base/action-button'
import Tooltip from '@/app/components/base/tooltip'
import type { TriggerSubscription } from '@/app/components/workflow/block-selector/types'
import cn from '@/utils/classnames'
import {
RiDeleteBinLine,
RiWebhookLine,
} from '@remixicon/react'
import { useBoolean } from 'ahooks'
import { useTranslation } from 'react-i18next'
import { DeleteConfirm } from './delete-confirm'
type Props = {
data: TriggerSubscription
}
const SubscriptionCard = ({ data }: Props) => {
const { t } = useTranslation()
const [isShowDeleteModal, {
setTrue: showDeleteModal,
setFalse: hideDeleteModal,
}] = useBoolean(false)
return (
<>
<div
className={cn(
'group relative cursor-pointer rounded-lg border-[0.5px] px-4 py-3 shadow-xs transition-all',
'border-components-panel-border-subtle bg-components-panel-on-panel-item-bg',
'hover:bg-components-panel-on-panel-item-bg-hover',
'has-[.subscription-delete-btn:hover]:!border-state-destructive-border has-[.subscription-delete-btn:hover]:!bg-state-destructive-hover',
)}
>
<div className='flex items-center justify-between'>
<div className='flex h-6 items-center gap-1'>
<RiWebhookLine className='h-4 w-4 text-text-secondary' />
<span className='system-md-semibold text-text-secondary'>
{data.name}
</span>
</div>
<ActionButton
onClick={showDeleteModal}
className='subscription-delete-btn hidden transition-colors hover:bg-state-destructive-hover hover:text-text-destructive group-hover:block'
>
<RiDeleteBinLine className='h-4 w-4' />
</ActionButton>
</div>
<div className='mt-1 flex items-center justify-between'>
<Tooltip
disabled={!data.endpoint}
popupContent={data.endpoint && (
<div className='max-w-[320px] break-all'>
{data.endpoint}
</div>
)}
position='left'
>
<div className='system-xs-regular flex-1 truncate text-text-tertiary'>
{data.endpoint}
</div>
</Tooltip>
<div className="mx-2 text-xs text-text-tertiary opacity-30">·</div>
<div className='system-xs-regular shrink-0 text-text-tertiary'>
{data.workflows_in_use > 0 ? t('pluginTrigger.subscription.list.item.usedByNum', { num: data.workflows_in_use }) : t('pluginTrigger.subscription.list.item.noUsed')}
</div>
</div>
</div>
{isShowDeleteModal && (
<DeleteConfirm
onClose={hideDeleteModal}
isShow={isShowDeleteModal}
currentId={data.id}
currentName={data.name}
workflowsInUse={data.workflows_in_use}
/>
)}
</>
)
}
export default SubscriptionCard

View File

@@ -0,0 +1,15 @@
import { useTriggerSubscriptions } from '@/service/use-triggers'
import { usePluginStore } from '../store'
export const useSubscriptionList = () => {
const detail = usePluginStore(state => state.detail)
const { data: subscriptions, isLoading, refetch } = useTriggerSubscriptions(detail?.provider || '')
return {
detail,
subscriptions,
isLoading,
refetch,
}
}

View File

@@ -0,0 +1,14 @@
import {
usePluginManifestInfo,
} from '@/service/use-plugins'
export const usePluginInstalledCheck = (providerName = '') => {
const pluginID = providerName?.split('/').splice(0, 2).join('/')
const { data: manifest } = usePluginManifestInfo(pluginID)
return {
inMarketPlace: !!manifest,
manifest: manifest?.data.plugin,
}
}

View File

@@ -0,0 +1,406 @@
'use client'
import type { FC } from 'react'
import React, { useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import Link from 'next/link'
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 ToolItem from '@/app/components/plugins/plugin-detail-panel/tool-selector/tool-item'
import ToolPicker from '@/app/components/workflow/block-selector/tool-picker'
import ToolForm from '@/app/components/workflow/nodes/tool/components/tool-form'
import Textarea from '@/app/components/base/textarea'
import Divider from '@/app/components/base/divider'
import TabSlider from '@/app/components/base/tab-slider-plain'
import ReasoningConfigForm from '@/app/components/plugins/plugin-detail-panel/tool-selector/reasoning-config-form'
import { generateFormValue, getPlainValue, getStructureValue, toolParametersToFormSchemas } from '@/app/components/tools/utils/to-form-schema'
import {
useAllBuiltInTools,
useAllCustomTools,
useAllMCPTools,
useAllWorkflowTools,
useInvalidateAllBuiltInTools,
} from '@/service/use-tools'
import { useInvalidateInstalledPluginList } from '@/service/use-plugins'
import { usePluginInstalledCheck } from '@/app/components/plugins/plugin-detail-panel/tool-selector/hooks'
import { CollectionType } from '@/app/components/tools/types'
import type { ToolDefaultValue, ToolValue } from '@/app/components/workflow/block-selector/types'
import type {
OffsetOptions,
Placement,
} from '@floating-ui/react'
import { MARKETPLACE_API_PREFIX } from '@/config'
import type { Node } from 'reactflow'
import type { NodeOutPutVar } from '@/app/components/workflow/types'
import cn from '@/utils/classnames'
import {
AuthCategory,
PluginAuthInAgent,
} from '@/app/components/plugins/plugin-auth'
import { ReadmeEntrance } from '../../readme-panel/entrance'
type Props = {
disabled?: boolean
placement?: Placement
offset?: OffsetOptions
scope?: string
value?: ToolValue
selectedTools?: ToolValue[]
onSelect: (tool: ToolValue) => void
onSelectMultiple?: (tool: ToolValue[]) => void
isEdit?: boolean
onDelete?: () => void
supportEnableSwitch?: boolean
supportAddCustomTool?: boolean
trigger?: React.ReactNode
controlledState?: boolean
onControlledStateChange?: (state: boolean) => void
panelShowState?: boolean
onPanelShowStateChange?: (state: boolean) => void
nodeOutputVars: NodeOutPutVar[],
availableNodes: Node[],
nodeId?: string,
canChooseMCPTool?: boolean,
}
const ToolSelector: FC<Props> = ({
value,
selectedTools,
isEdit,
disabled,
placement = 'left',
offset = 4,
onSelect,
onSelectMultiple,
onDelete,
scope,
supportEnableSwitch,
trigger,
controlledState,
onControlledStateChange,
panelShowState,
onPanelShowStateChange,
nodeOutputVars,
availableNodes,
nodeId = '',
canChooseMCPTool,
}) => {
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 { data: mcpTools } = useAllMCPTools()
const invalidateAllBuiltinTools = useInvalidateAllBuiltInTools()
const invalidateInstalledPluginList = useInvalidateInstalledPluginList()
// plugin info check
const { inMarketPlace, manifest } = usePluginInstalledCheck(value?.provider_name)
const currentProvider = useMemo(() => {
const mergedTools = [...(buildInTools || []), ...(customTools || []), ...(workflowTools || []), ...(mcpTools || [])]
return mergedTools.find((toolWithProvider) => {
return toolWithProvider.id === value?.provider_name
})
}, [value, buildInTools, customTools, workflowTools, mcpTools])
const [isShowChooseTool, setIsShowChooseTool] = useState(false)
const getToolValue = (tool: ToolDefaultValue) => {
const settingValues = generateFormValue(tool.params, toolParametersToFormSchemas(tool.paramSchemas.filter(param => param.form !== 'llm') as any))
const paramValues = generateFormValue(tool.params, toolParametersToFormSchemas(tool.paramSchemas.filter(param => param.form === 'llm') as any), true)
return {
provider_name: tool.provider_id,
provider_show_name: tool.provider_name,
type: tool.provider_type,
tool_name: tool.tool_name,
tool_label: tool.tool_label,
tool_description: tool.tool_description,
settings: settingValues,
parameters: paramValues,
enabled: tool.is_team_authorization,
extra: {
description: tool.tool_description,
},
schemas: tool.paramSchemas,
}
}
const handleSelectTool = (tool: ToolDefaultValue) => {
const toolValue = getToolValue(tool)
onSelect(toolValue)
// setIsShowChooseTool(false)
}
const handleSelectMultipleTool = (tool: ToolDefaultValue[]) => {
const toolValues = tool.map(item => getToolValue(item))
onSelectMultiple?.(toolValues)
}
const handleDescriptionChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
onSelect({
...value,
extra: {
...value?.extra,
description: e.target.value || '',
},
} as any)
}
// tool settings & params
const currentToolSettings = useMemo(() => {
if (!currentProvider) return []
return currentProvider.tools.find(tool => tool.name === value?.tool_name)?.parameters.filter(param => param.form !== 'llm') || []
}, [currentProvider, value])
const currentToolParams = useMemo(() => {
if (!currentProvider) return []
return currentProvider.tools.find(tool => tool.name === value?.tool_name)?.parameters.filter(param => param.form === 'llm') || []
}, [currentProvider, value])
const [currType, setCurrType] = useState('settings')
const showTabSlider = currentToolSettings.length > 0 && currentToolParams.length > 0
const userSettingsOnly = currentToolSettings.length > 0 && !currentToolParams.length
const reasoningConfigOnly = currentToolParams.length > 0 && !currentToolSettings.length
const settingsFormSchemas = useMemo(() => toolParametersToFormSchemas(currentToolSettings), [currentToolSettings])
const paramsFormSchemas = useMemo(() => toolParametersToFormSchemas(currentToolParams), [currentToolParams])
const handleSettingsFormChange = (v: Record<string, any>) => {
const newValue = getStructureValue(v)
const toolValue = {
...value,
settings: newValue,
}
onSelect(toolValue as any)
}
const handleParamsFormChange = (v: Record<string, any>) => {
const toolValue = {
...value,
parameters: v,
}
onSelect(toolValue as any)
}
const handleEnabledChange = (state: boolean) => {
onSelect({
...value,
enabled: state,
} as any)
}
// install from marketplace
const currentTool = useMemo(() => {
return currentProvider?.tools.find(tool => tool.name === value?.tool_name)
}, [currentProvider?.tools, value?.tool_name])
const manifestIcon = useMemo(() => {
if (!manifest)
return ''
return `${MARKETPLACE_API_PREFIX}/plugins/${(manifest as any).plugin_id}/icon`
}, [manifest])
const handleInstall = async () => {
invalidateAllBuiltinTools()
invalidateInstalledPluginList()
}
const handleAuthorizationItemClick = (id: string) => {
onSelect({
...value,
credential_id: id,
} as any)
}
return (
<>
<PortalToFollowElem
placement={placement}
offset={offset}
open={trigger ? controlledState : isShow}
onOpenChange={trigger ? onControlledStateChange : onShowChange}
>
<PortalToFollowElemTrigger
className='w-full'
onClick={() => {
if (!currentProvider || !currentTool) return
handleTriggerClick()
}}
>
{trigger}
{!trigger && !value?.provider_name && (
<ToolTrigger
isConfigure
open={isShow}
value={value}
provider={currentProvider}
/>
)}
{!trigger && value?.provider_name && (
<ToolItem
open={isShow}
icon={currentProvider?.icon || manifestIcon}
isMCPTool={currentProvider?.type === CollectionType.mcp}
providerName={value.provider_name}
providerShowName={value.provider_show_name}
toolLabel={value.tool_label || value.tool_name}
showSwitch={supportEnableSwitch}
switchValue={value.enabled}
onSwitchChange={handleEnabledChange}
onDelete={onDelete}
noAuth={currentProvider && currentTool && !currentProvider.is_team_authorization}
uninstalled={!currentProvider && inMarketPlace}
versionMismatch={currentProvider && inMarketPlace && !currentTool}
installInfo={manifest?.latest_package_identifier}
onInstall={() => handleInstall()}
isError={(!currentProvider || !currentTool) && !inMarketPlace}
errorTip={
<div className='max-w-[240px] space-y-1 text-xs'>
<h3 className='font-semibold text-text-primary'>{currentTool ? t('plugin.detailPanel.toolSelector.uninstalledTitle') : t('plugin.detailPanel.toolSelector.unsupportedTitle')}</h3>
<p className='tracking-tight text-text-secondary'>{currentTool ? t('plugin.detailPanel.toolSelector.uninstalledContent') : t('plugin.detailPanel.toolSelector.unsupportedContent')}</p>
<p>
<Link href={'/plugins'} className='tracking-tight text-text-accent'>{t('plugin.detailPanel.toolSelector.uninstalledLink')}</Link>
</p>
</div>
}
canChooseMCPTool={canChooseMCPTool}
/>
)}
</PortalToFollowElemTrigger>
<PortalToFollowElemContent className='z-10'>
<div className={cn('relative max-h-[642px] min-h-20 w-[361px] rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur pb-4 shadow-lg backdrop-blur-sm', 'overflow-y-auto pb-2')}>
<>
<div className='system-xl-semibold px-4 pb-1 pt-3.5 text-text-primary'>{t(`plugin.detailPanel.toolSelector.${isEdit ? 'toolSetting' : 'title'}`)}</div>
{/* base form */}
<div className='flex flex-col gap-3 px-4 py-2'>
<div className='flex flex-col gap-1'>
<div className='system-sm-semibold flex h-6 items-center justify-between text-text-secondary'>
{t('plugin.detailPanel.toolSelector.toolLabel')}
<ReadmeEntrance pluginDetail={currentProvider as any} showShortTip className='pb-0' />
</div>
<ToolPicker
placement='bottom'
offset={offset}
trigger={
<ToolTrigger
open={panelShowState || isShowChooseTool}
value={value}
provider={currentProvider}
/>
}
isShow={panelShowState || isShowChooseTool}
onShowChange={trigger ? onPanelShowStateChange as any : setIsShowChooseTool}
disabled={false}
supportAddCustomTool
onSelect={handleSelectTool}
onSelectMultiple={handleSelectMultipleTool}
scope={scope}
selectedTools={selectedTools}
canChooseMCPTool={canChooseMCPTool}
/>
</div>
<div className='flex flex-col gap-1'>
<div className='system-sm-semibold flex h-6 items-center text-text-secondary'>{t('plugin.detailPanel.toolSelector.descriptionLabel')}</div>
<Textarea
className='resize-none'
placeholder={t('plugin.detailPanel.toolSelector.descriptionPlaceholder')}
value={value?.extra?.description || ''}
onChange={handleDescriptionChange}
disabled={!value?.provider_name}
/>
</div>
</div>
{/* authorization */}
{currentProvider && currentProvider.type === CollectionType.builtIn && currentProvider.allow_delete && (
<>
<Divider className='my-1 w-full' />
<div className='px-4 py-2'>
<PluginAuthInAgent
pluginPayload={{
provider: currentProvider.name,
category: AuthCategory.tool,
providerType: currentProvider.type,
detail: currentProvider as any,
}}
credentialId={value?.credential_id}
onAuthorizationItemClick={handleAuthorizationItemClick}
/>
</div>
</>
)}
{/* tool settings */}
{(currentToolSettings.length > 0 || currentToolParams.length > 0) && currentProvider?.is_team_authorization && (
<>
<Divider className='my-1 w-full' />
{/* tabs */}
{nodeId && showTabSlider && (
<TabSlider
className='mt-1 shrink-0 px-4'
itemClassName='py-3'
noBorderBottom
smallItem
value={currType}
onChange={(value) => {
setCurrType(value)
}}
options={[
{ value: 'settings', text: t('plugin.detailPanel.toolSelector.settings')! },
{ value: 'params', text: t('plugin.detailPanel.toolSelector.params')! },
]}
/>
)}
{nodeId && showTabSlider && currType === 'params' && (
<div className='px-4 py-2'>
<div className='system-xs-regular text-text-tertiary'>{t('plugin.detailPanel.toolSelector.paramsTip1')}</div>
<div className='system-xs-regular text-text-tertiary'>{t('plugin.detailPanel.toolSelector.paramsTip2')}</div>
</div>
)}
{/* user settings only */}
{userSettingsOnly && (
<div className='p-4 pb-1'>
<div className='system-sm-semibold-uppercase text-text-primary'>{t('plugin.detailPanel.toolSelector.settings')}</div>
</div>
)}
{/* reasoning config only */}
{nodeId && reasoningConfigOnly && (
<div className='mb-1 p-4 pb-1'>
<div className='system-sm-semibold-uppercase text-text-primary'>{t('plugin.detailPanel.toolSelector.params')}</div>
<div className='pb-1'>
<div className='system-xs-regular text-text-tertiary'>{t('plugin.detailPanel.toolSelector.paramsTip1')}</div>
<div className='system-xs-regular text-text-tertiary'>{t('plugin.detailPanel.toolSelector.paramsTip2')}</div>
</div>
</div>
)}
{/* user settings form */}
{(currType === 'settings' || userSettingsOnly) && (
<div className='px-4 py-2'>
<ToolForm
inPanel
readOnly={false}
nodeId={nodeId}
schema={settingsFormSchemas as any}
value={getPlainValue(value?.settings || {})}
onChange={handleSettingsFormChange}
/>
</div>
)}
{/* reasoning config form */}
{nodeId && (currType === 'params' || reasoningConfigOnly) && (
<ReasoningConfigForm
value={value?.parameters || {}}
onChange={handleParamsFormChange}
schemas={paramsFormSchemas as any}
nodeOutputVars={nodeOutputVars}
availableNodes={availableNodes}
nodeId={nodeId}
/>
)}
</>
)}
</>
</div>
</PortalToFollowElemContent>
</PortalToFollowElem>
</>
)
}
export default React.memo(ToolSelector)

View File

@@ -0,0 +1,367 @@
import { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { produce } from 'immer'
import {
RiArrowRightUpLine,
RiBracesLine,
} from '@remixicon/react'
import Tooltip from '@/app/components/base/tooltip'
import Switch from '@/app/components/base/switch'
import MixedVariableTextInput from '@/app/components/workflow/nodes/tool/components/mixed-variable-text-input'
import Input from '@/app/components/base/input'
import FormInputTypeSwitch from '@/app/components/workflow/nodes/_base/components/form-input-type-switch'
import FormInputBoolean from '@/app/components/workflow/nodes/_base/components/form-input-boolean'
import { SimpleSelect } from '@/app/components/base/select'
import CodeEditor from '@/app/components/workflow/nodes/_base/components/editor/code-editor'
import VarReferencePicker from '@/app/components/workflow/nodes/_base/components/variable/var-reference-picker'
import AppSelector from '@/app/components/plugins/plugin-detail-panel/app-selector'
import ModelParameterModal from '@/app/components/plugins/plugin-detail-panel/model-selector'
import { CodeLanguage } from '@/app/components/workflow/nodes/code/types'
import { useLanguage } from '@/app/components/header/account-setting/model-provider-page/hooks'
import { FormTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
import type { Node } from 'reactflow'
import type {
NodeOutPutVar,
ValueSelector,
} from '@/app/components/workflow/types'
import type { ToolVarInputs } from '@/app/components/workflow/nodes/tool/types'
import { VarType as VarKindType } from '@/app/components/workflow/nodes/tool/types'
import { VarType } from '@/app/components/workflow/types'
import cn from '@/utils/classnames'
import { useBoolean } from 'ahooks'
import SchemaModal from './schema-modal'
import type { SchemaRoot } from '@/app/components/workflow/nodes/llm/types'
type Props = {
value: Record<string, any>
onChange: (val: Record<string, any>) => void
schemas: any[]
nodeOutputVars: NodeOutPutVar[],
availableNodes: Node[],
nodeId: string
}
const ReasoningConfigForm: React.FC<Props> = ({
value,
onChange,
schemas,
nodeOutputVars,
availableNodes,
nodeId,
}) => {
const { t } = useTranslation()
const language = useLanguage()
const getVarKindType = (type: FormTypeEnum) => {
if (type === FormTypeEnum.file || type === FormTypeEnum.files)
return VarKindType.variable
if (type === FormTypeEnum.select || type === FormTypeEnum.checkbox || type === FormTypeEnum.textNumber || type === FormTypeEnum.array || type === FormTypeEnum.object)
return VarKindType.constant
if (type === FormTypeEnum.textInput || type === FormTypeEnum.secretInput)
return VarKindType.mixed
}
const handleAutomatic = (key: string, val: any, type: FormTypeEnum) => {
onChange({
...value,
[key]: {
value: val ? null : { type: getVarKindType(type), value: null },
auto: val ? 1 : 0,
},
})
}
const handleTypeChange = useCallback((variable: string, defaultValue: any) => {
return (newType: VarKindType) => {
const res = produce(value, (draft: ToolVarInputs) => {
draft[variable].value = {
type: newType,
value: newType === VarKindType.variable ? '' : defaultValue,
}
})
onChange(res)
}
}, [onChange, value])
const handleValueChange = useCallback((variable: string, varType: FormTypeEnum) => {
return (newValue: any) => {
const res = produce(value, (draft: ToolVarInputs) => {
draft[variable].value = {
type: getVarKindType(varType),
value: newValue,
}
})
onChange(res)
}
}, [onChange, value])
const handleAppChange = useCallback((variable: string) => {
return (app: {
app_id: string
inputs: Record<string, any>
files?: any[]
}) => {
const newValue = produce(value, (draft: ToolVarInputs) => {
draft[variable].value = app as any
})
onChange(newValue)
}
}, [onChange, value])
const handleModelChange = useCallback((variable: string) => {
return (model: any) => {
const newValue = produce(value, (draft: ToolVarInputs) => {
draft[variable].value = {
...draft[variable].value,
...model,
} as any
})
onChange(newValue)
}
}, [onChange, value])
const handleVariableSelectorChange = useCallback((variable: string) => {
return (newValue: ValueSelector | string) => {
const res = produce(value, (draft: ToolVarInputs) => {
draft[variable].value = {
type: VarKindType.variable,
value: newValue,
}
})
onChange(res)
}
}, [onChange, value])
const [isShowSchema, {
setTrue: showSchema,
setFalse: hideSchema,
}] = useBoolean(false)
const [schema, setSchema] = useState<SchemaRoot | null>(null)
const [schemaRootName, setSchemaRootName] = useState<string>('')
const renderField = (schema: any, showSchema: (schema: SchemaRoot, rootName: string) => void) => {
const {
default: defaultValue,
variable,
label,
required,
tooltip,
type,
scope,
url,
input_schema,
placeholder,
options,
} = schema
const auto = value[variable]?.auto
const tooltipContent = (tooltip && (
<Tooltip
popupContent={<div className='w-[200px]'>
{tooltip[language] || tooltip.en_US}
</div>}
triggerClassName='ml-0.5 w-4 h-4'
asChild={false} />
))
const varInput = value[variable].value
const isString = type === FormTypeEnum.textInput || type === FormTypeEnum.secretInput
const isNumber = type === FormTypeEnum.textNumber
const isObject = type === FormTypeEnum.object
const isArray = type === FormTypeEnum.array
const isShowJSONEditor = isObject || isArray
const isFile = type === FormTypeEnum.file || type === FormTypeEnum.files
const isBoolean = type === FormTypeEnum.checkbox
const isSelect = type === FormTypeEnum.select
const isAppSelector = type === FormTypeEnum.appSelector
const isModelSelector = type === FormTypeEnum.modelSelector
const showTypeSwitch = isNumber || isObject || isArray
const isConstant = varInput?.type === VarKindType.constant || !varInput?.type
const showVariableSelector = isFile || varInput?.type === VarKindType.variable
const targetVarType = () => {
if (isString)
return VarType.string
else if (isNumber)
return VarType.number
else if (type === FormTypeEnum.files)
return VarType.arrayFile
else if (type === FormTypeEnum.file)
return VarType.file
else if (isBoolean)
return VarType.boolean
else if (isObject)
return VarType.object
else if (isArray)
return VarType.arrayObject
else
return VarType.string
}
const getFilterVar = () => {
if (isNumber)
return (varPayload: any) => varPayload.type === VarType.number
else if (isString)
return (varPayload: any) => [VarType.string, VarType.number, VarType.secret].includes(varPayload.type)
else if (isFile)
return (varPayload: any) => [VarType.file, VarType.arrayFile].includes(varPayload.type)
else if (isBoolean)
return (varPayload: any) => varPayload.type === VarType.boolean
else if (isObject)
return (varPayload: any) => varPayload.type === VarType.object
else if (isArray)
return (varPayload: any) => [VarType.array, VarType.arrayString, VarType.arrayNumber, VarType.arrayObject].includes(varPayload.type)
return undefined
}
return (
<div key={variable} className='space-y-0.5'>
<div className='system-sm-semibold flex items-center justify-between py-2 text-text-secondary'>
<div className='flex items-center'>
<span className={cn('code-sm-semibold max-w-[140px] truncate text-text-secondary')} title={label[language] || label.en_US}>{label[language] || label.en_US}</span>
{required && (
<span className='ml-1 text-red-500'>*</span>
)}
{tooltipContent}
<span className='system-xs-regular mx-1 text-text-quaternary'>·</span>
<span className='system-xs-regular text-text-tertiary'>{targetVarType()}</span>
{isShowJSONEditor && (
<Tooltip
popupContent={<div className='system-xs-medium text-text-secondary'>
{t('workflow.nodes.agent.clickToViewParameterSchema')}
</div>}
asChild={false}>
<div
className='ml-0.5 cursor-pointer rounded-[4px] p-px text-text-tertiary hover:bg-state-base-hover hover:text-text-secondary'
onClick={() => showSchema(input_schema as SchemaRoot, label[language] || label.en_US)}
>
<RiBracesLine className='size-3.5'/>
</div>
</Tooltip>
)}
</div>
<div className='flex cursor-pointer items-center gap-1 rounded-[6px] border border-divider-subtle bg-background-default-lighter px-2 py-1 hover:bg-state-base-hover' onClick={() => handleAutomatic(variable, !auto, type)}>
<span className='system-xs-medium text-text-secondary'>{t('plugin.detailPanel.toolSelector.auto')}</span>
<Switch
size='xs'
defaultValue={!!auto}
onChange={val => handleAutomatic(variable, val, type)}
/>
</div>
</div>
{auto === 0 && (
<div className={cn('gap-1', !(isShowJSONEditor && isConstant) && 'flex')}>
{showTypeSwitch && (
<FormInputTypeSwitch value={varInput?.type || VarKindType.constant} onChange={handleTypeChange(variable, defaultValue)}/>
)}
{isString && (
<MixedVariableTextInput
value={varInput?.value as string || ''}
onChange={handleValueChange(variable, type)}
nodesOutputVars={nodeOutputVars}
availableNodes={availableNodes}
/>
)}
{isNumber && isConstant && (
<Input
className='h-8 grow'
type='number'
value={varInput?.value || ''}
onChange={e => handleValueChange(variable, type)(e.target.value)}
placeholder={placeholder?.[language] || placeholder?.en_US}
/>
)}
{isBoolean && (
<FormInputBoolean
value={varInput?.value as boolean}
onChange={handleValueChange(variable, type)}
/>
)}
{isSelect && (
<SimpleSelect
wrapperClassName='h-8 grow'
defaultValue={varInput?.value}
items={options.filter((option: { show_on: any[] }) => {
if (option.show_on.length)
return option.show_on.every(showOnItem => value[showOnItem.variable] === showOnItem.value)
return true
}).map((option: { value: any; label: { [x: string]: any; en_US: any } }) => ({ value: option.value, name: option.label[language] || option.label.en_US }))}
onSelect={item => handleValueChange(variable, type)(item.value as string)}
placeholder={placeholder?.[language] || placeholder?.en_US}
/>
)}
{isShowJSONEditor && isConstant && (
<div className='mt-1 w-full'>
<CodeEditor
title='JSON'
value={varInput?.value as any}
isExpand
isInNode
height={100}
language={CodeLanguage.json}
onChange={handleValueChange(variable, type)}
className='w-full'
placeholder={<div className='whitespace-pre'>{placeholder?.[language] || placeholder?.en_US}</div>}
/>
</div>
)}
{isAppSelector && (
<AppSelector
disabled={false}
scope={scope || 'all'}
value={varInput as any}
onSelect={handleAppChange(variable)}
/>
)}
{isModelSelector && (
<ModelParameterModal
popupClassName='!w-[387px]'
isAdvancedMode
isInWorkflow
value={varInput}
setModel={handleModelChange(variable)}
scope={scope}
/>
)}
{showVariableSelector && (
<VarReferencePicker
zIndex={1001}
className='h-8 grow'
readonly={false}
isShowNodeName
nodeId={nodeId}
value={varInput?.value || []}
onChange={handleVariableSelectorChange(variable)}
filterVar={getFilterVar()}
schema={schema}
valueTypePlaceHolder={targetVarType()}
/>
)}
</div>
)}
{url && (
<a
href={url}
target='_blank' rel='noopener noreferrer'
className='inline-flex items-center text-xs text-text-accent'
>
{t('tools.howToGet')}
<RiArrowRightUpLine className='ml-1 h-3 w-3' />
</a>
)}
</div>
)
}
return (
<div className='space-y-3 px-4 py-2'>
{!isShowSchema && schemas.map(schema => renderField(schema, (s: SchemaRoot, rootName: string) => {
setSchema(s)
setSchemaRootName(rootName)
showSchema()
}))}
{isShowSchema && (
<SchemaModal
isShow={isShowSchema}
schema={schema!}
rootName={schemaRootName}
onClose={hideSchema}
/>
)}
</div>
)
}
export default ReasoningConfigForm

View File

@@ -0,0 +1,59 @@
'use client'
import type { FC } from 'react'
import React from 'react'
import Modal from '@/app/components/base/modal'
import VisualEditor from '@/app/components/workflow/nodes/llm/components/json-schema-config-modal/visual-editor'
import type { SchemaRoot } from '@/app/components/workflow/nodes/llm/types'
import { MittProvider, VisualEditorContextProvider } from '@/app/components/workflow/nodes/llm/components/json-schema-config-modal/visual-editor/context'
import { useTranslation } from 'react-i18next'
import { RiCloseLine } from '@remixicon/react'
type Props = {
isShow: boolean
schema: SchemaRoot
rootName: string
onClose: () => void
}
const SchemaModal: FC<Props> = ({
isShow,
schema,
rootName,
onClose,
}) => {
const { t } = useTranslation()
return (
<Modal
isShow={isShow}
onClose={onClose}
className='max-w-[960px] p-0'
wrapperClassName='z-[9999]'
>
<div className='pb-6'>
{/* Header */}
<div className='relative flex p-6 pb-3 pr-14'>
<div className='title-2xl-semi-bold grow truncate text-text-primary'>
{t('workflow.nodes.agent.parameterSchema')}
</div>
<div className='absolute right-5 top-5 flex h-8 w-8 items-center justify-center p-1.5' onClick={onClose}>
<RiCloseLine className='h-[18px] w-[18px] text-text-tertiary' />
</div>
</div>
{/* Content */}
<div className='flex max-h-[700px] overflow-y-auto px-6 py-2'>
<MittProvider>
<VisualEditorContextProvider>
<VisualEditor
className='w-full'
schema={schema}
rootName={rootName}
readOnly
></VisualEditor>
</VisualEditorContextProvider>
</MittProvider>
</div>
</div>
</Modal>
)
}
export default React.memo(SchemaModal)

View File

@@ -0,0 +1,97 @@
'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 { useRenderI18nObject } from '@/hooks/use-i18n'
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 getValueFromI18nObject = useRenderI18nObject()
const { t } = useTranslation()
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: getValueFromI18nObject(field.label) }) })
return
}
}
onSaved(tempCredential)
}
return (
<>
{!credentialSchema
? <div className='pt-3'><Loading type='app' /></div>
: (
<>
<div className='max-h-[464px] overflow-y-auto px-4'>
<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-text-accent'
>
{t('tools.howToGet')}
<RiArrowRightUpLine className='ml-1 h-3 w-3' />
</a>)
: null}
/>
</div>
<div className={cn('mt-1 flex justify-end px-4')} >
<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>
</>
)
}
</>
)
}
export default React.memo(ToolCredentialForm)

View File

@@ -0,0 +1,180 @@
'use client'
import React, { useState } from 'react'
import { useTranslation } from 'react-i18next'
import {
RiDeleteBinLine,
RiEqualizer2Line,
RiErrorWarningFill,
} from '@remixicon/react'
import { Group } from '@/app/components/base/icons/src/vender/other'
import AppIcon from '@/app/components/base/app-icon'
import Switch from '@/app/components/base/switch'
import Button from '@/app/components/base/button'
import Indicator from '@/app/components/header/indicator'
import ActionButton from '@/app/components/base/action-button'
import Tooltip from '@/app/components/base/tooltip'
import { ToolTipContent } from '@/app/components/base/tooltip/content'
import { InstallPluginButton } from '@/app/components/workflow/nodes/_base/components/install-plugin-button'
import { SwitchPluginVersion } from '@/app/components/workflow/nodes/_base/components/switch-plugin-version'
import cn from '@/utils/classnames'
import McpToolNotSupportTooltip from '@/app/components/workflow/nodes/_base/components/mcp-tool-not-support-tooltip'
type Props = {
icon?: any
providerName?: string
isMCPTool?: boolean
providerShowName?: string
toolLabel?: string
showSwitch?: boolean
switchValue?: boolean
onSwitchChange?: (value: boolean) => void
onDelete?: () => void
noAuth?: boolean
isError?: boolean
errorTip?: any
uninstalled?: boolean
installInfo?: string
onInstall?: () => void
versionMismatch?: boolean
open: boolean
authRemoved?: boolean
canChooseMCPTool?: boolean,
}
const ToolItem = ({
open,
icon,
isMCPTool,
providerShowName,
providerName,
toolLabel,
showSwitch,
switchValue,
onSwitchChange,
onDelete,
noAuth,
uninstalled,
installInfo,
onInstall,
isError,
errorTip,
versionMismatch,
authRemoved,
canChooseMCPTool,
}: Props) => {
const { t } = useTranslation()
const providerNameText = isMCPTool ? providerShowName : providerName?.split('/').pop()
const isTransparent = uninstalled || versionMismatch || isError
const [isDeleting, setIsDeleting] = useState(false)
const isShowCanNotChooseMCPTip = isMCPTool && !canChooseMCPTool
return (
<div className={cn(
'group flex cursor-default items-center gap-1 rounded-lg border-[0.5px] border-components-panel-border-subtle bg-components-panel-on-panel-item-bg p-1.5 pr-2 shadow-xs hover:bg-components-panel-on-panel-item-bg-hover hover:shadow-sm',
open && 'bg-components-panel-on-panel-item-bg-hover shadow-sm',
isDeleting && 'border-state-destructive-border shadow-xs hover:bg-state-destructive-hover',
)}>
{icon && (
<div className={cn('shrink-0', isTransparent && 'opacity-50', isShowCanNotChooseMCPTip && 'opacity-30')}>
{typeof icon === 'string' && <div className='h-7 w-7 rounded-lg border-[0.5px] border-components-panel-border-subtle bg-background-default-dodge bg-cover bg-center' style={{ backgroundImage: `url(${icon})` }} />}
{typeof icon !== 'string' && <AppIcon className='h-7 w-7 rounded-lg border-[0.5px] border-components-panel-border-subtle bg-background-default-dodge' size='xs' icon={icon?.content} background={icon?.background} />}
</div>
)}
{!icon && (
<div className={cn(
'flex h-7 w-7 items-center justify-center rounded-md border-[0.5px] border-components-panel-border-subtle bg-background-default-subtle',
isTransparent && 'opacity-50', isShowCanNotChooseMCPTip && 'opacity-30',
)}>
<div className='flex h-5 w-5 items-center justify-center opacity-35'>
<Group className='text-text-tertiary' />
</div>
</div>
)}
<div className={cn('grow truncate pl-0.5', isTransparent && 'opacity-50', isShowCanNotChooseMCPTip && 'opacity-30')}>
<div className='system-2xs-medium-uppercase text-text-tertiary'>{providerNameText}</div>
<div className='system-xs-medium text-text-secondary'>{toolLabel}</div>
</div>
<div className='hidden items-center gap-1 group-hover:flex'>
{!noAuth && !isError && !uninstalled && !versionMismatch && !isShowCanNotChooseMCPTip && (
<ActionButton>
<RiEqualizer2Line className='h-4 w-4' />
</ActionButton>
)}
<div
className='cursor-pointer rounded-md p-1 text-text-tertiary hover:text-text-destructive'
onClick={(e) => {
e.stopPropagation()
onDelete?.()
}}
onMouseOver={() => setIsDeleting(true)}
onMouseLeave={() => setIsDeleting(false)}
>
<RiDeleteBinLine className='h-4 w-4' />
</div>
</div>
{!isError && !uninstalled && !noAuth && !versionMismatch && !isShowCanNotChooseMCPTip && showSwitch && (
<div className='mr-1' onClick={e => e.stopPropagation()}>
<Switch
size='md'
defaultValue={switchValue}
onChange={onSwitchChange}
/>
</div>
)}
{isShowCanNotChooseMCPTip && (
<McpToolNotSupportTooltip />
)}
{!isError && !uninstalled && !versionMismatch && noAuth && (
<Button variant='secondary' size='small'>
{t('tools.notAuthorized')}
<Indicator className='ml-2' color='orange' />
</Button>
)}
{!isError && !uninstalled && !versionMismatch && authRemoved && (
<Button variant='secondary' size='small'>
{t('plugin.auth.authRemoved')}
<Indicator className='ml-2' color='red' />
</Button>
)}
{!isError && !uninstalled && versionMismatch && installInfo && (
<div onClick={e => e.stopPropagation()}>
<SwitchPluginVersion
className='-mt-1'
uniqueIdentifier={installInfo}
tooltip={
<ToolTipContent
title={t('plugin.detailPanel.toolSelector.unsupportedTitle')}
>
{`${t('plugin.detailPanel.toolSelector.unsupportedContent')} ${t('plugin.detailPanel.toolSelector.unsupportedContent2')}`}
</ToolTipContent>
}
onChange={() => {
onInstall?.()
}}
/>
</div>
)}
{!isError && uninstalled && installInfo && (
<InstallPluginButton
onClick={e => e.stopPropagation()}
size={'small'}
uniqueIdentifier={installInfo}
onSuccess={() => {
onInstall?.()
}}
/>
)}
{isError && (
<Tooltip
popupContent={errorTip}
>
<div>
<RiErrorWarningFill className='h-4 w-4 text-text-destructive' />
</div>
</Tooltip>
)}
</div>
)
}
export default ToolItem

View File

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

View File

@@ -0,0 +1,157 @@
'use client'
import ActionButton from '@/app/components/base/action-button'
import Divider from '@/app/components/base/divider'
import Drawer from '@/app/components/base/drawer'
import { useLanguage } from '@/app/components/header/account-setting/model-provider-page/hooks'
import Icon from '@/app/components/plugins/card/base/card-icon'
import Description from '@/app/components/plugins/card/base/description'
import OrgInfo from '@/app/components/plugins/card/base/org-info'
import { triggerEventParametersToFormSchemas } from '@/app/components/tools/utils/to-form-schema'
import type { TriggerProviderApiEntity } from '@/app/components/workflow/block-selector/types'
import Field from '@/app/components/workflow/nodes/_base/components/variable/object-child-tree-panel/show/field'
import cn from '@/utils/classnames'
import {
RiArrowLeftLine,
RiCloseLine,
} from '@remixicon/react'
import type { TFunction } from 'i18next'
import type { FC } from 'react'
import { useTranslation } from 'react-i18next'
import type { TriggerEvent } from '@/app/components/plugins/types'
type EventDetailDrawerProps = {
eventInfo: TriggerEvent
providerInfo: TriggerProviderApiEntity
onClose: () => void
}
const getType = (type: string, t: TFunction) => {
if (type === 'number-input')
return t('tools.setBuiltInTools.number')
if (type === 'text-input')
return t('tools.setBuiltInTools.string')
if (type === 'checkbox')
return 'boolean'
if (type === 'file')
return t('tools.setBuiltInTools.file')
return type
}
// Convert JSON Schema to StructuredOutput format
const convertSchemaToField = (schema: any): any => {
const field: any = {
type: Array.isArray(schema.type) ? schema.type[0] : schema.type || 'string',
}
if (schema.description)
field.description = schema.description
if (schema.properties) {
field.properties = Object.entries(schema.properties).reduce((acc, [key, value]: [string, any]) => ({
...acc,
[key]: convertSchemaToField(value),
}), {})
}
if (schema.required)
field.required = schema.required
if (schema.items)
field.items = convertSchemaToField(schema.items)
if (schema.enum)
field.enum = schema.enum
return field
}
export const EventDetailDrawer: FC<EventDetailDrawerProps> = (props) => {
const { eventInfo, providerInfo, onClose } = props
const language = useLanguage()
const { t } = useTranslation()
const parametersSchemas = triggerEventParametersToFormSchemas(eventInfo.parameters)
// Convert output_schema properties to array for direct rendering
const outputFields = eventInfo.output_schema?.properties
? Object.entries(eventInfo.output_schema.properties).map(([name, schema]: [string, any]) => ({
name,
field: convertSchemaToField(schema),
required: eventInfo.output_schema.required?.includes(name) || false,
}))
: []
return (
<Drawer
isOpen
clickOutsideNotOpen={false}
onClose={onClose}
footer={null}
mask={false}
positionCenter={false}
panelClassName={cn('mb-2 mr-2 mt-[64px] !w-[420px] !max-w-[420px] justify-start rounded-2xl border-[0.5px] border-components-panel-border !bg-components-panel-bg !p-0 shadow-xl')}
>
<div className='relative border-b border-divider-subtle p-4 pb-3'>
<div className='absolute right-3 top-3'>
<ActionButton onClick={onClose}>
<RiCloseLine className='h-4 w-4' />
</ActionButton>
</div>
<div
className='system-xs-semibold-uppercase mb-2 flex cursor-pointer items-center gap-1 text-text-accent-secondary'
onClick={onClose}
>
<RiArrowLeftLine className='h-4 w-4' />
{t('plugin.detailPanel.operation.back')}
</div>
<div className='flex items-center gap-1'>
<Icon size='tiny' className='h-6 w-6' src={providerInfo.icon!} />
<OrgInfo
packageNameClassName='w-auto'
orgName={providerInfo.author}
packageName={providerInfo.name.split('/').pop() || ''}
/>
</div>
<div className='system-md-semibold mt-1 text-text-primary'>{eventInfo?.identity?.label[language]}</div>
<Description className='mb-2 mt-3 h-auto' text={eventInfo.description[language]} descriptionLineRows={2}></Description>
</div>
<div className='flex h-full flex-col gap-2 overflow-y-auto px-4 pb-2 pt-4'>
<div className='system-sm-semibold-uppercase text-text-secondary'>{t('tools.setBuiltInTools.parameters')}</div>
{parametersSchemas.length > 0 ? (
parametersSchemas.map((item, index) => (
<div key={index} className='py-1'>
<div className='flex items-center gap-2'>
<div className='code-sm-semibold text-text-secondary'>{item.label[language]}</div>
<div className='system-xs-regular text-text-tertiary'>
{getType(item.type, t)}
</div>
{item.required && (
<div className='system-xs-medium text-text-warning-secondary'>{t('tools.setBuiltInTools.required')}</div>
)}
</div>
{item.description && (
<div className='system-xs-regular mt-0.5 text-text-tertiary'>
{item.description?.[language]}
</div>
)}
</div>
))
) : <div className='system-xs-regular text-text-tertiary'>{t('pluginTrigger.events.item.noParameters')}</div>}
<Divider className='mb-2 mt-1 h-px' />
<div className='flex flex-col gap-2'>
<div className='system-sm-semibold-uppercase text-text-secondary'>{t('pluginTrigger.events.output')}</div>
<div className='relative left-[-7px]'>
{outputFields.map(item => (
<Field
key={item.name}
name={item.name}
payload={item.field}
required={item.required}
rootClassName='code-sm-semibold text-text-secondary'
/>
))}
</div>
</div>
</div>
</Drawer>
)
}

View File

@@ -0,0 +1,71 @@
import { useLanguage } from '@/app/components/header/account-setting/model-provider-page/hooks'
import type { TriggerEvent } from '@/app/components/plugins/types'
import type { TriggerProviderApiEntity } from '@/app/components/workflow/block-selector/types'
import { useTriggerProviderInfo } from '@/service/use-triggers'
import cn from '@/utils/classnames'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { usePluginStore } from '../store'
import { EventDetailDrawer } from './event-detail-drawer'
type TriggerEventCardProps = {
eventInfo: TriggerEvent
providerInfo: TriggerProviderApiEntity
}
const TriggerEventCard = ({ eventInfo, providerInfo }: TriggerEventCardProps) => {
const { identity, description } = eventInfo
const language = useLanguage()
const [showDetail, setShowDetail] = useState(false)
const title = identity.label?.[language] ?? identity.label?.en_US ?? ''
const descriptionText = description?.[language] ?? description?.en_US ?? ''
return (
<>
<div
className={cn('bg-components-panel-item-bg cursor-pointer rounded-xl border-[0.5px] border-components-panel-border-subtle px-4 py-3 shadow-xs hover:bg-components-panel-on-panel-item-bg-hover')}
onClick={() => setShowDetail(true)}
>
<div className='system-md-semibold pb-0.5 text-text-secondary'>{title}</div>
<div className='system-xs-regular line-clamp-2 text-text-tertiary' title={descriptionText}>{descriptionText}</div>
</div>
{showDetail && (
<EventDetailDrawer
eventInfo={eventInfo}
providerInfo={providerInfo}
onClose={() => setShowDetail(false)}
/>
)}
</>
)
}
export const TriggerEventsList = () => {
const { t } = useTranslation()
const detail = usePluginStore(state => state.detail)
const { data: providerInfo } = useTriggerProviderInfo(detail?.provider || '')
const triggerEvents = providerInfo?.events || []
if (!providerInfo || !triggerEvents.length)
return null
return (
<div className='px-4 pb-4 pt-2'>
<div className='mb-1 py-1'>
<div className='system-sm-semibold-uppercase mb-1 flex h-6 items-center justify-between text-text-secondary'>
{t('pluginTrigger.events.actionNum', { num: triggerEvents.length, event: t(`pluginTrigger.events.${triggerEvents.length > 1 ? 'events' : 'event'}`) })}
</div>
</div>
<div className='flex flex-col gap-2'>
{
triggerEvents.map((triggerEvent: TriggerEvent) => (
<TriggerEventCard
key={`${detail?.plugin_id}${triggerEvent.identity?.name || ''}`}
eventInfo={triggerEvent}
providerInfo={providerInfo}
/>))
}
</div>
</div>
)
}

View File

@@ -0,0 +1,21 @@
import { FormTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
export const NAME_FIELD = {
type: FormTypeEnum.textInput,
name: 'name',
label: {
en_US: 'Endpoint Name',
zh_Hans: '端点名称',
ja_JP: 'エンドポイント名',
pt_BR: 'Nome do ponto final',
},
placeholder: {
en_US: 'Endpoint Name',
zh_Hans: '端点名称',
ja_JP: 'エンドポイント名',
pt_BR: 'Nome do ponto final',
},
required: true,
default: '',
help: null,
}