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,69 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import { checkForUpdates, fetchReleases } from '../hooks'
const { mockToastError } = vi.hoisted(() => ({
mockToastError: vi.fn(),
}))
vi.mock('@/app/notifications', () => ({
toast: {
error: mockToastError,
},
}))
const mockFetch = vi.fn<typeof fetch>()
describe('install-plugin/hooks', () => {
beforeEach(() => {
mockFetch.mockReset()
mockToastError.mockReset()
vi.stubGlobal('fetch', mockFetch)
})
afterEach(() => {
vi.unstubAllGlobals()
})
describe('fetchReleases', () => {
it('leaves failed responses to the business caller', async () => {
mockFetch.mockResolvedValue(new Response(null, { status: 500 }))
await expect(fetchReleases('owner', 'repo')).rejects.toThrow(
'Failed to fetch repository releases',
)
expect(mockFetch).toHaveBeenCalledOnce()
expect(mockFetch).toHaveBeenCalledWith('https://ungh.cc/repos/owner/repo/releases')
expect(mockToastError).not.toHaveBeenCalled()
})
})
describe('checkForUpdates', () => {
it('detects newer version available', () => {
const releases = [
{ tag_name: 'v1.0.0', assets: [] },
{ tag_name: 'v2.0.0', assets: [] },
]
const { needUpdate, toastProps } = checkForUpdates(releases, 'v1.0.0')
expect(needUpdate).toBe(true)
expect(toastProps.message).toContain('v2.0.0')
})
it('returns no update when current is latest', () => {
const releases = [{ tag_name: 'v1.0.0', assets: [] }]
const { needUpdate, toastProps } = checkForUpdates(releases, 'v1.0.0')
expect(needUpdate).toBe(false)
expect(toastProps.type).toBe('info')
})
it('returns error for empty releases', () => {
const { needUpdate, toastProps } = checkForUpdates([], 'v1.0.0')
expect(needUpdate).toBe(false)
expect(toastProps.type).toBe('error')
expect(toastProps.message).toContain('empty')
})
})
})
@@ -0,0 +1,217 @@
import type { PluginDeclaration, PluginManifestInMarket } from '../../types'
import { describe, expect, it } from 'vite-plus/test'
import { PluginCategoryEnum } from '../../types'
import {
convertRepoToUrl,
parseGitHubUrl,
pluginDeclarationToCardPluginProps,
pluginManifestInMarketToPluginProps,
pluginManifestToCardPluginProps,
toPluginText,
} from '../utils'
describe('pluginManifestToCardPluginProps', () => {
const createMockPluginDeclaration = (
overrides?: Partial<PluginDeclaration>,
): PluginDeclaration => ({
plugin_unique_identifier: 'test-plugin-123',
version: '1.0.0',
author: 'test-author',
icon: '/test-icon.png',
name: 'test-plugin',
category: PluginCategoryEnum.tool,
label: { 'en-US': 'Test Plugin' } as Record<string, string>,
description: { 'en-US': 'Test description' } as Record<string, string>,
created_at: '2024-01-01',
resource: {},
plugins: {},
verified: true,
endpoint: { settings: [], endpoints: [] },
model: {},
tags: ['search', 'api'],
agent_strategy: null,
meta: { version: '1.0.0' },
trigger: {} as PluginDeclaration['trigger'],
...overrides,
})
it('converts a package manifest into its card identity and metadata', () => {
const manifest = createMockPluginDeclaration({
category: PluginCategoryEnum.model,
label: {
...createMockPluginDeclaration().label,
'en-US': 'My Plugin',
'zh-Hans': '我的插件',
},
icon_dark: '/dark-icon.png',
})
expect(pluginManifestToCardPluginProps(manifest)).toEqual({
plugin_id: 'test-plugin-123',
type: PluginCategoryEnum.model,
category: PluginCategoryEnum.model,
name: 'test-plugin',
version: '1.0.0',
org: 'test-author',
author: 'test-author',
label: { 'en-US': 'My Plugin', 'zh-Hans': '我的插件' },
brief: { 'en-US': 'Test description' },
description: { 'en-US': 'Test description' },
icon: '/test-icon.png',
icon_dark: '/dark-icon.png',
verified: true,
latest_version: '',
latest_package_identifier: '',
introduction: '',
repository: '',
install_count: 0,
endpoint: { settings: [] },
tags: [{ name: 'search' }, { name: 'api' }],
badges: [],
verification: { authorized_category: 'langgenius' },
from: 'package',
})
})
it('keeps untagged package manifests untagged', () => {
expect(pluginManifestToCardPluginProps(createMockPluginDeclaration({ tags: [] })).tags).toEqual(
[],
)
})
})
describe('pluginDeclarationToCardPluginProps', () => {
const manifest = {
author: null,
category: 'agent-strategy',
created_at: '2026-01-01T00:00:00Z',
description: { en_US: 'Description', zh_Hans: null },
icon: 'icon.svg',
label: { en_US: 'Agent', zh_Hans: '代理' },
meta: { minimum_dify_version: null, version: '0.0.1' },
name: 'agent',
plugins: {},
resource: { memory: 0 },
version: '1.0.0',
} satisfies Parameters<typeof pluginDeclarationToCardPluginProps>[0]
it('reads the uploaded package as a card', () => {
expect(
pluginDeclarationToCardPluginProps(manifest, 'langgenius/agent:1.0.0@hash'),
).toMatchObject({
plugin_id: 'langgenius/agent:1.0.0@hash',
type: 'agent_strategy',
category: 'agent-strategy',
org: '',
author: undefined,
label: { en_US: 'Agent', zh_Hans: '代理' },
description: { en_US: 'Description' },
verified: false,
tags: [],
})
})
it('leaves untranslated locales out of card text', () => {
expect(toPluginText({ en_US: 'Name', ja_JP: null, pt_BR: 'Nome' })).toEqual({
en_US: 'Name',
pt_BR: 'Nome',
})
})
})
describe('pluginManifestInMarketToPluginProps', () => {
const createMockPluginManifestInMarket = (
overrides?: Partial<PluginManifestInMarket>,
): PluginManifestInMarket => ({
plugin_unique_identifier: 'market-plugin-123',
name: 'market-plugin',
org: 'market-org',
icon: '/market-icon.png',
label: { 'en-US': 'Market Plugin' } as Record<string, string>,
category: PluginCategoryEnum.tool,
version: '1.0.0',
latest_version: '1.2.0',
brief: { 'en-US': 'Market plugin description' } as Record<string, string>,
introduction: 'Full introduction text',
verified: true,
install_count: 5000,
badges: ['partner', 'verified'],
verification: { authorized_category: 'langgenius' },
from: 'marketplace',
...overrides,
})
it('uses the latest marketplace version and marketplace metadata for the card', () => {
const manifest = createMockPluginManifestInMarket({ category: PluginCategoryEnum.model })
expect(pluginManifestInMarketToPluginProps(manifest)).toEqual({
plugin_id: 'market-plugin-123',
type: PluginCategoryEnum.model,
category: PluginCategoryEnum.model,
name: 'market-plugin',
version: '1.2.0',
latest_version: '1.2.0',
org: 'market-org',
label: { 'en-US': 'Market Plugin' },
brief: { 'en-US': 'Market plugin description' },
description: { 'en-US': 'Market plugin description' },
icon: '/market-icon.png',
verified: true,
introduction: 'Full introduction text',
latest_package_identifier: '',
repository: '',
install_count: 0,
tags: [],
endpoint: { settings: [] },
badges: ['partner', 'verified'],
verification: { authorized_category: 'langgenius' },
from: 'marketplace',
})
})
it.each([
[{ authorized_category: 'partner' }, { authorized_category: 'partner' }],
[{}, { authorized_category: 'langgenius' }],
])('normalizes marketplace verification %j', (verification, expected) => {
expect(
pluginManifestInMarketToPluginProps(
createMockPluginManifestInMarket({
verification: verification as PluginManifestInMarket['verification'],
from: 'github',
}),
),
).toMatchObject({ verification: expected, from: 'github' })
})
})
describe('parseGitHubUrl', () => {
it.each([
['https://github.com/owner/repo', 'owner', 'repo'],
['https://github.com/owner/repo/', 'owner', 'repo'],
['https://github.com/my-org/my_repo123', 'my-org', 'my_repo123'],
])('parses %s', (url, owner, repo) => {
expect(parseGitHubUrl(url)).toEqual({ isValid: true, owner, repo })
})
it.each([
'https://gitlab.com/owner/repo',
'https://github.com/owner/repo/tree/main',
'https://github.com/owner',
'',
'not-a-url',
'http://github.com/owner/repo',
'https://www.github.com/owner/repo',
])('rejects %s', (url) => {
expect(parseGitHubUrl(url)).toEqual({ isValid: false })
})
})
describe('convertRepoToUrl', () => {
it.each([
[
'organization_name/repository-name.js',
'https://github.com/organization_name/repository-name.js',
],
['', ''],
])('converts %s to its repository URL', (repo, expected) => {
expect(convertRepoToUrl(repo)).toBe(expected)
})
})
@@ -0,0 +1,86 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import { TaskStatus } from '../../../types'
import checkTaskStatus from '../check-task-status'
const { fetchTask } = vi.hoisted(() => ({ fetchTask: vi.fn() }))
vi.mock('@/service/plugins', () => ({ checkTaskStatus: fetchTask }))
const task = (status: TaskStatus) => ({
task: {
plugins: [
{
plugin_unique_identifier: 'other-plugin',
status: TaskStatus.failed,
message: 'Unrelated failure',
},
{ plugin_unique_identifier: 'test-plugin', status, message: '' },
],
},
})
const params = { taskId: 'task-1', pluginUniqueIdentifier: 'test-plugin' }
describe('checkTaskStatus', () => {
beforeEach(() => {
vi.resetAllMocks()
vi.useFakeTimers()
})
afterEach(() => vi.useRealTimers())
it('fails when the requested package is absent from the task', async () => {
fetchTask.mockResolvedValue({
task: { plugins: [{ plugin_unique_identifier: 'other-plugin', status: TaskStatus.success }] },
})
await expect(checkTaskStatus().check(params)).resolves.toEqual({
status: TaskStatus.failed,
error: 'Plugin package not found',
})
})
it('follows the requested package through pending and running until success', async () => {
fetchTask
.mockResolvedValueOnce(task(TaskStatus.pending))
.mockResolvedValueOnce(task(TaskStatus.running))
.mockResolvedValueOnce(task(TaskStatus.success))
const completed = vi.fn()
const result = checkTaskStatus().check(params).then(completed)
await vi.advanceTimersByTimeAsync(0)
expect(fetchTask).toHaveBeenCalledExactlyOnceWith('task-1')
expect(completed).not.toHaveBeenCalled()
await vi.advanceTimersByTimeAsync(10_000)
expect(fetchTask).toHaveBeenCalledTimes(2)
expect(completed).not.toHaveBeenCalled()
await vi.advanceTimersByTimeAsync(10_000)
await result
expect(fetchTask).toHaveBeenNthCalledWith(3, 'task-1')
expect(completed).toHaveBeenCalledExactlyOnceWith({ status: TaskStatus.success })
})
it('stops one checker before its first request without stopping another installation', async () => {
fetchTask.mockResolvedValue(task(TaskStatus.success))
const stopped = checkTaskStatus()
const active = checkTaskStatus()
stopped.stop()
await expect(stopped.check(params)).resolves.toEqual({ status: TaskStatus.success })
expect(fetchTask).not.toHaveBeenCalled()
await expect(active.check({ ...params, taskId: 'task-2' })).resolves.toEqual({
status: TaskStatus.success,
})
expect(fetchTask).toHaveBeenCalledExactlyOnceWith('task-2')
})
it('does not fetch again when stopped during the polling interval', async () => {
fetchTask.mockResolvedValue(task(TaskStatus.running))
const checker = checkTaskStatus()
const result = checker.check(params)
await vi.advanceTimersByTimeAsync(0)
checker.stop()
await vi.advanceTimersByTimeAsync(10_000)
await expect(result).resolves.toEqual({ status: TaskStatus.success })
expect(fetchTask).toHaveBeenCalledExactlyOnceWith('task-1')
})
})
@@ -0,0 +1,59 @@
import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { renderWithConsoleQuery as render } from '@/test/console/query-data'
import { createPluginDeclarationFixture } from '@/test/fixtures/plugin'
import { PluginCategoryEnum } from '../../../types'
import Installed from '../installed'
it('closes without a navigation link when installation matches the current category', async () => {
const user = userEvent.setup()
const onCancel = vi.fn()
render(
<Installed
payload={createPluginDeclarationFixture({ category: PluginCategoryEnum.extension })}
installContextCategory={PluginCategoryEnum.extension}
isFailed={false}
onCancel={onCancel}
/>,
)
expect(
screen.queryByRole('link', { name: 'plugin.installModal.viewDetails' }),
).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'common.operation.close' }))
expect(onCancel).toHaveBeenCalledOnce()
})
it('links to the installed category after success but keeps failures in the current context', async () => {
const user = userEvent.setup()
const onCancel = vi.fn()
const payload = createPluginDeclarationFixture({ category: PluginCategoryEnum.extension })
const { rerender } = render(
<Installed
payload={payload}
installContextCategory={PluginCategoryEnum.trigger}
isFailed={false}
onCancel={onCancel}
/>,
)
const details = screen.getByRole('link', { name: 'plugin.installModal.viewDetails' })
expect(details).toHaveAttribute('href', '/integrations/extension')
await user.click(details)
expect(onCancel).toHaveBeenCalledOnce()
rerender(
<Installed
payload={payload}
installContextCategory={PluginCategoryEnum.trigger}
isFailed
errMsg="Package verification failed"
onCancel={onCancel}
/>,
)
expect(screen.getByText('Package verification failed')).toBeInTheDocument()
expect(
screen.queryByRole('link', { name: 'plugin.installModal.viewDetails' }),
).not.toBeInTheDocument()
expect(screen.getByRole('button', { name: 'common.operation.close' })).toBeEnabled()
})
@@ -0,0 +1,61 @@
import { checkTaskStatus as fetchCheckTaskStatus } from '@/service/plugins'
import { sleep } from '@/utils'
import { TaskStatus } from '../../types'
const INTERVAL = 10 * 1000 // 10 seconds
const isUnfinishedStatus = (status: TaskStatus) =>
status === TaskStatus.pending || status === TaskStatus.running
type Params = {
taskId: string
pluginUniqueIdentifier: string
}
function checkTaskStatus() {
let nextStatus: TaskStatus = TaskStatus.running
let isStop = false
const doCheckStatus = async ({ taskId, pluginUniqueIdentifier }: Params) => {
if (isStop) {
return {
status: TaskStatus.success,
}
}
const res = await fetchCheckTaskStatus(taskId)
const { plugins } = res.task
const plugin = plugins.find((p) => p.plugin_unique_identifier === pluginUniqueIdentifier)
if (!plugin) {
nextStatus = TaskStatus.failed
return {
status: TaskStatus.failed,
error: 'Plugin package not found',
}
}
nextStatus = plugin.status
if (isUnfinishedStatus(nextStatus)) {
await sleep(INTERVAL)
return await doCheckStatus({
taskId,
pluginUniqueIdentifier,
})
}
if (nextStatus === TaskStatus.failed) {
return {
status: TaskStatus.failed,
error: plugin.message,
}
}
return {
status: TaskStatus.success,
}
}
return {
check: doCheckStatus,
stop: () => {
isStop = true
},
}
}
export default checkTaskStatus
@@ -0,0 +1,156 @@
'use client'
import type { FC } from 'react'
import type { Plugin, PluginDeclaration, PluginManifestInMarket } from '../../types'
import { Button, buttonVariants } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import * as React from 'react'
import { Trans, useTranslation } from 'react-i18next'
import Badge from '@/app/components/base/badge/index'
import { buildIntegrationPath } from '@/app/components/integrations/routes'
import Link from '@/next/link'
import Card from '../../card'
import { PluginCategoryEnum } from '../../types'
import { pluginManifestInMarketToPluginProps, pluginManifestToCardPluginProps } from '../utils'
type Props = Readonly<{
payload?: Plugin | PluginDeclaration | PluginManifestInMarket | null
isMarketPayload?: boolean
isFailed: boolean
errMsg?: string | null
installContextCategory?: PluginCategoryEnum
onCancel: () => void
}>
type CategoryTarget = {
labelKey:
| 'menus.tools'
| 'settings.agentStrategy'
| 'settings.dataSource'
| 'settings.extension'
| 'settings.provider'
| 'settings.trigger'
path: string
}
const categoryTargetMap: Partial<Record<PluginCategoryEnum, CategoryTarget>> = {
[PluginCategoryEnum.model]: {
labelKey: 'settings.provider',
path: buildIntegrationPath('provider'),
},
[PluginCategoryEnum.tool]: {
labelKey: 'menus.tools',
path: buildIntegrationPath('builtin'),
},
[PluginCategoryEnum.datasource]: {
labelKey: 'settings.dataSource',
path: buildIntegrationPath('data-source'),
},
[PluginCategoryEnum.trigger]: {
labelKey: 'settings.trigger',
path: buildIntegrationPath('trigger'),
},
[PluginCategoryEnum.agent]: {
labelKey: 'settings.agentStrategy',
path: buildIntegrationPath('agent-strategy'),
},
[PluginCategoryEnum.extension]: {
labelKey: 'settings.extension',
path: buildIntegrationPath('extension'),
},
}
const Installed: FC<Props> = ({
payload,
isMarketPayload,
isFailed,
errMsg,
installContextCategory,
onCancel,
}) => {
const { t } = useTranslation(['plugin', 'common', 'navigation'])
const installedCategory = payload?.category
const categoryTarget =
!isFailed && installContextCategory && installedCategory !== installContextCategory
? categoryTargetMap[installedCategory as PluginCategoryEnum]
: undefined
const categoryName = categoryTarget
? t(($) => $[categoryTarget.labelKey], { ns: 'navigation' })
: ''
const handleClose = () => {
onCancel()
}
return (
<>
<div className="flex min-h-0 min-w-0 flex-col items-start justify-center gap-2 self-stretch overflow-x-hidden overflow-y-auto px-6 py-3">
<p
className={cn(
'w-full max-w-full min-w-0 system-md-regular text-text-secondary',
isFailed && 'wrap-anywhere whitespace-pre-wrap',
)}
>
{isFailed && errMsg ? (
errMsg
) : categoryTarget ? (
<Trans
t={t}
i18nKey={($) => $['installModal.installedSuccessfullyWithPageDesc']}
ns="plugin"
components={{
categoryName: <span className="system-sm-semibold text-text-secondary" />,
}}
values={{ categoryName }}
/>
) : (
t(
($) =>
$[`installModal.${isFailed ? 'installFailedDesc' : 'installedSuccessfullyDesc'}`],
{ ns: 'plugin' },
)
)}
</p>
{payload && (
<div className="flex flex-wrap content-start items-start gap-1 self-stretch rounded-2xl bg-background-section-burn p-2">
<Card
className="w-full"
payload={
isMarketPayload
? pluginManifestInMarketToPluginProps(payload as PluginManifestInMarket)
: pluginManifestToCardPluginProps(payload as PluginDeclaration)
}
installed={!isFailed}
installFailed={isFailed}
titleLeft={
<Badge className="mx-1" size="s">
{(payload as PluginDeclaration).version ||
(payload as PluginManifestInMarket).latest_version}
</Badge>
}
compact
/>
</div>
)}
</div>
{/* Action Buttons */}
<div className="flex shrink-0 items-center justify-end gap-2 self-stretch p-6 pt-5">
{categoryTarget ? (
<Link
href={categoryTarget.path}
className={cn(buttonVariants({ variant: 'primary' }), 'min-w-18')}
onClick={handleClose}
>
<>
<span>{t(($) => $['installModal.viewDetails'], { ns: 'plugin' })}</span>
<span className="i-ri-arrow-right-up-line size-4 shrink-0" aria-hidden="true" />
</>
</Link>
) : (
<Button variant="primary" className="min-w-18" onClick={handleClose}>
{t(($) => $['operation.close'], { ns: 'common' })}
</Button>
)}
</div>
</>
)
}
export default React.memo(Installed)
@@ -0,0 +1,41 @@
'use client'
import type { FC } from 'react'
import { CheckboxSkeleton } from '@langgenius/dify-ui/checkbox'
import { RiCloseLine } from '@remixicon/react'
import * as React from 'react'
import { useTranslation } from 'react-i18next'
import { LoadingPlaceholder } from '@/app/components/plugins/card/base/placeholder'
const LoadingError: FC = () => {
const { t } = useTranslation(['plugin'])
return (
<div className="flex items-center space-x-2">
<CheckboxSkeleton className="shrink-0" />
<div className="relative grow rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg p-4 pb-3 shadow-xs">
<div className="flex">
<div className="relative flex h-10 w-10 items-center justify-center gap-2 rounded-[10px] border-[0.5px] border-state-destructive-border bg-state-destructive-hover p-1 backdrop-blur-xs">
<div className="flex size-5 items-center justify-center">
<span
aria-hidden
className="i-custom-vender-other-group h-4 w-3.5 text-text-quaternary"
/>
</div>
<div className="absolute -right-1 -bottom-1 rounded-full border-2 border-components-panel-bg bg-state-destructive-solid">
<RiCloseLine className="size-3 text-text-primary-on-surface" />
</div>
</div>
<div className="ml-3 grow">
<div className="flex h-5 items-center system-md-semibold text-text-destructive">
{t(($) => $['installModal.pluginLoadError'], { ns: 'plugin' })}
</div>
<div className="mt-0.5 system-xs-regular text-text-tertiary">
{t(($) => $['installModal.pluginLoadErrorDesc'], { ns: 'plugin' })}
</div>
</div>
</div>
<LoadingPlaceholder className="mt-3 w-105" />
</div>
</div>
)
}
export default React.memo(LoadingError)
@@ -0,0 +1,17 @@
'use client'
import { CheckboxSkeleton } from '@langgenius/dify-ui/checkbox'
import * as React from 'react'
import Placeholder from '../../card/base/placeholder'
const Loading = () => {
return (
<div className="flex items-center space-x-2">
<CheckboxSkeleton className="shrink-0" />
<div className="relative grow rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg p-4 pb-3 shadow-xs">
<Placeholder wrapClassName="w-full" />
</div>
</div>
)
}
export default React.memo(Loading)
@@ -0,0 +1,20 @@
import { useAtomValue } from 'jotai'
import { useCallback } from 'react'
import { API_PREFIX } from '@/config'
import { currentWorkspaceIdAtom } from '@/context/workspace-state'
const useGetIcon = () => {
const currentWorkspaceId = useAtomValue(currentWorkspaceIdAtom)
const getIconUrl = useCallback(
(fileName: string) => {
return `${API_PREFIX}/workspaces/current/plugin/icon?tenant_id=${currentWorkspaceId}&filename=${fileName}`
},
[currentWorkspaceId],
)
return {
getIconUrl,
}
}
export default useGetIcon
@@ -0,0 +1,28 @@
'use client'
import type { FC } from 'react'
import type { VersionProps } from '../../types'
import * as React from 'react'
import Badge from '@/app/components/base/badge/index'
const Version: FC<VersionProps> = ({ hasInstalled, installedVersion, toInstallVersion }) => {
return (
<>
{!hasInstalled ? (
<Badge className="mx-1" size="s">
{toInstallVersion}
</Badge>
) : (
<>
<Badge className="mx-1" size="s" variant="warning">
{`${installedVersion} -> ${toInstallVersion}`}
</Badge>
{/* <div className='flex px-0.5 justify-center items-center gap-0.5'>
<div className='text-text-warning system-xs-medium'>Used in 3 apps</div>
<RiInformation2Line className='w-4 h-4 text-text-tertiary' />
</div> */}
</>
)}
</>
)
}
export default React.memo(Version)
@@ -0,0 +1,61 @@
'use client'
import type { ReactNode } from 'react'
import { use, useEffect, useState } from 'react'
import {
createPluginInstallPermissionStore,
PluginInstallPermissionContext,
} from '../hooks/use-plugin-install-permission'
type PluginInstallPermissionProviderProps = {
canInstallPlugin: boolean
canUpdatePlugin?: boolean
currentDifyVersion?: string
children: ReactNode
}
export const PluginInstallPermissionProvider = ({
canInstallPlugin,
canUpdatePlugin,
currentDifyVersion,
children,
}: PluginInstallPermissionProviderProps) => {
const [store] = useState(() =>
createPluginInstallPermissionStore({
canInstallPlugin,
canUpdatePlugin,
currentDifyVersion,
}),
)
useEffect(() => {
store.getState().setPluginInstallPermission({
canInstallPlugin,
canUpdatePlugin: canUpdatePlugin ?? canInstallPlugin,
currentDifyVersion,
})
}, [canInstallPlugin, canUpdatePlugin, currentDifyVersion, store])
return <PluginInstallPermissionContext value={store}>{children}</PluginInstallPermissionContext>
}
export const PluginInstallPermissionProviderGuard = ({
canInstallPlugin,
canUpdatePlugin,
currentDifyVersion,
children,
}: PluginInstallPermissionProviderProps) => {
const store = use(PluginInstallPermissionContext)
if (store) return children
return (
<PluginInstallPermissionProvider
canInstallPlugin={canInstallPlugin}
canUpdatePlugin={canUpdatePlugin}
currentDifyVersion={currentDifyVersion}
>
{children}
</PluginInstallPermissionProvider>
)
}
@@ -0,0 +1,69 @@
import type { ToastType } from '@langgenius/dify-ui/toast'
import type { GitHubRepoReleaseResponse } from '../types'
import { uploadGitHub } from '@/service/plugins'
import { compareVersion, getLatestVersion } from '@/utils/semver'
const normalizeAssetName = (downloadUrl: string) => {
const parts = downloadUrl.split('/')
return parts[parts.length - 1]
}
const formatReleases = (releases: any) => {
return releases.map((release: any) => ({
tag_name: release.tag,
assets: release.assets.map((asset: any) => ({
browser_download_url: asset.downloadUrl,
name: normalizeAssetName(asset.downloadUrl),
})),
}))
}
export const fetchReleases = async (owner: string, repo: string) => {
// Fetch releases without authentication from client.
const res = await fetch(`https://ungh.cc/repos/${owner}/${repo}/releases`)
if (!res.ok) throw new Error('Failed to fetch repository releases')
const data = await res.json()
return formatReleases(data.releases)
}
export const checkForUpdates = (
fetchedReleases: GitHubRepoReleaseResponse[],
currentVersion: string,
) => {
let needUpdate = false
const toastProps: { type: ToastType; message: string } = {
type: 'info',
message: 'No new version available',
}
if (fetchedReleases.length === 0) {
toastProps.type = 'error'
toastProps.message = 'Input releases is empty'
return { needUpdate, toastProps }
}
const versions = fetchedReleases.map((release) => release.tag_name)
const latestVersion = getLatestVersion(versions)
try {
needUpdate = compareVersion(latestVersion!, currentVersion) === 1
if (needUpdate) toastProps.message = `New version available: ${latestVersion}`
} catch {
needUpdate = false
toastProps.type = 'error'
toastProps.message = 'Fail to compare versions, please check the version format'
}
return { needUpdate, toastProps }
}
export const handleUpload = async (
repoUrl: string,
selectedVersion: string,
selectedPackage: string,
onSuccess?: (GitHubPackage: { manifest: any; unique_identifier: string }) => void,
) => {
const response = await uploadGitHub(repoUrl, selectedVersion, selectedPackage, { silent: true })
const GitHubPackage = {
manifest: response.manifest,
unique_identifier: response.unique_identifier,
}
onSuccess?.(GitHubPackage)
return GitHubPackage
}
@@ -0,0 +1,48 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import createFoldAnimInto from '../create-fold-anim-into'
const mountModal = () => {
const modal = document.createElement('div')
modal.className = 'install-modal'
vi.spyOn(modal, 'getBoundingClientRect').mockReturnValue(new DOMRect(100, 100, 400, 300))
document.body.appendChild(modal)
return modal
}
beforeEach(() => vi.useFakeTimers())
afterEach(() => {
vi.useRealTimers()
vi.restoreAllMocks()
document
.querySelectorAll('.install-modal, #plugin-task-trigger, .plugins-nav-button')
.forEach((element) => element.remove())
})
describe('createFoldAnimInto', () => {
it.each([false, true])(
'closes immediately without an animation target (modal present: %s)',
async (hasModal) => {
if (hasModal) mountModal()
const onClose = vi.fn()
await createFoldAnimInto(onClose).foldIntoAnim()
expect(onClose).toHaveBeenCalledOnce()
},
)
it.each(['task', 'navigation'])('closes after folding to the %s target', async (target) => {
mountModal()
const trigger = document.createElement('button')
if (target === 'task') trigger.id = 'plugin-task-trigger'
else trigger.className = 'plugins-nav-button'
vi.spyOn(trigger, 'getBoundingClientRect').mockReturnValue(new DOMRect(50, 50, 40, 40))
document.body.appendChild(trigger)
const onClose = vi.fn()
const pending = createFoldAnimInto(onClose).foldIntoAnim()
await vi.advanceTimersByTimeAsync(749)
expect(onClose).not.toHaveBeenCalled()
await vi.advanceTimersByTimeAsync(1)
await pending
expect(onClose).toHaveBeenCalledOnce()
})
})
@@ -0,0 +1,63 @@
import { act, waitFor } from '@testing-library/react'
import { renderHookWithConsoleQuery as renderHook } from '@/test/console/query-data'
import { createDeferred } from '@/test/deferred'
import { createPluginEntity } from '@/test/fixtures/plugin'
import useCheckInstalled from '../use-check-installed'
const request = vi.hoisted(() => vi.fn())
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': request,
}),
}
})
beforeEach(() => {
request.mockResolvedValue({ plugins: [] })
})
it('waits for installed plugins and maps their server identities and versions', async () => {
const pending = createDeferred<{ plugins: ReturnType<typeof createPluginEntity>[] }>()
request.mockReturnValue(pending.promise)
const plugin = createPluginEntity()
const { result } = renderHook(() =>
useCheckInstalled({ pluginIds: [plugin.plugin_id], enabled: true }),
)
expect(result.current.isLoading).toBe(true)
expect(result.current.installedInfo).toBeUndefined()
await act(async () => pending.resolve({ plugins: [plugin] }))
await waitFor(() => expect(result.current.isLoading).toBe(false))
expect(request).toHaveBeenCalledWith({ body: { plugin_ids: [plugin.plugin_id] } })
expect(result.current.installedInfo).toEqual({
[plugin.plugin_id]: {
installedId: plugin.id,
installedVersion: plugin.declaration.version,
uniqueIdentifier: plugin.plugin_unique_identifier,
},
})
})
it('starts the installation lookup only after the caller enables it', async () => {
const { result, rerender } = renderHook(
({ enabled }) => useCheckInstalled({ pluginIds: ['plugin-1'], enabled }),
{ initialProps: { enabled: false } },
)
expect(request).not.toHaveBeenCalled()
expect(result.current.installedInfo).toBeUndefined()
rerender({ enabled: true })
await waitFor(() => expect(result.current.installedInfo).toEqual({}))
expect(request).toHaveBeenCalledOnce()
})
it('exposes lookup failures without manufacturing an installed result', async () => {
const error = new Error('lookup failed')
request.mockRejectedValue(error)
const { result } = renderHook(() => useCheckInstalled({ pluginIds: ['plugin-1'], enabled: true }))
await waitFor(() => expect(result.current.error).toBe(error))
expect(result.current.installedInfo).toBeUndefined()
expect(result.current.isLoading).toBe(false)
})
@@ -0,0 +1,60 @@
import { act, renderHook } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import useHideLogic from '../use-hide-logic'
beforeEach(() => vi.useFakeTimers())
afterEach(() => {
vi.clearAllTimers()
vi.useRealTimers()
})
describe('installation window lifetime', () => {
it('cancels the pending automatic close when the user hides an ongoing installation', async () => {
const onClose = vi.fn()
const { result } = renderHook(() => useHideLogic(onClose))
act(() => result.current.handleStartToInstall())
// Without a task trigger, folding falls back to closing immediately.
act(() => result.current.foldAnimInto())
expect(onClose).toHaveBeenCalledOnce()
await act(() => vi.advanceTimersByTimeAsync(15_000))
expect(onClose).toHaveBeenCalledOnce()
})
it('keeps the original countdown through rerenders and calls the latest close callback', async () => {
const initialOnClose = vi.fn()
const latestOnClose = vi.fn()
const { result, rerender } = renderHook(({ onClose }) => useHideLogic(onClose), {
initialProps: { onClose: initialOnClose },
})
act(() => result.current.handleStartToInstall())
await act(() => vi.advanceTimersByTimeAsync(1_000))
rerender({ onClose: latestOnClose })
await act(() => vi.advanceTimersByTimeAsync(13_999))
expect(initialOnClose).not.toHaveBeenCalled()
expect(latestOnClose).not.toHaveBeenCalled()
await act(() => vi.advanceTimersByTimeAsync(1))
expect(latestOnClose).toHaveBeenCalledOnce()
expect(initialOnClose).not.toHaveBeenCalled()
})
it('keeps the completed installation open until the user closes it', async () => {
const onClose = vi.fn()
const { result } = renderHook(() => useHideLogic(onClose))
act(() => result.current.handleStartToInstall())
// Starting and completing installation commit separately, as the async request does.
act(() => result.current.setIsInstalling(false))
await act(() => vi.advanceTimersByTimeAsync(15_000))
expect(onClose).not.toHaveBeenCalled()
act(() => result.current.foldAnimInto())
expect(onClose).toHaveBeenCalledOnce()
})
it('cancels the automatic close when the installation window unmounts', async () => {
const onClose = vi.fn()
const { result, unmount } = renderHook(() => useHideLogic(onClose))
act(() => result.current.handleStartToInstall())
unmount()
await act(() => vi.advanceTimersByTimeAsync(15_000))
expect(onClose).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,93 @@
import type { PluginInstallationScope } from '@dify/contracts/api/console/system-features/types.gen'
import { zPluginInstallationScope } from '@dify/contracts/api/console/system-features/zod.gen'
import { describe, expect, it } from 'vite-plus/test'
import { pluginInstallLimit } from '../use-install-plugin-limit'
type PluginInstallCandidate = Parameters<typeof pluginInstallLimit>[0]
type SystemFeatures = Parameters<typeof pluginInstallLimit>[1]
const basePlugin = {
from: 'marketplace' as const,
verification: { authorized_category: 'langgenius' },
} satisfies PluginInstallCandidate
function makeSystemFeatures(
scope: PluginInstallationScope,
restrictToMarketplaceOnly = false,
): SystemFeatures {
return {
plugin_installation_permission: {
restrict_to_marketplace_only: restrictToMarketplaceOnly,
plugin_installation_scope: scope,
},
}
}
describe('pluginInstallLimit', () => {
it('should allow all plugins when scope is ALL', () => {
const features = makeSystemFeatures(zPluginInstallationScope.enum.all)
expect(pluginInstallLimit(basePlugin, features).canInstall).toBe(true)
})
it('should deny all plugins when scope is NONE', () => {
const features = makeSystemFeatures(zPluginInstallationScope.enum.none)
expect(pluginInstallLimit(basePlugin, features).canInstall).toBe(false)
})
it('should allow langgenius plugins when scope is OFFICIAL_ONLY', () => {
const features = makeSystemFeatures(zPluginInstallationScope.enum.official_only)
expect(pluginInstallLimit(basePlugin, features).canInstall).toBe(true)
})
it('should deny non-official plugins when scope is OFFICIAL_ONLY', () => {
const features = makeSystemFeatures(zPluginInstallationScope.enum.official_only)
const plugin = {
...basePlugin,
verification: { authorized_category: 'community' as const },
} satisfies PluginInstallCandidate
expect(pluginInstallLimit(plugin, features).canInstall).toBe(false)
})
it('should allow partner plugins when scope is OFFICIAL_AND_PARTNER', () => {
const features = makeSystemFeatures(
zPluginInstallationScope.enum.official_and_specific_partners,
)
const plugin = {
...basePlugin,
verification: { authorized_category: 'partner' as const },
} satisfies PluginInstallCandidate
expect(pluginInstallLimit(plugin, features).canInstall).toBe(true)
})
it('should deny github plugins when restrict_to_marketplace_only is true', () => {
const features = makeSystemFeatures(zPluginInstallationScope.enum.all, true)
const plugin = { ...basePlugin, from: 'github' as const } satisfies PluginInstallCandidate
expect(pluginInstallLimit(plugin, features).canInstall).toBe(false)
})
it('should deny package plugins when restrict_to_marketplace_only is true', () => {
const features = makeSystemFeatures(zPluginInstallationScope.enum.all, true)
const plugin = { ...basePlugin, from: 'package' as const } satisfies PluginInstallCandidate
expect(pluginInstallLimit(plugin, features).canInstall).toBe(false)
})
it('should allow marketplace plugins even when restrict_to_marketplace_only is true', () => {
const features = makeSystemFeatures(zPluginInstallationScope.enum.all, true)
expect(pluginInstallLimit(basePlugin, features).canInstall).toBe(true)
})
it('should default to langgenius when no verification info', () => {
const features = makeSystemFeatures(zPluginInstallationScope.enum.official_only)
const plugin = { from: 'marketplace' as const } satisfies PluginInstallCandidate
expect(pluginInstallLimit(plugin, features).canInstall).toBe(true)
})
})
@@ -0,0 +1,49 @@
import type { ReactNode } from 'react'
import { renderHook } from '@testing-library/react'
import usePluginInstallPermission, {
createPluginInstallPermissionStore,
PluginInstallPermissionContext,
usePluginInstallPermissionStore,
} from '../use-plugin-install-permission'
describe('usePluginInstallPermission', () => {
// Store creation defaults update permission to install permission when not provided.
describe('Store Defaults', () => {
it('should default update permission from install permission', () => {
const store = createPluginInstallPermissionStore({
canInstallPlugin: false,
})
expect(store.getState().canInstallPlugin).toBe(false)
expect(store.getState().canUpdatePlugin).toBe(false)
})
})
// Hook consumers read values from the plugin install permission context.
describe('Context', () => {
it('should expose plugin install permissions from context store', () => {
const store = createPluginInstallPermissionStore({
canInstallPlugin: true,
canUpdatePlugin: false,
currentDifyVersion: '1.2.3',
})
const wrapper = ({ children }: { children: ReactNode }) => (
<PluginInstallPermissionContext value={store}>{children}</PluginInstallPermissionContext>
)
const { result } = renderHook(() => usePluginInstallPermission(), { wrapper })
expect(result.current).toEqual({
canInstallPlugin: true,
canUpdatePlugin: false,
currentDifyVersion: '1.2.3',
})
})
it('should throw when provider is missing', () => {
expect(() => {
renderHook(() => usePluginInstallPermissionStore((state) => state.canInstallPlugin))
}).toThrow('Missing PluginInstallPermissionProvider in the tree')
})
})
})
@@ -0,0 +1,175 @@
import type { PropsWithChildren } from 'react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { act, renderHook, waitFor } from '@testing-library/react'
import { createElement } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import { consoleQuery } from '@/service/console'
import { PluginCategoryEnum } from '../../../types'
import useRefreshPluginList from '../use-refresh-plugin-list'
const mocks = vi.hoisted(() => ({
request: vi.fn<(url: string) => Promise<Response>>(),
installed: vi.fn(),
checkInstalled: vi.fn(),
defaultModel: vi.fn(),
triggers: vi.fn(),
}))
vi.mock('@/service/base', () => ({ request: mocks.request }))
vi.mock('@/service/use-plugins', () => ({
useInvalidateCheckInstalled: () => mocks.checkInstalled,
useInvalidateInstalledPluginList: () => mocks.installed,
}))
vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({
useInvalidateDefaultModel: () => mocks.defaultModel,
}))
vi.mock('@/service/use-triggers', () => ({
useInvalidateAllTriggerPlugins: () => mocks.triggers,
}))
const current = consoleQuery.workspaces.current
const strategyKeys = [
current.agentProviders.get.queryKey(),
current.agentProvider.byProviderName.get.queryKey({
input: { params: { provider_name: 'langgenius/agent/react' } },
}),
current.agentProvider.byProviderName.get.queryKey({
input: { params: { provider_name: 'langgenius/agent/function-calling' } },
}),
]
const providerKeys = [
current.modelProviders.summary.get.key(),
consoleQuery.workspaces.current.modelProviders.get.key(),
]
const pluginVersionKeys = [
current.plugin.list.installations.ids.post.queryKey({
input: { body: { plugin_ids: ['langgenius/test'] } },
}),
current.plugin.list.latestVersions.post.queryKey({
input: { body: { plugin_ids: ['langgenius/test'] } },
}),
]
const datasourceKey = consoleQuery.rag.pipelines.datasourcePlugins.get.queryKey()
const dataSourceAuthKey = consoleQuery.auth.plugin.datasource.list.get.queryKey()
const toolKeys = [
current.toolProviders.get.queryKey({ input: { query: {} } }),
current.toolProviders.get.queryKey({ input: { query: { type: 'mcp' } } }),
current.tools.builtin.get.queryKey(),
consoleQuery.rag.pipelines.recommendedPlugins.get.queryKey({
input: { query: { type: 'tool' } },
}),
]
const otherRecommendedKey = consoleQuery.rag.pipelines.recommendedPlugins.get.queryKey({
input: { query: { type: 'datasource' } },
})
const unrelatedKey = consoleQuery.account.profile.get.key()
const modelTypes = ['llm', 'text-embedding', 'rerank', 'speech2text', 'tts']
describe('plugin installation refresh', () => {
let client: QueryClient
const wrapper = ({ children }: PropsWithChildren) =>
createElement(QueryClientProvider, { client }, children)
beforeEach(() => {
vi.clearAllMocks()
client = new QueryClient({
defaultOptions: { queries: { retry: false, staleTime: Infinity } },
})
for (const key of [...strategyKeys, ...providerKeys, ...pluginVersionKeys, unrelatedKey])
client.setQueryData(key, { cached: true })
client.setQueryData(datasourceKey, [])
client.setQueryData(dataSourceAuthKey, { result: [] })
for (const key of [...toolKeys, otherRecommendedKey]) client.setQueryData(key, [])
for (const model_type of modelTypes) {
client.setQueryData(
current.models.modelTypes.byModelType.get.queryKey({ input: { params: { model_type } } }),
{ data: [] },
)
}
mocks.request.mockImplementation(async () => Response.json({ data: [] }))
})
afterEach(() => client.clear())
it('invalidates the strategy catalog and every provider detail after an agent plugin changes', () => {
const { result } = renderHook(useRefreshPluginList, { wrapper })
act(() => result.current.refreshPluginList({ category: PluginCategoryEnum.agent }))
for (const key of pluginVersionKeys) expect(client.getQueryState(key)?.isInvalidated).toBe(true)
expect(mocks.installed).toHaveBeenCalledWith(PluginCategoryEnum.agent)
expect(mocks.checkInstalled).toHaveBeenCalledOnce()
for (const key of strategyKeys) expect(client.getQueryState(key)?.isInvalidated).toBe(true)
for (const key of [...providerKeys, unrelatedKey])
expect(client.getQueryState(key)?.isInvalidated).toBe(false)
expect(mocks.request).not.toHaveBeenCalled()
})
it.each([PluginCategoryEnum.tool, PluginCategoryEnum.datasource, PluginCategoryEnum.trigger])(
'keeps strategy caches fresh when a %s plugin changes',
(category) => {
const { result } = renderHook(useRefreshPluginList, { wrapper })
act(() => result.current.refreshPluginList({ category }))
expect(mocks.installed).toHaveBeenCalledWith(category)
for (const key of strategyKeys) expect(client.getQueryState(key)?.isInvalidated).toBe(false)
expect(client.getQueryState(datasourceKey)?.isInvalidated).toBe(
category === PluginCategoryEnum.datasource,
)
for (const key of toolKeys)
expect(client.getQueryState(key)?.isInvalidated).toBe(category === PluginCategoryEnum.tool)
expect(client.getQueryState(otherRecommendedKey)?.isInvalidated).toBe(false)
if (category === PluginCategoryEnum.datasource) {
expect(client.getQueryState(datasourceKey)?.isInvalidated).toBe(true)
expect(client.getQueryState(dataSourceAuthKey)?.isInvalidated).toBe(true)
}
if (category === PluginCategoryEnum.trigger) expect(mocks.triggers).toHaveBeenCalledOnce()
},
)
it.each([false, true])('refreshes model data and defaults; all categories = %s', async (all) => {
const { result } = renderHook(useRefreshPluginList, { wrapper })
act(() => result.current.refreshPluginList({ category: PluginCategoryEnum.model }, all))
await waitFor(() => expect(mocks.request).toHaveBeenCalledTimes(modelTypes.length))
for (const modelType of modelTypes) {
expect(
mocks.request.mock.calls.some(([url]) => url.endsWith(`/model-types/${modelType}`)),
).toBe(true)
expect(mocks.defaultModel).toHaveBeenCalledWith(modelType)
}
for (const key of providerKeys) expect(client.getQueryState(key)?.isInvalidated).toBe(true)
for (const key of strategyKeys) expect(client.getQueryState(key)?.isInvalidated).toBe(all)
expect(client.getQueryState(unrelatedKey)?.isInvalidated).toBe(false)
expect(client.getQueryState(datasourceKey)?.isInvalidated).toBe(all)
if (all) {
expect(mocks.installed).toHaveBeenCalledWith()
for (const key of toolKeys) expect(client.getQueryState(key)?.isInvalidated).toBe(true)
expect(client.getQueryState(datasourceKey)?.isInvalidated).toBe(true)
expect(client.getQueryState(dataSourceAuthKey)?.isInvalidated).toBe(true)
expect(mocks.triggers).toHaveBeenCalledOnce()
}
})
it('only refreshes installation caches without a manifest', () => {
const { result } = renderHook(useRefreshPluginList, { wrapper })
act(() => result.current.refreshPluginList())
expect(mocks.installed).toHaveBeenCalledWith()
expect(mocks.checkInstalled).toHaveBeenCalledOnce()
for (const key of [
...strategyKeys,
...providerKeys,
...toolKeys,
datasourceKey,
dataSourceAuthKey,
])
expect(client.getQueryState(key)?.isInvalidated).toBe(false)
expect(mocks.triggers).not.toHaveBeenCalled()
expect(mocks.request).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,84 @@
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import { createConsoleQueryWrapper } from '@/test/console/query-data'
import { renderHook } from '@/test/console/render'
import useWorkspacePluginInstallPermission from '../use-workspace-plugin-install-permission'
let mockWorkspacePermissionKeys: string[] = []
vi.mock('@/context/permission-state', async () => {
const { createPermissionStateModuleMock } = await import('@/test/console/state-fixture')
return createPermissionStateModuleMock(() => ({
workspacePermissionKeys: mockWorkspacePermissionKeys,
}))
})
const renderPermissionHook = () => {
const { wrapper } = createConsoleQueryWrapper({
accountProfileMeta: { currentVersion: '1.0.0' },
})
return renderHook(() => useWorkspacePluginInstallPermission(), { wrapper })
}
describe('useWorkspacePluginInstallPermission', () => {
beforeEach(() => {
mockWorkspacePermissionKeys = []
})
it('should grant install and update capabilities with plugin.install', () => {
mockWorkspacePermissionKeys = ['plugin.install']
const { result } = renderPermissionHook()
expect(result.current.canInstallPlugin).toBe(true)
expect(result.current.canUpdatePlugin).toBe(true)
expect(result.current.canDeletePlugin).toBe(false)
expect(result.current.canDebugPlugin).toBe(false)
expect(result.current.canSetPluginPreferences).toBe(false)
})
it('should grant delete capability but not install or update with plugin.delete', () => {
mockWorkspacePermissionKeys = ['plugin.delete']
const { result } = renderPermissionHook()
expect(result.current.canInstallPlugin).toBe(false)
expect(result.current.canUpdatePlugin).toBe(false)
expect(result.current.canDeletePlugin).toBe(true)
expect(result.current.canDebugPlugin).toBe(false)
expect(result.current.canSetPluginPreferences).toBe(false)
})
it('should grant plugin debug capability with plugin.debug', () => {
mockWorkspacePermissionKeys = ['plugin.debug']
const { result } = renderPermissionHook()
expect(result.current.canInstallPlugin).toBe(false)
expect(result.current.canUpdatePlugin).toBe(false)
expect(result.current.canDeletePlugin).toBe(false)
expect(result.current.canDebugPlugin).toBe(true)
expect(result.current.canSetPluginPreferences).toBe(false)
})
it('should grant plugin preference setting capability with plugin.plugin_preferences', () => {
mockWorkspacePermissionKeys = ['plugin.plugin_preferences']
const { result } = renderPermissionHook()
expect(result.current.canInstallPlugin).toBe(false)
expect(result.current.canUpdatePlugin).toBe(false)
expect(result.current.canDeletePlugin).toBe(false)
expect(result.current.canDebugPlugin).toBe(false)
expect(result.current.canSetPluginPreferences).toBe(true)
})
it('should deny plugin capabilities without plugin install or manage permissions', () => {
const { result } = renderPermissionHook()
expect(result.current.canInstallPlugin).toBe(false)
expect(result.current.canUpdatePlugin).toBe(false)
expect(result.current.canDeletePlugin).toBe(false)
expect(result.current.canDebugPlugin).toBe(false)
expect(result.current.canSetPluginPreferences).toBe(false)
})
})
@@ -0,0 +1,59 @@
import { sleep } from '@/utils'
const animTime = 750
const modalClassName = 'install-modal'
const COUNT_DOWN_TIME = 15000 // 15s
function getElemCenter(elem: HTMLElement) {
const rect = elem.getBoundingClientRect()
return {
x: rect.left + rect.width / 2 + window.scrollX,
y: rect.top + rect.height / 2 + window.scrollY,
}
}
const createFoldAnimInto = (onClose: () => void) => {
let countDownRunId: number
const clearCountDown = () => {
clearTimeout(countDownRunId)
}
// modalElem fold into plugin install task btn
const foldIntoAnim = async () => {
clearCountDown()
const modalElem = document.querySelector(`.${modalClassName}`) as HTMLElement
const pluginTaskTriggerElem =
document.getElementById('plugin-task-trigger') ||
document.querySelector('.plugins-nav-button')
if (!modalElem || !pluginTaskTriggerElem) {
onClose()
return
}
const modelCenter = getElemCenter(modalElem)
const modalElemRect = modalElem.getBoundingClientRect()
const pluginTaskTriggerCenter = getElemCenter(pluginTaskTriggerElem)
const xDiff = pluginTaskTriggerCenter.x - modelCenter.x
const yDiff = pluginTaskTriggerCenter.y - modelCenter.y
const scale = 1 / Math.max(modalElemRect.width, modalElemRect.height)
modalElem.style.transition = `all cubic-bezier(0.4, 0, 0.2, 1) ${animTime}ms`
modalElem.style.transform = `translate(${xDiff}px, ${yDiff}px) scale(${scale})`
await sleep(animTime)
onClose()
}
const countDownFoldIntoAnim = async () => {
countDownRunId = window.setTimeout(() => {
foldIntoAnim()
}, COUNT_DOWN_TIME)
}
return {
modalClassName,
foldIntoAnim,
clearCountDown,
countDownFoldIntoAnim,
}
}
export default createFoldAnimInto
@@ -0,0 +1,32 @@
import type { VersionInfo } from '../../types'
import { useMemo } from 'react'
import { useCheckInstalled as useDoCheckInstalled } from '@/service/use-plugins'
type Props = Readonly<{
pluginIds: string[]
enabled: boolean
}>
const useCheckInstalled = (props: Props) => {
const { data, isLoading, error } = useDoCheckInstalled(props)
const installedInfo = useMemo(() => {
if (!data) return undefined
const res: Record<string, VersionInfo> = {}
data?.plugins.forEach((plugin) => {
res[plugin.plugin_id] = {
installedId: plugin.id,
installedVersion: plugin.declaration.version,
uniqueIdentifier: plugin.plugin_unique_identifier,
}
})
return res
}, [data])
return {
installedInfo,
isLoading,
error,
}
}
export default useCheckInstalled
@@ -0,0 +1,51 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import createFoldAnimInto from './create-fold-anim-into'
const useHideLogic = (onClose: () => void) => {
const onCloseRef = useRef(onClose)
useEffect(() => {
onCloseRef.current = onClose
}, [onClose])
const [controller] = useState(() => createFoldAnimInto(() => onCloseRef.current()))
const {
modalClassName,
foldIntoAnim: doFoldAnimInto,
clearCountDown,
countDownFoldIntoAnim,
} = controller
useEffect(() => clearCountDown, [clearCountDown])
const [isInstalling, doSetIsInstalling] = useState(false)
const setIsInstalling = useCallback(
(isInstalling: boolean) => {
if (!isInstalling) clearCountDown()
doSetIsInstalling(isInstalling)
},
[clearCountDown],
)
const foldAnimInto = useCallback(() => {
if (isInstalling) {
doFoldAnimInto()
return
}
onClose()
}, [doFoldAnimInto, isInstalling, onClose])
const handleStartToInstall = useCallback(() => {
setIsInstalling(true)
countDownFoldIntoAnim()
}, [countDownFoldIntoAnim, setIsInstalling])
return {
modalClassName,
foldAnimInto,
foldIntoTaskTrigger: doFoldAnimInto,
setIsInstalling,
handleStartToInstall,
}
}
export default useHideLogic
@@ -0,0 +1,124 @@
'use client'
import type { Dependency, PluginDeclaration, PluginManifestInMarket } from '../../types'
import { useEffect, useState } from 'react'
import { parseMarketplacePluginId } from '@/app/components/plugins/plugin-routes'
import { getMarketplacePluginIconUrl } from '@/features/marketplace/api'
import { usePluginInstallation } from '@/hooks/use-query-params'
import {
fetchBundleInfoFromMarketPlace,
fetchManifestFromMarketPlace,
fetchPluginInfoFromMarketPlace,
} from '@/service/plugins'
type MarketplaceInstall = {
manifest: PluginDeclaration | PluginManifestInMarket
packageId: string
uniqueIdentifier: string
}
async function resolveMarketplaceUniqueIdentifier(packageId: string) {
const pluginId = parseMarketplacePluginId(packageId)
if (!pluginId) return packageId
const { data } = await fetchPluginInfoFromMarketPlace(pluginId)
return data.plugin.latest_package_identifier
}
export type UseInstallFromMarketplaceQueryOptions = {
canInstallPlugin: boolean
isPermissionLoading?: boolean
onPackageCategoryResolved?: (category: string | undefined, packageId: string) => boolean
}
export const useInstallFromMarketplaceQuery = ({
canInstallPlugin,
isPermissionLoading = false,
onPackageCategoryResolved,
}: UseInstallFromMarketplaceQueryOptions) => {
const [{ packageId, bundleInfo }, setInstallState] = usePluginInstallation()
const [marketplaceInstall, setMarketplaceInstall] = useState<MarketplaceInstall | null>(null)
const [dependencies, setDependencies] = useState<Dependency[]>([])
const [isShowInstallFromMarketplace, setIsShowInstallFromMarketplace] = useState(false)
useEffect(() => {
if (!packageId && !bundleInfo) return
if (isPermissionLoading) return
if (!canInstallPlugin) {
setInstallState(null)
return
}
let ignore = false
const loadMarketplaceInstall = async () => {
if (packageId) {
try {
const uniqueIdentifier = await resolveMarketplaceUniqueIdentifier(packageId)
const { data } = await fetchManifestFromMarketPlace(encodeURIComponent(uniqueIdentifier))
if (ignore) return
const { plugin, version } = data
const redirected = onPackageCategoryResolved?.(plugin.category, packageId)
if (redirected) return
setMarketplaceInstall({
packageId,
uniqueIdentifier,
manifest: {
...plugin,
version: version.version,
icon: getMarketplacePluginIconUrl(`${plugin.org}/${plugin.name}`),
},
})
setIsShowInstallFromMarketplace(true)
} catch (error) {
if (!ignore) console.error('Failed to load marketplace plugin manifest:', error)
}
return
}
if (bundleInfo) {
try {
const { data } = await fetchBundleInfoFromMarketPlace(bundleInfo)
if (ignore) return
setDependencies(data.version.dependencies)
setIsShowInstallFromMarketplace(true)
} catch (error) {
if (!ignore) console.error('Failed to load bundle info:', error)
}
}
}
loadMarketplaceInstall()
return () => {
ignore = true
}
}, [
bundleInfo,
canInstallPlugin,
isPermissionLoading,
onPackageCategoryResolved,
packageId,
setInstallState,
])
const hideInstallFromMarketplace = () => {
setMarketplaceInstall(null)
setDependencies([])
setIsShowInstallFromMarketplace(false)
setInstallState(null)
}
return {
bundleInfo,
dependencies,
hideInstallFromMarketplace,
isShowInstallFromMarketplace,
marketplaceInstall: marketplaceInstall?.packageId === packageId ? marketplaceInstall : null,
}
}
@@ -0,0 +1,56 @@
import type { GetSystemFeaturesResponse } from '@dify/contracts/api/console/system-features/types.gen'
import type {
PluginBundleDependencyType,
PluginVerification,
} from '@dify/contracts/api/console/workspaces/types.gen'
import { zPluginInstallationScope } from '@dify/contracts/api/console/system-features/zod.gen'
import { useSuspenseQuery } from '@tanstack/react-query'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
type PluginInstallCandidate = {
from: PluginBundleDependencyType
verification?: PluginVerification | null
}
type PluginInstallLimitResult = {
canInstall: boolean
}
function denyUnsupportedInstallationScope(_scope: never): PluginInstallLimitResult {
return { canInstall: false }
}
export function pluginInstallLimit(
plugin: PluginInstallCandidate,
systemFeatures: Pick<GetSystemFeaturesResponse, 'plugin_installation_permission'>,
) {
const permission = systemFeatures.plugin_installation_permission
if (permission.restrict_to_marketplace_only) {
if (plugin.from === 'github' || plugin.from === 'package') return { canInstall: false }
}
const authorizedCategory = plugin.verification?.authorized_category ?? 'langgenius'
const scope = permission.plugin_installation_scope
switch (scope) {
case zPluginInstallationScope.enum.all:
return { canInstall: true }
case zPluginInstallationScope.enum.none:
return { canInstall: false }
case zPluginInstallationScope.enum.official_only:
return { canInstall: authorizedCategory === 'langgenius' }
case zPluginInstallationScope.enum.official_and_specific_partners:
return {
canInstall: authorizedCategory === 'langgenius' || authorizedCategory === 'partner',
}
default:
return denyUnsupportedInstallationScope(scope)
}
}
export default function usePluginInstallLimit(
plugin: PluginInstallCandidate,
): PluginInstallLimitResult {
const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
return pluginInstallLimit(plugin, systemFeatures)
}
@@ -0,0 +1,80 @@
import type { StoreApi } from 'zustand'
import { createContext, use } from 'react'
import { useStore } from 'zustand'
import { createStore } from 'zustand/vanilla'
export type PluginInstallPermissionState = {
canInstallPlugin: boolean
canUpdatePlugin: boolean
currentDifyVersion?: string
}
type PluginInstallPermissionAction = {
setPluginInstallPermission: (state: PluginInstallPermissionState) => void
}
export type PluginInstallPermissionStoreState = PluginInstallPermissionState &
PluginInstallPermissionAction
export type PluginInstallPermissionStore = StoreApi<PluginInstallPermissionStoreState>
const defaultPluginInstallPermissionState: PluginInstallPermissionState = {
canInstallPlugin: true,
canUpdatePlugin: true,
}
export const createPluginInstallPermissionStore = (
initProps?: Partial<PluginInstallPermissionState>,
) => {
const canInstallPlugin =
initProps?.canInstallPlugin ?? defaultPluginInstallPermissionState.canInstallPlugin
return createStore<PluginInstallPermissionStoreState>()((set) => ({
...defaultPluginInstallPermissionState,
...initProps,
canUpdatePlugin: initProps?.canUpdatePlugin ?? canInstallPlugin,
setPluginInstallPermission: (state) => set(() => state),
}))
}
const fallbackPluginInstallPermissionStore = createPluginInstallPermissionStore()
export const PluginInstallPermissionContext = createContext<PluginInstallPermissionStore | null>(
null,
)
export const usePluginInstallPermissionStore = <T>(
selector: (state: PluginInstallPermissionStoreState) => T,
): T => {
const store = use(PluginInstallPermissionContext)
if (!store) throw new Error('Missing PluginInstallPermissionProvider in the tree')
return useStore(store, selector)
}
const usePluginInstallPermission = () => {
const canInstallPlugin = usePluginInstallPermissionStore((state) => state.canInstallPlugin)
const canUpdatePlugin = usePluginInstallPermissionStore((state) => state.canUpdatePlugin)
const currentDifyVersion = usePluginInstallPermissionStore((state) => state.currentDifyVersion)
return {
canInstallPlugin,
canUpdatePlugin,
currentDifyVersion,
}
}
export const useOptionalPluginInstallPermission = () => {
const store = use(PluginInstallPermissionContext) ?? fallbackPluginInstallPermissionStore
const canInstallPlugin = useStore(store, (state) => state.canInstallPlugin)
const canUpdatePlugin = useStore(store, (state) => state.canUpdatePlugin)
const currentDifyVersion = useStore(store, (state) => state.currentDifyVersion)
return {
canInstallPlugin,
canUpdatePlugin,
currentDifyVersion,
}
}
export default usePluginInstallPermission
@@ -0,0 +1,133 @@
import type { Plugin, PluginDeclaration, PluginManifestInMarket } from '../../types'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
import { useInvalidateDefaultModel } from '@/app/components/header/account-setting/model-provider-page/hooks'
import { consoleQuery } from '@/service/console'
import {
useInvalidateCheckInstalled,
useInvalidateInstalledPluginList,
} from '@/service/use-plugins'
import { useInvalidateAllTriggerPlugins } from '@/service/use-triggers'
import { PluginCategoryEnum } from '../../types'
type PluginCategoryPayload = {
category: PluginCategoryEnum
}
const SYSTEM_MODEL_TYPES = [
ModelTypeEnum.textGeneration,
ModelTypeEnum.textEmbedding,
ModelTypeEnum.rerank,
ModelTypeEnum.speech2text,
ModelTypeEnum.tts,
]
const useRefreshPluginList = () => {
const invalidateInstalledPluginList = useInvalidateInstalledPluginList()
const invalidateCheckInstalled = useInvalidateCheckInstalled()
const { refetch: refetchLLMModelList } = useQuery(
consoleQuery.workspaces.current.models.modelTypes.byModelType.get.queryOptions({
input: { params: { model_type: ModelTypeEnum.textGeneration } },
}),
)
const { refetch: refetchEmbeddingModelList } = useQuery(
consoleQuery.workspaces.current.models.modelTypes.byModelType.get.queryOptions({
input: { params: { model_type: ModelTypeEnum.textEmbedding } },
}),
)
const { refetch: refetchRerankModelList } = useQuery(
consoleQuery.workspaces.current.models.modelTypes.byModelType.get.queryOptions({
input: { params: { model_type: ModelTypeEnum.rerank } },
}),
)
const { refetch: refetchSpeech2textModelList } = useQuery(
consoleQuery.workspaces.current.models.modelTypes.byModelType.get.queryOptions({
input: { params: { model_type: ModelTypeEnum.speech2text } },
}),
)
const { refetch: refetchTTSModelList } = useQuery(
consoleQuery.workspaces.current.models.modelTypes.byModelType.get.queryOptions({
input: { params: { model_type: ModelTypeEnum.tts } },
}),
)
const invalidateDefaultModel = useInvalidateDefaultModel()
const queryClient = useQueryClient()
const invalidateAllTriggerPlugins = useInvalidateAllTriggerPlugins()
return {
refreshPluginList: (
manifest?: PluginManifestInMarket | Plugin | PluginDeclaration | PluginCategoryPayload | null,
refreshAllType?: boolean,
) => {
// installed list
if (refreshAllType || !manifest) invalidateInstalledPluginList()
else invalidateInstalledPluginList(manifest.category)
invalidateCheckInstalled()
queryClient.invalidateQueries({
queryKey: consoleQuery.workspaces.current.plugin.list.installations.ids.post.key(),
})
queryClient.invalidateQueries({
queryKey: consoleQuery.workspaces.current.plugin.list.latestVersions.post.key(),
})
// tool page, tool select
if ((manifest && PluginCategoryEnum.tool.includes(manifest.category)) || refreshAllType) {
queryClient.invalidateQueries({
queryKey: consoleQuery.workspaces.current.toolProviders.get.key(),
})
queryClient.invalidateQueries({
queryKey: consoleQuery.workspaces.current.tools.builtin.get.queryKey(),
})
queryClient.invalidateQueries({
queryKey: consoleQuery.rag.pipelines.recommendedPlugins.get.queryKey({
input: { query: { type: 'tool' } },
}),
})
// TODO: update suggested tools. It's a function in hook useMarketplacePlugins,handleUpdatePlugins
}
if ((manifest && PluginCategoryEnum.trigger.includes(manifest.category)) || refreshAllType)
invalidateAllTriggerPlugins()
if (
(manifest && PluginCategoryEnum.datasource.includes(manifest.category)) ||
refreshAllType
) {
queryClient.invalidateQueries({
queryKey: consoleQuery.rag.pipelines.datasourcePlugins.get.key(),
})
queryClient.invalidateQueries({
queryKey: consoleQuery.auth.plugin.datasource.list.get.queryKey(),
})
}
// model select
if ((manifest && PluginCategoryEnum.model.includes(manifest.category)) || refreshAllType) {
queryClient.invalidateQueries({
queryKey: consoleQuery.workspaces.current.modelProviders.summary.get.key(),
})
queryClient.invalidateQueries({
queryKey: consoleQuery.workspaces.current.modelProviders.get.key(),
})
refetchLLMModelList()
refetchEmbeddingModelList()
refetchRerankModelList()
refetchSpeech2textModelList()
refetchTTSModelList()
SYSTEM_MODEL_TYPES.forEach((type) => invalidateDefaultModel(type))
}
// agent select
if ((manifest && PluginCategoryEnum.agent.includes(manifest.category)) || refreshAllType) {
queryClient.invalidateQueries({
queryKey: consoleQuery.workspaces.current.agentProviders.get.key(),
})
queryClient.invalidateQueries({
queryKey: consoleQuery.workspaces.current.agentProvider.byProviderName.get.key(),
})
}
},
}
}
export default useRefreshPluginList
@@ -0,0 +1,45 @@
import { useSuspenseQuery } from '@tanstack/react-query'
import { useAtomValue } from 'jotai'
import { useMemo } from 'react'
import { workspacePermissionKeysAtom } from '@/context/permission-state'
import { userProfileQueryOptions } from '@/features/account-profile/client'
import { hasPermission } from '@/utils/permission'
const useWorkspacePluginInstallPermission = () => {
const { data: currentVersion } = useSuspenseQuery({
...userProfileQueryOptions(),
select: (data) => data.meta.currentVersion ?? '',
})
const workspacePermissionKeys = useAtomValue(workspacePermissionKeysAtom)
const canInstallPlugin = useMemo(() => {
return hasPermission(workspacePermissionKeys, 'plugin.install')
}, [workspacePermissionKeys])
const canUpdatePlugin = useMemo(() => {
return hasPermission(workspacePermissionKeys, 'plugin.install')
}, [workspacePermissionKeys])
const canDeletePlugin = useMemo(() => {
return hasPermission(workspacePermissionKeys, 'plugin.delete')
}, [workspacePermissionKeys])
const canDebugPlugin = useMemo(() => {
return hasPermission(workspacePermissionKeys, 'plugin.debug')
}, [workspacePermissionKeys])
const canSetPluginPreferences = useMemo(() => {
return hasPermission(workspacePermissionKeys, 'plugin.plugin_preferences')
}, [workspacePermissionKeys])
return {
canInstallPlugin,
canUpdatePlugin,
canDeletePlugin,
canDebugPlugin,
canSetPluginPreferences,
currentDifyVersion: currentVersion,
}
}
export default useWorkspacePluginInstallPermission
@@ -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)
@@ -0,0 +1,400 @@
import type { ComponentProps } from 'react'
import { act, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { createHttpError } from '@/service/http-error'
import { renderWithConsoleQuery } from '@/test/console/query-data'
import { createDeferred } from '@/test/deferred'
import { createPluginDeclarationFixture, createPluginEntity } from '@/test/fixtures/plugin'
import { TaskStatus } from '../../../types'
import InstallFromGitHub from '../index'
const { fetchReleases, upload, install, pollTask, refresh, notify, installed, upgrade } =
vi.hoisted(() => ({
installed: vi.fn(),
upgrade: vi.fn(),
fetchReleases: vi.fn(),
upload: vi.fn(),
install: vi.fn(),
pollTask: vi.fn(),
refresh: vi.fn(),
notify: vi.fn(),
}))
vi.mock('@/service/plugins', async (importOriginal) => ({
...(await importOriginal<typeof import('@/service/plugins')>()),
uploadGitHub: upload,
updateFromGitHub: upgrade,
checkTaskStatus: pollTask,
}))
vi.mock('@/service/console', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/service/console')>()
const { withConsoleClientResponses, withConsoleResponses } =
await import('@/test/console/service-responses')
return {
...actual,
consoleQuery: withConsoleResponses(actual.consoleQuery, {
'workspaces.current.plugin.list.installations.ids.post': installed,
}),
consoleClient: withConsoleClientResponses(actual.consoleClient, {
'workspaces.current.plugin.tasks.get': async () => ({ tasks: [] }),
'workspaces.current.plugin.install.github.post': install,
}),
}
})
// Refreshing the separate model/tool catalogs is covered by use-refresh-plugin-list.
vi.mock('../../hooks/use-refresh-plugin-list', () => ({
default: () => ({ refreshPluginList: refresh }),
}))
vi.mock('@/app/notifications', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/app/notifications')>()
return { ...actual, toast: Object.assign(vi.fn(), actual.toast, { error: notify }) }
})
const manifest = createPluginDeclarationFixture({ name: 'github' })
const uploadedPackage = { unique_identifier: 'test/github:1.0.0', manifest }
const releases = [
{
tag: 'v1.0.0',
assets: [
{ downloadUrl: 'https://github.com/owner/repo/releases/download/v1.0.0/plugin.difypkg' },
],
},
{
tag: 'v0.9.0',
assets: [{ downloadUrl: 'https://github.com/owner/repo/releases/download/v0.9.0/old.difypkg' }],
},
]
const renderInstaller = (props: Partial<ComponentProps<typeof InstallFromGitHub>> = {}) => {
const onSuccess = vi.fn()
const onClose = vi.fn()
renderWithConsoleQuery(<InstallFromGitHub onSuccess={onSuccess} onClose={onClose} {...props} />)
return { onSuccess, onClose }
}
const nextButton = () => screen.getByRole('button', { name: 'plugin.installModal.next' })
const versionSelect = () =>
screen.getByRole('combobox', { name: 'plugin.installFromGitHub.selectVersion' })
const packageSelect = () =>
screen.getByRole('combobox', { name: 'plugin.installFromGitHub.selectPackage' })
const submitRepo = async (user: ReturnType<typeof userEvent.setup>) => {
await user.type(
screen.getByRole('textbox', { name: 'plugin.installFromGitHub.gitHubRepo' }),
'https://github.com/owner/repo',
)
await user.keyboard('{Enter}')
await screen.findByRole('combobox', { name: 'plugin.installFromGitHub.selectVersion' })
}
const selectPackage = async (user: ReturnType<typeof userEvent.setup>) => {
await user.click(versionSelect())
await user.click(await screen.findByRole('option', { name: 'v1.0.0' }))
await user.click(packageSelect())
await user.click(await screen.findByRole('option', { name: 'plugin.difypkg' }))
}
const loadPackage = async (user: ReturnType<typeof userEvent.setup>) => {
await submitRepo(user)
await selectPackage(user)
await user.click(nextButton())
return await screen.findByRole('button', { name: 'plugin.installModal.install' })
}
beforeEach(() => {
vi.resetAllMocks()
installed.mockResolvedValue({ plugins: [] })
upgrade.mockResolvedValue({ all_installed: true, task_id: '' })
vi.stubGlobal('fetch', fetchReleases)
fetchReleases.mockImplementation(async () => Response.json({ releases }))
upload.mockResolvedValue(uploadedPackage)
install.mockResolvedValue({ all_installed: true, task_id: '' })
})
afterEach(() => vi.unstubAllGlobals())
it('submits the URL with Enter, installs the selected release, and waits for asynchronous completion handling', async () => {
const user = userEvent.setup()
const success = createDeferred<void>()
const onSuccess = vi.fn(() => success.promise)
const { onClose } = renderInstaller({ onSuccess })
const input = screen.getByRole('textbox', { name: 'plugin.installFromGitHub.gitHubRepo' })
await waitFor(() => expect(input).toHaveFocus())
expect(nextButton()).toBeDisabled()
const button = await loadPackage(user)
expect(fetchReleases).toHaveBeenCalledExactlyOnceWith('https://ungh.cc/repos/owner/repo/releases')
expect(upload).toHaveBeenCalledExactlyOnceWith('owner/repo', 'v1.0.0', 'plugin.difypkg', {
silent: true,
})
await user.click(button)
await waitFor(() => expect(onSuccess).toHaveBeenCalledOnce())
const pendingButton = screen.getByRole('button', { name: 'plugin.installModal.installing' })
await user.click(pendingButton)
expect(install).toHaveBeenCalledExactlyOnceWith({
body: {
repo: 'owner/repo',
version: 'v1.0.0',
package: 'plugin.difypkg',
plugin_unique_identifier: 'test/github:1.0.0',
},
})
expect(
screen.queryByRole('dialog', { name: 'plugin.installFromGitHub.installedSuccessfully' }),
).not.toBeInTheDocument()
success.resolve()
await screen.findByRole('dialog', { name: 'plugin.installFromGitHub.installedSuccessfully' })
expect(screen.getByText('Test Plugin')).toBeInTheDocument()
expect(screen.queryByText('plugin.installFromGitHub.installNote')).not.toBeInTheDocument()
expect(refresh).toHaveBeenCalledExactlyOnceWith(
expect.objectContaining({
name: 'github',
icon: expect.stringContaining('filename=test-icon.png'),
}),
)
await user.click(screen.getAllByRole('button', { name: 'common.operation.close' }).at(-1)!)
expect(onClose).toHaveBeenCalledOnce()
})
it('keeps URL and selections when navigating back through the real steps', async () => {
const user = userEvent.setup()
renderInstaller()
await loadPackage(user)
await user.click(screen.getByRole('button', { name: 'plugin.installModal.back' }))
expect(versionSelect()).toHaveTextContent('v1.0.0')
expect(packageSelect()).toHaveTextContent('plugin.difypkg')
await user.click(screen.getByRole('button', { name: 'plugin.installModal.back' }))
expect(screen.getByRole('textbox', { name: 'plugin.installFromGitHub.gitHubRepo' })).toHaveValue(
'https://github.com/owner/repo',
)
expect(install).not.toHaveBeenCalled()
})
it('derives the package options from the selected release and blocks upload before selection', async () => {
const user = userEvent.setup()
renderInstaller()
await submitRepo(user)
expect(packageSelect()).toBeDisabled()
expect(nextButton()).toBeDisabled()
await user.click(versionSelect())
await user.click(await screen.findByRole('option', { name: 'v0.9.0' }))
await user.click(packageSelect())
expect(await screen.findByRole('option', { name: 'old.difypkg' })).toBeInTheDocument()
expect(screen.queryByRole('option', { name: 'plugin.difypkg' })).not.toBeInTheDocument()
await user.keyboard('{Escape}')
expect(nextButton()).toBeDisabled()
expect(upload).not.toHaveBeenCalled()
})
it('blocks a release without assets from proceeding to upload', async () => {
const user = userEvent.setup()
fetchReleases.mockImplementation(async () =>
Response.json({ releases: [{ tag: 'v1.0.0', assets: [] }] }),
)
renderInstaller()
await submitRepo(user)
await user.click(versionSelect())
await user.click(await screen.findByRole('option', { name: 'v1.0.0' }))
await user.click(packageSelect())
expect(screen.queryByRole('option')).not.toBeInTheDocument()
await user.keyboard('{Escape}')
expect(nextButton()).toBeDisabled()
expect(upload).not.toHaveBeenCalled()
})
it('rejects an invalid URL before fetching releases', async () => {
const user = userEvent.setup()
renderInstaller()
await user.type(
screen.getByRole('textbox', { name: 'plugin.installFromGitHub.gitHubRepo' }),
'invalid-url',
)
await user.click(nextButton())
expect(notify).toHaveBeenCalledWith('plugin.error.inValidGitHubUrl')
expect(fetchReleases).not.toHaveBeenCalled()
expect(screen.queryByRole('combobox')).not.toBeInTheDocument()
})
it.each(['empty', 'error'])(
'allows retrying release lookup after an %s response',
async (response) => {
const user = userEvent.setup()
if (response === 'empty') fetchReleases.mockResolvedValueOnce(Response.json({ releases: [] }))
else fetchReleases.mockRejectedValueOnce(new Error('Release service unavailable'))
renderInstaller()
await user.type(
screen.getByRole('textbox', { name: 'plugin.installFromGitHub.gitHubRepo' }),
'https://github.com/owner/repo',
)
await user.click(nextButton())
await waitFor(() =>
expect(notify).toHaveBeenCalledExactlyOnceWith(
response === 'empty' ? 'plugin.error.noReleasesFound' : 'plugin.error.fetchReleasesError',
),
)
expect(screen.queryByRole('combobox')).not.toBeInTheDocument()
await user.click(nextButton())
await screen.findByRole('combobox', { name: 'plugin.installFromGitHub.selectVersion' })
expect(fetchReleases).toHaveBeenCalledTimes(2)
},
)
it.each([
[new Error('Package download failed'), 'Package download failed'],
[
createHttpError(new Response(null, { status: 500 }), { message: 'Package rejected' }),
'Package rejected',
],
['Unexpected server response', 'plugin.installFromGitHub.uploadFailed'],
])('shows upload failure %s without starting installation', async (error, message) => {
const user = userEvent.setup()
upload.mockRejectedValue(error)
const { onSuccess, onClose } = renderInstaller()
await submitRepo(user)
await selectPackage(user)
await user.click(nextButton())
await screen.findByText(message)
expect(notify).not.toHaveBeenCalled()
expect(screen.queryByRole('combobox')).not.toBeInTheDocument()
expect(install).not.toHaveBeenCalled()
expect(onSuccess).not.toHaveBeenCalled()
await user.click(screen.getAllByRole('button', { name: 'common.operation.close' }).at(-1)!)
expect(onClose).toHaveBeenCalledOnce()
})
it.each([TaskStatus.success, TaskStatus.failed])(
'shows the asynchronous install result: %s',
async (status) => {
const user = userEvent.setup()
install.mockResolvedValue({ all_installed: false, task_id: 'github-task' })
pollTask.mockResolvedValue({
task: {
plugins: [
{
plugin_unique_identifier: 'test/github:1.0.0',
status,
message: 'Plugin initialization failed',
},
],
},
})
const { onSuccess } = renderInstaller()
await user.click(await loadPackage(user))
await screen.findByRole('dialog', {
name:
status === TaskStatus.success
? 'plugin.installFromGitHub.installedSuccessfully'
: 'plugin.installFromGitHub.installFailed',
})
expect(pollTask).toHaveBeenCalledExactlyOnceWith('github-task')
if (status === TaskStatus.failed) {
expect(screen.getByText('Plugin initialization failed')).toBeInTheDocument()
expect(onSuccess).not.toHaveBeenCalled()
} else expect(onSuccess).toHaveBeenCalledOnce()
expect(refresh).not.toHaveBeenCalled()
},
)
it.each([
[new Error('Connection failed'), 'plugin.installModal.installFailedDesc'],
['Server install error', 'Server install error'],
])('shows the install failure for %s', async (error, message) => {
const user = userEvent.setup()
install.mockRejectedValue(error)
const { onSuccess } = renderInstaller()
await user.click(await loadPackage(user))
await screen.findByRole('dialog', { name: 'plugin.installFromGitHub.installFailed' })
expect(screen.getByText(message)).toBeInTheDocument()
expect(onSuccess).not.toHaveBeenCalled()
})
it.each(['plugin.installModal.cancel', 'common.operation.close'])(
'allows %s before selecting a repository',
async (name) => {
const user = userEvent.setup()
const { onClose } = renderInstaller()
await user.click(screen.getByRole('button', { name }))
expect(onClose).toHaveBeenCalledOnce()
expect(fetchReleases).not.toHaveBeenCalled()
expect(upload).not.toHaveBeenCalled()
},
)
it('blocks repeated upload and backward navigation until the selected package finishes loading', async () => {
const user = userEvent.setup()
const pending = createDeferred<typeof uploadedPackage>()
upload.mockReturnValueOnce(pending.promise)
renderInstaller()
await submitRepo(user)
await selectPackage(user)
const next = nextButton()
await user.click(next)
expect(next).toBeDisabled()
const back = screen.getByRole('button', { name: 'plugin.installModal.back' })
expect(back).toBeDisabled()
await user.click(next)
await user.click(back)
expect(upload).toHaveBeenCalledExactlyOnceWith('owner/repo', 'v1.0.0', 'plugin.difypkg', {
silent: true,
})
expect(
screen.queryByRole('button', { name: 'plugin.installModal.install' }),
).not.toBeInTheDocument()
pending.resolve(uploadedPackage)
expect(
await screen.findByRole('button', { name: 'plugin.installModal.install' }),
).toBeInTheDocument()
expect(install).not.toHaveBeenCalled()
})
it('waits for the installed version before upgrading the package selected from GitHub', async () => {
const user = userEvent.setup()
const existing = createPluginEntity({
plugin_id: 'test/github',
plugin_unique_identifier: 'test/github:0.9.0',
})
existing.declaration.version = '0.9.0'
const lookup = createDeferred<{ plugins: ReturnType<typeof createPluginEntity>[] }>()
installed.mockReturnValueOnce(lookup.promise)
upload.mockResolvedValueOnce({
...uploadedPackage,
manifest: { ...manifest, plugin_id: 'test/github' },
})
const { onSuccess } = renderInstaller()
const button = await loadPackage(user)
expect(button).toBeDisabled()
await user.click(button)
expect(install).not.toHaveBeenCalled()
expect(upgrade).not.toHaveBeenCalled()
await act(async () => lookup.resolve({ plugins: [existing] }))
await waitFor(() => expect(button).toBeEnabled())
expect(screen.getByText('0.9.0 -> 1.0.0')).toBeInTheDocument()
expect(onSuccess).not.toHaveBeenCalled()
await user.click(button)
await screen.findByRole('dialog', { name: 'plugin.installFromGitHub.installedSuccessfully' })
expect(upgrade).toHaveBeenCalledExactlyOnceWith(
'owner/repo',
'v1.0.0',
'plugin.difypkg',
'test/github:0.9.0',
'test/github:1.0.0',
)
expect(onSuccess).toHaveBeenCalledOnce()
expect(install).not.toHaveBeenCalled()
})
it('finishes without an install or upgrade when the selected GitHub package is already installed', async () => {
const user = userEvent.setup()
installed.mockResolvedValueOnce({
plugins: [
createPluginEntity({
plugin_id: 'test/github',
plugin_unique_identifier: uploadedPackage.unique_identifier,
}),
],
})
upload.mockResolvedValueOnce({
...uploadedPackage,
manifest: { ...manifest, plugin_id: 'test/github' },
})
const { onSuccess } = renderInstaller()
await submitRepo(user)
await selectPackage(user)
await user.click(nextButton())
await screen.findByRole('dialog', { name: 'plugin.installFromGitHub.installedSuccessfully' })
expect(onSuccess).toHaveBeenCalledOnce()
expect(upgrade).not.toHaveBeenCalled()
expect(install).not.toHaveBeenCalled()
})
@@ -0,0 +1,103 @@
import type { UpdateFromGitHubPayload } from '../../../types'
import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { renderWithConsoleQuery as render } from '@/test/console/query-data'
import { createPluginDeclarationFixture } from '@/test/fixtures/plugin'
import InstallFromGitHub from '../index'
const { uploadGitHub, updateFromGitHub } = vi.hoisted(() => ({
uploadGitHub: vi.fn(),
updateFromGitHub: vi.fn(),
}))
vi.mock('@/service/plugins', async (importOriginal) => ({
...(await importOriginal<typeof import('@/service/plugins')>()),
uploadGitHub,
updateFromGitHub,
}))
vi.mock('@/service/console', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/service/console')>()
const { withConsoleClientResponses } = await import('@/test/console/service-responses')
return {
...actual,
consoleClient: withConsoleClientResponses(actual.consoleClient, {
'workspaces.current.plugin.tasks.get': async () => ({ tasks: [] }),
}),
}
})
// Model/tool catalog refresh is covered by its own hook tests.
vi.mock('../../hooks/use-refresh-plugin-list', () => ({
default: () => ({ refreshPluginList: vi.fn() }),
}))
const github: UpdateFromGitHubPayload = {
originalPackageInfo: {
id: 'github-original-id',
repo: 'owner/repo',
version: 'v1.0.0',
package: 'plugin.difypkg',
releases: [
{
tag_name: 'v1.0.0',
assets: [
{
id: 1,
name: 'plugin.difypkg',
browser_download_url:
'https://github.com/owner/repo/releases/download/v1.0.0/plugin.difypkg',
},
],
},
{
tag_name: 'v2.0.0',
assets: [
{
id: 2,
name: 'plugin.difypkg',
browser_download_url:
'https://github.com/owner/repo/releases/download/v2.0.0/plugin.difypkg',
},
],
},
],
},
}
beforeEach(() => vi.resetAllMocks())
it('updates a GitHub plugin using the selected release and the existing installation identifier', async () => {
const user = userEvent.setup()
uploadGitHub.mockResolvedValueOnce({
unique_identifier: 'github-target-id',
manifest: createPluginDeclarationFixture({ version: '2.0.0' }),
})
updateFromGitHub.mockResolvedValueOnce({ all_installed: true, task_id: '' })
const onSave = vi.fn()
const onCancel = vi.fn()
render(<InstallFromGitHub updatePayload={github} onSuccess={onSave} onClose={onCancel} />)
await user.click(screen.getByRole('combobox', { name: 'plugin.installFromGitHub.selectVersion' }))
expect(await screen.findByRole('option', { name: /v1\.0\.0.*INSTALLED/ })).toBeInTheDocument()
await user.click(await screen.findByRole('option', { name: 'v2.0.0' }))
expect(
screen.getByRole('combobox', { name: 'plugin.installFromGitHub.selectVersion' }),
).toHaveTextContent('v1.0.0 -> v2.0.0')
expect(screen.queryByRole('button', { name: 'plugin.installModal.back' })).not.toBeInTheDocument()
await user.click(screen.getByRole('combobox', { name: 'plugin.installFromGitHub.selectPackage' }))
await user.click(await screen.findByRole('option', { name: 'plugin.difypkg' }))
await user.click(screen.getByRole('button', { name: 'plugin.installModal.next' }))
const install = await screen.findByRole('button', { name: 'plugin.installModal.install' })
expect(uploadGitHub).toHaveBeenCalledExactlyOnceWith('owner/repo', 'v2.0.0', 'plugin.difypkg', {
silent: true,
})
await user.click(install)
await screen.findByRole('dialog', { name: 'plugin.installFromGitHub.installedSuccessfully' })
expect(updateFromGitHub).toHaveBeenCalledExactlyOnceWith(
'owner/repo',
'v2.0.0',
'plugin.difypkg',
'github-original-id',
'github-target-id',
)
expect(onSave).toHaveBeenCalledOnce()
expect(onCancel).not.toHaveBeenCalled()
})
@@ -0,0 +1,304 @@
'use client'
import type { PluginCategoryEnum, PluginDeclaration, UpdateFromGitHubPayload } from '../../types'
import type { InstallState } from '@/app/components/plugins/types'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import {
Dialog,
DialogBody,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogHeaderCloseButton,
DialogTitle,
} from '@langgenius/dify-ui/dialog'
import { Field, FieldLabel } from '@langgenius/dify-ui/field'
import { Form } from '@langgenius/dify-ui/form'
import { Input } from '@langgenius/dify-ui/input'
import * as React from 'react'
import { useCallback, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import useGetIcon from '@/app/components/plugins/install-plugin/base/use-get-icon'
import { toast } from '@/app/notifications'
import { InstallStepFromGitHub } from '../../types'
import Installed from '../base/installed'
import { fetchReleases } from '../hooks'
import useHideLogic from '../hooks/use-hide-logic'
import useRefreshPluginList from '../hooks/use-refresh-plugin-list'
import { convertRepoToUrl, parseGitHubUrl } from '../utils'
import Loaded from './steps/loaded'
import SelectPackage from './steps/selectPackage'
const i18nPrefix = 'installFromGitHub'
type SelectOption = {
value: string
name: string
}
type InstallFromGitHubProps = {
updatePayload?: UpdateFromGitHubPayload
installContextCategory?: PluginCategoryEnum
onClose: () => void
onSuccess: () => void | Promise<void>
}
const InstallFromGitHub: React.FC<InstallFromGitHubProps> = ({
updatePayload,
installContextCategory,
onClose,
onSuccess,
}) => {
const repoUrlInputRef = useRef<HTMLInputElement>(null)
const { t } = useTranslation(['common', 'plugin'])
const { getIconUrl } = useGetIcon()
const { refreshPluginList } = useRefreshPluginList()
const { modalClassName, foldAnimInto, setIsInstalling, handleStartToInstall } =
useHideLogic(onClose)
const [state, setState] = useState<InstallState>({
step: updatePayload ? InstallStepFromGitHub.selectPackage : InstallStepFromGitHub.setUrl,
repoUrl: updatePayload?.originalPackageInfo?.repo
? convertRepoToUrl(updatePayload.originalPackageInfo.repo)
: '',
selectedVersion: '',
selectedPackage: '',
releases: updatePayload ? updatePayload.originalPackageInfo.releases : [],
})
const [uniqueIdentifier, setUniqueIdentifier] = useState<string | null>(null)
const [manifest, setManifest] = useState<PluginDeclaration | null>(null)
const [errorMsg, setErrorMsg] = useState<string | null>(null)
const versions: SelectOption[] = state.releases.map((release) => ({
value: release.tag_name,
name: release.tag_name,
}))
const packages: SelectOption[] = state.selectedVersion
? state.releases
.find((release) => release.tag_name === state.selectedVersion)
?.assets.map((asset) => ({
value: asset.name,
name: asset.name,
})) || []
: []
const getTitle = useCallback(() => {
if (state.step === InstallStepFromGitHub.installed)
return t(($) => $[`${i18nPrefix}.installedSuccessfully`], { ns: 'plugin' })
if (state.step === InstallStepFromGitHub.installFailed)
return t(($) => $[`${i18nPrefix}.installFailed`], { ns: 'plugin' })
return updatePayload
? t(($) => $[`${i18nPrefix}.updatePlugin`], { ns: 'plugin' })
: t(($) => $[`${i18nPrefix}.installPlugin`], { ns: 'plugin' })
}, [state.step, t, updatePayload])
const handleUrlSubmit = async () => {
const { isValid, owner, repo } = parseGitHubUrl(state.repoUrl)
if (!isValid || !owner || !repo) {
toast.error(t(($) => $['error.inValidGitHubUrl'], { ns: 'plugin' }))
return
}
try {
const fetchedReleases = await fetchReleases(owner, repo)
if (fetchedReleases.length > 0) {
setState((prevState) => ({
...prevState,
releases: fetchedReleases,
step: InstallStepFromGitHub.selectPackage,
}))
} else {
toast.error(t(($) => $['error.noReleasesFound'], { ns: 'plugin' }))
}
} catch {
toast.error(t(($) => $['error.fetchReleasesError'], { ns: 'plugin' }))
}
}
const handleError = (e: any, isInstall: boolean) => {
const message =
(e instanceof Error ? e.message : undefined) ||
t(($) => $['installModal.installFailedDesc'], { ns: 'plugin' })
setErrorMsg(message)
setState((prevState) => ({
...prevState,
step: isInstall ? InstallStepFromGitHub.installFailed : InstallStepFromGitHub.uploadFailed,
}))
}
const handleUploaded = async (GitHubPackage: any) => {
try {
const icon = await getIconUrl(GitHubPackage.manifest.icon)
setManifest({
...GitHubPackage.manifest,
icon,
})
setUniqueIdentifier(GitHubPackage.uniqueIdentifier)
setState((prevState) => ({ ...prevState, step: InstallStepFromGitHub.readyToInstall }))
} catch (e) {
handleError(e, false)
}
}
const handleUploadFail = useCallback((errorMsg: string) => {
setErrorMsg(errorMsg)
setState((prevState) => ({ ...prevState, step: InstallStepFromGitHub.uploadFailed }))
}, [])
const handleInstalled = useCallback(
async (notRefresh?: boolean) => {
if (!notRefresh) refreshPluginList(manifest)
await onSuccess()
setState((prevState) => ({ ...prevState, step: InstallStepFromGitHub.installed }))
setIsInstalling(false)
},
[manifest, onSuccess, refreshPluginList, setIsInstalling],
)
const handleFailed = useCallback(
(errorMsg?: string) => {
setState((prevState) => ({ ...prevState, step: InstallStepFromGitHub.installFailed }))
setIsInstalling(false)
if (errorMsg) setErrorMsg(errorMsg)
},
[setIsInstalling],
)
const handleBack = () => {
setState((prevState) => {
switch (prevState.step) {
case InstallStepFromGitHub.selectPackage:
return { ...prevState, step: InstallStepFromGitHub.setUrl }
case InstallStepFromGitHub.readyToInstall:
return { ...prevState, step: InstallStepFromGitHub.selectPackage }
default:
return prevState
}
})
}
const completedSteps: InstallStepFromGitHub[] = [
InstallStepFromGitHub.uploadFailed,
InstallStepFromGitHub.installed,
InstallStepFromGitHub.installFailed,
]
const failedSteps: InstallStepFromGitHub[] = [
InstallStepFromGitHub.uploadFailed,
InstallStepFromGitHub.installFailed,
]
return (
<Dialog
open
onOpenChange={(open) => {
if (!open) foldAnimInto()
}}
>
<DialogContent
initialFocus={repoUrlInputRef}
backdropProps={{ forceRender: true }}
className={cn('w-140', modalClassName, 'max-h-[calc(100dvh-48px)]')}
>
<DialogHeader>
<DialogTitle>{getTitle()}</DialogTitle>
{!completedSteps.includes(state.step) && (
<DialogDescription>
{t(($) => $['installFromGitHub.installNote'], { ns: 'plugin' })}
</DialogDescription>
)}
<DialogHeaderCloseButton aria-label={t(($) => $['operation.close'], { ns: 'common' })} />
</DialogHeader>
{completedSteps.includes(state.step) ? (
<Installed
payload={manifest}
isFailed={failedSteps.includes(state.step)}
errMsg={errorMsg}
installContextCategory={installContextCategory}
onCancel={onClose}
/>
) : state.step === InstallStepFromGitHub.setUrl ? (
<Form className="contents" onFormSubmit={handleUrlSubmit}>
<DialogBody>
<Field name="repoUrl" className="gap-4">
<FieldLabel className="flex w-full flex-col items-start justify-center p-0 text-text-secondary">
<span className="system-sm-semibold">
{t(($) => $['installFromGitHub.gitHubRepo'], { ns: 'plugin' })}
</span>
</FieldLabel>
<Input
ref={repoUrlInputRef}
type="text"
inputMode="url"
autoComplete="off"
spellCheck={false}
value={state.repoUrl}
onValueChange={(value) =>
setState((prevState) => ({ ...prevState, repoUrl: value }))
}
className="flex grow items-center gap-0.5 self-stretch overflow-hidden rounded-lg border-components-input-border-active bg-components-input-bg-active p-2 text-ellipsis"
placeholder="Please enter GitHub repo URL"
/>
</Field>
</DialogBody>
<DialogFooter>
<Button variant="secondary" className="min-w-18" onClick={onClose}>
{t(($) => $['installModal.cancel'], { ns: 'plugin' })}
</Button>
<Button
variant="primary"
type="submit"
className="min-w-18"
disabled={!state.repoUrl.trim()}
>
{t(($) => $['installModal.next'], { ns: 'plugin' })}
</Button>
</DialogFooter>
</Form>
) : (
<DialogBody className="flex flex-col items-start gap-4">
{state.step === InstallStepFromGitHub.selectPackage && (
<SelectPackage
updatePayload={updatePayload!}
repoUrl={state.repoUrl}
selectedVersion={state.selectedVersion}
versions={versions}
onSelectVersion={(item) =>
setState((prevState) => ({ ...prevState, selectedVersion: String(item.value) }))
}
selectedPackage={state.selectedPackage}
packages={packages}
onSelectPackage={(item) =>
setState((prevState) => ({ ...prevState, selectedPackage: String(item.value) }))
}
onUploaded={handleUploaded}
onFailed={handleUploadFail}
onBack={handleBack}
/>
)}
{state.step === InstallStepFromGitHub.readyToInstall &&
manifest &&
uniqueIdentifier && (
<Loaded
updatePayload={updatePayload!}
uniqueIdentifier={uniqueIdentifier}
payload={manifest}
repoUrl={state.repoUrl}
selectedVersion={state.selectedVersion}
selectedPackage={state.selectedPackage}
onBack={handleBack}
onStartToInstall={handleStartToInstall}
onInstalled={handleInstalled}
onFailed={handleFailed}
/>
)}
</DialogBody>
)}
</DialogContent>
</Dialog>
)
}
export default InstallFromGitHub
@@ -0,0 +1,184 @@
'use client'
import type { Plugin, PluginDeclaration, UpdateFromGitHubPayload } from '../../../types'
import { Button } from '@langgenius/dify-ui/button'
import * as React from 'react'
import { useEffect } from 'react'
import { useTranslation } from 'react-i18next'
import useCheckInstalled from '@/app/components/plugins/install-plugin/hooks/use-check-installed'
import { updateFromGitHub } from '@/service/plugins'
import { useInstallPackageFromGitHub, usePluginTaskList } from '@/service/use-plugins'
import Card from '../../../card'
import { TaskStatus } from '../../../types'
import checkTaskStatus from '../../base/check-task-status'
import Version from '../../base/version'
import { parseGitHubUrl, pluginManifestToCardPluginProps } from '../../utils'
type LoadedProps = {
updatePayload?: UpdateFromGitHubPayload
uniqueIdentifier: string
payload: PluginDeclaration | Plugin
repoUrl: string
selectedVersion: string
selectedPackage: string
onBack: () => void
onStartToInstall?: () => void
onInstalled: (notRefresh?: boolean) => void | Promise<void>
onFailed: (message?: string) => void
}
const i18nPrefix = 'installModal'
const Loaded: React.FC<LoadedProps> = ({
updatePayload,
uniqueIdentifier,
payload,
repoUrl,
selectedVersion,
selectedPackage,
onBack,
onStartToInstall,
onInstalled,
onFailed,
}) => {
const { t } = useTranslation(['plugin'])
const installButtonLabelId = React.useId()
const toInstallVersion = payload.version
const pluginId = (payload as Plugin).plugin_id
const { installedInfo, isLoading } = useCheckInstalled({
pluginIds: [pluginId],
enabled: !!pluginId,
})
const installedInfoPayload = installedInfo?.[pluginId]
const installedVersion = installedInfoPayload?.installedVersion
const hasInstalled = !!installedVersion
const [isInstalling, setIsInstalling] = React.useState(false)
const { mutateAsync: installPackageFromGitHub } = useInstallPackageFromGitHub()
const { handleInstallTaskStart } = usePluginTaskList(payload.category)
const { check } = checkTaskStatus()
useEffect(() => {
if (hasInstalled && uniqueIdentifier === installedInfoPayload.uniqueIdentifier) onInstalled()
}, [hasInstalled])
const handleInstall = async () => {
if (isInstalling) return
setIsInstalling(true)
onStartToInstall?.()
try {
const { owner, repo } = parseGitHubUrl(repoUrl)
let taskId
let isInstalled
if (updatePayload) {
const response = await updateFromGitHub(
`${owner}/${repo}`,
selectedVersion,
selectedPackage,
updatePayload.originalPackageInfo.id,
uniqueIdentifier,
)
const { all_installed, task_id } = response
handleInstallTaskStart(response)
taskId = task_id
isInstalled = all_installed
} else {
if (hasInstalled) {
const response = await updateFromGitHub(
`${owner}/${repo}`,
selectedVersion,
selectedPackage,
installedInfoPayload.uniqueIdentifier,
uniqueIdentifier,
)
const { all_installed, task_id } = response
handleInstallTaskStart(response)
taskId = task_id
isInstalled = all_installed
} else {
const response = await installPackageFromGitHub({
repoUrl: `${owner}/${repo}`,
selectedVersion,
selectedPackage,
uniqueIdentifier,
})
const { all_installed, task_id } = response
handleInstallTaskStart(response)
taskId = task_id
isInstalled = all_installed
}
}
if (isInstalled) {
await onInstalled()
return
}
const { status, error } = await check({
taskId,
pluginUniqueIdentifier: uniqueIdentifier,
})
if (status === TaskStatus.failed) {
onFailed(error)
return
}
await onInstalled(true)
} catch (e) {
if (typeof e === 'string') {
onFailed(e)
return
}
onFailed()
} finally {
setIsInstalling(false)
}
}
return (
<>
<div className="system-md-regular text-text-secondary">
<p>{t(($) => $[`${i18nPrefix}.readyToInstall`], { ns: 'plugin' })}</p>
</div>
<div className="flex flex-wrap content-start items-start gap-1 self-stretch rounded-2xl bg-background-section-burn p-2">
<Card
className="w-full"
payload={pluginManifestToCardPluginProps(payload as PluginDeclaration)}
titleLeft={
!isLoading && (
<Version
hasInstalled={hasInstalled}
installedVersion={installedVersion}
toInstallVersion={toInstallVersion}
/>
)
}
/>
</div>
<div className="mt-4 flex items-center justify-end gap-2 self-stretch">
{!isInstalling && (
<Button variant="secondary" className="min-w-18" onClick={onBack}>
{t(($) => $['installModal.back'], { ns: 'plugin' })}
</Button>
)}
<Button
variant="primary"
className="min-w-18"
onClick={handleInstall}
disabled={isLoading}
loading={isInstalling}
aria-labelledby={installButtonLabelId}
>
<span id={installButtonLabelId}>
{t(($) => $[`${i18nPrefix}.${isInstalling ? 'installing' : 'install'}`], {
ns: 'plugin',
})}
</span>
</Button>
</div>
</>
)
}
export default Loaded
@@ -0,0 +1,177 @@
'use client'
import type { PluginDeclaration, UpdateFromGitHubPayload } from '../../../types'
import { Button } from '@langgenius/dify-ui/button'
import { Field } from '@langgenius/dify-ui/field'
import {
Select,
SelectContent,
SelectItem,
SelectItemIndicator,
SelectItemText,
SelectLabel,
SelectTrigger,
} from '@langgenius/dify-ui/select'
import * as React from 'react'
import { useTranslation } from 'react-i18next'
import Badge from '@/app/components/base/badge'
import { handleUpload } from '../../hooks'
const i18nPrefix = 'installFromGitHub'
type SelectOption = {
value: string
name: string
}
type SelectPackageProps = {
updatePayload: UpdateFromGitHubPayload
repoUrl: string
selectedVersion: string
versions: SelectOption[]
onSelectVersion: (item: SelectOption) => void
selectedPackage: string
packages: SelectOption[]
onSelectPackage: (item: SelectOption) => void
onUploaded: (result: { uniqueIdentifier: string; manifest: PluginDeclaration }) => void
onFailed: (errorMsg: string) => void
onBack: () => void
}
const SelectPackage: React.FC<SelectPackageProps> = ({
updatePayload,
repoUrl,
selectedVersion,
versions,
onSelectVersion,
selectedPackage,
packages,
onSelectPackage,
onUploaded,
onFailed,
onBack,
}) => {
const { t } = useTranslation(['plugin'])
const isEdit = Boolean(updatePayload)
const [isUploading, setIsUploading] = React.useState(false)
const selectedVersionOption = versions.find((item) => item.value === selectedVersion) ?? null
const selectedPackageOption = packages.find((item) => item.value === selectedPackage) ?? null
const handleUploadPackage = async () => {
if (isUploading) return
setIsUploading(true)
try {
const repo = repoUrl.replace('https://github.com/', '')
await handleUpload(repo, selectedVersion, selectedPackage, (GitHubPackage) => {
onUploaded({
uniqueIdentifier: GitHubPackage.unique_identifier,
manifest: GitHubPackage.manifest,
})
})
} catch (e) {
if (e instanceof Error && e.message) onFailed(e.message)
else onFailed(t(($) => $[`${i18nPrefix}.uploadFailed`], { ns: 'plugin' }))
} finally {
setIsUploading(false)
}
}
return (
<>
<Field name="version" className="gap-4 self-stretch">
<Select
value={selectedVersionOption?.value ?? null}
onValueChange={(value) => {
if (value == null) return
const selectedItem = versions.find((item) => item.value === value)
if (selectedItem) onSelectVersion(selectedItem)
}}
>
<SelectLabel className="flex w-full flex-col items-start justify-center p-0 text-text-secondary">
<span className="system-sm-semibold">
{t(($) => $[`${i18nPrefix}.selectVersion`], { ns: 'plugin' })}
</span>
</SelectLabel>
<SelectTrigger className="h-9 text-components-input-text-filled">
<div className="flex items-center justify-between gap-2">
<span className="truncate">
{selectedVersionOption?.name ??
t(($) => $[`${i18nPrefix}.selectVersionPlaceholder`], { ns: 'plugin' }) ??
''}
</span>
{!!(
updatePayload?.originalPackageInfo.version &&
selectedVersionOption &&
selectedVersionOption.value !== updatePayload.originalPackageInfo.version
) && (
<Badge>
{updatePayload.originalPackageInfo.version} {'->'} {selectedVersionOption.value}
</Badge>
)}
</div>
</SelectTrigger>
<SelectContent className="w-lg">
{versions.map((item) => (
<SelectItem key={item.value} value={item.value}>
<SelectItemText>{item.name}</SelectItemText>
{item.value === updatePayload?.originalPackageInfo.version && (
<Badge uppercase={true} className="ml-1 shrink-0">
INSTALLED
</Badge>
)}
<SelectItemIndicator />
</SelectItem>
))}
</SelectContent>
</Select>
</Field>
<Field name="package" className="gap-4 self-stretch">
<Select
value={selectedPackageOption?.value ?? null}
disabled={!selectedVersion}
onValueChange={(value) => {
if (value == null) return
const selectedItem = packages.find((item) => item.value === value)
if (selectedItem) onSelectPackage(selectedItem)
}}
>
<SelectLabel className="flex w-full flex-col items-start justify-center p-0 text-text-secondary">
<span className="system-sm-semibold">
{t(($) => $[`${i18nPrefix}.selectPackage`], { ns: 'plugin' })}
</span>
</SelectLabel>
<SelectTrigger className="h-9 text-components-input-text-filled">
{selectedPackageOption?.name ??
t(($) => $[`${i18nPrefix}.selectPackagePlaceholder`], { ns: 'plugin' }) ??
''}
</SelectTrigger>
<SelectContent className="w-lg">
{packages.map((item) => (
<SelectItem key={item.value} value={item.value}>
<SelectItemText>{item.name}</SelectItemText>
<SelectItemIndicator />
</SelectItem>
))}
</SelectContent>
</Select>
</Field>
<div className="mt-4 flex items-center justify-end gap-2 self-stretch">
{!isEdit && (
<Button variant="secondary" className="min-w-18" onClick={onBack} disabled={isUploading}>
{t(($) => $['installModal.back'], { ns: 'plugin' })}
</Button>
)}
<Button
variant="primary"
className="min-w-18"
onClick={handleUploadPackage}
disabled={!selectedVersion || !selectedPackage || isUploading}
>
{t(($) => $['installModal.next'], { ns: 'plugin' })}
</Button>
</div>
</>
)
}
export default SelectPackage
@@ -0,0 +1,312 @@
import type { PluginInstallTaskStartResponse } from '@dify/contracts/api/console/workspaces/types.gen'
import type { ConsoleQueryTestOptions } from '@/test/console/query-data'
import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { API_PREFIX } from '@/config'
import { createHttpError } from '@/service/http-error'
import { renderWithConsoleQuery } from '@/test/console/query-data'
import { createDeferred } from '@/test/deferred'
import { createPluginDeclarationFixture, createPluginEntity } from '@/test/fixtures/plugin'
import { PermissionType, TaskStatus } from '../../../types'
import InstallFromLocalPackage from '../index'
const { upload, install, installedPlugins, uninstall, pollTask, refresh } = vi.hoisted(() => ({
upload: vi.fn(),
install: vi.fn(),
installedPlugins: vi.fn(),
uninstall: vi.fn(),
pollTask: vi.fn(),
refresh: vi.fn(),
}))
vi.mock('@/service/plugins', async (importOriginal) => ({
...(await importOriginal<typeof import('@/service/plugins')>()),
uploadFile: upload,
uninstallPlugin: uninstall,
checkTaskStatus: pollTask,
}))
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.pkg.post': install,
}),
consoleQuery: withConsoleResponses(actual.consoleQuery, {
'workspaces.current.plugin.list.installations.ids.post': installedPlugins,
}),
}
})
// Refreshing the separate model/tool catalogs is covered by use-refresh-plugin-list.
vi.mock('../../hooks/use-refresh-plugin-list', () => ({
default: () => ({ refreshPluginList: refresh }),
}))
const manifest = createPluginDeclarationFixture({
author: 'test',
name: 'local',
label: { ...createPluginDeclarationFixture().label, en_US: 'Local plugin' },
})
const uploadedPackage = { unique_identifier: 'test/local:1.0.0', manifest }
const file = new File(['package'], 'local.difypkg', { type: 'application/octet-stream' })
const renderInstaller = (selectedFile = file, options: ConsoleQueryTestOptions = {}) => {
const onClose = vi.fn()
renderWithConsoleQuery(
<InstallFromLocalPackage file={selectedFile} onClose={onClose} onSuccess={vi.fn()} />,
{
accountProfileMeta: { currentVersion: '1.0.0' },
currentWorkspace: { id: 'local-install-workspace' },
workspacePermissionKeys: ['plugin.install'],
systemFeatures: {
enable_marketplace: true,
rbac_enabled: true,
plugin_installation_permission: {
plugin_installation_scope: 'all',
restrict_to_marketplace_only: false,
},
},
...options,
},
)
return { onClose }
}
const installButton = () => screen.getByRole('button', { name: 'plugin.installModal.install' })
const startInstall = async (user: ReturnType<typeof userEvent.setup>) => {
await screen.findByText('plugin.installModal.readyToInstall')
await waitFor(() => expect(installButton()).toBeEnabled())
await user.click(installButton())
}
beforeEach(() => {
vi.resetAllMocks()
upload.mockResolvedValue(uploadedPackage)
installedPlugins.mockResolvedValue({ plugins: [] })
install.mockResolvedValue({ all_installed: true, task_id: '' })
uninstall.mockResolvedValue({})
})
it('uploads the file, prevents duplicate installs while pending, and shows the completed package', async () => {
const user = userEvent.setup()
const uploaded = createDeferred<typeof uploadedPackage>()
const started = createDeferred<PluginInstallTaskStartResponse>()
upload.mockReturnValue(uploaded.promise)
install.mockReturnValue(started.promise)
const { onClose } = renderInstaller()
expect(screen.getByText(/plugin.installModal.uploadingPackage/)).toHaveTextContent(
'local.difypkg',
)
expect(installButton()).toBeDisabled()
expect(upload).toHaveBeenCalledExactlyOnceWith(file, false)
uploaded.resolve(uploadedPackage)
await startInstall(user)
expect(screen.queryByText(/plugin.installModal.uploadingPackage/)).not.toBeInTheDocument()
const pendingButton = screen.getByRole('button', { name: 'plugin.installModal.installing' })
expect(pendingButton).toBeDisabled()
expect(screen.queryByRole('button', { name: 'common.operation.cancel' })).not.toBeInTheDocument()
await user.click(pendingButton)
expect(install).toHaveBeenCalledExactlyOnceWith({
body: { plugin_unique_identifiers: ['test/local:1.0.0'] },
})
started.resolve({ all_installed: true, task_id: '' })
await screen.findByRole('dialog', { name: 'plugin.installModal.installedSuccessfully' })
expect(screen.getByText('Local plugin')).toBeInTheDocument()
expect(screen.getByText('1.0.0')).toBeInTheDocument()
expect(refresh).toHaveBeenCalledExactlyOnceWith(
expect.objectContaining({
name: 'local',
icon: `${API_PREFIX}/workspaces/current/plugin/icon?tenant_id=local-install-workspace&filename=test-icon.png`,
}),
)
expect(pollTask).not.toHaveBeenCalled()
await user.click(screen.getAllByRole('button', { name: 'common.operation.close' }).at(-1)!)
expect(onClose).toHaveBeenCalledOnce()
})
it.each(['common.operation.cancel', 'common.operation.close'])(
'allows %s while upload is pending without installing',
async (name) => {
const user = userEvent.setup()
upload.mockReturnValue(new Promise(() => {}))
const { onClose } = renderInstaller()
await user.click(screen.getByRole('button', { name }))
expect(onClose).toHaveBeenCalledOnce()
expect(install).not.toHaveBeenCalled()
},
)
it.each([
{
reason: 'server error',
error: createHttpError(new Response(null, { status: 413 }), { message: 'File too large' }),
message: 'File too large',
},
{
reason: 'transport error',
error: new TypeError('Failed to fetch'),
message: 'plugin.installModal.uploadFailed',
},
])('shows $reason from upload and allows closing the failure', async ({ error, message }) => {
const user = userEvent.setup()
upload.mockRejectedValue(error)
const { onClose } = renderInstaller()
await screen.findByRole('dialog', { name: 'plugin.installModal.uploadFailed' })
expect(screen.getAllByText(message).length).toBeGreaterThan(0)
expect(
screen.queryByRole('button', { name: 'plugin.installModal.install' }),
).not.toBeInTheDocument()
expect(install).not.toHaveBeenCalled()
await user.click(screen.getAllByRole('button', { name: 'common.operation.close' }).at(-1)!)
expect(onClose).toHaveBeenCalledOnce()
})
it.each(['local.difypkg', 'local.difybndl'])(
'rejects an invalid upload response for %s before installing',
async (name) => {
upload.mockResolvedValue({})
renderInstaller(new File(['invalid'], name))
await screen.findByRole('dialog', { name: 'plugin.installModal.uploadFailed' })
expect(
screen.queryByRole('button', { name: 'plugin.installModal.install' }),
).not.toBeInTheDocument()
expect(install).not.toHaveBeenCalled()
},
)
it('waits for installed-version lookup, then preserves credentials before replacing the package', async () => {
const user = userEvent.setup()
const previous = createPluginEntity({
id: 'old-installation',
plugin_id: 'test/local',
plugin_unique_identifier: 'test/local:0.9.0',
})
previous.declaration.version = '0.9.0'
const lookup = createDeferred<{ plugins: (typeof previous)[] }>()
const removal = createDeferred<void>()
installedPlugins.mockReturnValue(lookup.promise)
uninstall.mockReturnValue(removal.promise)
renderInstaller()
await screen.findByText('plugin.installModal.readyToInstall')
expect(installButton()).toBeDisabled()
lookup.resolve({ plugins: [previous] })
await screen.findByText('0.9.0 -> 1.0.0')
await startInstall(user)
expect(uninstall).toHaveBeenCalledExactlyOnceWith('old-installation', {
preserveCredentials: true,
})
expect(install).not.toHaveBeenCalled()
removal.resolve()
await screen.findByRole('dialog', { name: 'plugin.installModal.installedSuccessfully' })
expect(install).toHaveBeenCalledExactlyOnceWith({
body: { plugin_unique_identifiers: ['test/local:1.0.0'] },
})
})
it('skips reinstalling an identical package', async () => {
installedPlugins.mockResolvedValue({
plugins: [
createPluginEntity({ plugin_id: 'test/local', plugin_unique_identifier: 'test/local:1.0.0' }),
],
})
renderInstaller()
await screen.findByRole('dialog', { name: 'plugin.installModal.installedSuccessfully' })
expect(install).not.toHaveBeenCalled()
expect(uninstall).not.toHaveBeenCalled()
})
it.each([TaskStatus.success, TaskStatus.failed])(
'shows the asynchronous task result: %s',
async (status) => {
const user = userEvent.setup()
const task = createDeferred<{
task: { plugins: { plugin_unique_identifier: string; status: TaskStatus; message: string }[] }
}>()
install.mockResolvedValue({ all_installed: false, task_id: 'install-task' })
pollTask.mockReturnValue(task.promise)
renderInstaller()
await startInstall(user)
await waitFor(() => expect(pollTask).toHaveBeenCalledExactlyOnceWith('install-task'))
expect(screen.getByRole('button', { name: 'plugin.installModal.installing' })).toBeDisabled()
task.resolve({
task: {
plugins: [
{
plugin_unique_identifier: 'test/local:1.0.0',
status,
message: 'Dependency unavailable',
},
],
},
})
await screen.findByRole('dialog', {
name:
status === TaskStatus.success
? 'plugin.installModal.installedSuccessfully'
: 'plugin.installModal.installFailed',
})
if (status === TaskStatus.failed)
expect(screen.getByText('Dependency unavailable')).toBeInTheDocument()
expect(refresh).not.toHaveBeenCalled()
},
)
it('shows a generic installation failure when the install request rejects', async () => {
const user = userEvent.setup()
install.mockRejectedValue(new Error('Connection failed'))
renderInstaller()
await startInstall(user)
await screen.findByRole('dialog', { name: 'plugin.installModal.installFailed' })
expect(screen.getByText('plugin.installModal.installFailedDesc')).toBeInTheDocument()
expect(refresh).not.toHaveBeenCalled()
})
it('uploads a bundle and installs its returned package dependency', async () => {
const user = userEvent.setup()
const bundle = new File(['bundle'], 'local.difybndl')
upload.mockResolvedValue(
['bundled'].map((name) => ({
type: 'package',
value: {
unique_identifier: `test/${name}:1.0.0`,
manifest: createPluginDeclarationFixture({ author: 'test', name }),
},
})),
)
renderInstaller(bundle)
await waitFor(() => expect(installButton()).toBeEnabled())
await user.click(installButton())
await screen.findByRole('dialog', { name: 'plugin.installModal.installedSuccessfully' })
expect(upload).toHaveBeenCalledExactlyOnceWith(bundle, true)
expect(install).toHaveBeenCalledExactlyOnceWith({
body: { plugin_unique_identifiers: ['test/bundled:1.0.0'] },
})
expect(
screen.getByText('plugin.installModal.installedSuccessfullyCountDesc:{"num":1}'),
).toBeInTheDocument()
})
it.each([
{ currentVersion: '1.0.0', minimum: '0.8.0', warns: false },
{ currentVersion: '1.0.0', minimum: '2.0.0', warns: true },
{ currentVersion: '1.0.0', minimum: undefined, warns: false },
{ currentVersion: null, minimum: '2.0.0', warns: false },
])(
'warns about compatibility for Dify $currentVersion and minimum $minimum without blocking installation',
async ({ currentVersion, minimum, warns }) => {
upload.mockResolvedValue({
...uploadedPackage,
manifest: { ...manifest, meta: { version: '1.0.0', minimum_dify_version: minimum } },
})
renderInstaller(file, { accountProfileMeta: { currentVersion } })
await screen.findByText('plugin.installModal.readyToInstall')
await waitFor(() => expect(installButton()).toBeEnabled())
if (warns)
expect(screen.getByText(/plugin.difyVersionNotCompatible/)).toHaveTextContent('2.0.0')
else expect(screen.queryByText(/plugin.difyVersionNotCompatible/)).not.toBeInTheDocument()
},
)
@@ -0,0 +1,141 @@
'use client'
import type { Dependency, PluginCategoryEnum, PluginDeclaration } 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 useGetIcon from '@/app/components/plugins/install-plugin/base/use-get-icon'
import { InstallStep } from '../../types'
import useHideLogic from '../hooks/use-hide-logic'
import ReadyToInstallBundle from '../install-bundle/ready-to-install'
import ReadyToInstallPackage from './ready-to-install'
import Uploading from './steps/uploading'
const i18nPrefix = 'installModal'
type InstallFromLocalPackageProps = {
file: File
installContextCategory?: PluginCategoryEnum
onSuccess: () => void
onClose: () => void
}
const InstallFromLocalPackage: React.FC<InstallFromLocalPackageProps> = ({
file,
installContextCategory,
onClose,
}) => {
const { t } = useTranslation(['common', 'plugin'])
// uploading -> !uploadFailed -> readyToInstall -> installed/failed
const [step, setStep] = useState<InstallStep>(InstallStep.uploading)
const [uniqueIdentifier, setUniqueIdentifier] = useState<string | null>(null)
const [manifest, setManifest] = useState<PluginDeclaration | null>(null)
const [errorMsg, setErrorMsg] = useState<string | null>(null)
const isBundle = file.name.endsWith('.difybndl')
const [dependencies, setDependencies] = useState<Dependency[]>([])
const { modalClassName, foldAnimInto, setIsInstalling, handleStartToInstall } =
useHideLogic(onClose)
const getTitle = useCallback(() => {
if (step === InstallStep.uploadFailed)
return t(($) => $[`${i18nPrefix}.uploadFailed`], { ns: 'plugin' })
if (isBundle && step === InstallStep.installed)
return t(($) => $[`${i18nPrefix}.installedSuccessfully`], { ns: 'plugin' })
if (step === InstallStep.installed)
return t(($) => $[`${i18nPrefix}.installedSuccessfully`], { ns: 'plugin' })
if (step === InstallStep.installFailed)
return t(($) => $[`${i18nPrefix}.installFailed`], { ns: 'plugin' })
return t(($) => $[`${i18nPrefix}.installPlugin`], { ns: 'plugin' })
}, [isBundle, step, t])
const { getIconUrl } = useGetIcon()
const handlePackageUploaded = useCallback(
async (result: { uniqueIdentifier: string; manifest: PluginDeclaration }) => {
const { manifest, uniqueIdentifier } = result
const icon = await getIconUrl(manifest!.icon)
const iconDark = manifest.icon_dark ? await getIconUrl(manifest.icon_dark) : undefined
setUniqueIdentifier(uniqueIdentifier)
setManifest({
...manifest,
icon,
icon_dark: iconDark,
})
setStep(InstallStep.readyToInstall)
},
[getIconUrl],
)
const handleBundleUploaded = useCallback((result: Dependency[]) => {
setDependencies(result)
setStep(InstallStep.readyToInstall)
}, [])
const handleUploadFail = useCallback((errorMsg: string) => {
setErrorMsg(errorMsg)
setStep(InstallStep.uploadFailed)
}, [])
return (
<Dialog
open
onOpenChange={(open) => {
if (!open) foldAnimInto()
}}
>
<DialogContent
backdropProps={{ forceRender: true }}
className={cn('w-140', modalClassName, 'max-h-[calc(100dvh-48px)]')}
>
<DialogHeader>
<DialogTitle>{getTitle()}</DialogTitle>
<DialogHeaderCloseButton aria-label={t(($) => $['operation.close'], { ns: 'common' })} />
</DialogHeader>
{step === InstallStep.uploading && (
<Uploading
isBundle={isBundle}
file={file}
onCancel={onClose}
onPackageUploaded={handlePackageUploaded}
onBundleUploaded={handleBundleUploaded}
onFailed={handleUploadFail}
/>
)}
{isBundle ? (
<ReadyToInstallBundle
step={step}
onStepChange={setStep}
onStartToInstall={handleStartToInstall}
setIsInstalling={setIsInstalling}
onClose={onClose}
allPlugins={dependencies}
/>
) : (
<ReadyToInstallPackage
step={step}
onStepChange={setStep}
onStartToInstall={handleStartToInstall}
setIsInstalling={setIsInstalling}
onClose={onClose}
uniqueIdentifier={uniqueIdentifier}
manifest={manifest}
errorMsg={errorMsg}
installContextCategory={installContextCategory}
onError={setErrorMsg}
/>
)}
</DialogContent>
</Dialog>
)
}
export default InstallFromLocalPackage
@@ -0,0 +1,87 @@
'use client'
import type { FC } from 'react'
import type { PluginCategoryEnum, PluginDeclaration } from '../../types'
import * as React from 'react'
import { useCallback } from 'react'
import { InstallStep } from '../../types'
import Installed from '../base/installed'
import useRefreshPluginList from '../hooks/use-refresh-plugin-list'
import Install from './steps/install'
type Props = Readonly<{
step: InstallStep
onStepChange: (step: InstallStep) => void
onStartToInstall: () => void
setIsInstalling: (isInstalling: boolean) => void
onClose: () => void
uniqueIdentifier: string | null
manifest: PluginDeclaration | null
errorMsg: string | null
installContextCategory?: PluginCategoryEnum
onError: (errorMsg: string) => void
}>
const ReadyToInstall: FC<Props> = ({
step,
onStepChange,
onStartToInstall,
setIsInstalling,
onClose,
uniqueIdentifier,
manifest,
errorMsg,
installContextCategory,
onError,
}) => {
const { refreshPluginList } = useRefreshPluginList()
const handleInstalled = useCallback(
(notRefresh?: boolean) => {
onStepChange(InstallStep.installed)
if (!notRefresh) refreshPluginList(manifest)
setIsInstalling(false)
},
[manifest, onStepChange, refreshPluginList, setIsInstalling],
)
const handleFailed = useCallback(
(errorMsg?: string) => {
onStepChange(InstallStep.installFailed)
setIsInstalling(false)
if (errorMsg) onError(errorMsg)
},
[onError, onStepChange, setIsInstalling],
)
const completedSteps: InstallStep[] = [
InstallStep.uploadFailed,
InstallStep.installed,
InstallStep.installFailed,
]
const failedSteps: InstallStep[] = [InstallStep.uploadFailed, InstallStep.installFailed]
return (
<>
{step === InstallStep.readyToInstall && (
<Install
uniqueIdentifier={uniqueIdentifier!}
payload={manifest!}
onCancel={onClose}
onInstalled={handleInstalled}
onFailed={handleFailed}
onStartToInstall={onStartToInstall}
/>
)}
{completedSteps.includes(step) && (
<Installed
payload={manifest}
isFailed={failedSteps.includes(step)}
errMsg={errorMsg}
installContextCategory={installContextCategory}
onCancel={onClose}
/>
)}
</>
)
}
export default React.memo(ReadyToInstall)
@@ -0,0 +1,174 @@
'use client'
import type { FC } from 'react'
import type { PluginDeclaration } from '../../../types'
import { Button } from '@langgenius/dify-ui/button'
import { RiLoader2Line } from '@remixicon/react'
import { useSuspenseQuery } from '@tanstack/react-query'
import * as React from 'react'
import { useEffect, useMemo } from 'react'
import { Trans, useTranslation } from 'react-i18next'
import useCheckInstalled from '@/app/components/plugins/install-plugin/hooks/use-check-installed'
import { userProfileQueryOptions } from '@/features/account-profile/client'
import { uninstallPlugin } from '@/service/plugins'
import { useInstallPackageFromLocal, usePluginTaskList } from '@/service/use-plugins'
import { isEqualOrLaterThanVersion } from '@/utils/semver'
import Card from '../../../card'
import { TaskStatus } from '../../../types'
import checkTaskStatus from '../../base/check-task-status'
import Version from '../../base/version'
import { pluginManifestToCardPluginProps } from '../../utils'
const i18nPrefix = 'installModal'
type Props = Readonly<{
uniqueIdentifier: string
payload: PluginDeclaration
onCancel: () => void
onStartToInstall?: () => void
onInstalled: (notRefresh?: boolean) => void
onFailed: (message?: string) => void
}>
const Installed: FC<Props> = ({
uniqueIdentifier,
payload,
onCancel,
onStartToInstall,
onInstalled,
onFailed,
}) => {
const { t } = useTranslation(['common', 'plugin'])
const toInstallVersion = payload.version
const pluginId = `${payload.author}/${payload.name}`
const { installedInfo, isLoading } = useCheckInstalled({
pluginIds: [pluginId],
enabled: !!pluginId,
})
const installedInfoPayload = installedInfo?.[pluginId]
const installedVersion = installedInfoPayload?.installedVersion
const hasInstalled = !!installedVersion
useEffect(() => {
if (hasInstalled && uniqueIdentifier === installedInfoPayload.uniqueIdentifier) onInstalled()
}, [hasInstalled])
const [isInstalling, setIsInstalling] = React.useState(false)
const { mutateAsync: installPackageFromLocal } = useInstallPackageFromLocal()
const { check, stop } = checkTaskStatus()
const handleCancel = () => {
stop()
onCancel()
}
const { handleInstallTaskStart } = usePluginTaskList(payload.category)
const handleInstall = async () => {
if (isInstalling) return
setIsInstalling(true)
onStartToInstall?.()
try {
if (hasInstalled) {
await uninstallPlugin(installedInfoPayload.installedId, { preserveCredentials: true })
}
const response = await installPackageFromLocal(uniqueIdentifier)
const { all_installed, task_id } = response
handleInstallTaskStart(response)
const taskId = task_id
const isInstalled = all_installed
if (isInstalled) {
onInstalled()
return
}
const { status, error } = await check({
taskId,
pluginUniqueIdentifier: uniqueIdentifier,
})
if (status === TaskStatus.failed) {
onFailed(error)
return
}
onInstalled(true)
} catch (e) {
if (typeof e === 'string') {
onFailed(e)
return
}
onFailed()
}
}
const { data: currentVersion } = useSuspenseQuery({
...userProfileQueryOptions(),
select: (data) => data.meta.currentVersion ?? '',
})
const isDifyVersionCompatible = useMemo(() => {
if (!currentVersion) return true
return isEqualOrLaterThanVersion(currentVersion, payload.meta.minimum_dify_version ?? '0.0.0')
}, [currentVersion, payload.meta.minimum_dify_version])
return (
<>
<div className="flex flex-col items-start justify-center gap-2 self-stretch px-6 py-3">
<div className="system-md-regular text-text-secondary">
<p>{t(($) => $[`${i18nPrefix}.readyToInstall`], { ns: 'plugin' })}</p>
<p>
<Trans
i18nKey={($) => $[`${i18nPrefix}.fromTrustSource`]}
ns="plugin"
components={{ trustSource: <span className="system-md-semibold" /> }}
/>
</p>
{!isDifyVersionCompatible && (
<p className="flex items-center gap-1 system-md-regular text-text-warning">
{t(($) => $.difyVersionNotCompatible, {
ns: 'plugin',
minimalDifyVersion: payload.meta.minimum_dify_version ?? '0.0.0',
})}
</p>
)}
</div>
<div className="flex flex-wrap content-start items-start gap-1 self-stretch rounded-2xl bg-background-section-burn p-2">
<Card
className="w-full"
payload={pluginManifestToCardPluginProps(payload)}
titleLeft={
!isLoading && (
<Version
hasInstalled={hasInstalled}
installedVersion={installedVersion}
toInstallVersion={toInstallVersion}
/>
)
}
/>
</div>
</div>
{/* Action Buttons */}
<div className="flex items-center justify-end gap-2 self-stretch p-6 pt-5">
{!isInstalling && (
<Button variant="secondary" className="min-w-18" onClick={handleCancel}>
{t(($) => $['operation.cancel'], { ns: 'common' })}
</Button>
)}
<Button
variant="primary"
className="flex min-w-18"
disabled={isInstalling || isLoading}
onClick={handleInstall}
>
{isInstalling && <RiLoader2Line className="size-4 animate-spin-slow" />}
<span>
{t(($) => $[`${i18nPrefix}.${isInstalling ? 'installing' : 'install'}`], {
ns: 'plugin',
})}
</span>
</Button>
</div>
</>
)
}
export default React.memo(Installed)
@@ -0,0 +1,124 @@
'use client'
import type { FC } from 'react'
import type { Dependency, Plugin, PluginDeclaration } from '../../../types'
import { Button } from '@langgenius/dify-ui/button'
import { ORPCError } from '@orpc/client'
import * as React from 'react'
import { useTranslation } from 'react-i18next'
import { uploadFile } from '@/service/plugins'
import Card from '../../../card'
const i18nPrefix = 'installModal'
type PackageUploadResponse = {
unique_identifier: string
manifest: PluginDeclaration
}
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null
}
function isPackageUploadResponse(value: unknown): value is PackageUploadResponse {
if (!isObject(value)) return false
return typeof value.unique_identifier === 'string' && isObject(value.manifest)
}
type Props = Readonly<{
isBundle: boolean
file: File
onCancel: () => void
onPackageUploaded: (result: { uniqueIdentifier: string; manifest: PluginDeclaration }) => void
onBundleUploaded: (result: Dependency[]) => void
onFailed: (errorMsg: string) => void
}>
const Uploading: FC<Props> = ({
isBundle,
file,
onCancel,
onPackageUploaded,
onBundleUploaded,
onFailed,
}) => {
const { t } = useTranslation(['common', 'plugin'])
const fileName = file.name
const handleUploadedResponse = React.useCallback(
(response: unknown) => {
if (isBundle) {
if (Array.isArray(response)) {
onBundleUploaded(response)
return
}
onFailed(t(($) => $[`${i18nPrefix}.uploadFailed`], { ns: 'plugin' }))
return
}
if (!isPackageUploadResponse(response)) {
onFailed(t(($) => $[`${i18nPrefix}.uploadFailed`], { ns: 'plugin' }))
return
}
onPackageUploaded({
uniqueIdentifier: response.unique_identifier,
manifest: response.manifest,
})
},
[isBundle, onBundleUploaded, onFailed, onPackageUploaded, t],
)
const handleUpload = React.useCallback(async () => {
try {
handleUploadedResponse(await uploadFile(file, isBundle))
} catch (error: unknown) {
// Only server answers carry a user-facing message; transport errors use the localized fallback.
const message = error instanceof ORPCError ? error.message : undefined
if (message) {
onFailed(message)
return
}
onFailed(t(($) => $[`${i18nPrefix}.uploadFailed`], { ns: 'plugin' }))
}
}, [file, handleUploadedResponse, isBundle, onFailed, t])
React.useEffect(() => {
handleUpload()
}, [handleUpload])
return (
<>
<div className="flex flex-col items-start justify-center gap-2 self-stretch px-6 py-3">
<div className="flex items-center gap-1 self-stretch">
<span className="i-ri-loader-2-line size-4 animate-spin-slow text-text-accent" />
<div className="system-md-regular text-text-secondary">
{t(($) => $[`${i18nPrefix}.uploadingPackage`], {
ns: 'plugin',
packageName: fileName,
})}
</div>
</div>
<div className="flex flex-wrap content-start items-start gap-1 self-stretch rounded-2xl bg-background-section-burn p-2">
<Card
className="w-full"
payload={{ name: fileName } as Plugin}
isLoading
loadingFileName={fileName}
installed={false}
/>
</div>
</div>
{/* Action Buttons */}
<div className="flex items-center justify-end gap-2 self-stretch p-6 pt-5">
<Button variant="secondary" className="min-w-18" onClick={onCancel}>
{t(($) => $['operation.cancel'], { ns: 'common' })}
</Button>
<Button variant="primary" className="min-w-18" disabled>
{t(($) => $[`${i18nPrefix}.install`], { ns: 'plugin' })}
</Button>
</div>
</>
)
}
export default React.memo(Uploading)
@@ -0,0 +1,41 @@
'use client'
import type { PluginCategoryEnum, PluginManifestInMarket } from '../types'
import type { UseInstallFromMarketplaceQueryOptions } from './hooks/use-install-from-marketplace-query'
import { useInstallFromMarketplaceQuery as useInstallFromMarketplaceQueryHook } from './hooks/use-install-from-marketplace-query'
import InstallFromMarketplace from './install-from-marketplace'
type InstallFromMarketplaceQueryProps = UseInstallFromMarketplaceQueryOptions & {
installContextCategory?: PluginCategoryEnum
}
const InstallFromMarketplaceQuery = ({
installContextCategory,
...options
}: InstallFromMarketplaceQueryProps) => {
const {
bundleInfo,
dependencies,
hideInstallFromMarketplace,
isShowInstallFromMarketplace,
marketplaceInstall,
} = useInstallFromMarketplaceQueryHook(options)
if (!isShowInstallFromMarketplace) return null
if (!marketplaceInstall && !bundleInfo) return null
return (
<InstallFromMarketplace
manifest={marketplaceInstall?.manifest as PluginManifestInMarket}
uniqueIdentifier={marketplaceInstall?.uniqueIdentifier ?? ''}
isBundle={!!bundleInfo}
dependencies={dependencies}
installContextCategory={installContextCategory}
onClose={hideInstallFromMarketplace}
onSuccess={hideInstallFromMarketplace}
/>
)
}
export default InstallFromMarketplaceQuery
@@ -0,0 +1,400 @@
import type { PluginInstallTaskStartResponse } from '@dify/contracts/api/console/workspaces/types.gen'
import type { ComponentProps } from 'react'
import type { Dependency, Plugin, PluginManifestInMarket } from '../../../types'
import type { ConsoleQueryTestOptions } from '@/test/console/query-data'
import { act, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
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 InstallFromMarketplace from '../index'
const { install, upgrade, installedPlugins, declaration, pollTask, marketplace, refresh } =
vi.hoisted(() => ({
install: vi.fn(),
upgrade: vi.fn(),
installedPlugins: vi.fn(),
declaration: vi.fn(),
pollTask: vi.fn(),
marketplace: vi.fn(),
refresh: 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: pollTask,
}))
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.marketplace.pkg.get': declaration,
'workspaces.current.plugin.install.marketplace.post': install,
'workspaces.current.plugin.upgrade.marketplace.post': upgrade,
}),
consoleQuery: withConsoleResponses(actual.consoleQuery, {
'workspaces.current.plugin.list.installations.ids.post': installedPlugins,
}),
}
})
// Catalog refresh is independently covered by use-refresh-plugin-list.
vi.mock('../../hooks/use-refresh-plugin-list', () => ({
default: () => ({ refreshPluginList: refresh }),
}))
const createMockManifest = (
overrides: Partial<PluginManifestInMarket> = {},
): PluginManifestInMarket => ({
plugin_unique_identifier: 'test-unique-identifier',
name: 'test-plugin',
org: 'test-org',
icon: 'test-icon.png',
label: { en_US: 'Test Plugin' } as PluginManifestInMarket['label'],
category: PluginCategoryEnum.tool,
version: '1.0.0',
latest_version: '1.0.0',
brief: { en_US: 'A test plugin' } as PluginManifestInMarket['brief'],
introduction: 'Introduction text',
verified: true,
install_count: 100,
badges: [],
verification: { authorized_category: 'community' },
from: 'marketplace',
...overrides,
})
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-package-id',
icon: 'test-icon.png',
verified: true,
label: { en_US: 'Test Plugin' },
brief: { en_US: 'A test plugin' },
description: { en_US: 'A test plugin description' },
introduction: 'Introduction text',
repository: 'https://github.com/test/plugin',
category: PluginCategoryEnum.tool,
install_count: 100,
endpoint: { settings: [] },
tags: [],
badges: [],
verification: { authorized_category: 'community' },
from: 'marketplace',
...overrides,
})
const renderInstaller = (
props: Partial<ComponentProps<typeof InstallFromMarketplace>> = {},
options: ConsoleQueryTestOptions = {},
) => {
const onClose = vi.fn()
const onSuccess = vi.fn()
const manifest = createMockManifest()
const rendered = renderWithConsoleQuery(
<InstallFromMarketplace
uniqueIdentifier="test-unique-identifier"
manifest={manifest}
onClose={onClose}
onSuccess={onSuccess}
{...props}
/>,
{
accountProfileMeta: { currentVersion: '1.0.0' },
workspacePermissionKeys: ['plugin.install'],
systemFeatures: {
enable_marketplace: true,
rbac_enabled: true,
plugin_installation_permission: {
plugin_installation_scope: 'all',
restrict_to_marketplace_only: false,
},
},
...options,
},
)
return { ...rendered, onClose, onSuccess, manifest }
}
const installButton = () => screen.getByRole('button', { name: 'plugin.installModal.install' })
const successDialog = () =>
screen.findByRole('dialog', { name: 'plugin.installModal.installedSuccessfully' })
// The footer and the dialog dismiss button share a name; the footer is the visible text action.
const closeResult = (user: ReturnType<typeof userEvent.setup>) =>
user.click(screen.getByText('common.operation.close'))
beforeEach(() => {
vi.resetAllMocks()
install.mockResolvedValue({ all_installed: true, task_id: '' })
upgrade.mockResolvedValue({ all_installed: true, task_id: '' })
installedPlugins.mockResolvedValue({ plugins: [] })
declaration.mockResolvedValue({ manifest: createPluginDeclarationFixture() })
pollTask.mockResolvedValue({
task: {
plugins: [{ plugin_unique_identifier: 'test-unique-identifier', status: TaskStatus.success }],
},
})
})
it('installs the displayed version once while pending, refreshes the catalog and completes on close', async () => {
const user = userEvent.setup()
const pending = createDeferred<PluginInstallTaskStartResponse>()
install.mockReturnValueOnce(pending.promise)
const { onSuccess, onClose, manifest } = renderInstaller({
uniqueIdentifier: 'selected-version-id',
})
expect(
screen.getByRole('dialog', { name: 'plugin.installModal.installPlugin' }),
).toBeInTheDocument()
expect(screen.getByText('Test Plugin')).toBeInTheDocument()
expect(screen.getByText('1.0.0')).toBeInTheDocument()
await user.click(installButton())
const installing = await screen.findByRole('button', { name: 'plugin.installModal.installing' })
expect(installing).toBeDisabled()
expect(screen.queryByRole('button', { name: 'common.operation.cancel' })).not.toBeInTheDocument()
await user.click(installing)
expect(install).toHaveBeenCalledOnce()
expect(onSuccess).not.toHaveBeenCalled()
expect(refresh).not.toHaveBeenCalled()
await act(async () => pending.resolve({ all_installed: true, task_id: '' }))
await successDialog()
expect(install).toHaveBeenCalledExactlyOnceWith({
body: { plugin_unique_identifiers: ['selected-version-id'] },
})
expect(upgrade).not.toHaveBeenCalled()
expect(pollTask).not.toHaveBeenCalled()
expect(refresh).toHaveBeenCalledExactlyOnceWith(manifest)
expect(onSuccess).not.toHaveBeenCalled()
expect(
screen.queryByRole('button', { name: 'plugin.installModal.install' }),
).not.toBeInTheDocument()
await closeResult(user)
expect(onSuccess).toHaveBeenCalledOnce()
expect(onClose).not.toHaveBeenCalled()
})
it.each(['common.operation.cancel', 'common.operation.close'])(
'dismisses before installation through %s',
async (name) => {
const user = userEvent.setup()
const { onClose, onSuccess } = renderInstaller()
await user.click(screen.getByRole('button', { name }))
expect(onClose).toHaveBeenCalledOnce()
expect(onSuccess).not.toHaveBeenCalled()
expect(install).not.toHaveBeenCalled()
},
)
it('waits for a legacy task result without refreshing the catalog a second time', async () => {
const user = userEvent.setup()
const pending = createDeferred<{
task: { plugins: { plugin_unique_identifier: string; status: TaskStatus }[] }
}>()
install.mockResolvedValueOnce({ all_installed: false, task_id: 'task-123' })
pollTask.mockReturnValueOnce(pending.promise)
renderInstaller()
await user.click(installButton())
await waitFor(() => expect(pollTask).toHaveBeenCalledExactlyOnceWith('task-123'))
expect(
screen.queryByRole('dialog', { name: 'plugin.installModal.installedSuccessfully' }),
).not.toBeInTheDocument()
await act(async () =>
pending.resolve({
task: {
plugins: [
{ plugin_unique_identifier: 'test-unique-identifier', status: TaskStatus.success },
],
},
}),
)
await successDialog()
expect(refresh).not.toHaveBeenCalled()
})
it('hands a started task to the task list and closes without claiming installation succeeded', async () => {
const user = userEvent.setup()
const task: NonNullable<PluginInstallTaskStartResponse['task']> = {
id: 'task-123',
created_at: '2026-06-05T03:34:59Z',
updated_at: '2026-06-05T03:34:59Z',
status: TaskStatus.running,
total_plugins: 1,
completed_plugins: 0,
plugins: [
{
plugin_unique_identifier: 'test-unique-identifier',
plugin_id: 'test-plugin-id',
source: 'marketplace',
status: TaskStatus.pending,
message: '',
icon: 'test-icon.png',
labels: { en_US: 'Test Plugin' },
},
],
}
install.mockResolvedValueOnce({ all_installed: false, task_id: task.id, task })
const { onClose, onSuccess, queryClient } = renderInstaller()
await user.click(installButton())
await waitFor(() => expect(onClose).toHaveBeenCalledOnce())
expect(queryClient.getQueryData(['plugins', 'pluginTaskList'])).toEqual({
tasks: [expect.objectContaining({ id: task.id, status: TaskStatus.running })],
})
expect(pollTask).not.toHaveBeenCalled()
expect(onSuccess).not.toHaveBeenCalled()
expect(refresh).not.toHaveBeenCalled()
})
it('shows a failed task message and allows closing the result', async () => {
const user = userEvent.setup()
install.mockResolvedValueOnce({ all_installed: false, task_id: 'failed-task' })
pollTask.mockResolvedValueOnce({
task: {
plugins: [
{
plugin_unique_identifier: 'test-unique-identifier',
status: TaskStatus.failed,
message: 'Package verification failed',
},
],
},
})
const { onSuccess } = renderInstaller()
await user.click(installButton())
await screen.findByRole('dialog', { name: 'plugin.installModal.installFailed' })
expect(screen.getByText('Package verification failed')).toBeInTheDocument()
expect(refresh).not.toHaveBeenCalled()
await closeResult(user)
expect(onSuccess).toHaveBeenCalledOnce()
})
it.each([
['Request rejected', 'Request rejected'],
[new Error('Request rejected'), 'plugin.installModal.installFailedDesc'],
])('shows an installation request failure: %s', async (error, message) => {
const user = userEvent.setup()
install.mockRejectedValueOnce(error)
renderInstaller()
await user.click(installButton())
await screen.findByRole('dialog', { name: 'plugin.installModal.installFailed' })
expect(screen.getByText(message)).toBeInTheDocument()
expect(refresh).not.toHaveBeenCalled()
expect(pollTask).not.toHaveBeenCalled()
})
it('waits for installed-version lookup, then upgrades the existing plugin', async () => {
const user = userEvent.setup()
const pending = createDeferred<{ plugins: ReturnType<typeof createPluginEntity>[] }>()
installedPlugins.mockReturnValueOnce(pending.promise)
renderInstaller({ manifest: createMockPlugin() })
expect(installButton()).toBeDisabled()
await user.click(installButton())
expect(install).not.toHaveBeenCalled()
const existingPlugin = createPluginEntity({
plugin_id: 'test-plugin-id',
plugin_unique_identifier: 'previous-version-id',
})
existingPlugin.declaration.version = '0.9.0'
await act(async () => pending.resolve({ plugins: [existingPlugin] }))
await waitFor(() => expect(installButton()).toBeEnabled())
expect(screen.getByText('0.9.0 -> 1.0.0')).toBeInTheDocument()
await user.click(installButton())
await successDialog()
expect(upgrade).toHaveBeenCalledExactlyOnceWith({
body: {
original_plugin_unique_identifier: 'previous-version-id',
new_plugin_unique_identifier: 'test-unique-identifier',
},
})
expect(install).not.toHaveBeenCalled()
})
it('recognizes an already installed package without submitting it again', async () => {
installedPlugins.mockResolvedValueOnce({
plugins: [
createPluginEntity({
plugin_id: 'test-plugin-id',
plugin_unique_identifier: 'test-unique-identifier',
}),
],
})
renderInstaller({ manifest: createMockPlugin() })
await successDialog()
expect(install).not.toHaveBeenCalled()
expect(upgrade).not.toHaveBeenCalled()
})
it('blocks installation when the workspace scope disallows the plugin', async () => {
const user = userEvent.setup()
renderInstaller(
{},
{ systemFeatures: { plugin_installation_permission: { plugin_installation_scope: 'none' } } },
)
expect(installButton()).toBeDisabled()
await user.click(installButton())
expect(install).not.toHaveBeenCalled()
})
it.each([
['2.0.0', true],
['0.9.0', false],
])('compares Dify 1.0.0 against the minimum version %s', async (minimumVersion, warns) => {
const response = {
manifest: createPluginDeclarationFixture({
meta: { version: '1.0.0', minimum_dify_version: minimumVersion },
}),
}
declaration.mockResolvedValueOnce(response)
const { queryClient } = renderInstaller()
await waitFor(() =>
expect(
queryClient.getQueryData(['plugins', 'pluginDeclaration', 'test-unique-identifier']),
).toEqual(response),
)
if (warns) expect(await screen.findByText(/plugin.difyVersionNotCompatible/)).toBeInTheDocument()
else expect(screen.queryByText(/plugin.difyVersionNotCompatible/)).not.toBeInTheDocument()
})
it('installs marketplace bundle dependencies through the real bundle flow', async () => {
const user = userEvent.setup()
const plugin = createMockPlugin({
name: 'bundle-plugin',
plugin_id: 'test-org/bundle-plugin',
latest_package_identifier: 'test-org/bundle-plugin:1.0.0',
})
const dependencies: Dependency[] = [
{
type: 'marketplace',
value: { marketplace_plugin_unique_identifier: plugin.latest_package_identifier },
},
]
marketplace.mockResolvedValueOnce({ data: { list: [{ plugin }] } })
const { onClose, onSuccess } = renderInstaller({ isBundle: true, dependencies })
await waitFor(() => expect(installButton()).toBeEnabled())
await user.click(installButton())
await successDialog()
expect(install).toHaveBeenCalledExactlyOnceWith({
body: { plugin_unique_identifiers: [plugin.latest_package_identifier] },
})
expect(refresh).toHaveBeenCalledWith(undefined, true)
await closeResult(user)
expect(onClose).toHaveBeenCalledOnce()
expect(onSuccess).not.toHaveBeenCalled()
})
@@ -0,0 +1,146 @@
'use client'
import type { Dependency, Plugin, PluginCategoryEnum, PluginManifestInMarket } from '../../types'
import { cn } from '@langgenius/dify-ui/cn'
import { Dialog, DialogClose, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import * as React from 'react'
import { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { InstallStep } from '../../types'
import Installed from '../base/installed'
import useHideLogic from '../hooks/use-hide-logic'
import useRefreshPluginList from '../hooks/use-refresh-plugin-list'
import ReadyToInstallBundle from '../install-bundle/ready-to-install'
import Install from './steps/install'
const i18nPrefix = 'installModal'
type InstallFromMarketplaceProps = {
uniqueIdentifier: string
manifest: PluginManifestInMarket | Plugin
isBundle?: boolean
dependencies?: Dependency[]
installContextCategory?: PluginCategoryEnum
onSuccess: () => void
onClose: () => void
}
const InstallFromMarketplace: React.FC<InstallFromMarketplaceProps> = ({
uniqueIdentifier,
manifest,
isBundle,
dependencies,
installContextCategory,
onSuccess,
onClose,
}) => {
const { t } = useTranslation(['common', 'plugin'])
// readyToInstall -> check installed -> installed/failed
const [step, setStep] = useState<InstallStep>(InstallStep.readyToInstall)
const [errorMsg, setErrorMsg] = useState<string | null>(null)
const { refreshPluginList } = useRefreshPluginList()
const {
modalClassName,
foldAnimInto,
foldIntoTaskTrigger,
setIsInstalling,
handleStartToInstall,
} = useHideLogic(onClose)
const getTitle = useCallback(() => {
if (isBundle && step === InstallStep.installed)
return t(($) => $[`${i18nPrefix}.installedSuccessfully`], { ns: 'plugin' })
if (step === InstallStep.installed)
return t(($) => $[`${i18nPrefix}.installedSuccessfully`], { ns: 'plugin' })
if (step === InstallStep.installFailed)
return t(($) => $[`${i18nPrefix}.installFailed`], { ns: 'plugin' })
return t(($) => $[`${i18nPrefix}.installPlugin`], { ns: 'plugin' })
}, [isBundle, step, t])
const handleInstalled = useCallback(
(notRefresh?: boolean) => {
setStep(InstallStep.installed)
if (!notRefresh) refreshPluginList(manifest)
setIsInstalling(false)
},
[manifest, refreshPluginList, setIsInstalling],
)
const handleFailed = useCallback(
(errorMsg?: string) => {
setStep(InstallStep.installFailed)
setIsInstalling(false)
if (errorMsg) setErrorMsg(errorMsg)
},
[setIsInstalling],
)
const completedSteps: InstallStep[] = [InstallStep.installed, InstallStep.installFailed]
return (
<Dialog
open
onOpenChange={(open) => {
if (!open) foldAnimInto()
}}
>
<DialogContent
backdropProps={{ forceRender: true }}
className={cn('max-h-[calc(100dvh-48px)] w-140', modalClassName)}
>
<div className="flex shrink-0 items-start gap-2 self-stretch pt-6 pr-14 pb-3 pl-6">
<DialogTitle>{getTitle()}</DialogTitle>
</div>
{isBundle ? (
<ReadyToInstallBundle
step={step}
onStepChange={setStep}
onStartToInstall={handleStartToInstall}
setIsInstalling={setIsInstalling}
onClose={onClose}
allPlugins={dependencies!}
isFromMarketPlace
/>
) : (
<>
{step === InstallStep.readyToInstall && (
<Install
uniqueIdentifier={uniqueIdentifier}
payload={manifest!}
onCancel={onClose}
onInstalled={handleInstalled}
onFailed={handleFailed}
onStartToInstall={handleStartToInstall}
onTaskStarted={foldIntoTaskTrigger}
/>
)}
{completedSteps.includes(step) && (
<Installed
payload={manifest!}
isMarketPayload
isFailed={step === InstallStep.installFailed}
errMsg={errorMsg}
installContextCategory={installContextCategory}
onCancel={onSuccess}
/>
)}
</>
)}
<DialogClose
render={
<IconButton
aria-label={t(($) => $['operation.close'], { ns: 'common' })}
size="lg"
className="absolute inset-e-6 top-6"
>
<span aria-hidden className="i-ri-close-line size-4" />
</IconButton>
}
/>
</DialogContent>
</Dialog>
)
}
export default InstallFromMarketplace
@@ -0,0 +1,203 @@
'use client'
import type { PluginInstallTaskStartResponse } from '@dify/contracts/api/console/workspaces/types.gen'
import type { FC } from 'react'
import type { Plugin, PluginManifestInMarket } from '../../../types'
import { Button } from '@langgenius/dify-ui/button'
import { RiLoader2Line } from '@remixicon/react'
import { useSuspenseQuery } from '@tanstack/react-query'
import * as React from 'react'
import { useEffect, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import useCheckInstalled from '@/app/components/plugins/install-plugin/hooks/use-check-installed'
import { userProfileQueryOptions } from '@/features/account-profile/client'
import {
useInstallPackageFromMarketPlace,
usePluginDeclarationFromMarketPlace,
usePluginTaskList,
useUpdatePackageFromMarketPlace,
} from '@/service/use-plugins'
import { isEqualOrLaterThanVersion } from '@/utils/semver'
import Card from '../../../card'
// import { RiInformation2Line } from '@remixicon/react'
import { TaskStatus } from '../../../types'
import checkTaskStatus from '../../base/check-task-status'
import Version from '../../base/version'
import useInstallPluginLimit from '../../hooks/use-install-plugin-limit'
import { pluginManifestInMarketToPluginProps } from '../../utils'
const i18nPrefix = 'installModal'
type Props = Readonly<{
uniqueIdentifier: string
payload: PluginManifestInMarket | Plugin
onCancel: () => void
onStartToInstall?: () => void
onTaskStarted: () => void
onInstalled: (notRefresh?: boolean) => void
onFailed: (message?: string) => void
}>
const Installed: FC<Props> = ({
uniqueIdentifier,
payload,
onCancel,
onStartToInstall,
onTaskStarted,
onInstalled,
onFailed,
}) => {
const { t } = useTranslation(['common', 'plugin'])
const toInstallVersion = payload.version || payload.latest_version
const pluginId = (payload as Plugin).plugin_id
const { installedInfo, isLoading } = useCheckInstalled({
pluginIds: [pluginId],
enabled: !!pluginId,
})
const installedInfoPayload = installedInfo?.[pluginId]
const installedVersion = installedInfoPayload?.installedVersion
const hasInstalled = !!installedVersion
const { mutateAsync: installPackageFromMarketPlace } = useInstallPackageFromMarketPlace()
const { mutateAsync: updatePackageFromMarketPlace } = useUpdatePackageFromMarketPlace()
const [isInstalling, setIsInstalling] = React.useState(false)
const { check, stop } = checkTaskStatus()
const { handleInstallTaskStart } = usePluginTaskList(payload.category)
useEffect(() => {
if (hasInstalled && uniqueIdentifier === installedInfoPayload.uniqueIdentifier) onInstalled()
}, [hasInstalled])
const handleCancel = () => {
stop()
onCancel()
}
const handleInstall = async () => {
if (isInstalling) return
onStartToInstall?.()
setIsInstalling(true)
try {
let taskId
let isInstalled
let installResponse: PluginInstallTaskStartResponse | undefined
if (hasInstalled) {
const response = await updatePackageFromMarketPlace({
original_plugin_unique_identifier: installedInfoPayload.uniqueIdentifier,
new_plugin_unique_identifier: uniqueIdentifier,
})
installResponse = response
const { all_installed, task_id } = response
handleInstallTaskStart(response)
taskId = task_id
isInstalled = all_installed
} else {
const response = await installPackageFromMarketPlace(uniqueIdentifier)
installResponse = response
const { all_installed, task_id } = response
handleInstallTaskStart(response)
taskId = task_id
isInstalled = all_installed
}
if (isInstalled) {
onInstalled()
return
}
if (installResponse?.task) {
onTaskStarted()
return
}
const { status, error } = await check({
taskId,
pluginUniqueIdentifier: uniqueIdentifier,
})
if (status === TaskStatus.failed) {
onFailed(error)
return
}
onInstalled(true)
} catch (e) {
if (typeof e === 'string') {
onFailed(e)
return
}
onFailed()
}
}
const { data: currentVersion } = useSuspenseQuery({
...userProfileQueryOptions(),
select: (data) => data.meta.currentVersion ?? '',
})
const { data: pluginDeclaration } = usePluginDeclarationFromMarketPlace(uniqueIdentifier)
const isDifyVersionCompatible = useMemo(() => {
if (!pluginDeclaration || !currentVersion) return true
return isEqualOrLaterThanVersion(
currentVersion,
pluginDeclaration?.manifest.meta.minimum_dify_version ?? '0.0.0',
)
}, [currentVersion, pluginDeclaration])
const { canInstall } = useInstallPluginLimit({
...payload,
from: 'marketplace',
})
return (
<>
<div className="flex flex-col items-start justify-center gap-4 self-stretch px-6 py-3">
<div className="system-md-regular text-text-secondary">
<p>{t(($) => $[`${i18nPrefix}.readyToInstall`], { ns: 'plugin' })}</p>
{!isDifyVersionCompatible && (
<p className="system-md-regular text-text-warning">
{t(($) => $.difyVersionNotCompatible, {
ns: 'plugin',
minimalDifyVersion:
pluginDeclaration?.manifest.meta.minimum_dify_version ?? '0.0.0',
})}
</p>
)}
</div>
<div className="flex flex-wrap content-start items-start gap-1 self-stretch rounded-2xl bg-background-section-burn p-2">
<Card
className="w-full"
payload={pluginManifestInMarketToPluginProps(payload as PluginManifestInMarket)}
titleLeft={
!isLoading && (
<Version
hasInstalled={hasInstalled}
installedVersion={installedVersion}
toInstallVersion={toInstallVersion}
/>
)
}
limitedInstall={!canInstall}
/>
</div>
</div>
{/* Action Buttons */}
<div className="flex items-center justify-end gap-2 self-stretch p-6 pt-5">
{!isInstalling && (
<Button variant="secondary" className="min-w-18" onClick={handleCancel}>
{t(($) => $['operation.cancel'], { ns: 'common' })}
</Button>
)}
<Button
variant="primary"
className="flex min-w-18"
disabled={isInstalling || isLoading || !canInstall}
onClick={handleInstall}
>
{isInstalling && <RiLoader2Line className="size-4 animate-spin-slow" />}
<span>
{t(($) => $[`${i18nPrefix}.${isInstalling ? 'installing' : 'install'}`], {
ns: 'plugin',
})}
</span>
</Button>
</div>
</>
)
}
export default React.memo(Installed)
@@ -0,0 +1,119 @@
import type {
I18nObject,
PluginDeclarationResponse,
} from '@dify/contracts/api/console/workspaces/types.gen'
import type { GitHubUrlInfo, Plugin, PluginDeclaration, PluginManifestInMarket } from '../types'
import { isEmpty } from 'es-toolkit/compat'
export const pluginManifestToCardPluginProps = (pluginManifest: PluginDeclaration): Plugin => {
return {
plugin_id: pluginManifest.plugin_unique_identifier,
type: pluginManifest.category as Plugin['type'],
category: pluginManifest.category,
name: pluginManifest.name,
version: pluginManifest.version,
latest_version: '',
latest_package_identifier: '',
org: pluginManifest.author,
author: pluginManifest.author,
label: pluginManifest.label,
brief: pluginManifest.description,
description: pluginManifest.description,
icon: pluginManifest.icon,
icon_dark: pluginManifest.icon_dark,
verified: pluginManifest.verified,
introduction: '',
repository: '',
install_count: 0,
endpoint: {
settings: [],
},
tags: pluginManifest.tags.map((tag) => ({ name: tag })),
badges: [],
verification: { authorized_category: 'langgenius' },
from: 'package',
}
}
/** Plugin card text from a translated object; untranslated locales are left out. */
export const toPluginText = ({ en_US, zh_Hans, ja_JP, pt_BR }: I18nObject): Plugin['label'] => ({
en_US,
...(zh_Hans != null && { zh_Hans }),
...(ja_JP != null && { ja_JP }),
...(pt_BR != null && { pt_BR }),
})
/** Card props for the manifest of a package the console has just uploaded. */
export const pluginDeclarationToCardPluginProps = (
manifest: PluginDeclarationResponse,
uniqueIdentifier: string,
): Plugin => ({
plugin_id: uniqueIdentifier,
type: manifest.category === 'agent-strategy' ? 'agent_strategy' : manifest.category,
category: manifest.category,
name: manifest.name,
version: manifest.version,
latest_version: '',
latest_package_identifier: '',
// A manifest without an author shows no organization.
org: manifest.author ?? '',
author: manifest.author ?? undefined,
label: toPluginText(manifest.label),
brief: toPluginText(manifest.description),
description: toPluginText(manifest.description),
icon: manifest.icon,
icon_dark: manifest.icon_dark ?? undefined,
verified: manifest.verified ?? false,
introduction: '',
repository: '',
install_count: 0,
endpoint: {
settings: [],
},
tags: (manifest.tags ?? []).map((tag) => ({ name: tag })),
badges: [],
verification: { authorized_category: 'langgenius' },
from: 'package',
})
export const pluginManifestInMarketToPluginProps = (
pluginManifest: PluginManifestInMarket,
): Plugin => {
return {
plugin_id: pluginManifest.plugin_unique_identifier,
type: pluginManifest.category as Plugin['type'],
category: pluginManifest.category,
name: pluginManifest.name,
version: pluginManifest.latest_version,
latest_version: pluginManifest.latest_version,
latest_package_identifier: '',
org: pluginManifest.org,
label: pluginManifest.label,
brief: pluginManifest.brief,
description: pluginManifest.brief,
icon: pluginManifest.icon,
verified: true,
introduction: pluginManifest.introduction,
repository: '',
install_count: 0,
endpoint: {
settings: [],
},
tags: [],
badges: pluginManifest.badges,
verification: isEmpty(pluginManifest.verification)
? { authorized_category: 'langgenius' }
: pluginManifest.verification,
from: pluginManifest.from,
}
}
export const parseGitHubUrl = (url: string): GitHubUrlInfo => {
const githubUrlRegex = /^https:\/\/github\.com\/([^/]+)\/([^/]+)\/?$/
const match = githubUrlRegex.exec(url)
return match ? { isValid: true, owner: match[1], repo: match[2] } : { isValid: false }
}
export const convertRepoToUrl = (repo: string) => {
return repo ? `https://github.com/${repo}` : ''
}