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,261 @@
import type { MetaData, PluginCategoryEnum } from '../../types'
import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import { expectLoadingButton } from '@/test/button'
import { renderWithConfigurationModals as render } from '@/test/configuration-modals'
import { createDeferred } from '@/test/deferred'
import { createPluginDeclarationFixture } from '@/test/fixtures/plugin'
import Action from '../action'
const requests = vi.hoisted(() => ({
uninstall: vi.fn(),
releases: vi.fn(),
uploadGitHub: vi.fn(),
updateFromGitHub: vi.fn(),
invalidate: vi.fn(),
notify: vi.fn(),
}))
vi.mock('@/service/plugins', async (importOriginal) => ({
...(await importOriginal<typeof import('@/service/plugins')>()),
uninstallPlugin: requests.uninstall,
uploadGitHub: requests.uploadGitHub,
updateFromGitHub: requests.updateFromGitHub,
}))
vi.mock('../../install-plugin/hooks', async (importOriginal) => ({
...(await importOriginal<typeof import('../../install-plugin/hooks')>()),
fetchReleases: requests.releases,
}))
vi.mock('@/app/notifications', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/app/notifications')>()
return { ...actual, toast: Object.assign(requests.notify, actual.toast) }
})
// Catalog refresh is an independent installer contract; the real host, release picker and installer stay mounted.
vi.mock('../../install-plugin/hooks/use-refresh-plugin-list', () => ({
default: () => ({ refreshPluginList: vi.fn() }),
}))
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: [] }),
}),
}
})
vi.mock('@/service/use-plugins', async (importOriginal) => ({
...(await importOriginal<typeof import('@/service/use-plugins')>()),
useInvalidateInstalledPluginList: () => requests.invalidate,
}))
type ActionProps = {
author: string
installationId: string
pluginUniqueIdentifier: string
pluginName: string
category: PluginCategoryEnum
usedInApps: number
isShowFetchNewVersion: boolean
isShowInfo: boolean
isShowDelete: boolean
onDelete: () => void
meta?: MetaData
}
const createActionProps = (overrides: Partial<ActionProps> = {}): ActionProps => ({
author: 'test-author',
installationId: 'install-123',
pluginUniqueIdentifier: 'test-author/test-plugin@1.0.0',
pluginName: 'test-plugin',
category: 'tool' as PluginCategoryEnum,
usedInApps: 5,
isShowFetchNewVersion: false,
isShowInfo: false,
isShowDelete: true,
onDelete: vi.fn(),
meta: {
repo: 'test-author/test-plugin',
version: '1.0.0',
package: 'test-plugin.difypkg',
},
...overrides,
})
const deleteButton = () => screen.getByRole('button', { name: 'plugin.action.delete' })
const confirmButton = () => screen.getByRole('button', { name: 'common.operation.confirm' })
const updateButton = () => screen.getByRole('button', { name: 'plugin.action.checkForUpdates' })
beforeEach(() => {
vi.clearAllMocks()
requests.uninstall.mockResolvedValue({ success: true })
requests.releases.mockResolvedValue([])
})
describe('installed plugin actions', () => {
it('hides unavailable actions', () => {
render(<Action {...createActionProps({ isShowDelete: false })} />)
expect(screen.queryByRole('button')).not.toBeInTheDocument()
})
it('identifies the plugin before deletion and allows cancellation', async () => {
const user = userEvent.setup()
const props = createActionProps()
render(<Action {...props} />)
await user.click(deleteButton())
expect(screen.getByRole('alertdialog', { name: 'plugin.action.delete' })).toHaveTextContent(
'test-plugin',
)
await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
expect(requests.uninstall).not.toHaveBeenCalled()
expect(props.onDelete).not.toHaveBeenCalled()
})
it('deletes the current installation once and refreshes only after the request succeeds', async () => {
const user = userEvent.setup()
const pending = createDeferred<{ success: boolean }>()
requests.uninstall.mockReturnValueOnce(pending.promise)
const previous = createActionProps({ installationId: 'old-installation' })
const props = createActionProps({
installationId: 'new-installation',
category: 'model' as PluginCategoryEnum,
})
const { rerender } = render(<Action {...previous} />)
rerender(<Action {...props} />)
await user.click(deleteButton())
await user.click(confirmButton())
expectLoadingButton(confirmButton())
await user.click(confirmButton())
expect(requests.uninstall).toHaveBeenCalledExactlyOnceWith('new-installation')
expect(requests.invalidate).not.toHaveBeenCalled()
expect(props.onDelete).not.toHaveBeenCalled()
pending.resolve({ success: true })
await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
expect(requests.invalidate).toHaveBeenCalledExactlyOnceWith('model')
expect(props.onDelete).toHaveBeenCalledOnce()
expect(previous.onDelete).not.toHaveBeenCalled()
})
it.each(['rejected', 'unsuccessful'])(
'keeps the confirmation available for retry after a %s uninstall',
async (failure) => {
const user = userEvent.setup()
const logError = vi.spyOn(console, 'error').mockImplementation(() => {})
if (failure === 'rejected')
requests.uninstall.mockRejectedValueOnce(new Error('Network error'))
else requests.uninstall.mockResolvedValueOnce({ success: false })
const props = createActionProps()
render(<Action {...props} />)
await user.click(deleteButton())
await user.click(confirmButton())
await waitFor(() => expect(confirmButton()).not.toHaveAttribute('aria-disabled', 'true'))
expect(screen.getByRole('alertdialog')).toBeInTheDocument()
expect(props.onDelete).not.toHaveBeenCalled()
expect(requests.invalidate).not.toHaveBeenCalled()
await user.click(confirmButton())
await waitFor(() => expect(props.onDelete).toHaveBeenCalledOnce())
expect(requests.uninstall).toHaveBeenCalledTimes(2)
logError.mockRestore()
},
)
it('opens repository, release and package information in the real dialog', async () => {
const user = userEvent.setup()
render(<Action {...createActionProps({ isShowInfo: true })} />)
await user.click(screen.getByRole('button', { name: 'plugin.action.pluginInfo' }))
expect(screen.getByRole('dialog', { name: 'plugin.pluginInfoModal.title' })).toBeInTheDocument()
expect(screen.getByText('https://github.com/test-author/test-plugin')).toBeInTheDocument()
expect(screen.getByText('1.0.0')).toBeInTheDocument()
expect(screen.getByText('test-plugin.difypkg')).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'common.operation.close' }))
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
})
it('updates the chosen release through the real modal and refreshes after saving', async () => {
const user = userEvent.setup()
requests.releases.mockResolvedValue([
{
tag_name: '2.0.0',
assets: [
{
id: 2,
name: 'test-plugin.difypkg',
browser_download_url:
'https://github.com/test-author/test-plugin/releases/download/2.0.0/test-plugin.difypkg',
},
],
},
{ tag_name: '1.0.0', assets: [] },
])
requests.uploadGitHub.mockResolvedValue({
unique_identifier: 'test-author/test-plugin@2.0.0',
manifest: createPluginDeclarationFixture({ version: '2.0.0' }),
})
const pending = createDeferred<{ all_installed: boolean; task_id: string }>()
requests.updateFromGitHub.mockReturnValueOnce(pending.promise)
render(<Action {...createActionProps({ isShowFetchNewVersion: true })} />)
await user.click(updateButton())
expect(
await screen.findByRole('dialog', { name: 'plugin.installFromGitHub.updatePlugin' }),
).toBeVisible()
expect(requests.releases).toHaveBeenCalledExactlyOnceWith('test-author', 'test-plugin')
expect(requests.notify).toHaveBeenCalledWith('New version available: 2.0.0', { type: 'info' })
await user.click(
screen.getByRole('combobox', { name: 'plugin.installFromGitHub.selectVersion' }),
)
expect(await screen.findByRole('option', { name: /1\.0\.0.*INSTALLED/ })).toBeVisible()
await user.click(screen.getByRole('option', { name: '2.0.0' }))
await user.click(
screen.getByRole('combobox', { name: 'plugin.installFromGitHub.selectPackage' }),
)
await user.click(await screen.findByRole('option', { name: 'test-plugin.difypkg' }))
await user.click(screen.getByRole('button', { name: 'plugin.installModal.next' }))
await user.click(await screen.findByRole('button', { name: 'plugin.installModal.install' }))
expect(requests.uploadGitHub).toHaveBeenCalledExactlyOnceWith(
'test-author/test-plugin',
'2.0.0',
'test-plugin.difypkg',
{ silent: true },
)
expect(requests.updateFromGitHub).toHaveBeenCalledExactlyOnceWith(
'test-author/test-plugin',
'2.0.0',
'test-plugin.difypkg',
'test-author/test-plugin@1.0.0',
'test-author/test-plugin@2.0.0',
)
expect(requests.invalidate).not.toHaveBeenCalled()
pending.resolve({ all_installed: true, task_id: '' })
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
expect(requests.invalidate).toHaveBeenCalledExactlyOnceWith('tool')
})
it('falls back to plugin identity for incomplete repository metadata and reports an up-to-date version', async () => {
const user = userEvent.setup()
requests.releases.mockResolvedValue([{ tag_name: '1.0.0', assets: [] }])
render(
<Action
{...createActionProps({
isShowFetchNewVersion: true,
meta: { repo: '/', version: '1.0.0', package: 'plugin.difypkg' },
})}
/>,
)
await user.click(updateButton())
await waitFor(() =>
expect(requests.notify).toHaveBeenCalledWith('No new version available', { type: 'info' }),
)
expect(requests.releases).toHaveBeenCalledExactlyOnceWith('test-author', 'test-plugin')
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
})
it('does not open an update when the repository has no releases', async () => {
const user = userEvent.setup()
render(<Action {...createActionProps({ isShowFetchNewVersion: true })} />)
await user.click(updateButton())
await waitFor(() => expect(requests.releases).toHaveBeenCalledOnce())
expect(requests.notify).not.toHaveBeenCalled()
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
})
})
@@ -0,0 +1,451 @@
import type { ReactElement, ReactNode } from 'react'
import type { PluginDeclaration, PluginDetail } from '../../types'
import { useQuery } from '@tanstack/react-query'
import { screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useState } from 'react'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
import { ModalContextProvider } from '@/context/modal-context-provider'
import { consoleQuery } from '@/service/console'
import { useInstalledPluginList } from '@/service/use-plugins'
import { createCatalogModelFixture, createModelCatalogFixture } from '@/test/console/model-provider'
import { renderWithConsoleQuery } from '@/test/console/query-data'
import { createPluginEntity } from '@/test/fixtures/plugin'
import { PluginPageContext } from '../../plugin-page/context'
import { PluginCategoryEnum, PluginSource } from '../../types'
import PluginItem from '../index'
const mockEnableMarketplace = vi.fn(() => true)
const mockTheme = vi.fn(() => 'light')
vi.mock('@/hooks/use-theme', () => ({
default: () => ({ theme: mockTheme() }),
}))
const PluginPageContextProvider = PluginPageContext.Provider
const mockLangGeniusVersionInfo = vi.fn(() => ({
current_env: '',
current_version: '1.0.0',
latest_version: '',
release_notes: '',
version: '',
}))
const createLangGeniusVersionInfo = (currentVersion: string) => ({
current_env: '',
current_version: currentVersion,
latest_version: '',
release_notes: '',
version: '',
})
function PluginPageBoundary({ children }: { children: ReactNode }) {
const [selectedItem, setSelectedItem] = useState<
{ type: 'plugin'; id: string } | { type: 'builtinTool'; id: string }
>()
return (
<PluginPageContextProvider
value={{
containerRef: { current: null },
selectedItem,
setSelectedItem,
filters: { categories: [], tags: [], searchQuery: '' },
setFilters: () => {},
activeTab: 'plugins',
setActiveTab: () => {},
options: [],
}}
>
<output aria-label="selected plugin">
{selectedItem ? `${selectedItem.type}:${selectedItem.id}` : 'none'}
</output>
{children}
</PluginPageContextProvider>
)
}
const render = (ui: ReactElement) => {
const wrap = (element: ReactElement) => (
<PluginPageBoundary>
<ModalContextProvider>{element}</ModalContextProvider>
</PluginPageBoundary>
)
const rendered = renderWithConsoleQuery(wrap(ui), {
accountProfileMeta: {
currentVersion: mockLangGeniusVersionInfo().current_version,
},
systemFeatures: { enable_marketplace: mockEnableMarketplace() },
})
return { ...rendered, rerender: (element: ReactElement) => rendered.rerender(wrap(element)) }
}
const requests = vi.hoisted(() => ({
categoryList: vi.fn(),
models: vi.fn(),
uninstall: 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.byCategory.list.get': requests.categoryList,
'workspaces.current.models.modelTypes.byModelType.get': requests.models,
}),
}
})
vi.mock('@/service/plugins', async (importOriginal) => ({
...(await importOriginal<typeof import('@/service/plugins')>()),
uninstallPlugin: requests.uninstall,
}))
const createPluginDeclaration = (
overrides: Partial<PluginDeclaration> = {},
): PluginDeclaration => ({
plugin_unique_identifier: 'test-plugin-id',
version: '1.0.0',
author: 'test-author',
icon: 'test-icon.png',
icon_dark: 'test-icon-dark.png',
name: 'test-plugin',
category: PluginCategoryEnum.tool,
label: { en_US: 'Test Plugin' } as unknown as PluginDeclaration['label'],
description: { en_US: 'Test plugin description' } as unknown as PluginDeclaration['description'],
created_at: '2024-01-01',
resource: null,
plugins: null,
verified: false,
endpoint: undefined as PluginDeclaration['endpoint'],
model: null,
tags: [],
agent_strategy: null,
meta: {
version: '1.0.0',
minimum_dify_version: '0.5.0',
},
trigger: {} as unknown as PluginDeclaration['trigger'],
...overrides,
})
const createPluginDetail = (overrides: Partial<PluginDetail> = {}): PluginDetail => ({
id: 'plugin-1',
created_at: '2024-01-01',
updated_at: '2024-01-01',
name: 'test-plugin',
plugin_id: 'plugin-1',
plugin_unique_identifier: 'test-author/test-plugin@1.0.0',
declaration: createPluginDeclaration(),
installation_id: 'install-1',
tenant_id: 'tenant-1',
endpoints_setups: 0,
endpoints_active: 0,
version: '1.0.0',
latest_version: '1.0.0',
latest_unique_identifier: 'test-author/test-plugin@1.0.0',
source: PluginSource.marketplace,
meta: {
repo: 'test-author/test-plugin',
version: '1.0.0',
package: 'test-plugin.difypkg',
},
status: 'active',
deprecated_reason: '',
alternative_plugin_id: '',
...overrides,
})
let installedPlugins: ReturnType<typeof createPluginEntity>[] = []
let modelCatalog: ReturnType<typeof createModelCatalogFixture>[] = []
function InstalledPluginList({ category }: { category: PluginCategoryEnum }) {
const { data } = useInstalledPluginList({ category, staleTime: 0 })
const plugins = data?.plugins ?? []
return (
<output aria-label="installed plugin ids">
{plugins.map((plugin) => plugin.plugin_id).join(',') || 'none'}
</output>
)
}
function ModelCatalog() {
const { data = [] } = useQuery(
consoleQuery.workspaces.current.models.modelTypes.byModelType.get.queryOptions({
input: { params: { model_type: ModelTypeEnum.textGeneration } },
select: (response) =>
response.data.flatMap((provider) => provider.models.map((model) => model.model)),
}),
)
return <output aria-label="model ids">{data.join(',') || 'none'}</output>
}
beforeEach(() => {
vi.clearAllMocks()
installedPlugins = []
modelCatalog = []
requests.categoryList.mockImplementation(async () => ({
plugins: installedPlugins,
builtin_tools: [],
has_more: false,
}))
requests.models.mockImplementation(async () => ({ data: modelCatalog }))
requests.uninstall.mockResolvedValue({ success: true })
mockTheme.mockReturnValue('light')
mockEnableMarketplace.mockReturnValue(true)
mockLangGeniusVersionInfo.mockReturnValue(createLangGeniusVersionInfo('1.0.0'))
})
describe('Installed plugin card', () => {
it.each([
{ source: PluginSource.github, label: 'GitHub', version: '1.5.0', author: true },
{ source: PluginSource.marketplace, label: 'marketplace', version: '2.0.0', author: true },
{ source: PluginSource.local, label: 'Local Plugin', version: '2.0.0', author: false },
{ source: PluginSource.debugging, label: 'Debugging Plugin', version: '2.0.0', author: false },
])(
'shows the source and correct installed version for $source plugins',
({ source, label, version, author }) => {
render(
<PluginItem
plugin={createPluginDetail({
source,
version: '2.0.0',
meta: { repo: 'owner/repo', version: '1.5.0', package: 'pkg.difypkg' },
})}
/>,
)
expect(screen.getByRole('button', { name: 'Test Plugin' })).toBeInTheDocument()
expect(screen.getByText('Test plugin description')).toBeInTheDocument()
expect(screen.getByText(label)).toBeInTheDocument()
expect(screen.getByText(version)).toBeInTheDocument()
expect(!!screen.queryByText('test-author')).toBe(author)
if (source === PluginSource.github)
expect(screen.getByRole('link', { name: /GitHub/ })).toHaveAttribute(
'href',
'https://github.com/owner/repo',
)
else if (source === PluginSource.marketplace)
expect(screen.getByRole('link', { name: /marketplace/ })).toHaveAttribute(
'href',
expect.stringContaining('/plugins/test-author/test-plugin'),
)
else expect(screen.queryByRole('link')).not.toBeInTheDocument()
},
)
it('counts visible endpoint declarations independently of active endpoint instances', () => {
render(
<PluginItem
plugin={createPluginDetail({
declaration: createPluginDeclaration({
endpoint: {
settings: [],
endpoints: [
{ path: '/first', method: 'POST' },
{ path: '/second', method: 'GET' },
{ path: '/hidden', method: 'GET', hidden: true },
],
},
}),
endpoints_active: 0,
})}
/>,
)
expect(screen.getByText('plugin.endpointsEnabled:{"num":2}')).toBeInTheDocument()
})
it.each(['0.3.0', '0.5.0', '1.0.0'])(
'warns when Dify %s cannot run the installed plugin',
(version) => {
mockLangGeniusVersionInfo.mockReturnValue(createLangGeniusVersionInfo(version))
render(<PluginItem plugin={createPluginDetail()} />)
expect(!!screen.queryByRole('button', { name: /plugin.difyVersionNotCompatible/ })).toBe(
version === '0.3.0',
)
},
)
it.each([
{ source: PluginSource.marketplace, enabled: true, expected: true },
{ source: PluginSource.marketplace, enabled: false, expected: false },
{ source: PluginSource.github, enabled: true, expected: false },
])(
'reports withdrawal only for available marketplace entries: %j',
({ source, enabled, expected }) => {
mockEnableMarketplace.mockReturnValue(enabled)
const plugin = createPluginDetail({ source })
const { rerender } = render(<PluginItem plugin={plugin} />)
expect(screen.queryByText('plugin.deprecated')).not.toBeInTheDocument()
rerender(
<PluginItem
plugin={{ ...plugin, status: 'deleted', deprecated_reason: 'No longer maintained' }}
/>,
)
expect(!!screen.queryByText('plugin.deprecated')).toBe(expected)
if (!enabled)
expect(screen.queryByRole('link', { name: /marketplace/ })).not.toBeInTheDocument()
},
)
it('selects the plugin from the card and keeps its actions separate', async () => {
const user = userEvent.setup()
render(
<>
<section aria-label="Other plugin card">
<PluginItem
plugin={createPluginDetail({
id: 'plugin-2',
plugin_id: 'plugin-2',
declaration: createPluginDeclaration({
name: 'other-plugin',
label: { en_US: 'Other Plugin' } as PluginDeclaration['label'],
}),
})}
/>
</section>
<section aria-label="Test plugin card">
<PluginItem plugin={createPluginDetail()} />
</section>
</>,
)
const otherPlugin = within(screen.getByRole('region', { name: 'Other plugin card' }))
const testPlugin = within(screen.getByRole('region', { name: 'Test plugin card' }))
const otherCard = otherPlugin.getByRole('button', { name: 'Other Plugin' })
await user.tab()
expect(otherCard).toHaveFocus()
await user.keyboard('{Enter}')
expect(screen.getByRole('status', { name: 'selected plugin' })).toHaveTextContent(
'plugin:plugin-2',
)
const card = testPlugin.getByRole('button', { name: 'Test Plugin' })
const action = testPlugin.getByRole('button', { name: 'plugin.action.delete' })
expect(card).not.toContainElement(action)
expect(card).not.toContainElement(testPlugin.getByRole('link', { name: /marketplace/ }))
await user.click(action)
expect(screen.getByRole('alertdialog', { name: 'plugin.action.delete' })).toHaveTextContent(
'test-plugin',
)
await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
expect(screen.getByRole('status', { name: 'selected plugin' })).toHaveTextContent(
'plugin:plugin-2',
)
})
it('refreshes the visible plugin category after a real uninstall succeeds', async () => {
const user = userEvent.setup()
const installedModelPlugin = createPluginEntity({
id: 'new-installation',
installation_id: 'new-installation',
plugin_id: 'plugin-1',
})
installedModelPlugin.declaration.author = 'test-author'
installedModelPlugin.declaration.name = 'test-plugin'
installedModelPlugin.declaration.category = PluginCategoryEnum.model
installedModelPlugin.declaration.label = { en_US: 'Test Plugin' }
installedModelPlugin.declaration.description = { en_US: 'Test plugin description' }
installedPlugins = [installedModelPlugin]
modelCatalog = [
createModelCatalogFixture({
models: [createCatalogModelFixture({ model: 'catalog-model' })],
}),
]
requests.uninstall.mockImplementation(async () => {
installedPlugins = []
modelCatalog = []
return { success: true }
})
const renderCard = (plugin: PluginDetail) => (
<>
<PluginItem plugin={plugin} />
<InstalledPluginList category={PluginCategoryEnum.model} />
<ModelCatalog />
</>
)
const { rerender } = render(renderCard(createPluginDetail()))
await waitFor(() =>
expect(screen.getByRole('status', { name: 'installed plugin ids' })).toHaveTextContent(
'plugin-1',
),
)
await waitFor(() =>
expect(screen.getByRole('status', { name: 'model ids' })).toHaveTextContent('catalog-model'),
)
rerender(
renderCard(
createPluginDetail({
installation_id: 'new-installation',
declaration: createPluginDeclaration({ category: PluginCategoryEnum.model }),
}),
),
)
await user.click(screen.getByRole('button', { name: 'plugin.action.delete' }))
await user.click(screen.getByRole('button', { name: 'common.operation.confirm' }))
await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
expect(requests.uninstall).toHaveBeenCalledExactlyOnceWith('new-installation')
await waitFor(() =>
expect(screen.getByRole('status', { name: 'installed plugin ids' })).toHaveTextContent(
'none',
),
)
await waitFor(() =>
expect(screen.getByRole('status', { name: 'model ids' })).toHaveTextContent('none'),
)
})
it.each([
{ source: PluginSource.github, canDelete: true, canUpdate: true, update: true, info: true },
{ source: PluginSource.github, canDelete: false, canUpdate: false, update: false, info: true },
{
source: PluginSource.marketplace,
canDelete: false,
canUpdate: true,
update: false,
info: false,
},
])(
'exposes permitted actions for $source (delete: $canDelete, update: $canUpdate)',
({ source, canDelete, canUpdate, update, info }) => {
render(
<PluginItem
plugin={createPluginDetail({ source })}
canDeletePlugin={canDelete}
canUpdatePlugin={canUpdate}
/>,
)
expect(!!screen.queryByRole('button', { name: 'plugin.action.delete' })).toBe(canDelete)
expect(!!screen.queryByRole('button', { name: 'plugin.action.checkForUpdates' })).toBe(update)
expect(!!screen.queryByRole('button', { name: 'plugin.action.pluginInfo' })).toBe(info)
},
)
it.each([
{ theme: 'dark', icon: 'light.png', dark: 'dark.png', expected: 'dark.png' },
{ theme: 'light', icon: 'light.png', dark: 'dark.png', expected: 'light.png' },
{ theme: 'dark', icon: 'light.png', dark: undefined, expected: 'light.png' },
{
theme: 'light',
icon: 'https://example.com/icon.png',
dark: undefined,
expected: 'https://example.com/icon.png',
},
])('resolves the plugin icon in $theme mode: $expected', ({ theme, icon, dark, expected }) => {
mockTheme.mockReturnValue(theme)
render(
<PluginItem
plugin={createPluginDetail({
declaration: createPluginDeclaration({ icon, icon_dark: dark }),
})}
/>,
)
expect(screen.getByRole('presentation')).toHaveAttribute(
'src',
expect.stringContaining(expected),
)
expect(screen.queryByRole('img')).not.toBeInTheDocument()
})
})
@@ -0,0 +1,213 @@
'use client'
import type { FC } from 'react'
import type { MetaData } from '../types'
import type { PluginCategoryEnum } from '@/app/components/plugins/types'
import {
AlertDialog,
AlertDialogCancelButton,
AlertDialogConfirmButton,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@langgenius/dify-ui/alert-dialog'
import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
import { useBoolean } from 'ahooks'
import * as React from 'react'
import { useCallback } from 'react'
import { useTranslation } from 'react-i18next'
import { toast } from '@/app/notifications'
import { useModalContext } from '@/context/modal-context'
import { uninstallPlugin } from '@/service/plugins'
import { useInvalidateInstalledPluginList } from '@/service/use-plugins'
import { checkForUpdates, fetchReleases } from '../install-plugin/hooks'
import PluginInfoContent from '../plugin-page/plugin-info'
const i18nPrefix = 'action'
type Props = Readonly<{
author: string
installationId: string
pluginUniqueIdentifier: string
pluginName: string
category: PluginCategoryEnum
usedInApps: number
isShowFetchNewVersion: boolean
isShowInfo: boolean
isShowDelete: boolean
onDelete: () => void
meta?: MetaData
}>
const Action: FC<Props> = ({
author,
installationId,
pluginUniqueIdentifier,
pluginName,
category,
isShowFetchNewVersion,
isShowInfo,
isShowDelete,
onDelete,
meta,
}) => {
const { t } = useTranslation(['common', 'plugin'])
const [isShowPluginInfo, { setTrue: showPluginInfo, setFalse: hidePluginInfo }] =
useBoolean(false)
const [deleting, { setTrue: showDeleting, setFalse: hideDeleting }] = useBoolean(false)
const { setShowUpdatePluginModal } = useModalContext()
const invalidateInstalledPluginList = useInvalidateInstalledPluginList()
const handleFetchNewVersion = async () => {
const owner = meta!.repo.split('/')[0] || author
const repo = meta!.repo.split('/')[1] || pluginName
const fetchedReleases = await fetchReleases(owner, repo).catch(() => {
toast.error(t(($) => $['error.fetchReleasesError'], { ns: 'plugin' }))
return undefined
})
if (!fetchedReleases?.length) return
const { needUpdate, toastProps } = checkForUpdates(fetchedReleases, meta!.version)
toast(toastProps.message, { type: toastProps.type })
if (needUpdate) {
setShowUpdatePluginModal({
onSaveCallback: () => {
invalidateInstalledPluginList(category)
},
payload: {
category,
github: {
originalPackageInfo: {
id: pluginUniqueIdentifier,
repo: meta!.repo,
version: meta!.version,
package: meta!.package,
releases: fetchedReleases,
},
},
},
})
}
}
const [isShowDeleteConfirm, { setTrue: showDeleteConfirm, setFalse: hideDeleteConfirm }] =
useBoolean(false)
const handleDelete = useCallback(async () => {
showDeleting()
try {
const res = await uninstallPlugin(installationId)
if (res.success) {
hideDeleteConfirm()
invalidateInstalledPluginList(category)
onDelete()
}
} catch (error) {
console.error('uninstallPlugin error', error)
} finally {
hideDeleting()
}
}, [
hideDeleteConfirm,
hideDeleting,
installationId,
category,
invalidateInstalledPluginList,
onDelete,
showDeleting,
])
return (
<div className="flex space-x-1">
{/* Only plugin installed from GitHub need to check if it's the new version */}
{isShowFetchNewVersion && (
<Tooltip>
<TooltipTrigger
render={
<IconButton
aria-label={t(($) => $[`${i18nPrefix}.checkForUpdates`], { ns: 'plugin' })}
onClick={handleFetchNewVersion}
>
<span aria-hidden className="i-ri-loop-left-line size-4 text-text-tertiary" />
</IconButton>
}
/>
<TooltipContent>
{t(($) => $[`${i18nPrefix}.checkForUpdates`], { ns: 'plugin' })}
</TooltipContent>
</Tooltip>
)}
{isShowInfo && (
<Tooltip>
<TooltipTrigger
render={
<IconButton
aria-label={t(($) => $[`${i18nPrefix}.pluginInfo`], { ns: 'plugin' })}
onClick={showPluginInfo}
>
<span aria-hidden className="i-ri-information-2-line size-4 text-text-tertiary" />
</IconButton>
}
/>
<TooltipContent>
{t(($) => $[`${i18nPrefix}.pluginInfo`], { ns: 'plugin' })}
</TooltipContent>
</Tooltip>
)}
{isShowDelete && (
<Tooltip>
<TooltipTrigger
render={
<IconButton
aria-label={t(($) => $[`${i18nPrefix}.delete`], { ns: 'plugin' })}
tone="destructive"
onClick={showDeleteConfirm}
>
<span aria-hidden className="i-ri-delete-bin-line size-4" />
</IconButton>
}
/>
<TooltipContent>{t(($) => $[`${i18nPrefix}.delete`], { ns: 'plugin' })}</TooltipContent>
</Tooltip>
)}
<Dialog
open={isShowPluginInfo}
onOpenChange={(open) => {
if (!open) hidePluginInfo()
}}
>
<DialogContent className="w-120">
<PluginInfoContent
repository={meta?.repo}
release={meta?.version}
packageName={meta?.package}
/>
</DialogContent>
</Dialog>
<AlertDialog open={isShowDeleteConfirm} onOpenChange={(open) => !open && hideDeleteConfirm()}>
<AlertDialogContent backdropProps={{ forceRender: true }}>
<AlertDialogHeader>
<AlertDialogTitle>
{t(($) => $[`${i18nPrefix}.delete`], { ns: 'plugin' })}
</AlertDialogTitle>
<AlertDialogDescription>
{t(($) => $[`${i18nPrefix}.deleteContentLeft`], { ns: 'plugin' })}
<span className="system-md-semibold">{pluginName}</span>
{t(($) => $[`${i18nPrefix}.deleteContentRight`], { ns: 'plugin' })}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancelButton>
{t(($) => $['operation.cancel'], { ns: 'common' })}
</AlertDialogCancelButton>
<AlertDialogConfirmButton loading={deleting} onClick={handleDelete}>
{t(($) => $['operation.confirm'], { ns: 'common' })}
</AlertDialogConfirmButton>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
)
}
export default React.memo(Action)
@@ -0,0 +1,312 @@
'use client'
import type { FC } from 'react'
import type { PluginDetail } from '../types'
import { cn } from '@langgenius/dify-ui/cn'
import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'
import {
RiArrowRightUpLine,
RiBugLine,
RiErrorWarningLine,
RiHardDrive3Line,
RiLoginCircleLine,
} from '@remixicon/react'
import { useSuspenseQuery } from '@tanstack/react-query'
import * as React from 'react'
import { useCallback, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import useRefreshPluginList from '@/app/components/plugins/install-plugin/hooks/use-refresh-plugin-list'
import { API_PREFIX } from '@/config'
import { userProfileQueryOptions } from '@/features/account-profile/client'
import { useMarketplace } from '@/features/marketplace/client'
import { useRenderI18nObject } from '@/hooks/use-i18n'
import useTheme from '@/hooks/use-theme'
import { isEqualOrLaterThanVersion } from '@/utils/semver'
import Badge from '../../base/badge'
import Verified from '../base/badges/verified'
import Description from '../card/base/description'
import OrgInfo from '../card/base/org-info'
import Title from '../card/base/title'
import { usePluginPageContext } from '../plugin-page/context'
import { PluginSource } from '../types'
import Action from './action'
type Props = Readonly<{
canDeletePlugin?: boolean
canUpdatePlugin?: boolean
className?: string
plugin: PluginDetail
}>
const PluginItem: FC<Props> = ({
canDeletePlugin = true,
canUpdatePlugin = true,
className,
plugin,
}) => {
const { t } = useTranslation(['plugin'])
const { theme } = useTheme()
const selectedPluginID = usePluginPageContext((v) =>
v.selectedItem?.type === 'plugin' ? v.selectedItem.id : undefined,
)
const setSelectedItem = usePluginPageContext((v) => v.setSelectedItem)
const { refreshPluginList } = useRefreshPluginList()
const {
source,
tenant_id,
installation_id,
plugin_unique_identifier,
meta,
plugin_id,
status,
deprecated_reason,
} = plugin
const {
category,
author,
name,
label,
description,
icon,
icon_dark,
verified,
meta: declarationMeta,
} = plugin.declaration
const endpointCount =
plugin.declaration.endpoint?.endpoints?.filter((endpoint) => !endpoint.hidden).length ?? 0
const hasEndpointDeclaration = !!plugin.declaration.endpoint
const orgName = useMemo(() => {
const sourcesWithAuthor: PluginSource[] = [PluginSource.github, PluginSource.marketplace]
return sourcesWithAuthor.includes(source) ? author : ''
}, [source, author])
const { data: currentVersion } = useSuspenseQuery({
...userProfileQueryOptions(),
select: (data) => data.meta.currentVersion ?? '',
})
const isDifyVersionCompatible = useMemo(() => {
if (!currentVersion) return true
return isEqualOrLaterThanVersion(
currentVersion,
declarationMeta.minimum_dify_version ?? '0.0.0',
)
}, [currentVersion, declarationMeta.minimum_dify_version])
const isDeprecated = useMemo(() => {
return status === 'deleted' && !!deprecated_reason
}, [status, deprecated_reason])
const handleDelete = useCallback(() => {
refreshPluginList({ category } as any)
}, [category, refreshPluginList])
const getValueFromI18nObject = useRenderI18nObject()
const title = getValueFromI18nObject(label)
const titleId = React.useId()
const descriptionText = getValueFromI18nObject(description)
const marketplace = useMarketplace()
const iconFileName = theme === 'dark' && icon_dark ? icon_dark : icon
const iconSrc = iconFileName
? iconFileName.startsWith('http')
? iconFileName
: `${API_PREFIX}/workspaces/current/plugin/icon?tenant_id=${tenant_id}&filename=${iconFileName}`
: ''
return (
<div
className={cn(
'group/plugin-item relative flex min-w-[min(100%,496px)] flex-1 flex-col overflow-hidden rounded-xl p-0.75',
selectedPluginID === plugin_id &&
"after:pointer-events-none after:absolute after:inset-0 after:rounded-xl after:inset-ring-[1.5px] after:inset-ring-components-option-card-option-selected-border after:content-['']",
source === PluginSource.debugging
? 'bg-[repeating-linear-gradient(-45deg,rgba(16,24,40,0.04),rgba(16,24,40,0.04)_5px,rgba(0,0,0,0.02)_5px,rgba(0,0,0,0.02)_10px)]'
: 'bg-background-section-burn',
)}
>
<button
type="button"
aria-labelledby={titleId}
className="absolute inset-0 z-10 cursor-pointer rounded-xl border-0 bg-transparent p-0 outline-hidden focus-visible:inset-ring-2 focus-visible:inset-ring-state-accent-solid"
onClick={() => setSelectedItem({ type: 'plugin', id: plugin.plugin_id })}
/>
<div
className={cn(
'relative rounded-[10px] border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg p-3',
className,
)}
>
{/* Header */}
<div className="flex">
<div className="flex size-10 items-center justify-center overflow-hidden rounded-xl border border-components-panel-border-subtle">
<img
className="size-full"
decoding="async"
height={40}
loading="lazy"
src={iconSrc}
alt=""
width={40}
/>
</div>
<div className="ml-3 w-0 grow">
<div className="flex h-5 items-center">
<div id={titleId} className="min-w-0">
<Title title={title} />
</div>
{verified && (
<Verified
className="ml-0.5 size-4"
text={t(($) => $['marketplace.verifiedTip'], { ns: 'plugin' })}
/>
)}
{!isDifyVersionCompatible && (
<Popover>
<PopoverTrigger
openOnHover
aria-label={t(($) => $.difyVersionNotCompatible, {
ns: 'plugin',
minimalDifyVersion: declarationMeta.minimum_dify_version ?? '0.0.0',
})}
className="relative z-20 ml-0.5 inline-flex size-4 shrink-0 border-0 bg-transparent p-0"
>
<RiErrorWarningLine color="red" className="size-4 text-text-accent" />
</PopoverTrigger>
<PopoverContent className="px-3 py-2 system-xs-regular text-text-tertiary">
{t(($) => $.difyVersionNotCompatible, {
ns: 'plugin',
minimalDifyVersion: declarationMeta.minimum_dify_version ?? '0.0.0',
})}
</PopoverContent>
</Popover>
)}
<Badge
className="ml-1 shrink-0"
text={source === PluginSource.github ? plugin.meta!.version : plugin.version}
hasRedCornerMark={
source === PluginSource.marketplace &&
!!plugin.latest_version &&
plugin.latest_version !== plugin.version
}
/>
</div>
<div className="relative flex h-4 min-w-0 items-center">
<Description
className="min-w-0 flex-1 group-focus-within/plugin-item:pr-20 group-hover/plugin-item:pr-20 [@media(hover:none)]:pr-20"
text={descriptionText}
descriptionLineRows={1}
/>
<div className="pointer-events-none absolute top-1/2 right-0 z-20 -translate-y-1/2 opacity-0 transition-opacity group-focus-within/plugin-item:pointer-events-auto group-focus-within/plugin-item:opacity-100 group-hover/plugin-item:pointer-events-auto group-hover/plugin-item:opacity-100 [@media(hover:none)]:pointer-events-auto [@media(hover:none)]:opacity-100">
<Action
pluginUniqueIdentifier={plugin_unique_identifier}
installationId={installation_id}
author={author}
pluginName={name}
usedInApps={5}
isShowFetchNewVersion={canUpdatePlugin && source === PluginSource.github}
isShowInfo={source === PluginSource.github}
isShowDelete={canDeletePlugin}
meta={meta}
onDelete={handleDelete}
category={category}
/>
</div>
</div>
</div>
</div>
</div>
<div className="flex h-6.5 items-center gap-x-2 px-3 pt-1.5 pb-1">
{/* Organization & Name */}
<div className="flex grow items-center overflow-hidden">
<OrgInfo
orgName={orgName}
packageName={name}
packageNameClassName="w-auto max-w-[150px]"
/>
{hasEndpointDeclaration && (
<>
<div className="mx-2 system-xs-regular text-text-quaternary">·</div>
<div className="flex items-center gap-x-1 overflow-hidden system-xs-regular text-text-tertiary">
<RiLoginCircleLine className="size-3 shrink-0" />
<span
className="truncate"
title={t(($) => $.endpointsEnabled, { ns: 'plugin', num: endpointCount })}
>
{t(($) => $.endpointsEnabled, { ns: 'plugin', num: endpointCount })}
</span>
</div>
</>
)}
</div>
{/* Source */}
<div className="flex shrink-0 items-center">
{source === PluginSource.github && (
<>
<a
href={`https://github.com/${meta!.repo}`}
target="_blank"
className="relative z-20 flex items-center gap-1"
>
<div className="system-2xs-medium-uppercase text-text-tertiary">
{t(($) => $.from, { ns: 'plugin' })}
</div>
<div className="flex items-center space-x-0.5 text-text-secondary">
<span aria-hidden className="i-custom-public-common-github size-3" />
<div className="system-2xs-semibold-uppercase">GitHub</div>
<RiArrowRightUpLine className="size-3" />
</div>
</a>
</>
)}
{source === PluginSource.marketplace && marketplace && (
<>
<a
href={marketplace.plugin({ org: author, name }, { theme })}
target="_blank"
className="relative z-20 flex items-center gap-0.5"
>
<div className="system-2xs-medium-uppercase text-text-tertiary">
{t(($) => $.from, { ns: 'plugin' })}{' '}
<span className="text-text-secondary">marketplace</span>
</div>
<RiArrowRightUpLine className="size-3 text-text-secondary" />
</a>
</>
)}
{source === PluginSource.local && (
<>
<div className="flex items-center gap-1">
<RiHardDrive3Line className="size-3 text-text-tertiary" />
<div className="system-2xs-medium-uppercase text-text-tertiary">Local Plugin</div>
</div>
</>
)}
{source === PluginSource.debugging && (
<>
<div className="flex items-center gap-1">
<RiBugLine className="size-3 text-text-warning" />
<div className="system-2xs-medium-uppercase text-text-warning">
Debugging Plugin
</div>
</div>
</>
)}
</div>
{/* Deprecated */}
{source === PluginSource.marketplace && marketplace && isDeprecated && (
<div className="flex shrink-0 items-center gap-x-2 system-2xs-medium-uppercase">
<span className="text-text-tertiary">·</span>
<span className="text-text-warning">{t(($) => $.deprecated, { ns: 'plugin' })}</span>
</div>
)}
</div>
{/* BG Effect for Deprecated Plugin */}
{source === PluginSource.marketplace && marketplace && isDeprecated && (
<div className="absolute -right-11.25 -bottom-17.75 z-0 size-40 bg-components-badge-status-light-warning-halo opacity-60 blur-[120px]" />
)}
</div>
)
}
export default React.memo(PluginItem)