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,219 @@
import type { ComponentProps } from 'react'
import type { PluginPageTab } from '../../context'
import type { FilterState } from '../../filter-management'
import { fireEvent, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useMemo, useRef, useState } from 'react'
import { seedModelProviderQueries } from '@/test/console/model-provider'
import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/console/query-data'
import { createInstalledPluginFixture } from '@/test/fixtures/plugin'
import { PluginPageContext } from '../../context'
import Empty from '../index'
const requests = vi.hoisted(() => ({ list: vi.fn(), upload: vi.fn() }))
vi.mock('@/service/plugins', async (importOriginal) => ({
...(await importOriginal<typeof import('@/service/plugins')>()),
uploadFile: requests.upload,
}))
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,
consoleQuery: withConsoleResponses(actual.consoleQuery, {
'workspaces.current.plugin.list.get': requests.list,
'workspaces.current.plugin.list.installations.ids.post': () => ({ plugins: [] }),
}),
consoleClient: withConsoleClientResponses(actual.consoleClient, {
'workspaces.current.plugin.permission.fetch.get': () => ({
install_permission: 'everyone',
debug_permission: 'everyone',
}),
'workspaces.current.plugin.tasks.get': () => ({ tasks: [] }),
}),
}
})
function renderEmpty({
filters = {},
marketplace = true,
restricted = false,
customNavigation = false,
...props
}: Partial<ComponentProps<typeof Empty>> & {
filters?: Partial<FilterState>
marketplace?: boolean
restricted?: boolean
customNavigation?: boolean
} = {}) {
const initialFilters: FilterState = { categories: [], tags: [], searchQuery: '', ...filters }
function Caller() {
const containerRef = useRef<HTMLDivElement>(null)
const [activeTab, setActiveTab] = useState<PluginPageTab>('plugins')
const [customOpen, setCustomOpen] = useState(false)
const value = useMemo(
() => ({
containerRef,
selectedItem: undefined,
setSelectedItem: () => {},
filters: initialFilters,
setFilters: () => {},
activeTab,
setActiveTab,
options: [],
}),
[activeTab],
)
return (
<PluginPageContext.Provider value={value}>
{activeTab === 'discover' && <section aria-label="Discover marketplace" />}
{customOpen && <section aria-label="Caller marketplace" />}
<Empty
{...props}
onSwitchToMarketplace={
customNavigation ? () => setCustomOpen(true) : props.onSwitchToMarketplace
}
/>
</PluginPageContext.Provider>
)
}
const queryClient = createConsoleQueryClient()
seedModelProviderQueries(queryClient)
return renderWithConsoleQuery(<Caller />, {
queryClient,
workspacePermissionKeys: ['plugin.install'],
systemFeatures: {
rbac_enabled: true,
enable_marketplace: marketplace,
plugin_installation_permission: {
plugin_installation_scope: 'all',
restrict_to_marketplace_only: restricted,
},
},
})
}
const getFileInput = () => document.querySelector<HTMLInputElement>('input[type="file"]')!
const createFile = (name: string) =>
new File(['package'], name, { type: 'application/octet-stream' })
beforeEach(() => {
requests.list.mockReset().mockResolvedValue({ plugins: [], total: 0 })
// These existing scenarios cancel before uploading finishes. Keep the transport
// pending so the real upload view and its close action own the interaction.
requests.upload.mockReset().mockReturnValue(new Promise(() => {}))
})
it('shows the no-installed message even when filters are active', async () => {
renderEmpty({ filters: { categories: ['model'], searchQuery: 'test' } })
expect(await screen.findByText('plugin.list.noInstalled')).toBeInTheDocument()
expect(screen.queryByText('plugin.list.notFound')).not.toBeInTheDocument()
})
it.each([{ categories: ['model'] }, { tags: ['tag1'] }, { searchQuery: 'test query' }])(
'shows no results for an installed list filtered by %o',
async (filters) => {
requests.list.mockResolvedValue({ plugins: [createInstalledPluginFixture()], total: 1 })
renderEmpty({ filters })
expect(await screen.findByText('plugin.list.notFound')).toBeInTheDocument()
expect(screen.queryByText('plugin.list.noInstalled')).not.toBeInTheDocument()
},
)
it.each([
{ marketplace: true, restricted: false, methods: ['marketplace', 'github', 'local'] },
{ marketplace: true, restricted: true, methods: ['marketplace'] },
{ marketplace: false, restricted: false, methods: ['github', 'local'] },
{ marketplace: false, restricted: true, methods: [] },
])(
'offers $methods with marketplace=$marketplace and restricted=$restricted',
({ marketplace, restricted, methods }) => {
renderEmpty({ marketplace, restricted })
for (const method of ['marketplace', 'github', 'local']) {
const button = screen.queryByRole('button', { name: `plugin.source.${method}` })
if (methods.includes(method)) expect(button).toBeInTheDocument()
else expect(button).not.toBeInTheDocument()
}
},
)
it('hides installation actions and ignores file changes without install permission', () => {
renderEmpty({ canInstall: false })
expect(screen.queryAllByRole('button')).toHaveLength(0)
fireEvent.change(getFileInput(), { target: { files: [createFile('blocked.difypkg')] } })
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
expect(requests.upload).not.toHaveBeenCalled()
})
it('opens the discovery tab from the marketplace action', async () => {
const user = userEvent.setup()
renderEmpty()
await user.click(screen.getByRole('button', { name: 'plugin.source.marketplace' }))
expect(screen.getByRole('region', { name: 'Discover marketplace' })).toBeInTheDocument()
})
it('uses the supplied marketplace navigation instead of switching tabs', async () => {
const user = userEvent.setup()
renderEmpty({ customNavigation: true })
await user.click(screen.getByRole('button', { name: 'plugin.source.marketplace' }))
expect(screen.getByRole('region', { name: 'Caller marketplace' })).toBeInTheDocument()
expect(screen.queryByRole('region', { name: 'Discover marketplace' })).not.toBeInTheDocument()
})
it('opens, closes, and reopens the real GitHub installer', async () => {
const user = userEvent.setup()
renderEmpty()
await user.click(screen.getByRole('button', { name: 'plugin.source.github' }))
const dialog = await screen.findByRole('dialog', {
name: 'plugin.installFromGitHub.installPlugin',
})
expect(within(dialog).getByRole('textbox')).toHaveValue('')
await user.click(within(dialog).getByRole('button', { name: 'plugin.installModal.cancel' }))
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
await user.click(screen.getByRole('button', { name: 'plugin.source.github' }))
expect(
await screen.findByRole('dialog', { name: 'plugin.installFromGitHub.installPlugin' }),
).toBeInTheDocument()
})
it('opens the file picker for supported plugin and bundle files', async () => {
const user = userEvent.setup()
renderEmpty()
const input = getFileInput()
const clickSpy = vi.spyOn(input, 'click')
await user.click(screen.getByRole('button', { name: 'plugin.source.local' }))
expect(clickSpy).toHaveBeenCalledOnce()
expect(input).toHaveAttribute('accept', '.difypkg,.difybndl')
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
clickSpy.mockRestore()
})
it('uploads the selected package and accepts a new bundle after closing', async () => {
const user = userEvent.setup()
renderEmpty()
const file = createFile('my-plugin.difypkg')
await user.upload(getFileInput(), file)
const dialog = await screen.findByRole('dialog', { name: 'plugin.installModal.installPlugin' })
expect(within(dialog).getByText(/plugin.installModal.uploadingPackage/)).toHaveTextContent(
file.name,
)
expect(requests.upload).toHaveBeenCalledWith(file, false)
await user.click(within(dialog).getByRole('button', { name: 'common.operation.cancel' }))
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
const bundle = createFile('my-bundle.difybndl')
await user.upload(getFileInput(), bundle)
const reopened = await screen.findByRole('dialog', { name: 'plugin.installModal.installPlugin' })
expect(within(reopened).getByText(/plugin.installModal.uploadingPackage/)).toHaveTextContent(
bundle.name,
)
expect(requests.upload).toHaveBeenLastCalledWith(bundle, true)
})
it('does not open an installer when file selection is cancelled', () => {
renderEmpty()
fireEvent.change(getFileInput(), { target: { files: [] } })
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
expect(requests.upload).not.toHaveBeenCalled()
})
@@ -0,0 +1,201 @@
'use client'
import type { PluginPageContentInset } from '../content-inset'
import type { PluginCategoryEnum } from '@/app/components/plugins/types'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import { useSuspenseQuery } from '@tanstack/react-query'
import { noop } from 'es-toolkit/function'
import * as React from 'react'
import { useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import InstallFromGitHub from '@/app/components/plugins/install-plugin/install-from-github'
import InstallFromLocalPackage from '@/app/components/plugins/install-plugin/install-from-local-package'
import { SUPPORT_INSTALL_LOCAL_FILE_EXTENSIONS } from '@/config'
import { useMarketplace } from '@/features/marketplace/client'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import { useInstalledPluginList } from '@/service/use-plugins'
import Line from '../../marketplace/empty/line'
import {
pluginPageContentFrameClassNames,
pluginPageContentInsetClassNames,
} from '../content-inset'
import { usePluginPageContext } from '../context'
type InstallMethod = {
iconClassName: string
text: string
action: string
}
type EmptyProps = {
canInstall?: boolean
contentInset?: PluginPageContentInset
installContextCategory?: PluginCategoryEnum
onSwitchToMarketplace?: () => void
}
const Empty = ({
canInstall = true,
contentInset = 'default',
installContextCategory,
onSwitchToMarketplace,
}: EmptyProps) => {
const { t } = useTranslation(['plugin'])
const fileInputRef = useRef<HTMLInputElement>(null)
const [selectedAction, setSelectedAction] = useState<string | null>(null)
const [selectedFile, setSelectedFile] = useState<File | null>(null)
const enable_marketplace = useMarketplace() !== null
const { data: plugin_installation_permission } = useSuspenseQuery({
...systemFeaturesQueryOptions(),
select: (s) => s.plugin_installation_permission,
})
const setActiveTab = usePluginPageContext((v) => v.setActiveTab)
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
if (!canInstall) {
setSelectedFile(null)
setSelectedAction(null)
return
}
const file = event.target.files?.[0]
if (file) {
setSelectedFile(file)
setSelectedAction('local')
}
}
const filters = usePluginPageContext((v) => v.filters)
const { data: pluginList } = useInstalledPluginList()
const text = useMemo(() => {
if (pluginList?.plugins.length === 0) return t(($) => $['list.noInstalled'], { ns: 'plugin' })
if (filters.categories.length > 0 || filters.tags.length > 0 || filters.searchQuery)
return t(($) => $['list.notFound'], { ns: 'plugin' })
}, [
pluginList?.plugins.length,
t,
filters.categories.length,
filters.tags.length,
filters.searchQuery,
])
const installMethods = useMemo<InstallMethod[]>(() => {
if (!canInstall) return []
const methods: InstallMethod[] = []
if (enable_marketplace)
methods.push({
iconClassName: 'i-custom-vender-solid-mediaAndDevices-magic-box',
text: t(($) => $['source.marketplace'], { ns: 'plugin' }),
action: 'marketplace',
})
if (plugin_installation_permission.restrict_to_marketplace_only) return methods
methods.push({
iconClassName: 'i-custom-vender-solid-general-github',
text: t(($) => $['source.github'], { ns: 'plugin' }),
action: 'github',
})
methods.push({
iconClassName: 'i-custom-vender-solid-files-file-zip',
text: t(($) => $['source.local'], { ns: 'plugin' }),
action: 'local',
})
return methods
}, [canInstall, plugin_installation_permission, enable_marketplace, t])
const contentPaddingClassName = pluginPageContentInsetClassNames[contentInset]
const contentFrameClassName = cn(
pluginPageContentFrameClassNames[contentInset],
contentPaddingClassName,
)
return (
<div className="relative z-0 w-full grow bg-components-panel-bg">
<div
aria-hidden
className={cn(
'pointer-events-none absolute top-0 left-1/2 z-10 grid h-full -translate-x-1/2 grid-cols-2 content-start gap-2 overflow-hidden',
contentFrameClassName,
)}
>
{Array.from({ length: 20 }, (_, i) => (
<div key={i} className="h-24 rounded-xl bg-components-card-bg" />
))}
</div>
<div
aria-hidden
className="pointer-events-none absolute inset-0 z-20 bg-linear-to-b from-components-panel-bg-transparent to-components-panel-bg"
/>
<div className="relative z-30 flex h-full items-center justify-center">
<div className="flex h-full w-full items-center justify-center">
<div className="flex flex-col items-center gap-y-3">
<div className="flex flex-col items-center gap-y-3">
<div className="relative -z-10 flex size-14 items-center justify-center rounded-xl border border-dashed border-divider-deep bg-components-card-bg shadow-xl shadow-shadow-shadow-5 backdrop-blur-md">
<span
aria-hidden
className="i-custom-vender-other-group size-5 text-text-tertiary"
/>
<Line className="absolute top-1/2 -right-px -translate-y-1/2" />
<Line className="absolute top-1/2 -left-px -translate-y-1/2" />
<Line className="absolute top-0 left-1/2 -translate-x-1/2 -translate-y-1/2 rotate-90" />
<Line className="absolute top-full left-1/2 -translate-x-1/2 -translate-y-1/2 rotate-90" />
</div>
<div className="system-md-regular text-text-tertiary">{text}</div>
</div>
<div className="flex w-59 flex-col">
<input
type="file"
ref={fileInputRef}
style={{ display: 'none' }}
onChange={handleFileChange}
accept={SUPPORT_INSTALL_LOCAL_FILE_EXTENSIONS}
/>
<div className="flex w-full flex-col gap-y-1">
{installMethods.map(({ iconClassName, text, action }) => (
<Button
key={action}
variant="secondary"
title={text}
className="h-8 w-full justify-start py-2 system-sm-medium"
onClick={() => {
if (action === 'local') fileInputRef.current?.click()
else if (action === 'marketplace')
onSwitchToMarketplace ? onSwitchToMarketplace() : setActiveTab('discover')
else setSelectedAction(action)
}}
>
<span
aria-hidden
className={cn(iconClassName, 'size-4 text-components-button-secondary-text')}
/>
<span className="min-w-0 flex-1 truncate text-left">{text}</span>
</Button>
))}
</div>
</div>
</div>
</div>
{selectedAction === 'github' && (
<InstallFromGitHub
installContextCategory={installContextCategory}
onSuccess={noop}
onClose={() => setSelectedAction(null)}
/>
)}
{selectedAction === 'local' && selectedFile && (
<InstallFromLocalPackage
file={selectedFile}
installContextCategory={installContextCategory}
onClose={() => setSelectedAction(null)}
onSuccess={noop}
/>
)}
</div>
</div>
)
}
Empty.displayName = 'Empty'
export default React.memo(Empty)