chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动

演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
wuzilongandCursor committed 2026-11-18 13:59:25 +08:00
1 parent 60158935f4
commit 6519682885
15831 files changed
+3063428

No files matched your search

@@ -0,0 +1,399 @@
import type { Dependency, PackageDependency, Plugin } from '../../../types'
import type { ConsoleQueryTestOptions } from '@/test/console/query-data'
import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MARKETPLACE_API_PREFIX } from '@/features/marketplace/api'
import { renderWithConsoleQuery } from '@/test/console/query-data'
import { createDeferred } from '@/test/deferred'
import { createPluginDeclarationFixture, createPluginEntity } from '@/test/fixtures/plugin'
import { PermissionType, PluginCategoryEnum, TaskStatus } from '../../../types'
import InstallBundle from '../index'
const {
marketplace,
checkTask,
refresh,
installRequest,
uploadGithub,
installGithub,
installPackage,
installedPlugins,
upgrade,
} = vi.hoisted(() => ({
marketplace: vi.fn(),
checkTask: vi.fn(),
refresh: vi.fn(),
installRequest: vi.fn(),
uploadGithub: vi.fn(),
installGithub: vi.fn(),
installPackage: vi.fn(),
installedPlugins: vi.fn(),
upgrade: vi.fn(),
}))
vi.mock('@/service/base', async (importOriginal) => ({
...(await importOriginal<typeof import('@/service/base')>()),
postMarketplace: marketplace,
}))
vi.mock('@/service/plugins', async (importOriginal) => ({
...(await importOriginal<typeof import('@/service/plugins')>()),
checkTaskStatus: checkTask,
}))
vi.mock('@/service/console', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/service/console')>()
const { withConsoleResponses, withConsoleClientResponses } =
await import('@/test/console/service-responses')
return {
...actual,
consoleClient: withConsoleClientResponses(actual.consoleClient, {
'workspaces.current.plugin.permission.fetch.get': async () => ({
install_permission: PermissionType.everyone,
debug_permission: PermissionType.everyone,
}),
'workspaces.current.plugin.tasks.get': async () => ({ tasks: [] }),
'workspaces.current.plugin.install.marketplace.post': installRequest,
'workspaces.current.plugin.upload.github.post': uploadGithub,
'workspaces.current.plugin.install.github.post': installGithub,
'workspaces.current.plugin.install.pkg.post': installPackage,
'workspaces.current.plugin.upgrade.marketplace.post': upgrade,
}),
consoleQuery: withConsoleResponses(actual.consoleQuery, {
'workspaces.current.plugin.list.installations.ids.post': installedPlugins,
}),
}
})
// Refreshing unrelated model/tool catalogs is independently covered by use-refresh-plugin-list.
vi.mock('../../hooks/use-refresh-plugin-list', () => ({
default: () => ({ refreshPluginList: refresh }),
}))
const plugins: Plugin[] = ['finished', 'failed', 'running'].map((name) => ({
type: 'plugin',
org: 'test',
name,
plugin_id: `test/${name}`,
version: '1.0.0',
latest_version: '1.0.0',
latest_package_identifier: `test/${name}:1.0.0`,
icon: '',
verified: true,
label: { en_US: name },
brief: { en_US: 'Test plugin' },
description: { en_US: 'Test plugin' },
introduction: '',
repository: '',
category: PluginCategoryEnum.tool,
install_count: 1,
endpoint: { settings: [] },
tags: [],
badges: [],
verification: { authorized_category: 'community' },
from: 'marketplace',
}))
const dependencies: Dependency[] = plugins.map((plugin) => ({
type: 'marketplace',
value: { marketplace_plugin_unique_identifier: plugin.latest_package_identifier },
}))
beforeEach(() => {
vi.resetAllMocks()
installedPlugins.mockResolvedValue({ plugins: [] })
marketplace.mockResolvedValue({ data: { list: plugins.map((plugin) => ({ plugin })) } })
})
const renderInstall = (
fromDSLPayload: Dependency[] = dependencies,
options: ConsoleQueryTestOptions = {},
) => {
const onInstalled = vi.fn()
const onClose = vi.fn()
renderWithConsoleQuery(
<InstallBundle
fromDSLPayload={fromDSLPayload}
onInstallComplete={onInstalled}
onClose={onClose}
/>,
{
workspacePermissionKeys: ['plugin.install'],
systemFeatures: {
enable_marketplace: true,
rbac_enabled: true,
plugin_installation_permission: {
plugin_installation_scope: 'all',
restrict_to_marketplace_only: false,
},
},
...options,
},
)
return { onInstalled, onClose }
}
it('waits for marketplace metadata before rendering imported plugin icons', async () => {
const metadata = createDeferred<{ data: { list: { plugin: Plugin }[] } }>()
marketplace.mockReturnValue(metadata.promise)
renderInstall([dependencies[0]!])
expect(screen.queryByRole('presentation')).not.toBeInTheDocument()
metadata.resolve({ data: { list: [{ plugin: plugins[0]! }] } })
const icon = await screen.findByRole('presentation')
expect(icon).toHaveAttribute('src', `${MARKETPLACE_API_PREFIX}/plugins/test/finished/icon`)
expect(icon).toBeVisible()
})
it('aggregates finished, failed and running installs and polls only the unfinished task', async () => {
const user = userEvent.setup()
const pending = createDeferred<{ all_installed: boolean; task_id: string }>()
const install = installRequest.mockImplementation(
async ({ body }: { body: { plugin_unique_identifiers: string[] } }) => {
const id = body.plugin_unique_identifiers[0]
if (id === plugins[1]!.latest_package_identifier) throw new Error('Installation rejected')
if (id === plugins[2]!.latest_package_identifier) return pending.promise
return { all_installed: true, task_id: '' }
},
)
checkTask.mockResolvedValue({
task: {
plugins: [
{
plugin_unique_identifier: plugins[2]!.latest_package_identifier,
status: TaskStatus.success,
},
],
},
})
const { onInstalled, onClose } = renderInstall()
const button = await screen.findByRole('button', { name: 'plugin.installModal.install' })
await waitFor(() => expect(button).toBeEnabled())
await user.click(button)
await screen.findByRole('button', { name: 'plugin.installModal.installing' })
expect(
screen.getByRole('dialog', { name: 'plugin.installModal.installPlugin' }),
).toBeInTheDocument()
expect(onInstalled).not.toHaveBeenCalled()
expect(install).toHaveBeenCalledTimes(3)
pending.resolve({ all_installed: false, task_id: 'running-task' })
await waitFor(() => expect(onInstalled).toHaveBeenCalledOnce())
expect(
screen.getByRole('dialog', { name: 'plugin.installModal.installedSuccessfully' }),
).toBeInTheDocument()
expect(screen.queryByRole('checkbox')).not.toBeInTheDocument()
expect(checkTask).toHaveBeenCalledExactlyOnceWith('running-task')
expect(onInstalled).toHaveBeenCalledWith(
expect.arrayContaining(plugins.map(({ plugin_id }) => expect.objectContaining({ plugin_id }))),
[
{ success: true, isFromMarketPlace: true },
{ success: false, isFromMarketPlace: true },
{ success: true, isFromMarketPlace: true },
],
plugins.map(() => ({
hasInstalled: false,
installedVersion: undefined,
toInstallVersion: '1.0.0',
})),
)
await user.click(screen.getAllByRole('button', { name: 'common.operation.close' }).at(-1)!)
expect(onClose).toHaveBeenCalledOnce()
})
it('reports failed requests without polling or refreshing installed plugins', async () => {
const user = userEvent.setup()
installRequest.mockRejectedValue(new Error('Installation rejected'))
const { onInstalled } = renderInstall()
const button = await screen.findByRole('button', { name: 'plugin.installModal.install' })
await waitFor(() => expect(button).toBeEnabled())
await user.click(button)
await waitFor(() => expect(onInstalled).toHaveBeenCalledOnce())
expect(onInstalled).toHaveBeenCalledWith(
expect.any(Array),
plugins.map(() => ({ success: false, isFromMarketPlace: true })),
expect.any(Array),
)
expect(checkTask).not.toHaveBeenCalled()
expect(refresh).not.toHaveBeenCalled()
expect(
screen.queryByRole('button', { name: 'plugin.installModal.install' }),
).not.toBeInTheDocument()
})
it('installs only selected plugins and refreshes the catalog after immediate success', async () => {
const user = userEvent.setup()
const install = installRequest.mockResolvedValue({ all_installed: true, task_id: '' })
const { onInstalled } = renderInstall()
const button = await screen.findByRole('button', { name: 'plugin.installModal.install' })
await waitFor(() => expect(button).toBeEnabled())
await user.click(screen.getByRole('checkbox', { name: 'common.operation.deSelectAll' }))
expect(button).toBeDisabled()
await user.click(screen.getByRole('checkbox', { name: 'finished' }))
await user.click(button)
await waitFor(() => expect(onInstalled).toHaveBeenCalledOnce())
expect(install).toHaveBeenCalledExactlyOnceWith({
body: { plugin_unique_identifiers: [plugins[0]!.latest_package_identifier] },
})
expect(refresh).toHaveBeenCalledWith(undefined, true)
expect(checkTask).not.toHaveBeenCalled()
})
it.each(['common.operation.cancel', 'common.operation.close'])(
'allows %s before plugin metadata is ready without starting installation',
async (name) => {
const user = userEvent.setup()
marketplace.mockReturnValue(new Promise(() => {}))
const { onClose, onInstalled } = renderInstall()
expect(screen.getByRole('button', { name: 'plugin.installModal.install' })).toBeDisabled()
await user.click(screen.getByRole('button', { name }))
expect(onClose).toHaveBeenCalledOnce()
expect(installRequest).not.toHaveBeenCalled()
expect(onInstalled).not.toHaveBeenCalled()
},
)
const packageDependency: PackageDependency = {
type: 'package',
value: {
unique_identifier: 'test/local:2.0.0',
manifest: createPluginDeclarationFixture({
author: 'test',
name: 'local',
version: '2.0.0',
label: { ...createPluginDeclarationFixture().label, en_US: 'Local plugin' },
}),
},
}
const githubDependency: Dependency = {
type: 'github',
value: { repo: 'test/github', release: 'v3.0.0', packages: 'plugin.difypkg' },
}
it('keeps mixed-source results and version changes aligned with their dependencies', async () => {
const user = userEvent.setup()
marketplace.mockResolvedValue({ data: { list: [{ plugin: plugins[0] }] } })
const installed = createPluginEntity({
plugin_id: 'test/finished',
plugin_unique_identifier: 'test/finished:0.9.0',
})
installed.declaration.version = '0.9.0'
installedPlugins.mockResolvedValue({ plugins: [installed] })
uploadGithub.mockResolvedValue({
unique_identifier: 'test/github:3.0.0',
manifest: createPluginDeclarationFixture({
author: 'test',
name: 'github',
version: '3.0.0',
label: { ...createPluginDeclarationFixture().label, en_US: 'GitHub plugin' },
}),
})
installPackage.mockResolvedValue({ all_installed: true, task_id: '' })
upgrade.mockResolvedValue({ all_installed: true, task_id: '' })
installGithub.mockRejectedValue(new Error('Package rejected'))
const { onInstalled } = renderInstall([packageDependency, dependencies[0]!, githubDependency])
const button = screen.getByRole('button', { name: 'plugin.installModal.install' })
await waitFor(() => expect(button).toBeEnabled())
for (const name of ['local', 'finished', 'github']) {
expect(screen.getByRole('checkbox', { name })).toBeChecked()
}
await user.click(button)
await waitFor(() => expect(onInstalled).toHaveBeenCalledOnce())
expect(installPackage).toHaveBeenCalledExactlyOnceWith({
body: { plugin_unique_identifiers: ['test/local:2.0.0'] },
})
expect(installGithub).toHaveBeenCalledExactlyOnceWith({
body: {
repo: 'test/github',
version: 'v3.0.0',
package: 'plugin.difypkg',
plugin_unique_identifier: 'test/github:3.0.0',
},
})
expect(upgrade).toHaveBeenCalledExactlyOnceWith({
body: {
original_plugin_unique_identifier: 'test/finished:0.9.0',
new_plugin_unique_identifier: 'test/finished:1.0.0',
},
})
expect(installRequest).not.toHaveBeenCalled()
expect(onInstalled).toHaveBeenCalledWith(
[
expect.objectContaining({ name: 'local' }),
expect.objectContaining({ name: 'finished' }),
expect.objectContaining({ name: 'github' }),
],
[
{ success: true, isFromMarketPlace: false },
{ success: true, isFromMarketPlace: true },
{ success: false, isFromMarketPlace: false },
],
[
{ hasInstalled: false, installedVersion: undefined, toInstallVersion: '2.0.0' },
{ hasInstalled: true, installedVersion: '0.9.0', toInstallVersion: '1.0.0' },
{ hasInstalled: false, installedVersion: undefined, toInstallVersion: '3.0.0' },
],
)
expect(screen.getByText('0.9.0 -> 1.0.0')).toBeInTheDocument()
expect(screen.getByText('2.0.0')).toBeInTheDocument()
expect(screen.getByText('3.0.0')).toBeInTheDocument()
})
it('excludes failed metadata loads from selection and installs the remaining package', async () => {
const user = userEvent.setup()
marketplace.mockRejectedValue(new Error('Marketplace unavailable'))
uploadGithub.mockRejectedValue(new Error('GitHub unavailable'))
installPackage.mockResolvedValue({ all_installed: true, task_id: '' })
const { onInstalled } = renderInstall([dependencies[0]!, githubDependency, packageDependency])
await waitFor(() =>
expect(screen.getAllByText('plugin.installModal.pluginLoadError')).toHaveLength(2),
)
const button = screen.getByRole('button', { name: 'plugin.installModal.install' })
await waitFor(() => expect(button).toBeEnabled())
expect(screen.getByRole('checkbox', { name: 'local' })).toBeChecked()
await user.click(screen.getByRole('checkbox', { name: 'common.operation.deSelectAll' }))
expect(button).toBeDisabled()
await user.click(screen.getByRole('checkbox', { name: 'common.operation.selectAll' }))
await user.click(button)
await waitFor(() => expect(onInstalled).toHaveBeenCalledOnce())
expect(onInstalled).toHaveBeenCalledWith(
[expect.objectContaining({ name: 'local' })],
[{ success: true, isFromMarketPlace: false }],
[{ hasInstalled: false, installedVersion: undefined, toInstallVersion: '2.0.0' }],
)
expect(installPackage).toHaveBeenCalledExactlyOnceWith({
body: { plugin_unique_identifiers: ['test/local:2.0.0'] },
})
expect(installRequest).not.toHaveBeenCalled()
expect(installGithub).not.toHaveBeenCalled()
})
it('excludes restricted plugins when selecting all and prevents selecting them individually', async () => {
const user = userEvent.setup()
marketplace.mockResolvedValue({
data: {
list: [
{ plugin: { ...plugins[0], verification: { authorized_category: 'langgenius' } } },
{ plugin: plugins[1] },
],
},
})
installRequest.mockResolvedValue({ all_installed: true, task_id: '' })
const { onInstalled } = renderInstall(dependencies.slice(0, 2), {
systemFeatures: {
enable_marketplace: true,
plugin_installation_permission: {
plugin_installation_scope: 'official_only',
restrict_to_marketplace_only: false,
},
},
})
const button = screen.getByRole('button', { name: 'plugin.installModal.install' })
await waitFor(() => expect(button).toBeEnabled())
const restricted = screen.getByRole('checkbox', { name: 'failed' })
expect(restricted).toHaveAttribute('aria-disabled', 'true')
await user.click(restricted)
expect(restricted).not.toBeChecked()
expect(screen.getByRole('checkbox', { name: 'finished' })).toBeChecked()
await user.click(button)
await waitFor(() => expect(onInstalled).toHaveBeenCalledOnce())
expect(installRequest).toHaveBeenCalledExactlyOnceWith({
body: { plugin_unique_identifiers: ['test/finished:1.0.0'] },
})
})
@@ -0,0 +1,97 @@
'use client'
import type { FC } from 'react'
import type { Dependency, InstallStatus, Plugin, VersionProps } from '../../types'
import { cn } from '@langgenius/dify-ui/cn'
import {
Dialog,
DialogContent,
DialogHeader,
DialogHeaderCloseButton,
DialogTitle,
} from '@langgenius/dify-ui/dialog'
import * as React from 'react'
import { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { InstallStep } from '../../types'
import useHideLogic from '../hooks/use-hide-logic'
import ReadyToInstall from './ready-to-install'
const i18nPrefix = 'installModal'
export type InstallBundleCompleteCallback = (
plugins: Plugin[],
installStatus: InstallStatus[],
versionInfo: VersionProps[],
) => void
const InstallType = {
fromLocal: 'fromLocal',
fromMarketplace: 'fromMarketplace',
fromDSL: 'fromDSL',
} as const
type InstallType = (typeof InstallType)[keyof typeof InstallType]
type Props = Readonly<{
installType?: InstallType
fromDSLPayload: Dependency[]
// plugins?: PluginDeclaration[]
onClose: () => void
onInstallComplete?: InstallBundleCompleteCallback
}>
const InstallBundle: FC<Props> = ({
installType = InstallType.fromMarketplace,
fromDSLPayload,
onClose,
onInstallComplete,
}) => {
const { t } = useTranslation(['common', 'plugin'])
const [step, setStep] = useState<InstallStep>(
installType === InstallType.fromMarketplace
? InstallStep.readyToInstall
: InstallStep.uploading,
)
const { modalClassName, foldAnimInto, setIsInstalling, handleStartToInstall } =
useHideLogic(onClose)
const getTitle = useCallback(() => {
if (step === InstallStep.uploadFailed)
return t(($) => $[`${i18nPrefix}.uploadFailed`], { ns: 'plugin' })
if (step === InstallStep.installed)
return t(($) => $[`${i18nPrefix}.installedSuccessfully`], { ns: 'plugin' })
return t(($) => $[`${i18nPrefix}.installPlugin`], { ns: 'plugin' })
}, [step, t])
return (
<Dialog
open
onOpenChange={(open) => {
if (!open) foldAnimInto()
}}
>
<DialogContent
backdropProps={{ forceRender: true }}
className={cn('w-120', modalClassName, 'max-h-[calc(100dvh-48px)] min-w-140')}
>
<DialogHeader>
<DialogTitle>{getTitle()}</DialogTitle>
<DialogHeaderCloseButton aria-label={t(($) => $['operation.close'], { ns: 'common' })} />
</DialogHeader>
<ReadyToInstall
step={step}
onStepChange={setStep}
onStartToInstall={handleStartToInstall}
setIsInstalling={setIsInstalling}
allPlugins={fromDSLPayload}
onClose={onClose}
onInstallComplete={onInstallComplete}
/>
</DialogContent>
</Dialog>
)
}
export default React.memo(InstallBundle)
@@ -0,0 +1,57 @@
'use client'
import type { FC } from 'react'
import type { GitHubItemAndMarketPlaceDependency, Plugin, VersionProps } from '../../../types'
import * as React from 'react'
import { useEffect } from 'react'
import { useUploadGitHub } from '@/service/use-plugins'
import Loading from '../../base/loading'
import { pluginDeclarationToCardPluginProps } from '../../utils'
import LoadedItem from './loaded-item'
type Props = Readonly<{
checked: boolean
onCheckedChange: (plugin: Plugin) => void
dependency: GitHubItemAndMarketPlaceDependency
versionInfo: VersionProps
onFetchedPayload: (payload: Plugin) => void
onFetchError: () => void
}>
const Item: FC<Props> = ({
checked,
onCheckedChange,
dependency,
versionInfo,
onFetchedPayload,
onFetchError,
}) => {
const info = dependency.value
const { data, error } = useUploadGitHub({
repo: info.repo!,
version: info.release! || info.version!,
package: info.packages! || info.package!,
})
const [payload, setPayload] = React.useState<Plugin | null>(null)
useEffect(() => {
if (data) {
const payload = {
...pluginDeclarationToCardPluginProps(data.manifest, data.unique_identifier),
}
onFetchedPayload(payload)
setPayload({ ...payload, from: dependency.type })
}
}, [data])
useEffect(() => {
if (error) onFetchError()
}, [error])
if (!payload) return <Loading />
return (
<LoadedItem
payload={payload}
versionInfo={versionInfo}
checked={checked}
onCheckedChange={onCheckedChange}
/>
)
}
export default React.memo(Item)
@@ -0,0 +1,57 @@
'use client'
import type { FC } from 'react'
import type { Plugin, VersionProps } from '../../../types'
import { Checkbox } from '@langgenius/dify-ui/checkbox'
import * as React from 'react'
import { getMarketplacePluginIconUrl } from '@/features/marketplace/api'
import Card from '../../../card'
import useGetIcon from '../../base/use-get-icon'
import Version from '../../base/version'
import usePluginInstallLimit from '../../hooks/use-install-plugin-limit'
type Props = Readonly<{
checked: boolean
onCheckedChange: (plugin: Plugin) => void
payload: Plugin
isFromMarketPlace?: boolean
versionInfo: VersionProps
}>
const LoadedItem: FC<Props> = ({
checked,
onCheckedChange,
payload,
isFromMarketPlace,
versionInfo: particleVersionInfo,
}) => {
const { getIconUrl } = useGetIcon()
const versionInfo = {
...particleVersionInfo,
toInstallVersion: payload.version,
}
const { canInstall } = usePluginInstallLimit(payload)
return (
<div className="flex items-center space-x-2">
<Checkbox
disabled={!canInstall}
className="shrink-0"
checked={checked}
aria-label={payload.name}
onCheckedChange={() => onCheckedChange(payload)}
/>
<Card
className="grow"
payload={{
...payload,
icon: isFromMarketPlace
? getMarketplacePluginIconUrl(`${payload.org}/${payload.name}`)
: getIconUrl(payload.icon),
}}
titleLeft={payload.version ? <Version {...versionInfo} /> : null}
limitedInstall={!canInstall}
/>
</div>
)
}
export default React.memo(LoadedItem)
@@ -0,0 +1,35 @@
'use client'
import type { FC } from 'react'
import type { Plugin, VersionProps } from '../../../types'
import * as React from 'react'
import Loading from '../../base/loading'
import LoadedItem from './loaded-item'
type Props = Readonly<{
checked: boolean
onCheckedChange: (plugin: Plugin) => void
payload?: Plugin
version: string
versionInfo: VersionProps
}>
const MarketPlaceItem: FC<Props> = ({
checked,
onCheckedChange,
payload,
version,
versionInfo,
}) => {
if (!payload) return <Loading />
return (
<LoadedItem
checked={checked}
onCheckedChange={onCheckedChange}
payload={{ ...payload, version }}
isFromMarketPlace
versionInfo={versionInfo}
/>
)
}
export default React.memo(MarketPlaceItem)
@@ -0,0 +1,38 @@
'use client'
import type { FC } from 'react'
import type { PackageDependency, Plugin, VersionProps } from '../../../types'
import * as React from 'react'
import LoadingError from '../../base/loading-error'
import { pluginManifestToCardPluginProps } from '../../utils'
import LoadedItem from './loaded-item'
type Props = Readonly<{
checked: boolean
onCheckedChange: (plugin: Plugin) => void
payload: PackageDependency
isFromMarketPlace?: boolean
versionInfo: VersionProps
}>
const PackageItem: FC<Props> = ({
payload,
checked,
onCheckedChange,
isFromMarketPlace,
versionInfo,
}) => {
if (!payload.value?.manifest) return <LoadingError />
const plugin = pluginManifestToCardPluginProps(payload.value.manifest)
return (
<LoadedItem
payload={{ ...plugin, from: payload.type }}
checked={checked}
onCheckedChange={onCheckedChange}
isFromMarketPlace={isFromMarketPlace}
versionInfo={versionInfo}
/>
)
}
export default React.memo(PackageItem)
@@ -0,0 +1,68 @@
'use client'
import type { FC } from 'react'
import type { Dependency, InstallStatus, Plugin, VersionProps } from '../../types'
import type { InstallBundleCompleteCallback } from './index'
import * as React from 'react'
import { useCallback, useState } from 'react'
import { InstallStep } from '../../types'
import Install from './steps/install'
import Installed from './steps/installed'
type Props = Readonly<{
step: InstallStep
onStepChange: (step: InstallStep) => void
onStartToInstall: () => void
setIsInstalling: (isInstalling: boolean) => void
allPlugins: Dependency[]
onClose: () => void
onInstallComplete?: InstallBundleCompleteCallback
isFromMarketPlace?: boolean
}>
const ReadyToInstall: FC<Props> = ({
step,
onStepChange,
onStartToInstall,
setIsInstalling,
allPlugins,
onClose,
onInstallComplete,
isFromMarketPlace,
}) => {
const [installedPlugins, setInstalledPlugins] = useState<Plugin[]>([])
const [installStatus, setInstallStatus] = useState<InstallStatus[]>([])
const [installedVersionInfo, setInstalledVersionInfo] = useState<VersionProps[]>([])
const handleInstalled = useCallback(
(plugins: Plugin[], installStatus: InstallStatus[], versionInfo: VersionProps[]) => {
setInstallStatus(installStatus)
setInstalledPlugins(plugins)
setInstalledVersionInfo(versionInfo)
onStepChange(InstallStep.installed)
setIsInstalling(false)
onInstallComplete?.(plugins, installStatus, versionInfo)
},
[onInstallComplete, onStepChange, setIsInstalling],
)
return (
<>
{step === InstallStep.readyToInstall && (
<Install
allPlugins={allPlugins}
onCancel={onClose}
onStartToInstall={onStartToInstall}
onInstalled={handleInstalled}
isFromMarketPlace={isFromMarketPlace}
/>
)}
{step === InstallStep.installed && (
<Installed
list={installedPlugins}
installStatus={installStatus}
versionInfo={installedVersionInfo}
onCancel={onClose}
/>
)}
</>
)
}
export default React.memo(ReadyToInstall)
@@ -0,0 +1,216 @@
import type {
Dependency,
GitHubItemAndMarketPlaceDependency,
PackageDependency,
Plugin,
} from '@/app/components/plugins/types'
import { act, waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import { PluginCategoryEnum } from '@/app/components/plugins/types'
import { renderHookWithConsoleQuery as renderHook } from '@/test/console/query-data'
import { createDeferred } from '@/test/deferred'
import { createPluginDeclarationFixture } from '@/test/fixtures/plugin'
import { useInstallMultiState } from '../use-install-multi-state'
const requests = vi.hoisted(() => ({ marketplace: vi.fn(), installed: vi.fn() }))
vi.mock('@/service/base', async (importOriginal) => ({
...(await importOriginal<typeof import('@/service/base')>()),
postMarketplace: requests.marketplace,
}))
vi.mock('@/service/console', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/service/console')>()
const { withConsoleResponses } = await import('@/test/console/service-responses')
return {
...actual,
consoleQuery: withConsoleResponses(actual.consoleQuery, {
'workspaces.current.plugin.list.installations.ids.post': requests.installed,
}),
}
})
const createMockPlugin = (overrides: Partial<Plugin> = {}): Plugin => ({
type: 'plugin',
org: 'test-org',
name: 'Test Plugin',
plugin_id: 'test-plugin-id',
version: '1.0.0',
latest_version: '1.0.0',
latest_package_identifier: 'test-pkg-id',
icon: 'icon.png',
verified: true,
label: { 'en-US': 'Test Plugin' },
brief: { 'en-US': 'Brief' },
description: { 'en-US': 'Description' },
introduction: 'Intro',
repository: 'https://github.com/test/plugin',
category: PluginCategoryEnum.tool,
install_count: 100,
endpoint: { settings: [] },
tags: [],
badges: [],
verification: { authorized_category: 'community' },
from: 'marketplace',
...overrides,
})
const packageDependency: PackageDependency = {
type: 'package',
value: {
unique_identifier: 'test/local:1.0.0',
manifest: createPluginDeclarationFixture({ author: 'test', name: 'local' }),
},
}
const githubDependency: Dependency = {
type: 'github',
value: { repo: 'test/github', release: 'v1.0.0', packages: 'plugin.difypkg' },
}
const marketplaceDependency: GitHubItemAndMarketPlaceDependency = {
type: 'marketplace',
value: { marketplace_plugin_unique_identifier: 'test/remote:1.0.0@hash' },
}
const params = (allPlugins: Dependency[]) => ({
allPlugins,
selectedPlugins: [] as Plugin[],
onSelect: vi.fn(),
onLoadedAllPlugin: vi.fn(),
})
beforeEach(() => {
vi.clearAllMocks()
requests.installed.mockResolvedValue({ plugins: [] })
requests.marketplace.mockResolvedValue({ data: { list: [] } })
})
describe('bundle metadata', () => {
it.each([
{ marketplace_plugin_unique_identifier: 'test/remote:1.0.0@hash' },
{ organization: 'test', plugin: 'remote', version: '1.0.0' },
])('normalizes dependency %j and maps metadata back to the original slots', async (value) => {
const remote = createMockPlugin({ org: 'test', name: 'remote', plugin_id: 'test/remote' })
const second = createMockPlugin({
org: 'test',
name: 'second',
plugin_id: 'test/second',
version: '',
latest_version: '2.0.0',
})
// For identifier dependencies, the response can arrive in a different order.
const responseOrder =
'marketplace_plugin_unique_identifier' in value ? [remote, second] : [second, remote]
requests.marketplace.mockResolvedValue({
data: { list: responseOrder.map((plugin) => ({ plugin })) },
})
const input = params([
packageDependency,
{ type: 'marketplace', value: { marketplace_plugin_unique_identifier: 'test/second:2.0.0' } },
{ type: 'marketplace', value },
])
const { result } = renderHook(() => useInstallMultiState(input))
await waitFor(() => expect(input.onLoadedAllPlugin).toHaveBeenCalledWith({}))
expect(requests.marketplace).toHaveBeenCalledWith('/plugins/versions/batch', {
body: {
plugin_tuples: [
{ org: 'test', name: 'second', version: '2.0.0' },
{ org: 'test', name: 'remote', version: '1.0.0' },
],
},
})
expect(result.current.plugins).toMatchObject([
{ plugin_id: 'test/local:1.0.0' },
{ plugin_id: 'test/second', version: '2.0.0' },
{ plugin_id: 'test/remote', version: '1.0.0' },
])
expect(requests.installed).toHaveBeenCalledWith({
body: { plugin_ids: ['test/local', 'test/second', 'test/remote'] },
})
expect(result.current.errorIndexes).toEqual([])
})
it.each(['invalid-identifier', 'test/:1.0.0', undefined])(
'rejects malformed marketplace identifier %s without fetching it',
async (identifier) => {
const input = params([
packageDependency,
{ type: 'marketplace', value: { marketplace_plugin_unique_identifier: identifier } },
])
const { result } = renderHook(() => useInstallMultiState(input))
await waitFor(() => expect(input.onLoadedAllPlugin).toHaveBeenCalledWith({}))
expect(result.current.errorIndexes).toEqual([1])
expect(requests.marketplace).not.toHaveBeenCalled()
},
)
it('marks only missing marketplace entries as failed', async () => {
requests.marketplace.mockResolvedValue({
data: { list: [{ plugin: createMockPlugin({ plugin_id: 'test/remote' }) }] },
})
const input = params([
packageDependency,
marketplaceDependency,
{
type: 'marketplace',
value: { marketplace_plugin_unique_identifier: 'test/missing:1.0.0' },
},
])
const { result } = renderHook(() => useInstallMultiState(input))
await waitFor(() => expect(input.onLoadedAllPlugin).toHaveBeenCalledWith({}))
expect(result.current.errorIndexes).toEqual([2])
expect(result.current.plugins[0]?.plugin_id).toBe('test/local:1.0.0')
expect(result.current.plugins[1]?.plugin_id).toBe('test/remote')
})
it('waits for every source and installed lookup while preserving concurrent GitHub results and failures', async () => {
requests.marketplace.mockRejectedValueOnce(new Error('Marketplace unavailable'))
const installed = createDeferred<{ plugins: [] }>()
requests.installed.mockReturnValueOnce(installed.promise)
const input = params([
packageDependency,
marketplaceDependency,
githubDependency,
githubDependency,
githubDependency,
])
const { result } = renderHook(() => useInstallMultiState(input))
await waitFor(() => expect(result.current.errorIndexes).toEqual([1]))
expect(input.onLoadedAllPlugin).not.toHaveBeenCalled()
expect(requests.installed).not.toHaveBeenCalled()
const github = createMockPlugin({ org: 'test', name: 'github', plugin_id: 'test/github' })
act(() => {
result.current.handleGitHubPluginFetched(2)(github)
result.current.handleGitHubPluginFetchError(3)()
result.current.handleGitHubPluginFetchError(4)()
})
await waitFor(() => expect(requests.installed).toHaveBeenCalledOnce())
expect(input.onLoadedAllPlugin).not.toHaveBeenCalled()
installed.resolve({ plugins: [] })
await waitFor(() => expect(input.onLoadedAllPlugin).toHaveBeenCalledWith({}))
expect(result.current.errorIndexes).toEqual([1, 3, 4])
expect(result.current.plugins).toEqual([
expect.objectContaining({ plugin_id: 'test/local:1.0.0' }),
undefined,
github,
undefined,
undefined,
])
})
it('excludes unresolved plugins from bulk selection before metadata finishes', () => {
const input = params([packageDependency, githubDependency])
input.selectedPlugins = [createMockPlugin({ plugin_id: 'test/local:1.0.0' })]
const { result } = renderHook(() => useInstallMultiState(input), {
systemFeatures: {
plugin_installation_permission: {
plugin_installation_scope: 'all',
restrict_to_marketplace_only: false,
},
},
})
expect(result.current.getInstallablePlugins()).toEqual({
installablePlugins: [expect.objectContaining({ plugin_id: 'test/local:1.0.0' })],
selectedIndexes: [0],
})
expect(result.current.isPluginSelected(0)).toBe(true)
expect(result.current.isPluginSelected(1)).toBe(false)
expect(input.onLoadedAllPlugin).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,292 @@
'use client'
import type {
Dependency,
GitHubItemAndMarketPlaceDependency,
PackageDependency,
Plugin,
VersionInfo,
} from '@/app/components/plugins/types'
import { useSuspenseQuery } from '@tanstack/react-query'
import { useCallback, useEffect, useMemo, useState } from 'react'
import useCheckInstalled from '@/app/components/plugins/install-plugin/hooks/use-check-installed'
import { pluginInstallLimit } from '@/app/components/plugins/install-plugin/hooks/use-install-plugin-limit'
import { getFormattedPlugin } from '@/app/components/plugins/marketplace/utils'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import { useFetchPluginsInMarketPlaceByInfo } from '@/service/use-plugins'
type UseInstallMultiStateParams = {
allPlugins: Dependency[]
selectedPlugins: Plugin[]
onSelect: (plugin: Plugin, selectedIndex: number, allCanInstallPluginsLength: number) => void
onLoadedAllPlugin: (installedInfo: Record<string, VersionInfo>) => void
}
type MarketplacePluginInfo = {
organization: string
plugin: string
version?: string
}
type MarketplaceRequest = {
dslIndex: number
dependency: GitHubItemAndMarketPlaceDependency
info: MarketplacePluginInfo
}
export function getPluginKey(plugin: Plugin | undefined): string {
return `${plugin?.org || plugin?.author}/${plugin?.name}`
}
function parseMarketplaceIdentifier(identifier?: string): MarketplacePluginInfo | null {
if (!identifier) return null
const withoutHash = identifier.split('@')[0]
const [organization, nameAndVersionPart] = withoutHash!.split('/')
if (!organization || !nameAndVersionPart) return null
const [plugin, version] = nameAndVersionPart.split(':')
if (!plugin) return null
return { organization, plugin, version }
}
function getMarketplacePluginInfo(
value: GitHubItemAndMarketPlaceDependency['value'],
): MarketplacePluginInfo | null {
const parsedInfo = parseMarketplaceIdentifier(
value.marketplace_plugin_unique_identifier || value.plugin_unique_identifier,
)
if (parsedInfo) return parsedInfo
if (!value.organization || !value.plugin) return null
return {
organization: value.organization,
plugin: value.plugin,
version: value.version,
}
}
function initPluginsFromDependencies(allPlugins: Dependency[]): (Plugin | undefined)[] {
if (!allPlugins.some((d) => d.type === 'package')) return []
return allPlugins.map((d) => {
if (d.type !== 'package') return undefined
const { manifest, unique_identifier } = (d as PackageDependency).value
return {
...manifest,
plugin_id: unique_identifier,
} as unknown as Plugin
})
}
export function useInstallMultiState({
allPlugins,
selectedPlugins,
onSelect,
onLoadedAllPlugin,
}: UseInstallMultiStateParams) {
const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
// Marketplace plugins filtering and index mapping
const marketplacePlugins = useMemo(
() =>
allPlugins.filter((d): d is GitHubItemAndMarketPlaceDependency => d.type === 'marketplace'),
[allPlugins],
)
const marketPlaceInDSLIndex = useMemo(() => {
return allPlugins.reduce<number[]>((acc, d, index) => {
if (d.type === 'marketplace') acc.push(index)
return acc
}, [])
}, [allPlugins])
const { marketplaceRequests, invalidMarketplaceIndexes } = useMemo(() => {
return marketplacePlugins.reduce<{
marketplaceRequests: MarketplaceRequest[]
invalidMarketplaceIndexes: number[]
}>(
(acc, dependency, marketplaceIndex) => {
const dslIndex = marketPlaceInDSLIndex[marketplaceIndex]
if (dslIndex === undefined) return acc
const marketplaceInfo = getMarketplacePluginInfo(dependency.value)
if (!marketplaceInfo) acc.invalidMarketplaceIndexes.push(dslIndex)
else acc.marketplaceRequests.push({ dslIndex, dependency, info: marketplaceInfo })
return acc
},
{
marketplaceRequests: [],
invalidMarketplaceIndexes: [],
},
)
}, [marketPlaceInDSLIndex, marketplacePlugins])
// Marketplace data fetching: by normalized marketplace info
const {
isLoading: isFetchingById,
data: infoGetById,
error: infoByIdError,
} = useFetchPluginsInMarketPlaceByInfo(marketplaceRequests.map((request) => request.info))
// Derive marketplace plugin data and errors from API responses
const { marketplacePluginMap, marketplaceErrorIndexes } = useMemo(() => {
const pluginMap = new Map<number, Plugin>()
const errorSet = new Set<number>(invalidMarketplaceIndexes)
// Process "by ID" response
if (!isFetchingById && infoGetById?.data.list) {
const payloads = infoGetById.data.list
const pluginById = new Map(payloads.map((item) => [item.plugin.plugin_id, item.plugin]))
marketplaceRequests.forEach((request, requestIndex) => {
const pluginId = (
request.dependency.value.marketplace_plugin_unique_identifier ||
request.dependency.value.plugin_unique_identifier
)?.split(':')[0]
const pluginInfo =
(pluginId ? pluginById.get(pluginId) : undefined) || payloads[requestIndex]?.plugin
if (pluginInfo) {
pluginMap.set(
request.dslIndex,
getFormattedPlugin({
...pluginInfo,
from: request.dependency.type,
version: pluginInfo.version || pluginInfo.latest_version,
}),
)
} else {
errorSet.add(request.dslIndex)
}
})
}
// Mark all marketplace indexes as errors on fetch failure
if (infoByIdError) marketPlaceInDSLIndex.forEach((index) => errorSet.add(index))
return { marketplacePluginMap: pluginMap, marketplaceErrorIndexes: errorSet }
}, [
invalidMarketplaceIndexes,
isFetchingById,
infoGetById,
infoByIdError,
marketPlaceInDSLIndex,
marketplaceRequests,
])
// GitHub-fetched plugins and errors (imperative state from child callbacks)
const [githubPluginMap, setGithubPluginMap] = useState<Map<number, Plugin>>(() => new Map())
const [githubErrorIndexes, setGithubErrorIndexes] = useState<number[]>([])
// Merge all plugin sources into a single array
const plugins = useMemo(() => {
const initial = initPluginsFromDependencies(allPlugins)
const result: (Plugin | undefined)[] = allPlugins.map((_, i) => initial[i])
marketplacePluginMap.forEach((plugin, index) => {
result[index] = plugin
})
githubPluginMap.forEach((plugin, index) => {
result[index] = plugin
})
return result
}, [allPlugins, marketplacePluginMap, githubPluginMap])
// Merge all error sources
const errorIndexes = useMemo(() => {
return [...marketplaceErrorIndexes, ...githubErrorIndexes]
}, [marketplaceErrorIndexes, githubErrorIndexes])
// Check installed status after all data is loaded
const isLoadedAllData = plugins.filter(Boolean).length + errorIndexes.length === allPlugins.length
const { installedInfo } = useCheckInstalled({
pluginIds: plugins.filter(Boolean).map((d) => getPluginKey(d)) || [],
enabled: isLoadedAllData,
})
// Notify parent when all plugin data and install info is ready
useEffect(() => {
if (isLoadedAllData && installedInfo) onLoadedAllPlugin(installedInfo!)
// oxlint-disable-next-line react/exhaustive-deps
}, [isLoadedAllData, installedInfo])
// Callback: handle GitHub plugin fetch success
const handleGitHubPluginFetched = useCallback((index: number) => {
return (p: Plugin) => {
setGithubPluginMap((prev) => new Map(prev).set(index, p))
}
}, [])
// Callback: handle GitHub plugin fetch error
const handleGitHubPluginFetchError = useCallback((index: number) => {
return () => {
setGithubErrorIndexes((prev) => [...prev, index])
}
}, [])
// Callback: get version info for a plugin by its key
const getVersionInfo = useCallback(
(pluginId: string) => {
const pluginDetail = installedInfo?.[pluginId]
return {
hasInstalled: !!pluginDetail,
installedVersion: pluginDetail?.installedVersion,
toInstallVersion: '',
}
},
[installedInfo],
)
// Callback: handle plugin selection
const handleSelect = useCallback(
(index: number) => {
return () => {
const canSelectPlugins = plugins.filter((p) => {
const { canInstall } = pluginInstallLimit(p!, systemFeatures)
return canInstall
})
onSelect(plugins[index]!, index, canSelectPlugins.length)
}
},
[onSelect, plugins, systemFeatures],
)
// Callback: check if a plugin at given index is selected
const isPluginSelected = useCallback(
(index: number) => {
return !!selectedPlugins.find((p) => p.plugin_id === plugins[index]?.plugin_id)
},
[selectedPlugins, plugins],
)
// Callback: get all installable plugins with their indexes
const getInstallablePlugins = useCallback(() => {
const selectedIndexes: number[] = []
const installablePlugins: Plugin[] = []
allPlugins.forEach((_d, index) => {
const p = plugins[index]
if (!p) return
const { canInstall } = pluginInstallLimit(p, systemFeatures)
if (canInstall) {
selectedIndexes.push(index)
installablePlugins.push(p)
}
})
return { selectedIndexes, installablePlugins }
}, [allPlugins, plugins, systemFeatures])
return {
plugins,
errorIndexes,
handleGitHubPluginFetched,
handleGitHubPluginFetchError,
getVersionInfo,
handleSelect,
isPluginSelected,
getInstallablePlugins,
}
}
@@ -0,0 +1,119 @@
'use client'
import type {
Dependency,
GitHubItemAndMarketPlaceDependency,
PackageDependency,
Plugin,
VersionInfo,
} from '../../../types'
import * as React from 'react'
import { useImperativeHandle } from 'react'
import LoadingError from '../../base/loading-error'
import GithubItem from '../item/github-item'
import MarketplaceItem from '../item/marketplace-item'
import PackageItem from '../item/package-item'
import { getPluginKey, useInstallMultiState } from './hooks/use-install-multi-state'
type Props = Readonly<{
allPlugins: Dependency[]
selectedPlugins: Plugin[]
onSelect: (plugin: Plugin, selectedIndex: number, allCanInstallPluginsLength: number) => void
onSelectAll: (plugins: Plugin[], selectedIndexes: number[]) => void
onDeSelectAll: () => void
onLoadedAllPlugin: (installedInfo: Record<string, VersionInfo>) => void
isFromMarketPlace?: boolean
ref?: React.Ref<ExposeRefs>
}>
export type ExposeRefs = {
selectAllPlugins: () => void
deSelectAllPlugins: () => void
}
const InstallByDSLList = ({
allPlugins,
selectedPlugins,
onSelect,
onSelectAll,
onDeSelectAll,
onLoadedAllPlugin,
isFromMarketPlace,
ref,
}: Props) => {
const {
plugins,
errorIndexes,
handleGitHubPluginFetched,
handleGitHubPluginFetchError,
getVersionInfo,
handleSelect,
isPluginSelected,
getInstallablePlugins,
} = useInstallMultiState({
allPlugins,
selectedPlugins,
onSelect,
onLoadedAllPlugin,
})
useImperativeHandle(ref, () => ({
selectAllPlugins: () => {
const { installablePlugins, selectedIndexes } = getInstallablePlugins()
onSelectAll(installablePlugins, selectedIndexes)
},
deSelectAllPlugins: onDeSelectAll,
}))
return (
<>
{allPlugins.map((d, index) => {
if (errorIndexes.includes(index)) return <LoadingError key={index} />
const plugin = plugins[index]
const checked = isPluginSelected(index)
const versionInfo = getVersionInfo(getPluginKey(plugin))
if (d.type === 'github') {
return (
<GithubItem
key={index}
checked={checked}
onCheckedChange={handleSelect(index)}
dependency={d as GitHubItemAndMarketPlaceDependency}
onFetchedPayload={handleGitHubPluginFetched(index)}
onFetchError={handleGitHubPluginFetchError(index)}
versionInfo={versionInfo}
/>
)
}
if (d.type === 'marketplace') {
return (
<MarketplaceItem
key={index}
checked={checked}
onCheckedChange={handleSelect(index)}
payload={plugin}
version={
(d as GitHubItemAndMarketPlaceDependency).value.version! || plugin?.version || ''
}
versionInfo={versionInfo}
/>
)
}
return (
<PackageItem
key={index}
checked={checked}
onCheckedChange={handleSelect(index)}
payload={d as PackageDependency}
isFromMarketPlace={isFromMarketPlace}
versionInfo={versionInfo}
/>
)
})}
</>
)
}
export default InstallByDSLList
@@ -0,0 +1,255 @@
'use client'
import type { FC } from 'react'
import type { Dependency, InstallStatusResponse, Plugin, VersionInfo } from '../../../types'
import type { InstallBundleCompleteCallback } from '../index'
import type { ExposeRefs } from './install-multi'
import { Button } from '@langgenius/dify-ui/button'
import { Checkbox } from '@langgenius/dify-ui/checkbox'
import { RiLoader2Line } from '@remixicon/react'
import * as React from 'react'
import { useCallback, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useCanInstallPluginFromMarketplace } from '@/app/components/plugins/plugin-page/use-reference-setting'
import { useInstallOrUpdate, usePluginTaskList } from '@/service/use-plugins'
import { TaskStatus } from '../../../types'
import checkTaskStatus from '../../base/check-task-status'
import useRefreshPluginList from '../../hooks/use-refresh-plugin-list'
import { getPluginKey } from './hooks/use-install-multi-state'
import InstallMulti from './install-multi'
const i18nPrefix = 'installModal'
type Props = Readonly<{
allPlugins: Dependency[]
onStartToInstall?: () => void
onInstalled: InstallBundleCompleteCallback
onCancel: () => void
isFromMarketPlace?: boolean
isHideButton?: boolean
}>
const Install: FC<Props> = ({
allPlugins,
onStartToInstall,
onInstalled,
onCancel,
isFromMarketPlace,
isHideButton,
}) => {
const { t } = useTranslation(['common', 'plugin'])
const [selectedPlugins, setSelectedPlugins] = React.useState<Plugin[]>([])
const [selectedIndexes, setSelectedIndexes] = React.useState<number[]>([])
const selectedPluginsNum = selectedPlugins.length
const installMultiRef = useRef<ExposeRefs>(null)
const { refreshPluginList } = useRefreshPluginList()
const [isSelectAll, setIsSelectAll] = useState(false)
const handleClickSelectAll = useCallback(() => {
if (isSelectAll) installMultiRef.current?.deSelectAllPlugins()
else installMultiRef.current?.selectAllPlugins()
}, [isSelectAll])
const [canInstall, setCanInstall] = React.useState(false)
const [installedInfo, setInstalledInfo] = useState<Record<string, VersionInfo> | undefined>(
undefined,
)
const handleLoadedAllPlugin = useCallback(
(installedInfo: Record<string, VersionInfo> | undefined) => {
handleClickSelectAll()
setInstalledInfo(installedInfo)
setCanInstall(true)
},
[],
)
const { check, stop } = checkTaskStatus()
const handleCancel = useCallback(() => {
stop()
onCancel()
}, [onCancel, stop])
const { handleRefetch } = usePluginTaskList()
const getSelectedVersionInfo = useCallback(() => {
return selectedPlugins.map((plugin) => {
const pluginDetail = installedInfo?.[getPluginKey(plugin)]
return {
hasInstalled: !!pluginDetail,
installedVersion: pluginDetail?.installedVersion,
toInstallVersion: plugin.version,
}
})
}, [installedInfo, selectedPlugins])
// Install from marketplace and github
const { mutate: installOrUpdate, isPending: isInstalling } = useInstallOrUpdate({
onSuccess: async (res: InstallStatusResponse[]) => {
const isAllSettled = res.every(
(r) => r.status === TaskStatus.success || r.status === TaskStatus.failed,
)
// if all settled, return the install status
if (isAllSettled) {
onInstalled(
selectedPlugins,
res.map((r, i) => {
return {
success: r.status === TaskStatus.success,
isFromMarketPlace: allPlugins[selectedIndexes[i]!]!.type === 'marketplace',
}
}),
getSelectedVersionInfo(),
)
const hasInstallSuccess = res.some((r) => r.status === TaskStatus.success)
if (hasInstallSuccess) {
refreshPluginList(undefined, true)
}
return
}
// if not all settled, keep checking the status of the plugins
handleRefetch()
const installStatus = await Promise.all(
res.map(async (item, index) => {
if (item.status !== TaskStatus.running) {
return {
success: item.status === TaskStatus.success,
isFromMarketPlace: allPlugins[selectedIndexes[index]!]!.type === 'marketplace',
}
}
const { status } = await check({
taskId: item.taskId,
pluginUniqueIdentifier: item.uniqueIdentifier,
})
return {
success: status === TaskStatus.success,
isFromMarketPlace: allPlugins[selectedIndexes[index]!]!.type === 'marketplace',
}
}),
)
onInstalled(selectedPlugins, installStatus, getSelectedVersionInfo())
},
})
const handleInstall = () => {
onStartToInstall?.()
installOrUpdate({
payload: allPlugins.filter((_d, index) => selectedIndexes.includes(index)),
plugin: selectedPlugins,
installedInfo: installedInfo!,
})
}
const [isIndeterminate, setIsIndeterminate] = useState(false)
const handleSelectAll = useCallback((plugins: Plugin[], selectedIndexes: number[]) => {
setSelectedPlugins(plugins)
setSelectedIndexes(selectedIndexes)
setIsSelectAll(true)
setIsIndeterminate(false)
}, [])
const handleDeSelectAll = useCallback(() => {
setSelectedPlugins([])
setSelectedIndexes([])
setIsSelectAll(false)
setIsIndeterminate(false)
}, [])
const handleSelect = useCallback(
(plugin: Plugin, selectedIndex: number, allPluginsLength: number) => {
const isSelected = !!selectedPlugins.find((p) => p.plugin_id === plugin.plugin_id)
let nextSelectedPlugins
if (isSelected)
nextSelectedPlugins = selectedPlugins.filter((p) => p.plugin_id !== plugin.plugin_id)
else nextSelectedPlugins = [...selectedPlugins, plugin]
setSelectedPlugins(nextSelectedPlugins)
const nextSelectedIndexes = isSelected
? selectedIndexes.filter((i) => i !== selectedIndex)
: [...selectedIndexes, selectedIndex]
setSelectedIndexes(nextSelectedIndexes)
if (nextSelectedPlugins.length === 0) {
setIsSelectAll(false)
setIsIndeterminate(false)
} else if (nextSelectedPlugins.length === allPluginsLength) {
setIsSelectAll(true)
setIsIndeterminate(false)
} else {
setIsIndeterminate(true)
setIsSelectAll(false)
}
},
[selectedPlugins, selectedIndexes],
)
const { canInstallPluginFromMarketplace } = useCanInstallPluginFromMarketplace()
return (
<div className="flex min-h-0 flex-1 flex-col self-stretch overflow-hidden">
<div className="flex min-h-0 flex-1 flex-col items-start justify-center gap-4 self-stretch overflow-hidden px-6 py-3">
<div className="system-md-regular text-text-secondary">
<p>
{t(
($) =>
$[
`${i18nPrefix}.${selectedPluginsNum > 1 ? 'readyToInstallPackages' : 'readyToInstallPackage'}`
],
{ ns: 'plugin', num: selectedPluginsNum },
)}
</p>
</div>
<div className="flex min-h-0 w-full flex-1 flex-col gap-1 overflow-y-auto rounded-2xl bg-background-section-burn p-2">
<InstallMulti
ref={installMultiRef}
allPlugins={allPlugins}
selectedPlugins={selectedPlugins}
onSelect={handleSelect}
onSelectAll={handleSelectAll}
onDeSelectAll={handleDeSelectAll}
onLoadedAllPlugin={handleLoadedAllPlugin}
isFromMarketPlace={isFromMarketPlace}
/>
</div>
</div>
{/* Action Buttons */}
{!isHideButton && (
<div className="flex items-center justify-between gap-2 self-stretch p-6 pt-5">
<div className="px-2">
{canInstall && (
<label className="flex cursor-pointer items-center gap-x-2">
<Checkbox
checked={isSelectAll}
indeterminate={isIndeterminate}
onCheckedChange={() => handleClickSelectAll()}
/>
<span className="system-sm-medium text-text-secondary">
{isSelectAll
? t(($) => $['operation.deSelectAll'], { ns: 'common' })
: t(($) => $['operation.selectAll'], { ns: 'common' })}
</span>
</label>
)}
</div>
<div className="flex items-center justify-end gap-2 self-stretch">
{!canInstall && (
<Button variant="secondary" className="min-w-18" onClick={handleCancel}>
{t(($) => $['operation.cancel'], { ns: 'common' })}
</Button>
)}
<Button
variant="primary"
className="flex min-w-18"
disabled={
!canInstall ||
isInstalling ||
selectedPlugins.length === 0 ||
!canInstallPluginFromMarketplace
}
onClick={handleInstall}
>
{isInstalling && <RiLoader2Line className="size-4 animate-spin-slow" />}
<span>
{t(($) => $[`${i18nPrefix}.${isInstalling ? 'installing' : 'install'}`], {
ns: 'plugin',
})}
</span>
</Button>
</div>
</div>
)}
</div>
)
}
export default React.memo(Install)
@@ -0,0 +1,77 @@
'use client'
import type { FC } from 'react'
import type { InstallStatus, Plugin, VersionProps } from '../../../types'
import { Button } from '@langgenius/dify-ui/button'
import * as React from 'react'
import { useTranslation } from 'react-i18next'
import Badge from '@/app/components/base/badge/index'
import Card from '@/app/components/plugins/card'
import { getMarketplacePluginIconUrl } from '@/features/marketplace/api'
import useGetIcon from '../../base/use-get-icon'
import Version from '../../base/version'
type Props = Readonly<{
list: Plugin[]
installStatus: InstallStatus[]
versionInfo?: VersionProps[]
onCancel: () => void
isHideButton?: boolean
}>
const Installed: FC<Props> = ({ list, installStatus, versionInfo, onCancel, isHideButton }) => {
const { t } = useTranslation(['common', 'plugin'])
const { getIconUrl } = useGetIcon()
return (
<>
<div className="flex flex-col items-start justify-center gap-4 self-stretch px-6 py-3">
<p className="system-md-regular text-text-secondary">
{t(($) => $['installModal.installedSuccessfullyCountDesc'], {
ns: 'plugin',
num: list.length,
})}
</p>
<div className="flex flex-wrap content-start items-start gap-1 space-y-1 self-stretch rounded-2xl bg-background-section-burn p-2">
{list.map((plugin, index) => {
const pluginVersionInfo = versionInfo?.[index]
return (
<Card
key={plugin.plugin_id}
className="w-full"
payload={{
...plugin,
icon: installStatus[index]!.isFromMarketPlace
? getMarketplacePluginIconUrl(`${plugin.org}/${plugin.name}`)
: getIconUrl(plugin.icon),
}}
installed={installStatus[index]!.success}
installFailed={!installStatus[index]!.success}
titleLeft={
plugin.version ? (
pluginVersionInfo ? (
<Version {...pluginVersionInfo} />
) : (
<Badge className="mx-1" size="s">
{plugin.version}
</Badge>
)
) : null
}
compact
/>
)
})}
</div>
</div>
{/* Action Buttons */}
{!isHideButton && (
<div className="flex items-center justify-end gap-2 self-stretch p-6 pt-5">
<Button variant="primary" className="min-w-18" onClick={onCancel}>
{t(($) => $['operation.close'], { ns: 'common' })}
</Button>
</div>
)}
</>
)
}
export default React.memo(Installed)