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,226 @@
import type { PluginStatus, PluginTask } from '@/app/components/plugins/types'
import { act, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import { PermissionType, PluginSource, TaskStatus } from '@/app/components/plugins/types'
import { renderWithConsoleQuery } from '@/test/console/query-data'
import { createDeferred } from '@/test/deferred'
import PluginTasks from '../index'
const requests = vi.hoisted(() => ({ list: vi.fn(), clear: vi.fn(), refresh: 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': requests.list,
'workspaces.current.plugin.tasks.byTaskId.delete.byIdentifier.post': requests.clear,
'workspaces.current.plugin.permission.fetch.get': async () => ({
install_permission: PermissionType.everyone,
debug_permission: PermissionType.everyone,
}),
}),
}
})
// Refreshing unrelated catalogs has its own service tests.
vi.mock('@/app/components/plugins/install-plugin/hooks/use-refresh-plugin-list', () => ({
default: () => ({ refreshPluginList: requests.refresh }),
}))
const plugin = (name: string, status: TaskStatus, message = ''): PluginStatus => ({
plugin_unique_identifier: `test/${name}:1.0.0`,
plugin_id: `test/${name}`,
source: PluginSource.marketplace,
status,
message,
icon: 'test-icon.png',
labels: { en_US: name },
taskId: 'task-1',
})
let tasks: PluginTask[]
const task = (plugins: PluginStatus[], id = 'task-1'): PluginTask => ({
id,
plugins,
created_at: '',
updated_at: '',
status: plugins.some((p) => p.status === TaskStatus.running || p.status === TaskStatus.pending)
? TaskStatus.running
: plugins.some((p) => p.status === TaskStatus.failed)
? TaskStatus.failed
: TaskStatus.success,
total_plugins: plugins.length,
completed_plugins: plugins.filter((p) => p.status === TaskStatus.success).length,
})
const render = () =>
renderWithConsoleQuery(<PluginTasks />, { workspacePermissionKeys: ['plugin.install'] })
beforeEach(() => {
vi.clearAllMocks()
tasks = []
requests.list.mockImplementation(async () => ({ tasks }))
requests.clear.mockImplementation(
async ({ params }: { params: { task_id: string; identifier: string } }) => {
tasks = tasks
.map((t) =>
t.id === params.task_id
? task(
t.plugins.filter((p) => p.plugin_unique_identifier !== params.identifier),
t.id,
)
: t,
)
.filter((t) => t.plugins.length > 0)
return {}
},
)
})
describe('plugin installation tasks', () => {
it('hides the task trigger after an empty server response', async () => {
const { queryClient } = render()
await waitFor(() => expect(queryClient.isFetching()).toBe(0))
expect(requests.list).toHaveBeenCalledOnce()
expect(screen.queryByRole('button')).not.toBeInTheDocument()
})
it.each([
{ statuses: [TaskStatus.pending, TaskStatus.running], tip: 'installing', badge: null },
{
statuses: [TaskStatus.running, TaskStatus.success],
tip: 'installingWithSuccess',
badge: null,
},
{
statuses: [TaskStatus.running, TaskStatus.failed],
tip: 'installingWithError',
badge: 'error',
},
{ statuses: [TaskStatus.success], tip: 'installSuccess', badge: 'success' },
{ statuses: [TaskStatus.success, TaskStatus.failed], tip: 'installedError', badge: 'error' },
])('announces $tip and opens the actual task list', async ({ statuses, tip, badge }) => {
const user = userEvent.setup()
tasks = [task(statuses.map((status, index) => plugin(`Plugin ${index}`, status)))]
render()
const trigger = await screen.findByRole('button', {
name: new RegExp(`^plugin\\.task\\.${tip}(?::|$)`),
})
if (badge) expect(screen.getByTestId(`task-status-${badge}-badge`)).toBeInTheDocument()
else {
expect(screen.queryByTestId('task-status-success-badge')).not.toBeInTheDocument()
expect(screen.queryByTestId('task-status-error-badge')).not.toBeInTheDocument()
}
await user.click(trigger)
expect(trigger).toHaveAttribute('aria-expanded', 'true')
for (const [index] of statuses.entries())
expect(await screen.findByText(`Plugin ${index}`)).toBeInTheDocument()
await user.keyboard('{Escape}')
await waitFor(() => expect(trigger).toHaveAttribute('aria-expanded', 'false'))
})
it.each([
{ status: TaskStatus.success, tip: 'installSuccess', message: 'plugin.task.installed' },
{ status: TaskStatus.failed, tip: 'installedError', message: 'Network error' },
])(
'updates an open task list when installation ends with $status',
async ({ status, tip, message }) => {
const user = userEvent.setup()
tasks = [task([plugin('Search plugin', TaskStatus.running, 'Downloading package')])]
const { queryClient } = render()
await user.click(await screen.findByRole('button', { name: 'plugin.task.installing' }))
expect(await screen.findByText('Downloading package')).toBeInTheDocument()
tasks = [task([plugin('Search plugin', status, status === TaskStatus.failed ? message : '')])]
await act(async () => {
await queryClient.invalidateQueries({ queryKey: ['plugins', 'pluginTaskList'] })
})
expect(
await screen.findByRole('button', { name: new RegExp(`^plugin\\.task\\.${tip}(?::|$)`) }),
).toHaveAttribute('aria-expanded', 'true')
expect(screen.getByText(message)).toBeInTheDocument()
expect(screen.queryByText('Downloading package')).not.toBeInTheDocument()
},
)
it('clears only failed plugins across tasks and keeps running and successful entries visible', async () => {
const user = userEvent.setup()
tasks = [
task([
plugin('Running', TaskStatus.running),
plugin('Installed', TaskStatus.success),
plugin('Failed A', TaskStatus.failed, 'Error A'),
]),
task(
[plugin('Pending', TaskStatus.pending), plugin('Failed B', TaskStatus.failed, 'Error B')],
'task-2',
),
]
render()
await user.click(
await screen.findByRole('button', { name: /^plugin\.task\.installingWithError(?::|$)/ }),
)
expect(
screen.getByRole('heading', { name: 'plugin.task.runningPlugins (2)' }),
).toBeInTheDocument()
expect(
screen.getByRole('heading', { name: 'plugin.task.successPlugins (1)' }),
).toBeInTheDocument()
expect(
screen.getByRole('heading', { name: 'plugin.task.errorPlugins (2)' }),
).toBeInTheDocument()
await user.click(
screen.getByRole('button', { name: 'plugin.task.errorPlugins plugin.task.clearAll' }),
)
await waitFor(() => expect(requests.clear).toHaveBeenCalledTimes(2))
expect(requests.clear).toHaveBeenCalledWith({
params: { task_id: 'task-1', identifier: 'test/Failed A:1.0.0' },
})
expect(requests.clear).toHaveBeenCalledWith({
params: { task_id: 'task-2', identifier: 'test/Failed B:1.0.0' },
})
await waitFor(() => expect(screen.queryByText('Failed B')).not.toBeInTheDocument())
expect(screen.queryByText('Failed A')).not.toBeInTheDocument()
for (const name of ['Running', 'Pending', 'Installed'])
expect(screen.getByText(name)).toBeInTheDocument()
})
it('clears completed successes and failures together and hides the empty menu', async () => {
const user = userEvent.setup()
tasks = [task([plugin('Installed', TaskStatus.success), plugin('Failed', TaskStatus.failed)])]
render()
await user.click(
await screen.findByRole('button', { name: /^plugin\.task\.installedError(?::|$)/ }),
)
await user.click(
screen.getByRole('button', { name: 'plugin.task.successPlugins plugin.task.clearAll' }),
)
await waitFor(() => expect(screen.queryByText('Installed')).not.toBeInTheDocument())
expect(requests.clear.mock.calls).toEqual([
[{ params: { task_id: 'task-1', identifier: 'test/Installed:1.0.0' } }],
[{ params: { task_id: 'task-1', identifier: 'test/Failed:1.0.0' } }],
])
expect(
screen.queryByRole('button', { name: /^plugin\.task\.installedError(?::|$)/ }),
).not.toBeInTheDocument()
})
it('waits for an individual clear request before refreshing and closing the last failure', async () => {
const user = userEvent.setup()
const pending = createDeferred<object>()
requests.clear.mockReturnValueOnce(pending.promise)
tasks = [task([plugin('Failed', TaskStatus.failed)])]
render()
await user.click(
await screen.findByRole('button', { name: /^plugin\.task\.installedError(?::|$)/ }),
)
await user.click(screen.getByRole('button', { name: 'Clear Failed' }))
expect(requests.clear).toHaveBeenCalledExactlyOnceWith({
params: { task_id: 'task-1', identifier: 'test/Failed:1.0.0' },
})
expect(requests.list).toHaveBeenCalledOnce()
expect(screen.getByText('Failed')).toBeInTheDocument()
tasks = []
pending.resolve({})
await waitFor(() => expect(requests.list).toHaveBeenCalledTimes(2))
await waitFor(() => expect(screen.queryByText('Failed')).not.toBeInTheDocument())
})
})
@@ -0,0 +1,189 @@
import type { PluginInfoFromMarketPlace } from '@dify/contracts/marketplace'
import type { PluginStatus } from '@/app/components/plugins/types'
import { screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import {
PermissionType,
PluginCategoryEnum,
PluginSource,
TaskStatus,
} from '@/app/components/plugins/types'
import { fetchPluginInfoFromMarketPlace } from '@/service/plugins'
import { renderWithConsoleQuery } from '@/test/console/query-data'
import { createPluginDeclarationFixture } from '@/test/fixtures/plugin'
import ErrorPluginItem from '../error-plugin-item'
const { install, refresh } = vi.hoisted(() => ({ install: vi.fn(), refresh: vi.fn() }))
vi.mock('@/service/plugins', async (importOriginal) => ({
...(await importOriginal<typeof import('@/service/plugins')>()),
fetchPluginInfoFromMarketPlace: vi.fn(),
}))
vi.mock('@/app/components/plugins/install-plugin/hooks/use-refresh-plugin-list', () => ({
default: () => ({ refreshPluginList: refresh }),
}))
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': async () => ({
manifest: createPluginDeclarationFixture(),
}),
'workspaces.current.plugin.install.marketplace.post': install,
}),
consoleQuery: withConsoleResponses(actual.consoleQuery, {
'workspaces.current.plugin.list.installations.ids.post': async () => ({ plugins: [] }),
}),
}
})
vi.mock(
'@/app/components/plugins/install-plugin/hooks/use-workspace-plugin-install-permission',
() => ({
default: () => ({
canInstallPlugin: true,
currentDifyVersion: '1.0.0',
}),
}),
)
const mockFetch = vi.mocked(fetchPluginInfoFromMarketPlace)
const mockGetIconUrl = vi.fn((icon: string) => `https://icons/${icon}`)
function createMarketplaceResponse(identifier: string, version: string) {
return {
data: {
plugin: {
category: PluginCategoryEnum.tool,
latest_package_identifier: identifier,
latest_version: version,
} satisfies PluginInfoFromMarketPlace,
version: { version },
},
}
}
const createPlugin = (overrides: Partial<PluginStatus> = {}): PluginStatus => ({
plugin_unique_identifier: 'org/plugin:1.0.0',
plugin_id: 'org/plugin',
source: PluginSource.marketplace,
status: TaskStatus.failed,
message: '',
icon: 'icon.png',
labels: { en_US: 'Test Plugin' } as PluginStatus['labels'],
taskId: 'task-1',
...overrides,
})
describe('ErrorPluginItem', () => {
const renderError = (overrides: Partial<PluginStatus> = {}) => {
const onClear = vi.fn()
renderWithConsoleQuery(
<ErrorPluginItem
plugin={createPlugin(overrides)}
getIconUrl={mockGetIconUrl}
language="en_US"
onClear={onClear}
/>,
{ systemFeatures: { enable_marketplace: true } },
)
return { onClear }
}
const retry = () => screen.getByRole('button', { name: 'plugin.task.installFromMarketplace' })
beforeEach(() => {
vi.clearAllMocks()
mockFetch.mockResolvedValue(createMarketplaceResponse('org/plugin:2.0.0', '2.0.0'))
install.mockResolvedValue({ all_installed: true, task_id: '' })
})
it.each([
[PluginSource.marketplace, 'org/plugin', 'marketplace', 'plugin.task.installFromMarketplace'],
[PluginSource.github, 'org/plugin', 'github', 'plugin.task.installFromGithub'],
[
PluginSource.github,
'https://github.com/user/repo',
'github',
'plugin.task.installFromGithub',
],
[PluginSource.local, 'my-github-plugin', 'unknown', null],
[PluginSource.debugging, 'remote-plugin', 'unknown', null],
] as const)(
'derives the error and retry action from %s, not the id %s',
(source, plugin_id, message, action) => {
renderError({ source, plugin_id })
expect(screen.getByText('Test Plugin')).toBeInTheDocument()
expect(screen.getByText(`plugin.task.errorMsg.${message}`)).toBeInTheDocument()
if (action) expect(screen.getByRole('button', { name: action })).toBeInTheDocument()
else
expect(
screen.queryByRole('button', { name: /plugin.task.installFrom/ }),
).not.toBeInTheDocument()
},
)
it('shows the server error and lets the user clear the failed task', async () => {
const user = userEvent.setup()
const { onClear } = renderError({ message: 'Custom error occurred' })
expect(screen.getByText('Custom error occurred')).toBeInTheDocument()
expect(screen.queryByText('plugin.task.errorMsg.marketplace')).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Clear Test Plugin' }))
expect(onClear).toHaveBeenCalledOnce()
})
it('opens the latest marketplace version and cancels without clearing the error', async () => {
const user = userEvent.setup()
const { onClear } = renderError()
await user.click(retry())
await screen.findByRole('dialog', { name: 'plugin.installModal.installPlugin' })
expect(mockFetch).toHaveBeenCalledExactlyOnceWith({ org: 'org', name: 'plugin' })
expect(screen.getByText('2.0.0')).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
expect(onClear).not.toHaveBeenCalled()
expect(install).not.toHaveBeenCalled()
})
it('installs the latest version before clearing the completed error item', async () => {
const user = userEvent.setup()
const { onClear } = renderError()
await user.click(retry())
await user.click(await screen.findByRole('button', { name: 'plugin.installModal.install' }))
await screen.findByRole('dialog', { name: 'plugin.installModal.installedSuccessfully' })
expect(install).toHaveBeenCalledExactlyOnceWith({
body: { plugin_unique_identifiers: ['org/plugin:2.0.0'] },
})
expect(onClear).not.toHaveBeenCalled()
await user.click(screen.getByText('common.operation.close'))
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
expect(onClear).toHaveBeenCalledOnce()
})
it('keeps the failed task retryable after a marketplace lookup failure', async () => {
const user = userEvent.setup()
mockFetch.mockRejectedValueOnce(new Error('Network error'))
const { onClear } = renderError()
await user.click(retry())
await waitFor(() => expect(retry()).toBeEnabled())
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
expect(onClear).not.toHaveBeenCalled()
await user.click(retry())
await screen.findByRole('dialog', { name: 'plugin.installModal.installPlugin' })
expect(mockFetch).toHaveBeenCalledTimes(2)
})
it('does not request an invalid marketplace identifier', async () => {
const user = userEvent.setup()
renderError({ plugin_id: 'single-part' })
await user.click(retry())
expect(mockFetch).not.toHaveBeenCalled()
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
})
})
@@ -0,0 +1,152 @@
import type { FC } from 'react'
import type { Plugin, PluginStatus } from '@/app/components/plugins/types'
import type { PluginLanguage } from '@/i18n/metadata'
import { Button } from '@langgenius/dify-ui/button'
import { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { PluginInstallPermissionProvider } from '@/app/components/plugins/install-plugin/components/plugin-install-permission-provider'
import useWorkspacePluginInstallPermission from '@/app/components/plugins/install-plugin/hooks/use-workspace-plugin-install-permission'
import InstallFromMarketplace from '@/app/components/plugins/install-plugin/install-from-marketplace'
import { toPluginText } from '@/app/components/plugins/install-plugin/utils'
import { PluginSource } from '@/app/components/plugins/types'
import { fetchPluginInfoFromMarketPlace } from '@/service/plugins'
import PluginItem from './plugin-item'
type ErrorPluginItemProps = {
plugin: PluginStatus
getIconUrl: (icon: string) => string
language: PluginLanguage
onClear: () => void
}
const ErrorPluginItem: FC<ErrorPluginItemProps> = ({ plugin, getIconUrl, language, onClear }) => {
const { t } = useTranslation(['plugin'])
const source = plugin.source
const [showInstallModal, setShowInstallModal] = useState(false)
const [installPayload, setInstallPayload] = useState<{
uniqueIdentifier: string
manifest: Plugin
} | null>(null)
const [isFetching, setIsFetching] = useState(false)
const { canInstallPlugin, currentDifyVersion } = useWorkspacePluginInstallPermission()
const handleInstallFromMarketplace = useCallback(async () => {
const parts = plugin.plugin_id.split('/')
if (parts.length < 2) return
const [org, name] = parts
setIsFetching(true)
try {
const response = await fetchPluginInfoFromMarketPlace({ org: org!, name: name! })
const info = response.data.plugin
const manifest: Plugin = {
plugin_id: plugin.plugin_id,
type: info.category as Plugin['type'],
category: info.category as Plugin['category'],
name: name!,
org: org!,
version: info.latest_version,
latest_version: info.latest_version,
latest_package_identifier: info.latest_package_identifier,
label: toPluginText(plugin.labels),
brief: {},
description: {},
icon: plugin.icon,
verified: true,
introduction: '',
repository: '',
install_count: 0,
endpoint: { settings: [] },
tags: [],
badges: [],
verification: { authorized_category: 'langgenius' },
from: 'marketplace',
}
setInstallPayload({ uniqueIdentifier: info.latest_package_identifier, manifest })
setShowInstallModal(true)
} catch {
// silently fail
} finally {
setIsFetching(false)
}
}, [plugin.plugin_id, plugin.labels, plugin.icon])
const errorMsgKey:
| 'task.errorMsg.marketplace'
| 'task.errorMsg.github'
| 'task.errorMsg.unknown' =
source === PluginSource.marketplace
? 'task.errorMsg.marketplace'
: source === PluginSource.github
? 'task.errorMsg.github'
: 'task.errorMsg.unknown'
const errorMsg = t(($) => $[errorMsgKey], { ns: 'plugin' })
const renderAction = () => {
if (source === PluginSource.marketplace && canInstallPlugin) {
return (
<div className="pt-1">
<Button
variant="secondary"
size="small"
loading={isFetching}
onClick={handleInstallFromMarketplace}
>
{t(($) => $['task.installFromMarketplace'], { ns: 'plugin' })}
</Button>
</div>
)
}
if (source === PluginSource.github && canInstallPlugin) {
return (
<div className="pt-1">
<Button variant="secondary" size="small">
{t(($) => $['task.installFromGithub'], { ns: 'plugin' })}
</Button>
</div>
)
}
return undefined
}
return (
<>
<PluginItem
plugin={plugin}
getIconUrl={getIconUrl}
language={language}
statusIcon={
<span className="flex size-4 items-center justify-center rounded-full border border-components-panel-bg bg-components-panel-bg">
<span className="i-ri-error-warning-fill size-4 text-text-destructive" />
</span>
}
statusText={
<span className="block max-w-full min-w-0 wrap-anywhere wrap-break-word whitespace-pre-wrap">
{plugin.message || errorMsg}
</span>
}
statusClassName="text-text-destructive"
action={renderAction()}
onClear={onClear}
/>
{showInstallModal && installPayload && canInstallPlugin && (
<PluginInstallPermissionProvider
canInstallPlugin={canInstallPlugin}
currentDifyVersion={currentDifyVersion}
>
<InstallFromMarketplace
uniqueIdentifier={installPayload.uniqueIdentifier}
manifest={installPayload.manifest}
onClose={() => setShowInstallModal(false)}
onSuccess={() => {
setShowInstallModal(false)
onClear()
}}
/>
</PluginInstallPermissionProvider>
)}
</>
)
}
export default ErrorPluginItem
@@ -0,0 +1,68 @@
import type { ReactNode } from 'react'
import type { PluginStatus } from '@/app/components/plugins/types'
import type { PluginLanguage } from '@/i18n/metadata'
import CardIcon from '@/app/components/plugins/card/base/card-icon'
type PluginItemProps = {
plugin: PluginStatus
getIconUrl: (icon: string) => string
language: PluginLanguage
statusIcon: ReactNode
statusText: ReactNode
statusClassName?: string
action?: ReactNode
onClear?: () => void
}
function PluginItem({
plugin,
getIconUrl,
language,
statusIcon,
statusText,
statusClassName,
action,
onClear,
}: PluginItemProps) {
const hasPluginIcon = !!plugin.icon
const pluginName = plugin.labels[language] || plugin.plugin_unique_identifier
return (
<div className="group/item flex w-full max-w-full min-w-0 gap-1 overflow-hidden rounded-lg p-2 hover:bg-state-base-hover">
<div className="relative shrink-0 self-start">
{hasPluginIcon ? (
<CardIcon size="small" src={getIconUrl(plugin.icon)} />
) : (
<span
aria-hidden
className="i-custom-vender-solid-mediaAndDevices-magic-box size-8 text-text-tertiary"
/>
)}
<div className="absolute -right-0.5 -bottom-0.5 z-10">{statusIcon}</div>
</div>
<div className="flex min-w-0 flex-1 flex-col gap-0.5 px-1 wrap-anywhere">
<div className="truncate system-sm-medium text-text-secondary">
{plugin.labels[language]}
</div>
<div
className={`max-w-full min-w-0 system-xs-regular wrap-anywhere wrap-break-word ${statusClassName || 'text-text-tertiary'}`}
>
{statusText}
</div>
{action}
</div>
{onClear && (
<button
type="button"
aria-label={`Clear ${pluginName}`}
className="flex size-6 shrink-0 items-center justify-center self-start rounded-md opacity-0 outline-hidden group-hover/item:opacity-100 hover:bg-state-base-hover-alt focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-state-accent-solid [@media(hover:none)]:opacity-100"
onClick={onClear}
>
<span className="i-ri-close-line size-4 text-text-tertiary" />
</button>
)}
</div>
)
}
export default PluginItem
@@ -0,0 +1,80 @@
import type { ReactNode } from 'react'
import type { PluginStatus } from '@/app/components/plugins/types'
import type { PluginLanguage } from '@/i18n/metadata'
import {
ScrollArea,
ScrollAreaContent,
ScrollAreaScrollbar,
ScrollAreaThumb,
ScrollAreaViewport,
} from '@langgenius/dify-ui/scroll-area'
import PluginItem from './plugin-item'
type PluginSectionProps = {
title: string
count: number
plugins: PluginStatus[]
getIconUrl: (icon: string) => string
language: PluginLanguage
statusIcon: ReactNode
defaultStatusText: ReactNode
statusClassName?: string
headerAction?: ReactNode
renderItemAction?: (plugin: PluginStatus) => ReactNode
onClearSingle?: (taskId: string, pluginId: string) => void
}
function PluginSection({
title,
count,
plugins,
getIconUrl,
language,
statusIcon,
defaultStatusText,
statusClassName,
headerAction,
renderItemAction,
onClearSingle,
}: PluginSectionProps) {
if (plugins.length === 0) return null
return (
<>
<div className="sticky top-0 flex items-start justify-between pt-1 pr-1 pl-2 system-sm-semibold-uppercase text-text-secondary">
<h3 className="flex h-6 items-center">
{title} ({count})
</h3>
{headerAction}
</div>
<ScrollArea className="overflow-hidden">
<ScrollAreaViewport className="overscroll-contain">
<ScrollAreaContent style={{ minWidth: 0 }}>
{plugins.map((plugin) => (
<PluginItem
key={plugin.plugin_unique_identifier}
plugin={plugin}
getIconUrl={getIconUrl}
language={language}
statusIcon={statusIcon}
statusText={plugin.message || defaultStatusText}
statusClassName={statusClassName}
action={renderItemAction?.(plugin)}
onClear={
onClearSingle
? () => onClearSingle(plugin.taskId, plugin.plugin_unique_identifier)
: undefined
}
/>
))}
</ScrollAreaContent>
</ScrollAreaViewport>
<ScrollAreaScrollbar>
<ScrollAreaThumb />
</ScrollAreaScrollbar>
</ScrollArea>
</>
)
}
export default PluginSection
@@ -0,0 +1,133 @@
import type { PluginStatus } from '@/app/components/plugins/types'
import { Button } from '@langgenius/dify-ui/button'
import {
ScrollArea,
ScrollAreaContent,
ScrollAreaScrollbar,
ScrollAreaThumb,
ScrollAreaViewport,
} from '@langgenius/dify-ui/scroll-area'
import { useTranslation } from 'react-i18next'
import { useGetLanguage } from '@/context/i18n'
import ErrorPluginItem from './error-plugin-item'
import PluginSection from './plugin-section'
type PluginTaskListProps = {
runningPlugins: PluginStatus[]
successPlugins: PluginStatus[]
errorPlugins: PluginStatus[]
getIconUrl: (icon: string) => string
onClearAll: () => void
onClearErrors: () => void
onClearSingle: (taskId: string, pluginId: string) => void
}
function PluginTaskList({
runningPlugins,
successPlugins,
errorPlugins,
getIconUrl,
onClearAll,
onClearErrors,
onClearSingle,
}: PluginTaskListProps) {
const { t } = useTranslation(['plugin'])
const language = useGetLanguage()
const runningSectionTitle = t(($) => $['task.runningPlugins'], { ns: 'plugin' })
const successSectionTitle = t(($) => $['task.successPlugins'], { ns: 'plugin' })
const errorSectionTitle = t(($) => $['task.errorPlugins'], { ns: 'plugin' })
return (
<div
className="w-90 max-w-[calc(100vw-32px)] overflow-hidden rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur p-1 shadow-lg"
data-testid="plugin-task-list"
>
<ScrollArea className="max-h-105 overflow-hidden">
<ScrollAreaViewport
aria-label={t(($) => $['task.installing'], { ns: 'plugin' })}
style={{ overflowX: 'hidden' }}
className="max-h-105 overscroll-contain"
role="region"
>
<ScrollAreaContent style={{ minWidth: 0 }} className="w-full max-w-full pr-3">
{runningPlugins.length > 0 && (
<PluginSection
title={runningSectionTitle}
count={runningPlugins.length}
plugins={runningPlugins}
getIconUrl={getIconUrl}
language={language}
statusIcon={
<span className="i-ri-loader-2-line size-3.5 animate-spin text-text-accent" />
}
defaultStatusText={t(($) => $['task.installingHint'], { ns: 'plugin' })}
/>
)}
{successPlugins.length > 0 && (
<PluginSection
title={successSectionTitle}
count={successPlugins.length}
plugins={successPlugins}
getIconUrl={getIconUrl}
language={language}
statusIcon={
<span className="i-ri-checkbox-circle-fill size-3.5 text-text-success" />
}
defaultStatusText={t(($) => $['task.installed'], { ns: 'plugin' })}
statusClassName="text-text-success"
headerAction={
<Button
aria-label={`${successSectionTitle} ${t(($) => $['task.clearAll'], { ns: 'plugin' })}`}
className="shrink-0"
size="small"
variant="ghost"
onClick={onClearAll}
>
{t(($) => $['task.clearAll'], { ns: 'plugin' })}
</Button>
}
onClearSingle={onClearSingle}
/>
)}
{errorPlugins.length > 0 && (
<>
<div className="sticky top-0 flex h-7 items-center justify-between px-2 pt-1 system-sm-semibold-uppercase text-text-secondary">
<h3>
{errorSectionTitle} ({errorPlugins.length})
</h3>
<Button
aria-label={`${errorSectionTitle} ${t(($) => $['task.clearAll'], { ns: 'plugin' })}`}
className="shrink-0"
size="small"
variant="ghost"
onClick={onClearErrors}
>
{t(($) => $['task.clearAll'], { ns: 'plugin' })}
</Button>
</div>
<div className="w-full max-w-full min-w-0 overflow-hidden">
{errorPlugins.map((plugin) => (
<ErrorPluginItem
key={plugin.plugin_unique_identifier}
plugin={plugin}
getIconUrl={getIconUrl}
language={language}
onClear={() => onClearSingle(plugin.taskId, plugin.plugin_unique_identifier)}
/>
))}
</div>
</>
)}
</ScrollAreaContent>
</ScrollAreaViewport>
<ScrollAreaScrollbar>
<ScrollAreaThumb />
</ScrollAreaScrollbar>
</ScrollArea>
</div>
)
}
export default PluginTaskList
@@ -0,0 +1,22 @@
@reference "../../../../../styles/globals.css";
.indicator {
@apply relative overflow-visible bg-components-panel-bg p-2 shadow-none inset-ring-components-panel-border-subtle;
&[data-disabled] {
@apply cursor-default bg-components-panel-bg text-components-button-secondary-text shadow-none inset-ring-components-panel-border-subtle backdrop-blur-[5px];
}
&[data-popup-open] {
@apply bg-components-button-secondary-bg-hover shadow-xs shadow-shadow-shadow-3 inset-ring-components-button-secondary-border-hover backdrop-blur-[5px];
}
&[data-error] {
@apply cursor-pointer bg-state-destructive-hover text-components-button-destructive-secondary-text shadow-xs shadow-shadow-shadow-3 inset-ring-components-button-destructive-secondary-border-hover backdrop-blur-[5px];
&:hover,
&[data-popup-open] {
@apply bg-state-destructive-hover-alt;
}
}
}
@@ -0,0 +1,111 @@
import type { IconButtonProps } from '@langgenius/dify-ui/icon-button'
import { cn } from '@langgenius/dify-ui/cn'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
import DownloadingIcon from '@/app/components/header/plugins-nav/downloading-icon'
import styles from './task-status-indicator.module.css'
type TaskStatusIndicatorProps = Omit<
IconButtonProps,
'aria-label' | 'aria-labelledby' | 'children' | 'size' | 'tone' | 'variant'
> & {
tip: string
isInstalling: boolean
isInstallingWithSuccess: boolean
isInstallingWithError: boolean
isSuccess: boolean
isFailed: boolean
successPluginsLength: number
runningPluginsLength: number
}
function ErrorBadgeIcon() {
return (
<svg
aria-hidden
data-status-badge="error"
data-testid="task-status-error-badge"
className="size-3.5 text-text-destructive"
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
fill="currentColor"
d="M12 22C6.477 22 2 17.523 2 12S6.477 2 12 2s10 4.477 10 10s-4.477 10-10 10m-1-7v2h2v-2zm0-8v6h2V7z"
/>
</svg>
)
}
function SuccessBadgeIcon() {
return (
<svg
aria-hidden
data-status-badge="success"
data-testid="task-status-success-badge"
className="size-3.5 text-text-success"
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
fill="currentColor"
d="M12 22c5.523 0 10-4.477 10-10S17.523 2 12 2S2 6.477 2 12s4.477 10 10 10m5.457-12.543L11 15.914l-4.207-4.207l1.414-1.414L11 13.086l5.043-5.043z"
/>
</svg>
)
}
function TaskStatusIndicator({
tip,
isInstalling,
isInstallingWithSuccess,
isInstallingWithError,
isSuccess,
isFailed,
successPluginsLength,
runningPluginsLength,
className,
...buttonProps
}: TaskStatusIndicatorProps) {
const showErrorStyle = isInstallingWithError || isFailed
const hasActiveInstall = isInstalling || isInstallingWithSuccess || isInstallingWithError
const showSuccessIcon =
isSuccess ||
(!hasActiveInstall && !isFailed && successPluginsLength > 0 && runningPluginsLength === 0)
const showSuccessBadge = showSuccessIcon && !isInstallingWithError && !isFailed
const showBadge = isInstallingWithError || showSuccessBadge || isFailed
return (
<Tooltip>
<TooltipTrigger
render={
<IconButton
{...buttonProps}
aria-label={tip}
variant="secondary"
size="lg"
focusableWhenDisabled
data-error={showErrorStyle ? '' : undefined}
className={cn(styles.indicator, className)}
>
<span aria-hidden className="contents">
<DownloadingIcon active={hasActiveInstall} />
{showBadge && (
<span className="absolute -top-1.5 -right-1.5 box-content flex size-3.5 items-center justify-center rounded-full border border-components-panel-bg bg-components-panel-bg">
{isInstallingWithError && <ErrorBadgeIcon />}
{showSuccessBadge && <SuccessBadgeIcon />}
{isFailed && <ErrorBadgeIcon />}
</span>
)}
</span>
</IconButton>
}
/>
<TooltipContent>{tip}</TooltipContent>
</Tooltip>
)
}
export default TaskStatusIndicator
@@ -0,0 +1,74 @@
import type { PluginStatus } from '@/app/components/plugins/types'
import { useCallback } from 'react'
import { TaskStatus } from '@/app/components/plugins/types'
import { useMutationClearTaskPlugin, usePluginTaskList } from '@/service/use-plugins'
const isUnfinishedStatus = (status: PluginStatus['status']) =>
status === TaskStatus.pending || status === TaskStatus.running
export const usePluginTaskStatus = () => {
const { pluginTasks, handleRefetch } = usePluginTaskList()
const { mutateAsync } = useMutationClearTaskPlugin()
const allPlugins = pluginTasks
.map((task) =>
task.plugins.map((plugin) => {
return {
...plugin,
taskId: task.id,
}
}),
)
.flat()
const errorPlugins: PluginStatus[] = []
const successPlugins: PluginStatus[] = []
const runningPlugins: PluginStatus[] = []
allPlugins.forEach((plugin) => {
if (isUnfinishedStatus(plugin.status)) runningPlugins.push(plugin)
if (plugin.status === TaskStatus.failed) errorPlugins.push(plugin)
if (plugin.status === TaskStatus.success) successPlugins.push(plugin)
})
const handleClearErrorPlugin = useCallback(
async (taskId: string, pluginId: string) => {
await mutateAsync({
taskId,
pluginId,
})
handleRefetch()
},
[mutateAsync, handleRefetch],
)
const totalPluginsLength = allPlugins.length
const runningPluginsLength = runningPlugins.length
const errorPluginsLength = errorPlugins.length
const successPluginsLength = successPlugins.length
const isInstalling =
runningPluginsLength > 0 && errorPluginsLength === 0 && successPluginsLength === 0
const isInstallingWithSuccess =
runningPluginsLength > 0 && successPluginsLength > 0 && errorPluginsLength === 0
const isInstallingWithError = runningPluginsLength > 0 && errorPluginsLength > 0
const isSuccess = successPluginsLength === totalPluginsLength && totalPluginsLength > 0
const isFailed =
runningPluginsLength === 0 &&
errorPluginsLength + successPluginsLength === totalPluginsLength &&
totalPluginsLength > 0 &&
errorPluginsLength > 0
return {
errorPlugins,
successPlugins,
runningPlugins,
runningPluginsLength,
errorPluginsLength,
successPluginsLength,
totalPluginsLength,
isInstalling,
isInstallingWithSuccess,
isInstallingWithError,
isSuccess,
isFailed,
handleClearErrorPlugin,
}
}
@@ -0,0 +1,158 @@
import type { PopoverPositionerProps } from '@langgenius/dify-ui/popover'
import { cn } from '@langgenius/dify-ui/cn'
import {
Popover,
PopoverPopup,
PopoverPortal,
PopoverPositioner,
PopoverTrigger,
} from '@langgenius/dify-ui/popover'
import { useCallback, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import useGetIcon from '@/app/components/plugins/install-plugin/base/use-get-icon'
import PluginTaskList from './components/plugin-task-list'
import TaskStatusIndicator from './components/task-status-indicator'
import { usePluginTaskStatus } from './hooks'
type PluginTasksProps = Pick<PopoverPositionerProps, 'anchor'> & {
animatedSlot?: boolean
}
const PluginTasks = ({ animatedSlot = false, anchor }: PluginTasksProps) => {
const { t } = useTranslation(['plugin'])
const [open, setOpen] = useState(false)
const {
errorPlugins,
successPlugins,
runningPlugins,
runningPluginsLength,
successPluginsLength,
errorPluginsLength,
totalPluginsLength,
isInstalling,
isInstallingWithSuccess,
isInstallingWithError,
isSuccess,
isFailed,
handleClearErrorPlugin,
} = usePluginTaskStatus()
const { getIconUrl } = useGetIcon()
const hasPluginTasks = totalPluginsLength > 0
const canOpenPopover =
isFailed || isInstalling || isInstallingWithSuccess || isInstallingWithError || isSuccess
// Generate tooltip text based on status
const tip = useMemo(() => {
if (isInstallingWithError)
return t(($) => $['task.installingWithError'], {
ns: 'plugin',
installingLength: runningPluginsLength,
successLength: successPluginsLength,
errorLength: errorPluginsLength,
})
if (isInstallingWithSuccess)
return t(($) => $['task.installingWithSuccess'], {
ns: 'plugin',
installingLength: runningPluginsLength,
successLength: successPluginsLength,
})
if (isInstalling) return t(($) => $['task.installing'], { ns: 'plugin' })
if (isFailed)
return t(($) => $['task.installedError'], { ns: 'plugin', errorLength: errorPluginsLength })
if (isSuccess)
return t(($) => $['task.installSuccess'], {
ns: 'plugin',
successLength: successPluginsLength,
})
return t(($) => $['task.installed'], { ns: 'plugin' })
}, [
errorPluginsLength,
isFailed,
isInstalling,
isInstallingWithError,
isInstallingWithSuccess,
isSuccess,
runningPluginsLength,
successPluginsLength,
t,
])
// Generic clear function that handles clearing and modal closing
const clearPluginsAndClose = useCallback(
async (plugins: Array<{ taskId: string; plugin_unique_identifier: string }>) => {
for (const plugin of plugins)
await handleClearErrorPlugin(plugin.taskId, plugin.plugin_unique_identifier)
if (runningPluginsLength === 0) setOpen(false)
},
[handleClearErrorPlugin, runningPluginsLength],
)
// Clear handlers using the generic function
const handleClearAll = useCallback(
() => clearPluginsAndClose([...successPlugins, ...errorPlugins]),
[clearPluginsAndClose, successPlugins, errorPlugins],
)
const handleClearErrors = useCallback(
() => clearPluginsAndClose(errorPlugins),
[clearPluginsAndClose, errorPlugins],
)
const handleClearSingle = useCallback(
(taskId: string, pluginId: string) =>
clearPluginsAndClose([{ taskId, plugin_unique_identifier: pluginId }]),
[clearPluginsAndClose],
)
const rootClassName = animatedSlot
? cn(
'flex shrink-0 items-center overflow-visible transition-[width,margin-left,opacity] duration-200 ease-out',
hasPluginTasks ? 'ml-1 w-8 opacity-100' : 'ml-0 w-0 opacity-0',
)
: 'flex items-center'
if (!hasPluginTasks) {
if (animatedSlot) return <div aria-hidden className={rootClassName} />
return null
}
return (
<div className={rootClassName}>
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger
render={
<TaskStatusIndicator
id="plugin-task-trigger"
tip={tip}
isInstalling={isInstalling}
isInstallingWithSuccess={isInstallingWithSuccess}
isInstallingWithError={isInstallingWithError}
isSuccess={isSuccess}
isFailed={isFailed}
successPluginsLength={successPluginsLength}
runningPluginsLength={runningPluginsLength}
/>
}
disabled={!canOpenPopover}
/>
<PopoverPortal>
<PopoverPositioner align="start" sideOffset={4} anchor={anchor}>
<PopoverPopup aria-label={tip}>
<PluginTaskList
runningPlugins={runningPlugins}
successPlugins={successPlugins}
errorPlugins={errorPlugins}
getIconUrl={getIconUrl}
onClearAll={handleClearAll}
onClearErrors={handleClearErrors}
onClearSingle={handleClearSingle}
/>
</PopoverPopup>
</PopoverPositioner>
</PopoverPortal>
</Popover>
</div>
)
}
export default PluginTasks
@@ -0,0 +1,61 @@
import type { PluginStatus } from '@/app/components/plugins/types'
import { userEvent } from 'vite-plus/test/browser'
import { render } from 'vitest-browser-react'
import { PluginSource, TaskStatus } from '@/app/components/plugins/types'
import PluginTasks from './index'
const service = vi.hoisted(() => ({ clear: vi.fn().mockResolvedValue({}), refetch: vi.fn() }))
vi.mock('@/service/use-plugins', () => ({
usePluginTaskList: () => ({
pluginTasks: [
{
id: 'task-1',
plugins: [
{
plugin_unique_identifier: 'plugin-1',
plugin_id: 'plugin-1',
source: PluginSource.marketplace,
status: TaskStatus.success,
message: '',
icon: '',
labels: { en_US: 'Installed Plugin' },
} satisfies Omit<PluginStatus, 'taskId'>,
],
},
],
handleRefetch: service.refetch,
}),
useMutationClearTaskPlugin: () => ({ mutateAsync: service.clear }),
}))
vi.mock('@/app/components/plugins/install-plugin/install-from-marketplace', () => ({
default: () => null,
}))
vi.mock('@/app/components/plugins/install-plugin/base/use-get-icon', () => ({
default: () => ({ getIconUrl: () => '' }),
}))
vi.mock('@/context/i18n', async (importOriginal) => ({
...(await importOriginal<typeof import('@/context/i18n')>()),
useGetLanguage: () => 'en_US',
}))
it('clears a completed plugin installation task using the keyboard and returns focus to installation status', async () => {
// Native Tab must include the button that CSS used to hide from keyboard users.
const screen = await render(<PluginTasks />)
const trigger = screen.getByRole('button', { name: /plugin.task.installSuccess/ })
await trigger.click()
const taskDetails = screen.getByRole('dialog')
await expect.element(taskDetails).toBeVisible()
await expect.element(screen.getByRole('menu')).not.toBeInTheDocument()
const clearAll = screen.getByRole('button', {
name: 'plugin.task.successPlugins plugin.task.clearAll',
})
clearAll.element().focus()
await userEvent.tab()
const clear = screen.getByRole('button', { name: 'Clear Installed Plugin' })
await expect.element(clear).toHaveFocus()
await expect.poll(() => clear.element().checkVisibility({ checkOpacity: true })).toBe(true)
await userEvent.keyboard('{Enter}')
expect(service.clear).toHaveBeenCalledExactlyOnceWith({ taskId: 'task-1', pluginId: 'plugin-1' })
await expect.element(taskDetails).not.toBeInTheDocument()
await expect.element(trigger).toHaveFocus()
})