chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动
演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
60158935f4
commit
6519682885
15831 files changed
+3063428
No files matched your search
+216
@@ -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()
|
||||
})
|
||||
})
|
||||
+292
@@ -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,
|
||||
}
|
||||
}
|
||||
+119
@@ -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
|
||||
+255
@@ -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)
|
||||
+77
@@ -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)
|
||||
Reference in new issue
Block a user