Merge branch 'feat/plugins' of https://github.com/langgenius/dify into feat/plugins

This commit is contained in:
Yi 2025-01-08 14:45:10 +08:00
commit 2dac103463
18 changed files with 203 additions and 64 deletions

View File

@ -11,7 +11,7 @@ import Placeholder from './base/placeholder'
import cn from '@/utils/classnames'
import { useGetLanguage } from '@/context/i18n'
import { getLanguage } from '@/i18n/language'
import { useCategories } from '../hooks'
import { useSingleCategories } from '../hooks'
import { renderI18nObject } from '@/hooks/use-i18n'
export type Props = {
@ -43,7 +43,7 @@ const Card = ({
}: Props) => {
const defaultLocale = useGetLanguage()
const locale = localeFromProps ? getLanguage(localeFromProps) : defaultLocale
const { categoriesMap } = useCategories()
const { categoriesMap } = useSingleCategories()
const { category, type, name, org, label, brief, icon, verified } = payload
const isBundle = !['plugin', 'model', 'tool', 'extension', 'agent_strategy'].includes(type)
const cornerMark = isBundle ? categoriesMap.bundle?.label : categoriesMap[category]?.label

View File

@ -64,3 +64,31 @@ export const useCategories = (translateFromOut?: TFunction) => {
categoriesMap,
}
}
export const useSingleCategories = (translateFromOut?: TFunction) => {
const { t: translation } = useTranslation()
const t = translateFromOut || translation
const categories = categoryKeys.map((category) => {
if (category === 'agent') {
return {
name: 'agent_strategy',
label: t(`plugin.categorySingle.${category}`),
}
}
return {
name: category,
label: t(`plugin.categorySingle.${category}`),
}
})
const categoriesMap = categories.reduce((acc, category) => {
acc[category.name] = category
return acc
}, {} as Record<string, Category>)
return {
categories,
categoriesMap,
}
}

View File

@ -9,7 +9,6 @@ import AgentStrategyList from './agent-strategy-list'
import Drawer from '@/app/components/base/drawer'
import type { PluginDetail } from '@/app/components/plugins/types'
import cn from '@/utils/classnames'
import ToolSelector from '@/app/components/plugins/plugin-detail-panel/tool-selector'
type Props = {
detail?: PluginDetail
@ -28,16 +27,6 @@ const PluginDetailPanel: FC<Props> = ({
onUpdate()
}
const [value, setValue] = React.useState({
provider_name: 'langgenius/google/google',
tool_name: 'google_search',
})
const testHandle = (item: any) => {
console.log(item)
setValue(item)
}
if (!detail)
return null
@ -63,17 +52,6 @@ const PluginDetailPanel: FC<Props> = ({
{!!detail.declaration.agent_strategy && <AgentStrategyList detail={detail} />}
{!!detail.declaration.endpoint && <EndpointList detail={detail} />}
{!!detail.declaration.model && <ModelList detail={detail} />}
{false && (
<div className='px-4'>
<ToolSelector
scope={'all'}
value={value}
onSelect={item => testHandle(item)}
onDelete={() => testHandle(null)}
supportEnableSwitch
/>
</div>
)}
</div>
</>
)}

View File

@ -102,7 +102,7 @@ const ToolSelector: FC<Props> = ({
const currentProvider = useMemo(() => {
const mergedTools = [...(buildInTools || []), ...(customTools || []), ...(workflowTools || [])]
return mergedTools.find((toolWithProvider) => {
return toolWithProvider.id === value?.provider_name && toolWithProvider.tools.some(tool => tool.name === value?.tool_name)
return toolWithProvider.id === value?.provider_name
})
}, [value, buildInTools, customTools, workflowTools])
@ -172,7 +172,9 @@ const ToolSelector: FC<Props> = ({
})
// 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 ''
@ -193,7 +195,10 @@ const ToolSelector: FC<Props> = ({
>
<PortalToFollowElemTrigger
className='w-full'
onClick={handleTriggerClick}
onClick={() => {
if (!currentProvider || !currentTool) return
handleTriggerClick()
}}
>
{trigger}
{!trigger && !value?.provider_name && (
@ -214,19 +219,22 @@ const ToolSelector: FC<Props> = ({
switchValue={value.enabled}
onSwitchChange={handleEnabledChange}
onDelete={onDelete}
noAuth={currentProvider && !currentProvider.is_team_authorization}
noAuth={currentProvider && currentTool && !currentProvider.is_team_authorization}
onAuth={() => setShowSettingAuth(true)}
uninstalled={!currentProvider && inMarketPlace}
versionMismatch={currentProvider && inMarketPlace && !currentTool}
installInfo={manifest?.latest_package_identifier}
onInstall={() => handleInstall()}
isError={!currentProvider && !inMarketPlace}
errorTip={<div className='space-y-1 max-w-[240px] text-xs'>
<h3 className='text-text-primary font-semibold'>{t('plugin.detailPanel.toolSelector.uninstalledTitle')}</h3>
<p className='text-text-secondary tracking-tight'>{t('plugin.detailPanel.toolSelector.uninstalledContent')}</p>
<p>
<Link href={'/plugins'} className='text-text-accent tracking-tight'>{t('plugin.detailPanel.toolSelector.uninstalledLink')}</Link>
</p>
</div>}
isError={(!currentProvider || !currentTool) && !inMarketPlace}
errorTip={
<div className='space-y-1 max-w-[240px] text-xs'>
<h3 className='text-text-primary font-semibold'>{currentTool ? t('plugin.detailPanel.toolSelector.uninstalledTitle') : t('plugin.detailPanel.toolSelector.unsupportedTitle')}</h3>
<p className='text-text-secondary tracking-tight'>{currentTool ? t('plugin.detailPanel.toolSelector.uninstalledContent') : t('plugin.detailPanel.toolSelector.unsupportedContent')}</p>
<p>
<Link href={'/plugins'} className='text-text-accent tracking-tight'>{t('plugin.detailPanel.toolSelector.uninstalledLink')}</Link>
</p>
</div>
}
/>
)}
</PortalToFollowElemTrigger>

View File

@ -13,7 +13,9 @@ 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'
type Props = {
@ -31,6 +33,7 @@ type Props = {
uninstalled?: boolean
installInfo?: string
onInstall?: () => void
versionMismatch?: boolean
open: boolean
}
@ -50,10 +53,11 @@ const ToolItem = ({
onInstall,
isError,
errorTip,
versionMismatch,
}: Props) => {
const { t } = useTranslation()
const providerNameText = providerName?.split('/').pop()
const isTransparent = uninstalled || isError
const isTransparent = uninstalled || versionMismatch || isError
const [isDeleting, setIsDeleting] = useState(false)
return (
@ -82,7 +86,7 @@ const ToolItem = ({
<div className='text-text-secondary system-xs-medium'>{toolName}</div>
</div>
<div className='hidden group-hover:flex items-center gap-1'>
{!noAuth && !isError && !uninstalled && (
{!noAuth && !isError && !uninstalled && !versionMismatch && (
<ActionButton>
<RiEqualizer2Line className='w-4 h-4' />
</ActionButton>
@ -99,7 +103,7 @@ const ToolItem = ({
<RiDeleteBinLine className='w-4 h-4' />
</div>
</div>
{!isError && !uninstalled && !noAuth && showSwitch && (
{!isError && !uninstalled && !noAuth && !versionMismatch && showSwitch && (
<div className='mr-1' onClick={e => e.stopPropagation()}>
<Switch
size='md'
@ -108,12 +112,30 @@ const ToolItem = ({
/>
</div>
)}
{!isError && !uninstalled && noAuth && (
{!isError && !uninstalled && !versionMismatch && noAuth && (
<Button variant='secondary' size='small' onClick={onAuth}>
{t('tools.notAuthorized')}
<Indicator className='ml-2' color='orange' />
</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()}

View File

@ -22,7 +22,7 @@ import cn from '@/utils/classnames'
import { API_PREFIX, MARKETPLACE_URL_PREFIX } from '@/config'
import { useInvalidateInstalledPluginList } from '@/service/use-plugins'
import { useInvalidateAllBuiltInTools, useInvalidateAllToolProviders } from '@/service/use-tools'
import { useCategories } from '../hooks'
import { useSingleCategories } from '../hooks'
import { useProviderContext } from '@/context/provider-context'
import { useRenderI18nObject } from '@/hooks/use-i18n'
@ -36,7 +36,7 @@ const PluginItem: FC<Props> = ({
plugin,
}) => {
const { t } = useTranslation()
const { categoriesMap } = useCategories()
const { categoriesMap } = useSingleCategories()
const currentPluginID = usePluginPageContext(v => v.currentPluginID)
const setCurrentPluginID = usePluginPageContext(v => v.setCurrentPluginID)
const invalidateInstalledPluginList = useInvalidateInstalledPluginList()

View File

@ -0,0 +1,71 @@
import type { FC, ReactNode } from 'react'
import React, { memo } from 'react'
import Card from '@/app/components/plugins/card'
import Modal from '@/app/components/base/modal'
import Button from '@/app/components/base/button'
import type { Plugin } from '../types'
import type { UseMutationResult } from '@tanstack/react-query'
type Props = {
plugin: Plugin
onSave: () => void
onCancel: () => void
mutation: UseMutationResult
confirmButtonText: ReactNode
cancelButtonText: ReactNode
modelTitle: ReactNode
description: ReactNode
cardTitleLeft: ReactNode
}
const PluginMutationModal: FC<Props> = ({
plugin,
onCancel,
mutation,
confirmButtonText,
cancelButtonText,
modelTitle,
description,
cardTitleLeft,
}: Props) => {
return (
<Modal
isShow={true}
onClose={onCancel}
className='min-w-[560px]'
closable
title={modelTitle}
>
<div className='mt-3 mb-2 text-text-secondary system-md-regular'>
{description}
</div>
<div className='flex p-2 items-start content-start gap-1 self-stretch flex-wrap rounded-2xl bg-background-section-burn'>
<Card
installed={mutation.isSuccess}
payload={plugin}
className='w-full'
titleLeft={cardTitleLeft}
/>
</div>
<div className='flex pt-5 justify-end items-center gap-2 self-stretch'>
{mutation.isPending && (
<Button onClick={onCancel}>
{cancelButtonText}
</Button>
)}
<Button
variant='primary'
loading={mutation.isPending}
onClick={mutation.mutate}
disabled={mutation.isPending}
>
{confirmButtonText}
</Button>
</div>
</Modal>
)
}
PluginMutationModal.displayName = 'PluginMutationModal'
export default memo(PluginMutationModal)

View File

@ -404,6 +404,7 @@ export const SUPPORT_OUTPUT_VARS_NODE = [
BlockEnum.HttpRequest, BlockEnum.Tool, BlockEnum.VariableAssigner, BlockEnum.VariableAggregator, BlockEnum.QuestionClassifier,
BlockEnum.ParameterExtractor, BlockEnum.Iteration,
BlockEnum.DocExtractor, BlockEnum.ListFilter,
BlockEnum.Agent,
]
export const LLM_OUTPUT_STRUCT: Var[] = [

View File

@ -6,19 +6,20 @@ import PluginVersionPicker from '@/app/components/plugins/update-plugin/plugin-v
import { RiArrowLeftRightLine } from '@remixicon/react'
import type { ReactNode } from 'react'
import { type FC, useCallback, useState } from 'react'
import cn from '@/utils/classnames'
import UpdateFromMarketplace from '@/app/components/plugins/update-plugin/from-market-place'
import { useBoolean } from 'ahooks'
import { useCheckInstalled } from '@/service/use-plugins'
import cn from '@/utils/classnames'
export type SwitchPluginVersionProps = {
uniqueIdentifier: string
tooltip?: ReactNode
onChange?: (version: string) => void
className?: string
}
export const SwitchPluginVersion: FC<SwitchPluginVersionProps> = (props) => {
const { uniqueIdentifier, tooltip, onChange } = props
const { uniqueIdentifier, tooltip, onChange, className } = props
const [pluginId] = uniqueIdentifier.split(':')
const [isShow, setIsShow] = useState(false)
const [isShowUpdateModal, { setTrue: showUpdateModal, setFalse: hideUpdateModal }] = useBoolean(false)
@ -40,7 +41,7 @@ export const SwitchPluginVersion: FC<SwitchPluginVersionProps> = (props) => {
return uniqueIdentifier.replaceAll(pluginDetail.version, targetVersion)
})()
return <Tooltip popupContent={!isShow && !isShowUpdateModal && tooltip} triggerMethod='hover'>
<div className='w-fit'>
<div className={cn('w-fit', className)}>
{isShowUpdateModal && pluginDetail && <UpdateFromMarketplace
payload={{
originalPackageInfo: {

View File

@ -319,16 +319,13 @@ const formatItem = (
case BlockEnum.Agent: {
const payload = data as AgentNodeType
const outputs: Var[] = []
Object.keys(payload.output_schema.properties).forEach((outputKey) => {
Object.keys(payload.output_schema?.properties || {}).forEach((outputKey) => {
const output = payload.output_schema.properties[outputKey]
outputs.push({
variable: outputKey,
type: output.type === 'array'
? `Array[${output.items?.type.slice(0, 1).toLocaleUpperCase()}${output.items?.type.slice(1)}]` as VarType
: `${output.type.slice(0, 1).toLocaleUpperCase()}${output.type.slice(1)}` as VarType,
// TODO: is this required?
// @ts-expect-error todo added
description: output.description,
})
})
res.vars = [

View File

@ -30,26 +30,26 @@ const AgentLogItem = ({
<div className='border-[0.5px] border-components-panel-border rounded-[10px]'>
<div
className={cn(
'flex items-center pl-1.5 pt-2 pr-3 pb-2',
'flex items-center pl-1.5 pt-2 pr-3 pb-2 cursor-pointer',
expanded && 'pb-1',
)}
onClick={() => setExpanded(!expanded)}
>
{
expanded
? <RiArrowRightSLine className='shrink-0 w-4 h-4 rotate-90' />
: <RiArrowRightSLine className='shrink-0 w-4 h-4' />
? <RiArrowRightSLine className='shrink-0 w-4 h-4 rotate-90 text-text-quaternary' />
: <RiArrowRightSLine className='shrink-0 w-4 h-4 text-text-quaternary' />
}
<div className='shrink-0 mr-1.5 w-5 h-5'></div>
<div className='grow system-sm-semibold-uppercase text-text-secondary truncate'>{label}</div>
<div className='shrink-0 mr-2 system-xs-regular text-text-tertiary'>0.02s</div>
{/* <div className='shrink-0 mr-2 system-xs-regular text-text-tertiary'>0.02s</div> */}
<NodeStatusIcon status={status} />
</div>
{
expanded && (
<div className='p-1 pt-0'>
{
!!children.length && (
!!children?.length && (
<Button
className='flex items-center justify-between mb-1 w-full'
variant='tertiary'

View File

@ -19,7 +19,9 @@ const AgentLogNav = ({
className='shrink-0 px-[5px]'
size='small'
variant='ghost-accent'
onClick={() => onShowAgentOrToolLog()}
onClick={() => {
onShowAgentOrToolLog()
}}
>
<RiArrowLeftLine className='mr-1 w-3.5 h-3.5' />
Agent
@ -31,7 +33,6 @@ const AgentLogNav = ({
variant='ghost-accent'
onClick={() => {}}
>
<RiArrowLeftLine className='mr-1 w-3.5 h-3.5' />
Agent strategy
</Button>
{

View File

@ -24,7 +24,9 @@ const AgentLogTrigger = ({
<div className='grow mx-0.5 px-1 system-xs-medium text-text-secondary'></div>
<div
className='shrink-0 flex items-center px-[1px] system-xs-regular-uppercase text-text-tertiary cursor-pointer'
onClick={() => onShowAgentOrToolLog({ id: nodeInfo.id, children: agentLog || [] } as AgentLogItemWithChildren)}
onClick={() => {
onShowAgentOrToolLog({ id: nodeInfo.id, children: agentLog || [] } as AgentLogItemWithChildren)
}}
>
Detail
<RiArrowRightLine className='ml-0.5 w-3.5 h-3.5' />

View File

@ -36,7 +36,10 @@ const SpecialResultPanel = ({
handleShowAgentOrToolLog,
}: SpecialResultPanelProps) => {
return (
<>
<div onClick={(e) => {
e.stopPropagation()
e.nativeEvent.stopImmediatePropagation()
}}>
{
!!showRetryDetail && !!retryResultList?.length && setShowRetryDetailFalse && (
<RetryResultPanel
@ -63,7 +66,7 @@ const SpecialResultPanel = ({
/>
)
}
</>
</div>
)
}

View File

@ -166,7 +166,13 @@ const TracingPanel: FC<TracingPanelProps> = ({
}
return (
<div className={cn(className || 'bg-components-panel-bg', 'py-2')}>
<div
className={cn(className || 'bg-components-panel-bg', 'py-2')}
onClick={(e) => {
e.stopPropagation()
e.nativeEvent.stopImmediatePropagation()
}}
>
{treeNodes.map(renderNode)}
</div>
)

View File

@ -3,10 +3,17 @@ const translation = {
all: 'All',
models: 'Models',
tools: 'Tools',
agents: 'Agent Strategy',
agents: 'Agent Strategies',
extensions: 'Extensions',
bundles: 'Bundles',
},
categorySingle: {
model: 'Model',
tool: 'Tool',
agent: 'Agent Strategy',
extension: 'Extension',
bundle: 'Bundle',
},
search: 'Search',
allCategories: 'All Categories',
searchCategories: 'Search Categories',
@ -77,6 +84,9 @@ const translation = {
uninstalledTitle: 'Tool not installed',
uninstalledContent: 'This plugin is installed from the local/GitHub repository. Please use after installation.',
uninstalledLink: 'Manage in Plugins',
unsupportedTitle: 'Unsupported Action',
unsupportedContent: 'The installed plugin version does not provide this action.',
unsupportedContent2: 'Click to switch version.',
},
configureApp: 'Configure App',
configureModel: 'Configure model',

View File

@ -7,6 +7,13 @@ const translation = {
extensions: '扩展',
bundles: '插件集',
},
categorySingle: {
model: '模型',
tool: '工具',
agent: 'Agent 策略',
extension: '扩展',
bundle: '插件集',
},
search: '搜索',
allCategories: '所有类别',
searchCategories: '搜索类别',
@ -77,6 +84,9 @@ const translation = {
uninstalledTitle: '工具未安装',
uninstalledContent: '此插件安装自 本地 / GitHub 仓库,请安装后使用。',
uninstalledLink: '在插件中管理',
unsupportedTitle: '不支持的 Action',
unsupportedContent: '已安装的插件版本不提供这个 action。',
unsupportedContent2: '点击切换版本',
},
configureApp: '应用设置',
configureModel: '模型设置',

View File

@ -41,7 +41,7 @@ export const useCheckInstalled = ({
enabled: boolean
}) => {
return useQuery<{ plugins: PluginDetail[] }>({
queryKey: [NAME_SPACE, 'checkInstalled'],
queryKey: [NAME_SPACE, 'checkInstalled', pluginIds],
queryFn: () => post<{ plugins: PluginDetail[] }>('/workspaces/current/plugin/list/installations/ids', {
body: {
plugin_ids: pluginIds,
@ -82,8 +82,9 @@ export const useInstallPackageFromMarketPlace = (options?: MutateOptions<Install
})
}
export const useUpdatePackageFromMarketPlace = () => {
export const useUpdatePackageFromMarketPlace = (options?: MutateOptions<InstallPackageResponse, Error, object>) => {
return useMutation({
...options,
mutationFn: (body: object) => {
return post<InstallPackageResponse>('/workspaces/current/plugin/upgrade/marketplace', {
body,
@ -364,7 +365,7 @@ export const usePluginTaskList = () => {
queryKey: usePluginTaskListKey,
queryFn: async () => {
const currentData = await get<{ tasks: PluginTask[] }>('/workspaces/current/plugin/tasks?page=1&page_size=100')
const taskDone = currentData.tasks.every(task => task.status === TaskStatus.success)
const taskDone = currentData.tasks.every(task => task.status === TaskStatus.success || task.status === TaskStatus.failed)
if (taskDone)
setEnabled(false)