chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动
演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
60158935f4
commit
6519682885
15831 files changed
+3063428
No files matched your search
@@ -0,0 +1,77 @@
|
||||
import { renderHook } from '@testing-library/react'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
|
||||
import { useCategories, usePluginPageTabs, useTags } from '../hooks'
|
||||
|
||||
describe('useTags', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should return non-empty tags array with name and label properties', () => {
|
||||
const { result } = renderHook(() => useTags())
|
||||
|
||||
expect(result.current.tags.length).toBeGreaterThan(0)
|
||||
result.current.tags.forEach((tag) => {
|
||||
expect(result.current.tagsMap[tag.name]).toEqual(tag)
|
||||
expect(tag.label).toBe(`pluginTags.tags.${tag.name}`)
|
||||
})
|
||||
})
|
||||
|
||||
describe('getTagLabel', () => {
|
||||
it('should return translated label for existing tags', () => {
|
||||
const { result } = renderHook(() => useTags())
|
||||
|
||||
expect(result.current.getTagLabel('agent')).toBe('pluginTags.tags.agent')
|
||||
expect(result.current.getTagLabel('search')).toBe('pluginTags.tags.search')
|
||||
expect(result.current.getTagLabel('rag')).toBe('pluginTags.tags.rag')
|
||||
})
|
||||
|
||||
it('should return the name itself for non-existing tags', () => {
|
||||
const { result } = renderHook(() => useTags())
|
||||
|
||||
expect(result.current.getTagLabel('non-existing')).toBe('non-existing')
|
||||
expect(result.current.getTagLabel('custom-tag')).toBe('custom-tag')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('useCategories', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('isSingle parameter', () => {
|
||||
it('should use plural labels by default', () => {
|
||||
const { result } = renderHook(() => useCategories())
|
||||
|
||||
expect(result.current.categoriesMap.tool!.label).toBe('plugin.category.tools')
|
||||
expect(result.current.categoriesMap['agent-strategy']!.label).toBe('plugin.category.agents')
|
||||
})
|
||||
|
||||
it('should use singular labels when isSingle is true', () => {
|
||||
const { result } = renderHook(() => useCategories(true))
|
||||
|
||||
expect(result.current.categoriesMap.tool!.label).toBe('plugin.categorySingle.tool')
|
||||
expect(result.current.categoriesMap['agent-strategy']!.label).toBe(
|
||||
'plugin.categorySingle.agent',
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('usePluginPageTabs', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should return two tabs: plugins first, marketplace second', () => {
|
||||
const { result } = renderHook(() => usePluginPageTabs())
|
||||
|
||||
expect(result.current).toHaveLength(2)
|
||||
expect(result.current[0]).toEqual({ value: 'plugins', text: 'navigation.menus.plugins' })
|
||||
expect(result.current[1]).toEqual({
|
||||
value: 'discover',
|
||||
text: 'navigation.menus.exploreMarketplace',
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,161 @@
|
||||
import {
|
||||
getFirstPackageIdFromSearchParams,
|
||||
getInstallRedirectPathByPluginCategory,
|
||||
getInstallRedirectPathFromSearchParams,
|
||||
getLegacyPluginRedirectPath,
|
||||
shouldResolveInstallCategoryRedirect,
|
||||
} from '../plugin-routes'
|
||||
|
||||
describe('plugin routes', () => {
|
||||
it.each([
|
||||
[{}, '/integrations'],
|
||||
[{ tab: 'plugins' }, '/integrations'],
|
||||
[{ tab: ['plugins', 'discover'] }, '/integrations'],
|
||||
])('redirects installed plugin URLs for search params %j', (searchParams, expected) => {
|
||||
expect(getLegacyPluginRedirectPath(searchParams)).toBe(expected)
|
||||
})
|
||||
|
||||
it.each([
|
||||
[{ tab: 'trigger' }, '/integrations/trigger'],
|
||||
[{ tab: 'agent-strategy' }, '/integrations/agent-strategy'],
|
||||
[{ tab: 'extension' }, '/integrations/extension'],
|
||||
[
|
||||
{
|
||||
tab: 'trigger',
|
||||
'package-ids': '["langgenius/telegram_trigger"]',
|
||||
source: 'https://marketplace.dify.ai',
|
||||
},
|
||||
'/integrations/trigger?package-ids=%5B%22langgenius%2Ftelegram_trigger%22%5D',
|
||||
],
|
||||
])('redirects legacy plugin category URLs for search params %j', (searchParams, expected) => {
|
||||
expect(getLegacyPluginRedirectPath(searchParams)).toBe(expected)
|
||||
})
|
||||
|
||||
it.each([
|
||||
[{ 'package-ids': '["langgenius/telegram_trigger"]' }, '/integrations'],
|
||||
[{ tab: 'plugins', 'package-ids': '["langgenius/telegram_trigger"]' }, '/integrations'],
|
||||
[{ 'bundle-info': '{"org":"langgenius","name":"bundle","version":"1.0.0"}' }, '/integrations'],
|
||||
])(
|
||||
'redirects unresolved install deep links to integrations for search params %j',
|
||||
(searchParams, expected) => {
|
||||
expect(getLegacyPluginRedirectPath(searchParams)).toBe(expected)
|
||||
},
|
||||
)
|
||||
|
||||
it('parses the first package id from marketplace install search params', () => {
|
||||
expect(
|
||||
getFirstPackageIdFromSearchParams({
|
||||
'package-ids':
|
||||
'["junjiem/mcp_see_agent:0.2.4@82caf96890992e9dec2c43c3fac82bfce8bd18a41de7c2b6948151b2d7f7b7a2"]',
|
||||
}),
|
||||
).toBe(
|
||||
'junjiem/mcp_see_agent:0.2.4@82caf96890992e9dec2c43c3fac82bfce8bd18a41de7c2b6948151b2d7f7b7a2',
|
||||
)
|
||||
})
|
||||
|
||||
it.each([
|
||||
[{ 'package-ids': '["junjiem/mcp_see_agent"]' }, true],
|
||||
[{ tab: 'plugins', 'package-ids': '["junjiem/mcp_see_agent"]' }, true],
|
||||
[{ tab: 'trigger', 'package-ids': '["langgenius/telegram_trigger"]' }, false],
|
||||
[{ 'bundle-info': '{"org":"langgenius","name":"bundle","version":"1.0.0"}' }, false],
|
||||
])(
|
||||
'detects package install deep links that need category resolution for search params %j',
|
||||
(searchParams, expected) => {
|
||||
expect(shouldResolveInstallCategoryRedirect(searchParams)).toBe(expected)
|
||||
},
|
||||
)
|
||||
|
||||
it.each([
|
||||
[
|
||||
'model',
|
||||
{ 'package-ids': '["langgenius/openai"]' },
|
||||
'/integrations/model-provider?package-ids=%5B%22langgenius%2Fopenai%22%5D',
|
||||
],
|
||||
[
|
||||
'agent-strategy',
|
||||
{ 'package-ids': '["junjiem/mcp_see_agent"]' },
|
||||
'/integrations/agent-strategy?package-ids=%5B%22junjiem%2Fmcp_see_agent%22%5D',
|
||||
],
|
||||
[
|
||||
'trigger',
|
||||
{
|
||||
tab: 'plugins',
|
||||
'package-ids': '["langgenius/telegram_trigger"]',
|
||||
source: 'https://marketplace.dify.ai',
|
||||
},
|
||||
'/integrations/trigger?package-ids=%5B%22langgenius%2Ftelegram_trigger%22%5D',
|
||||
],
|
||||
[
|
||||
'datasource',
|
||||
{ 'package-ids': '["langgenius/notion_datasource"]' },
|
||||
'/integrations/data-source?package-ids=%5B%22langgenius%2Fnotion_datasource%22%5D',
|
||||
],
|
||||
])(
|
||||
'builds install redirect paths from marketplace plugin category %s',
|
||||
(category, searchParams, expected) => {
|
||||
expect(getInstallRedirectPathByPluginCategory(category, searchParams)).toBe(expected)
|
||||
},
|
||||
)
|
||||
|
||||
it.each([
|
||||
[
|
||||
{
|
||||
category: 'agent-strategy',
|
||||
'package-ids': '["junjiem/mcp_see_agent"]',
|
||||
source: 'https://marketplace.dify.ai',
|
||||
},
|
||||
'/integrations/agent-strategy?package-ids=%5B%22junjiem%2Fmcp_see_agent%22%5D',
|
||||
],
|
||||
[
|
||||
{
|
||||
tab: 'trigger',
|
||||
'package-ids': '["langgenius/telegram_trigger"]',
|
||||
source: 'https://marketplace.dify.ai',
|
||||
},
|
||||
'/integrations/trigger?package-ids=%5B%22langgenius%2Ftelegram_trigger%22%5D',
|
||||
],
|
||||
[
|
||||
{
|
||||
category: 'model',
|
||||
'package-ids': '["langgenius/openai"]',
|
||||
source: 'https://marketplace.dify.ai',
|
||||
},
|
||||
'/integrations/model-provider?package-ids=%5B%22langgenius%2Fopenai%22%5D',
|
||||
],
|
||||
[
|
||||
{
|
||||
category: 'datasource',
|
||||
'package-ids': '["langgenius/notion_datasource"]',
|
||||
source: 'https://marketplace.dify.ai',
|
||||
},
|
||||
'/integrations/data-source?package-ids=%5B%22langgenius%2Fnotion_datasource%22%5D',
|
||||
],
|
||||
[{ category: 'bundle', 'package-ids': '["langgenius/bundle"]' }, undefined],
|
||||
[{ category: 'agent-strategy' }, undefined],
|
||||
])(
|
||||
'builds install redirect paths directly from install search params %j',
|
||||
(searchParams, expected) => {
|
||||
expect(getInstallRedirectPathFromSearchParams(searchParams)).toBe(expected)
|
||||
},
|
||||
)
|
||||
|
||||
it.each([
|
||||
[{ tab: 'discover' }, '/marketplace'],
|
||||
[{ tab: 'discover', category: 'extension' }, '/marketplace?category=extension'],
|
||||
[{ tab: 'discover', q: 'slack', tags: ['a', 'b'] }, '/marketplace?q=slack&tags=a&tags=b'],
|
||||
[{ tab: 'all' }, '/marketplace?category=all'],
|
||||
[{ tab: 'tool' }, '/marketplace?category=tool'],
|
||||
[{ tab: 'model' }, '/marketplace?category=model'],
|
||||
[{ tab: 'datasource' }, '/marketplace?category=datasource'],
|
||||
[{ tab: 'bundle' }, '/marketplace?category=bundle'],
|
||||
])('redirects marketplace plugin URLs for search params %j', (searchParams, expected) => {
|
||||
expect(getLegacyPluginRedirectPath(searchParams)).toBe(expected)
|
||||
})
|
||||
|
||||
it.each([
|
||||
[{ tab: 'unsupported' }, '/integrations'],
|
||||
[{ tab: 'toString' }, '/integrations'],
|
||||
])('redirects unsupported plugin URLs for search params %j', (searchParams, expected) => {
|
||||
expect(getLegacyPluginRedirectPath(searchParams)).toBe(expected)
|
||||
})
|
||||
})
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
import type { PluginDetail } from '../types'
|
||||
import { waitFor } from '@testing-library/react'
|
||||
import { renderHookWithConsoleQuery as renderHook } from '@/test/console/query-data'
|
||||
import { usePluginsWithLatestVersion } from '../hooks'
|
||||
import { PluginSource } from '../types'
|
||||
const getVersions = vi.hoisted(() => vi.fn())
|
||||
vi.mock('@/service/console', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/service/console')>()
|
||||
const { withConsoleResponses } = await import('@/test/console/service-responses')
|
||||
return {
|
||||
...actual,
|
||||
consoleQuery: withConsoleResponses(actual.consoleQuery, {
|
||||
'workspaces.current.plugin.list.latestVersions.post': getVersions,
|
||||
}),
|
||||
}
|
||||
})
|
||||
|
||||
const createPlugin = (overrides: Partial<PluginDetail> = {}): PluginDetail => ({
|
||||
id: 'plugin-1',
|
||||
created_at: '2026-01-01T00:00:00Z',
|
||||
updated_at: '2026-01-01T00:00:00Z',
|
||||
name: 'demo-plugin',
|
||||
plugin_id: 'plugin-1',
|
||||
plugin_unique_identifier: 'plugin-1@1.0.0',
|
||||
declaration: {} as PluginDetail['declaration'],
|
||||
installation_id: 'installation-1',
|
||||
tenant_id: 'tenant-1',
|
||||
endpoints_setups: 0,
|
||||
endpoints_active: 0,
|
||||
version: '1.0.0',
|
||||
latest_version: '1.0.0',
|
||||
latest_unique_identifier: 'plugin-1@1.0.0',
|
||||
source: PluginSource.marketplace,
|
||||
meta: undefined,
|
||||
status: 'active',
|
||||
deprecated_reason: '',
|
||||
alternative_plugin_id: '',
|
||||
...overrides,
|
||||
})
|
||||
|
||||
describe('usePluginsWithLatestVersion', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
getVersions.mockReset().mockImplementation(() => new Promise(() => {}))
|
||||
})
|
||||
|
||||
it('should disable latest-version querying when there are no marketplace plugins', () => {
|
||||
const plugins = [createPlugin({ plugin_id: 'github-plugin', source: PluginSource.github })]
|
||||
|
||||
const { result } = renderHook(() => usePluginsWithLatestVersion(plugins))
|
||||
|
||||
expect(getVersions).not.toHaveBeenCalled()
|
||||
expect(result.current).toEqual(plugins)
|
||||
})
|
||||
|
||||
it('should return the original plugins when version data is unavailable', () => {
|
||||
const plugins = [createPlugin()]
|
||||
|
||||
const { result } = renderHook(() => usePluginsWithLatestVersion(plugins))
|
||||
|
||||
expect(result.current).toEqual(plugins)
|
||||
})
|
||||
|
||||
it('should keep plugins unchanged when a plugin has no matching latest version', async () => {
|
||||
const plugins = [createPlugin()]
|
||||
getVersions.mockResolvedValue({ versions: {} })
|
||||
|
||||
const { result, queryClient } = renderHook(() => usePluginsWithLatestVersion(plugins))
|
||||
|
||||
await waitFor(() => expect(queryClient.isFetching()).toBe(0))
|
||||
expect(result.current).toEqual(plugins)
|
||||
})
|
||||
|
||||
it('should merge latest version fields for marketplace plugins with version data', async () => {
|
||||
const plugins = [
|
||||
createPlugin(),
|
||||
createPlugin({
|
||||
id: 'plugin-2',
|
||||
plugin_id: 'plugin-2',
|
||||
plugin_unique_identifier: 'plugin-2@1.0.0',
|
||||
latest_version: '1.0.0',
|
||||
latest_unique_identifier: 'plugin-2@1.0.0',
|
||||
source: PluginSource.github,
|
||||
}),
|
||||
]
|
||||
getVersions.mockResolvedValue({
|
||||
versions: {
|
||||
'plugin-1': {
|
||||
version: '1.1.0',
|
||||
unique_identifier: 'plugin-1@1.1.0',
|
||||
status: 'deleted',
|
||||
deprecated_reason: 'replaced',
|
||||
alternative_plugin_id: 'plugin-3',
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const { result } = renderHook(() => usePluginsWithLatestVersion(plugins))
|
||||
|
||||
await waitFor(() => expect(result.current[0]?.latest_version).toBe('1.1.0'))
|
||||
expect(getVersions).toHaveBeenCalledWith({ body: { plugin_ids: ['plugin-1'] } })
|
||||
expect(result.current).toEqual([
|
||||
expect.objectContaining({
|
||||
plugin_id: 'plugin-1',
|
||||
latest_version: '1.1.0',
|
||||
latest_unique_identifier: 'plugin-1@1.1.0',
|
||||
status: 'deleted',
|
||||
deprecated_reason: 'replaced',
|
||||
alternative_plugin_id: 'plugin-3',
|
||||
}),
|
||||
plugins[1],
|
||||
])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,55 @@
|
||||
import type { Plugin } from '../types'
|
||||
import { describe, expect, it } from 'vite-plus/test'
|
||||
import { API_PREFIX } from '@/config'
|
||||
import { MARKETPLACE_API_PREFIX } from '@/features/marketplace/api'
|
||||
import { getPluginCardIconUrl } from '../utils'
|
||||
|
||||
const createPlugin = (
|
||||
overrides: Partial<Pick<Plugin, 'from' | 'name' | 'org' | 'type'>> = {},
|
||||
): Pick<Plugin, 'from' | 'name' | 'org' | 'type'> => ({
|
||||
from: 'github',
|
||||
name: 'demo-plugin',
|
||||
org: 'langgenius',
|
||||
type: 'plugin',
|
||||
...overrides,
|
||||
})
|
||||
|
||||
describe('plugins/utils', () => {
|
||||
describe('getPluginCardIconUrl', () => {
|
||||
it('returns an empty string when icon is missing', () => {
|
||||
expect(getPluginCardIconUrl(createPlugin(), undefined, 'tenant-1')).toBe('')
|
||||
})
|
||||
|
||||
it('returns absolute urls and root-relative urls as-is', () => {
|
||||
expect(getPluginCardIconUrl(createPlugin(), 'https://example.com/icon.png', 'tenant-1')).toBe(
|
||||
'https://example.com/icon.png',
|
||||
)
|
||||
expect(getPluginCardIconUrl(createPlugin(), '/icons/demo.png', 'tenant-1')).toBe(
|
||||
'/icons/demo.png',
|
||||
)
|
||||
})
|
||||
|
||||
it('builds the marketplace icon url for plugins and bundles', () => {
|
||||
expect(
|
||||
getPluginCardIconUrl(createPlugin({ from: 'marketplace' }), 'icon.png', 'tenant-1'),
|
||||
).toBe(`${MARKETPLACE_API_PREFIX}/plugins/langgenius/demo-plugin/icon`)
|
||||
expect(
|
||||
getPluginCardIconUrl(
|
||||
createPlugin({ from: 'marketplace', type: 'bundle' }),
|
||||
'icon.png',
|
||||
'tenant-1',
|
||||
),
|
||||
).toBe(`${MARKETPLACE_API_PREFIX}/bundles/langgenius/demo-plugin/icon`)
|
||||
})
|
||||
|
||||
it('falls back to the raw icon when tenant id is missing for non-marketplace plugins', () => {
|
||||
expect(getPluginCardIconUrl(createPlugin(), 'icon.png', '')).toBe('icon.png')
|
||||
})
|
||||
|
||||
it('builds the workspace icon url for tenant-scoped plugins', () => {
|
||||
expect(getPluginCardIconUrl(createPlugin(), 'icon.png', 'tenant-1')).toBe(
|
||||
`${API_PREFIX}/workspaces/current/plugin/icon?tenant_id=tenant-1&filename=icon.png`,
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,81 @@
|
||||
import { cleanup, render, screen } from '@testing-library/react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
|
||||
import DeprecationNotice from '../deprecation-notice'
|
||||
|
||||
vi.mock('@/next/link', () => ({
|
||||
default: ({ children, href }: { children: React.ReactNode; href: string }) => (
|
||||
<a data-testid="link" href={href}>
|
||||
{children}
|
||||
</a>
|
||||
),
|
||||
}))
|
||||
|
||||
describe('DeprecationNotice', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
})
|
||||
|
||||
it('returns null when status is not "deleted"', () => {
|
||||
const { container } = render(
|
||||
<DeprecationNotice
|
||||
status="active"
|
||||
deprecatedReason="business_adjustments"
|
||||
alternativePluginId="alt-plugin"
|
||||
alternativePluginURL="/plugins/alt-plugin"
|
||||
/>,
|
||||
)
|
||||
expect(container.firstChild).toBeNull()
|
||||
})
|
||||
|
||||
it('renders deprecation notice when status is "deleted"', () => {
|
||||
render(
|
||||
<DeprecationNotice
|
||||
status="deleted"
|
||||
deprecatedReason=""
|
||||
alternativePluginId=""
|
||||
alternativePluginURL=""
|
||||
/>,
|
||||
)
|
||||
expect(screen.getByText('plugin.detailPanel.deprecation.noReason')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders with valid reason and alternative plugin', () => {
|
||||
render(
|
||||
<DeprecationNotice
|
||||
status="deleted"
|
||||
deprecatedReason="business_adjustments"
|
||||
alternativePluginId="better-plugin"
|
||||
alternativePluginURL="/plugins/better-plugin"
|
||||
/>,
|
||||
)
|
||||
expect(screen.getByText('plugin.detailPanel.deprecation.fullMessage')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders only reason without alternative plugin', () => {
|
||||
render(
|
||||
<DeprecationNotice
|
||||
status="deleted"
|
||||
deprecatedReason="no_maintainer"
|
||||
alternativePluginId=""
|
||||
alternativePluginURL=""
|
||||
/>,
|
||||
)
|
||||
expect(screen.getByText(/plugin\.detailPanel\.deprecation\.onlyReason/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders no-reason message for invalid reason', () => {
|
||||
render(
|
||||
<DeprecationNotice
|
||||
status="deleted"
|
||||
deprecatedReason="unknown_reason"
|
||||
alternativePluginId=""
|
||||
alternativePluginURL=""
|
||||
/>,
|
||||
)
|
||||
expect(screen.getByText('plugin.detailPanel.deprecation.noReason')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,35 @@
|
||||
import { render, screen, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { describe, expect, it, vi } from 'vite-plus/test'
|
||||
import KeyValueItem from '../key-value-item'
|
||||
|
||||
const mockCopy = vi.fn()
|
||||
vi.mock('copy-to-clipboard', () => ({
|
||||
default: (...args: unknown[]) => mockCopy(...args),
|
||||
}))
|
||||
|
||||
describe('KeyValueItem', () => {
|
||||
it('renders label and value', () => {
|
||||
render(<KeyValueItem label="ID" value="abc-123" />)
|
||||
expect(screen.getByText('ID')).toBeInTheDocument()
|
||||
expect(screen.getByText('abc-123')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('associates the label with the copy action and announces the result', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<KeyValueItem label="Key" value="sk-secret" maskedValue="sk-***" />)
|
||||
expect(screen.getByText('sk-***')).toBeInTheDocument()
|
||||
expect(screen.queryByText('sk-secret')).not.toBeInTheDocument()
|
||||
|
||||
const keyGroup = screen.getByRole('group', { name: 'Key' })
|
||||
const copyButton = within(keyGroup).getByRole('button', {
|
||||
name: 'common.operation.copy: Key',
|
||||
})
|
||||
|
||||
await user.click(copyButton)
|
||||
|
||||
expect(mockCopy).toHaveBeenCalledWith('sk-secret')
|
||||
expect(copyButton).toHaveAccessibleName('common.operation.copy: Key')
|
||||
expect(within(keyGroup).getByRole('status')).toHaveTextContent('common.operation.copied: Key')
|
||||
})
|
||||
})
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { describe, expect, it } from 'vite-plus/test'
|
||||
import { Theme } from '@/types/app'
|
||||
import IconWithTooltip from '../icon-with-tooltip'
|
||||
|
||||
describe('IconWithTooltip', () => {
|
||||
it('exposes the badge meaning without opening the tooltip', () => {
|
||||
render(
|
||||
<IconWithTooltip
|
||||
theme={Theme.light}
|
||||
lightIconClassName="i-custom-public-plugins-partner-light"
|
||||
darkIconClassName="i-custom-public-plugins-partner-dark"
|
||||
popupContent="Partner plugin"
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByText('Partner plugin')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,41 @@
|
||||
import type { FC } from 'react'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
|
||||
import * as React from 'react'
|
||||
import { Theme } from '@/types/app'
|
||||
|
||||
type IconWithTooltipProps = {
|
||||
className?: string
|
||||
popupContent?: string
|
||||
theme: Theme
|
||||
lightIconClassName: string
|
||||
darkIconClassName: string
|
||||
}
|
||||
|
||||
const IconWithTooltip: FC<IconWithTooltipProps> = ({
|
||||
className,
|
||||
theme,
|
||||
popupContent,
|
||||
lightIconClassName,
|
||||
darkIconClassName,
|
||||
}) => {
|
||||
const isDark = theme === Theme.dark
|
||||
const iconClassName = cn(isDark ? darkIconClassName : lightIconClassName, 'size-5', className)
|
||||
const icon = (
|
||||
<span className="flex shrink-0 items-center justify-center">
|
||||
<span aria-hidden className={iconClassName} />
|
||||
{popupContent && <span className="sr-only">{popupContent}</span>}
|
||||
</span>
|
||||
)
|
||||
|
||||
if (!popupContent) return icon
|
||||
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger render={icon} />
|
||||
<TooltipContent>{popupContent}</TooltipContent>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
|
||||
export default React.memo(IconWithTooltip)
|
||||
@@ -0,0 +1,26 @@
|
||||
'use client'
|
||||
|
||||
import type { FC } from 'react'
|
||||
import useTheme from '@/hooks/use-theme'
|
||||
import IconWithTooltip from './icon-with-tooltip'
|
||||
|
||||
type PartnerProps = {
|
||||
className?: string
|
||||
text: string
|
||||
}
|
||||
|
||||
const Partner: FC<PartnerProps> = ({ className, text }) => {
|
||||
const { theme } = useTheme()
|
||||
|
||||
return (
|
||||
<IconWithTooltip
|
||||
className={className}
|
||||
theme={theme}
|
||||
lightIconClassName={'i-custom-public-plugins-partner-light'}
|
||||
darkIconClassName={'i-custom-public-plugins-partner-dark'}
|
||||
popupContent={text}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export default Partner
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { FC } from 'react'
|
||||
import useTheme from '@/hooks/use-theme'
|
||||
import IconWithTooltip from './icon-with-tooltip'
|
||||
|
||||
type VerifiedProps = {
|
||||
className?: string
|
||||
text: string
|
||||
}
|
||||
|
||||
const Verified: FC<VerifiedProps> = ({ className, text }) => {
|
||||
const { theme } = useTheme()
|
||||
|
||||
return (
|
||||
<IconWithTooltip
|
||||
className={className}
|
||||
theme={theme}
|
||||
lightIconClassName={'i-custom-public-plugins-verified-light'}
|
||||
darkIconClassName={'i-custom-public-plugins-verified-dark'}
|
||||
popupContent={text}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export default Verified
|
||||
@@ -0,0 +1,96 @@
|
||||
import type { FC } from 'react'
|
||||
import { Alert, AlertTitle } from '@langgenius/dify-ui/alert'
|
||||
import { camelCase } from 'es-toolkit/string'
|
||||
import * as React from 'react'
|
||||
import { useMemo } from 'react'
|
||||
import { Trans } from 'react-i18next'
|
||||
import { useTranslation } from '#i18n'
|
||||
import Link from '@/next/link'
|
||||
|
||||
type DeprecationNoticeProps = {
|
||||
status: 'deleted' | 'active'
|
||||
deprecatedReason: string
|
||||
alternativePluginId: string
|
||||
alternativePluginURL: string
|
||||
className?: string
|
||||
}
|
||||
|
||||
const i18nPrefix = 'detailPanel.deprecation'
|
||||
|
||||
type DeprecatedReasonKey = 'businessAdjustments' | 'ownershipTransferred' | 'noMaintainer'
|
||||
const validReasonKeys: DeprecatedReasonKey[] = [
|
||||
'businessAdjustments',
|
||||
'ownershipTransferred',
|
||||
'noMaintainer',
|
||||
]
|
||||
|
||||
function isValidReasonKey(key: string): key is DeprecatedReasonKey {
|
||||
return (validReasonKeys as string[]).includes(key)
|
||||
}
|
||||
|
||||
const DeprecationNotice: FC<DeprecationNoticeProps> = ({
|
||||
status,
|
||||
deprecatedReason,
|
||||
alternativePluginId,
|
||||
alternativePluginURL,
|
||||
className,
|
||||
}) => {
|
||||
const { t } = useTranslation(['plugin'])
|
||||
|
||||
const deprecatedReasonKey = useMemo(() => {
|
||||
if (!deprecatedReason) return null
|
||||
const key = camelCase(deprecatedReason)
|
||||
if (isValidReasonKey(key)) return key
|
||||
return null
|
||||
}, [deprecatedReason])
|
||||
|
||||
// Check if the deprecatedReasonKey exists in i18n
|
||||
const hasValidDeprecatedReason = deprecatedReasonKey !== null
|
||||
|
||||
if (status !== 'deleted') return null
|
||||
|
||||
return (
|
||||
<Alert type="warning" className={className}>
|
||||
<AlertTitle>
|
||||
{hasValidDeprecatedReason && alternativePluginId && (
|
||||
<Trans
|
||||
t={t}
|
||||
i18nKey={($) => $[`${i18nPrefix}.fullMessage`]}
|
||||
ns="plugin"
|
||||
components={{
|
||||
CustomLink: (
|
||||
<Link
|
||||
href={alternativePluginURL}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="underline"
|
||||
/>
|
||||
),
|
||||
}}
|
||||
values={{
|
||||
deprecatedReason: deprecatedReasonKey
|
||||
? t(($) => $[`${i18nPrefix}.reason.${deprecatedReasonKey}`], { ns: 'plugin' })
|
||||
: '',
|
||||
alternativePluginId,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{hasValidDeprecatedReason && !alternativePluginId && (
|
||||
<span>
|
||||
{t(($) => $[`${i18nPrefix}.onlyReason`], {
|
||||
ns: 'plugin',
|
||||
deprecatedReason: deprecatedReasonKey
|
||||
? t(($) => $[`${i18nPrefix}.reason.${deprecatedReasonKey}`], { ns: 'plugin' })
|
||||
: '',
|
||||
})}
|
||||
</span>
|
||||
)}
|
||||
{!hasValidDeprecatedReason && (
|
||||
<span>{t(($) => $[`${i18nPrefix}.noReason`], { ns: 'plugin' })}</span>
|
||||
)}
|
||||
</AlertTitle>
|
||||
</Alert>
|
||||
)
|
||||
}
|
||||
|
||||
export default React.memo(DeprecationNotice)
|
||||
@@ -0,0 +1,94 @@
|
||||
'use client'
|
||||
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 copy from 'copy-to-clipboard'
|
||||
import { useCallback, useEffect, useId, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
type Props = Readonly<{
|
||||
label: string
|
||||
labelWidthClassName?: string
|
||||
value: string
|
||||
maskedValue?: string
|
||||
valueMaxWidthClassName?: string
|
||||
}>
|
||||
|
||||
function KeyValueItem({
|
||||
label,
|
||||
labelWidthClassName = 'w-10',
|
||||
value,
|
||||
maskedValue,
|
||||
valueMaxWidthClassName = 'max-w-[162px]',
|
||||
}: Props) {
|
||||
const { t } = useTranslation(['common'])
|
||||
const [isCopied, setIsCopied] = useState(false)
|
||||
const labelId = useId()
|
||||
const handleCopy = useCallback(() => {
|
||||
copy(value)
|
||||
setIsCopied(true)
|
||||
}, [value])
|
||||
|
||||
useEffect(() => {
|
||||
if (isCopied) {
|
||||
const timer = setTimeout(() => {
|
||||
setIsCopied(false)
|
||||
}, 2000)
|
||||
return () => {
|
||||
clearTimeout(timer)
|
||||
}
|
||||
}
|
||||
}, [isCopied])
|
||||
|
||||
const copiedLabel = t(($) => $['operation.copied'], { ns: 'common' })
|
||||
const copyLabel = t(($) => $['operation.copy'], { ns: 'common' })
|
||||
const copyButtonLabel = `${copyLabel}: ${label}`
|
||||
const copyStatus = `${copiedLabel}: ${label}`
|
||||
const tooltipLabel = isCopied ? copiedLabel : copyLabel
|
||||
|
||||
return (
|
||||
<div role="group" aria-labelledby={labelId} className="flex items-center gap-1">
|
||||
<span
|
||||
id={labelId}
|
||||
className={cn(
|
||||
'flex flex-col items-start justify-center system-xs-medium text-text-tertiary',
|
||||
labelWidthClassName,
|
||||
)}
|
||||
>
|
||||
{label}
|
||||
</span>
|
||||
<div className="flex items-center justify-center gap-0.5">
|
||||
<span
|
||||
className={cn(valueMaxWidthClassName, 'truncate system-xs-medium text-text-secondary')}
|
||||
>
|
||||
{maskedValue || value}
|
||||
</span>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<IconButton aria-label={copyButtonLabel} onClick={handleCopy}>
|
||||
{isCopied ? (
|
||||
<span
|
||||
aria-hidden
|
||||
className="i-custom-vender-line-files-copy-check size-3.5 shrink-0 text-text-tertiary"
|
||||
/>
|
||||
) : (
|
||||
<span
|
||||
aria-hidden
|
||||
className="i-ri-clipboard-line size-3.5 shrink-0 text-text-tertiary"
|
||||
/>
|
||||
)}
|
||||
</IconButton>
|
||||
}
|
||||
/>
|
||||
<TooltipContent>{tooltipLabel}</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
<span role="status" aria-atomic="true" className="sr-only">
|
||||
{isCopied ? copyStatus : ''}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default KeyValueItem
|
||||
@@ -0,0 +1,25 @@
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { MARKETPLACE_API_PREFIX } from '@/features/marketplace/api'
|
||||
import { createMarketplacePluginFixture } from '@/test/fixtures/plugin'
|
||||
import Card from '../index'
|
||||
|
||||
it('renders a Marketplace card without workspace providers, even for a non-marketplace source', () => {
|
||||
const plugin = createMarketplacePluginFixture({
|
||||
org: 'langgenius',
|
||||
name: 'demo-plugin',
|
||||
from: 'github',
|
||||
label: { en_US: 'Marketplace plugin' },
|
||||
})
|
||||
|
||||
// Independent Marketplace has no Console Query or workspace provider.
|
||||
render(<Card payload={plugin} variant="marketplace" />)
|
||||
|
||||
expect(screen.getByText('Marketplace plugin')).toBeInTheDocument()
|
||||
expect(screen.getByRole('presentation')).toHaveAttribute(
|
||||
'src',
|
||||
`${MARKETPLACE_API_PREFIX}/plugins/langgenius/demo-plugin/icon`,
|
||||
)
|
||||
// This namespace is available on standalone Marketplace; tools.author is not.
|
||||
expect(screen.getByText('plugin.marketplace.by')).toBeInTheDocument()
|
||||
expect(screen.getByText('langgenius')).toBeInTheDocument()
|
||||
})
|
||||
@@ -0,0 +1,18 @@
|
||||
import { fireEvent, render, screen } from '@testing-library/react'
|
||||
import { describe, expect, it } from 'vite-plus/test'
|
||||
import Icon from '../card-icon'
|
||||
|
||||
describe('Plugin card icon', () => {
|
||||
it('lazy-loads URL icons and hides a failed image', () => {
|
||||
render(<Icon src="https://example.com/plugin-icon.png" />)
|
||||
|
||||
const image = screen.getByAltText('')
|
||||
|
||||
expect(image).toHaveAttribute('src', 'https://example.com/plugin-icon.png')
|
||||
expect(image).toHaveAttribute('loading', 'lazy')
|
||||
|
||||
fireEvent.error(image)
|
||||
|
||||
expect(image).not.toBeVisible()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,99 @@
|
||||
import { Avatar, AvatarFallback } from '@langgenius/dify-ui/avatar'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { RiCheckLine, RiCloseLine } from '@remixicon/react'
|
||||
import AppIcon from '@/app/components/base/app-icon'
|
||||
import { shouldUseMcpIcon } from '@/utils/mcp'
|
||||
|
||||
const iconSizeMap = {
|
||||
xs: 'w-4 h-4 text-base',
|
||||
tiny: 'w-6 h-6 text-base',
|
||||
small: 'w-8 h-8',
|
||||
medium: 'w-9 h-9',
|
||||
large: 'w-10 h-10',
|
||||
}
|
||||
|
||||
const iconPixelSizeMap = {
|
||||
xs: 16,
|
||||
tiny: 24,
|
||||
small: 32,
|
||||
medium: 36,
|
||||
large: 40,
|
||||
}
|
||||
|
||||
type IconSize = keyof typeof iconSizeMap
|
||||
|
||||
const Icon = ({
|
||||
className,
|
||||
src,
|
||||
installed = false,
|
||||
installFailed = false,
|
||||
size = 'large',
|
||||
}: {
|
||||
className?: string
|
||||
src:
|
||||
| string
|
||||
| {
|
||||
content: string
|
||||
background: string
|
||||
}
|
||||
installed?: boolean
|
||||
installFailed?: boolean
|
||||
size?: IconSize
|
||||
}) => {
|
||||
const iconClassName =
|
||||
'flex justify-center items-center gap-2 absolute bottom-[-4px] right-[-4px] w-[18px] h-[18px] rounded-full border-2 border-components-panel-bg'
|
||||
if (typeof src === 'object') {
|
||||
return (
|
||||
<div className={cn('relative', className)}>
|
||||
{shouldUseMcpIcon(src) ? (
|
||||
<Avatar
|
||||
aria-hidden="true"
|
||||
className={cn('rounded-md border-[0.5px] border-divider-regular', iconSizeMap[size])}
|
||||
>
|
||||
<AvatarFallback
|
||||
className="text-text-primary-on-surface"
|
||||
style={{ background: src.background || '#FFEAD5' }}
|
||||
>
|
||||
<span className="i-custom-vender-other-mcp size-8" />
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
) : (
|
||||
<AppIcon
|
||||
size={size}
|
||||
icon={{ icon_type: 'emoji', icon: src.content, icon_background: src.background }}
|
||||
className="rounded-md"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn('relative shrink-0 rounded-md', iconSizeMap[size], className)}>
|
||||
<img
|
||||
alt=""
|
||||
className="size-full rounded-md object-contain object-center"
|
||||
decoding="async"
|
||||
height={iconPixelSizeMap[size]}
|
||||
loading="lazy"
|
||||
src={src}
|
||||
width={iconPixelSizeMap[size]}
|
||||
onError={({ currentTarget }) => {
|
||||
currentTarget.style.display = 'none'
|
||||
}}
|
||||
/>
|
||||
{installed && (
|
||||
<div className={cn(iconClassName, 'bg-state-success-solid')}>
|
||||
<RiCheckLine className="size-3 text-text-primary-on-surface" />
|
||||
</div>
|
||||
)}
|
||||
{installFailed && (
|
||||
<div className={cn(iconClassName, 'bg-state-destructive-solid')}>
|
||||
<RiCloseLine className="size-3 text-text-primary-on-surface" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default Icon
|
||||
@@ -0,0 +1,17 @@
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
|
||||
const CornerMark = ({ className, text }: { className?: string; text: string }) => {
|
||||
return (
|
||||
<div className={cn('absolute top-0 right-0 flex pl-3.25', className)}>
|
||||
<span
|
||||
aria-hidden
|
||||
className="i-custom-vender-plugin-left-corner h-5 w-3.25 text-background-section"
|
||||
/>
|
||||
<div className="h-5 rounded-tr-xl bg-background-section pr-2 system-2xs-medium-uppercase leading-5 whitespace-nowrap text-text-tertiary">
|
||||
{text}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default CornerMark
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { FC } from 'react'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import * as React from 'react'
|
||||
import { useMemo } from 'react'
|
||||
|
||||
type Props = Readonly<{
|
||||
className?: string
|
||||
text: string
|
||||
descriptionLineRows: number
|
||||
}>
|
||||
|
||||
const Description: FC<Props> = ({ className, text, descriptionLineRows }) => {
|
||||
const lineClassName = useMemo(() => {
|
||||
if (descriptionLineRows === 1) return 'h-4 truncate'
|
||||
else if (descriptionLineRows === 2) return 'h-8 line-clamp-2'
|
||||
else return 'h-12 line-clamp-3'
|
||||
}, [descriptionLineRows])
|
||||
return (
|
||||
<div
|
||||
className={cn('system-xs-regular text-text-tertiary', lineClassName, className)}
|
||||
title={text}
|
||||
>
|
||||
{text}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default Description
|
||||
@@ -0,0 +1,21 @@
|
||||
import { RiInstallLine } from '@remixicon/react'
|
||||
import * as React from 'react'
|
||||
import { formatNumber } from '@/utils/format'
|
||||
|
||||
type Props = Readonly<{
|
||||
downloadCount: number
|
||||
}>
|
||||
|
||||
const DownloadCountComponent = ({ downloadCount }: Props) => {
|
||||
return (
|
||||
<div className="flex items-center space-x-1 text-text-tertiary">
|
||||
<RiInstallLine className="size-3 shrink-0" />
|
||||
<div className="system-xs-regular">{formatNumber(downloadCount)}</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Memoize to prevent unnecessary re-renders
|
||||
const DownloadCount = React.memo(DownloadCountComponent)
|
||||
|
||||
export default DownloadCount
|
||||
@@ -0,0 +1,37 @@
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
|
||||
type Props = Readonly<{
|
||||
className?: string
|
||||
orgName?: string
|
||||
packageName: string
|
||||
packageNameClassName?: string
|
||||
}>
|
||||
|
||||
const OrgInfo = ({ className, orgName, packageName, packageNameClassName }: Props) => {
|
||||
return (
|
||||
<div className={cn('flex h-4 min-w-0 items-center gap-0.5', className)}>
|
||||
{orgName && (
|
||||
<>
|
||||
<span
|
||||
className="min-w-0 shrink truncate system-xs-regular text-text-tertiary"
|
||||
title={orgName}
|
||||
>
|
||||
{orgName}
|
||||
</span>
|
||||
<span className="shrink-0 system-xs-regular text-text-quaternary">/</span>
|
||||
</>
|
||||
)}
|
||||
<span
|
||||
className={cn(
|
||||
'min-w-0 shrink truncate system-xs-regular text-text-tertiary',
|
||||
packageNameClassName,
|
||||
)}
|
||||
title={packageName}
|
||||
>
|
||||
{packageName}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default OrgInfo
|
||||
@@ -0,0 +1,53 @@
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import {
|
||||
SkeletonContainer,
|
||||
SkeletonPoint,
|
||||
SkeletonRectangle,
|
||||
SkeletonRow,
|
||||
} from '@/app/components/base/skeleton'
|
||||
import Title from './title'
|
||||
|
||||
type Props = Readonly<{
|
||||
wrapClassName: string
|
||||
loadingFileName?: string
|
||||
}>
|
||||
|
||||
export const LoadingPlaceholder = ({ className }: { className?: string }) => (
|
||||
<div className={cn('h-2 rounded-xs bg-text-quaternary opacity-20', className)} />
|
||||
)
|
||||
|
||||
const Placeholder = ({ wrapClassName, loadingFileName }: Props) => {
|
||||
return (
|
||||
<div className={cn(wrapClassName, 'p-3')}>
|
||||
<SkeletonRow>
|
||||
<div className="flex h-10 w-10 items-center justify-center gap-2 rounded-[10px] border-[0.5px] border-components-panel-border bg-background-default p-1 backdrop-blur-xs">
|
||||
<div className="flex size-5 items-center justify-center">
|
||||
<span
|
||||
aria-hidden
|
||||
className="i-custom-vender-other-group h-4 w-3.5 text-text-tertiary"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grow">
|
||||
<SkeletonContainer>
|
||||
<div className="flex h-5 items-center">
|
||||
{loadingFileName ? (
|
||||
<Title title={loadingFileName} />
|
||||
) : (
|
||||
<SkeletonRectangle className="w-65" />
|
||||
)}
|
||||
</div>
|
||||
<SkeletonRow className="h-4">
|
||||
<SkeletonRectangle className="w-10.25" />
|
||||
<SkeletonPoint />
|
||||
<SkeletonRectangle className="w-45" />
|
||||
</SkeletonRow>
|
||||
</SkeletonContainer>
|
||||
</div>
|
||||
</SkeletonRow>
|
||||
<SkeletonRectangle className="mt-3 w-105" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default Placeholder
|
||||
@@ -0,0 +1,9 @@
|
||||
const Title = ({ title }: { title: string }) => {
|
||||
return (
|
||||
<div className="truncate system-md-semibold text-text-secondary" title={title}>
|
||||
{title}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default Title
|
||||
@@ -0,0 +1,59 @@
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import * as React from 'react'
|
||||
import DownloadCount from './base/download-count'
|
||||
|
||||
type Props = Readonly<{
|
||||
downloadCount?: number
|
||||
tags: string[]
|
||||
variant?: 'default' | 'marketplace'
|
||||
}>
|
||||
|
||||
const CardMoreInfoComponent = ({ downloadCount, tags, variant = 'default' }: Props) => {
|
||||
if (variant === 'marketplace') {
|
||||
return (
|
||||
<div className="flex min-h-7 items-center py-1">
|
||||
<div className="flex min-w-0 flex-1 flex-wrap items-center gap-1 overflow-hidden">
|
||||
{tags.map((tag) => (
|
||||
<div
|
||||
key={tag}
|
||||
className={cn(
|
||||
'flex max-w-30 min-w-4.5 shrink-0 items-center justify-center gap-0.5 overflow-hidden rounded-[5px]',
|
||||
'border border-divider-deep bg-components-badge-bg-dimm px-1.25 py-0.75',
|
||||
'system-2xs-medium-uppercase text-text-tertiary',
|
||||
)}
|
||||
>
|
||||
<span className="i-ri-price-tag-3-line h-3 w-3 shrink-0 text-text-quaternary" />
|
||||
<span className="truncate">{tag}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-5 items-center">
|
||||
{downloadCount !== undefined && <DownloadCount downloadCount={downloadCount} />}
|
||||
{downloadCount !== undefined && tags && tags.length > 0 && (
|
||||
<div className="mx-2 system-xs-regular text-text-quaternary">·</div>
|
||||
)}
|
||||
{tags && tags.length > 0 && (
|
||||
<>
|
||||
<div className="flex h-4 flex-wrap space-x-2 overflow-hidden">
|
||||
{tags.map((tag) => (
|
||||
<div key={tag} className="flex max-w-30 space-x-1 overflow-hidden system-xs-regular">
|
||||
<span className="text-text-quaternary">#</span>
|
||||
<span className="truncate text-text-tertiary">{tag}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Memoize to prevent unnecessary re-renders when tags array hasn't changed
|
||||
const CardMoreInfo = React.memo(CardMoreInfoComponent)
|
||||
|
||||
export default CardMoreInfo
|
||||
@@ -0,0 +1,236 @@
|
||||
'use client'
|
||||
import type { Plugin } from '../types'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { useAtomValue } from 'jotai'
|
||||
import * as React from 'react'
|
||||
import { useTranslation } from '#i18n'
|
||||
import { useGetLanguage } from '@/context/i18n'
|
||||
import { currentWorkspaceIdAtom } from '@/context/workspace-state'
|
||||
import useTheme from '@/hooks/use-theme'
|
||||
import { renderI18nObject } from '@/i18n/metadata'
|
||||
import { Theme } from '@/types/app'
|
||||
import { formatNumber } from '@/utils/format'
|
||||
import Partner from '../base/badges/partner'
|
||||
import Verified from '../base/badges/verified'
|
||||
import Icon from '../card/base/card-icon'
|
||||
import { useCategories } from '../hooks'
|
||||
import { getPluginCardIconUrl } from '../utils'
|
||||
import CornerMark from './base/corner-mark'
|
||||
import Description from './base/description'
|
||||
import OrgInfo from './base/org-info'
|
||||
import Placeholder from './base/placeholder'
|
||||
import Title from './base/title'
|
||||
|
||||
export type CardPayload = Omit<Plugin, 'icon' | 'icon_dark'> & {
|
||||
icon: string | { content: string; background: string }
|
||||
icon_dark?: string | { content: string; background: string }
|
||||
}
|
||||
|
||||
type Props = Readonly<{
|
||||
className?: string
|
||||
payload: CardPayload
|
||||
titleLeft?: React.ReactNode
|
||||
installed?: boolean
|
||||
installFailed?: boolean
|
||||
hideCornerMark?: boolean
|
||||
descriptionLineRows?: number
|
||||
footer?: React.ReactNode
|
||||
isLoading?: boolean
|
||||
loadingFileName?: string
|
||||
limitedInstall?: boolean
|
||||
compact?: boolean
|
||||
variant?: 'default' | 'marketplace'
|
||||
}>
|
||||
|
||||
type CardIconProps = {
|
||||
icon: CardPayload['icon']
|
||||
installFailed?: boolean
|
||||
installed?: boolean
|
||||
marketplace?: boolean
|
||||
plugin: Pick<Plugin, 'from' | 'name' | 'org' | 'type'>
|
||||
}
|
||||
|
||||
const WorkspaceCardIcon = ({ icon, installFailed, installed, plugin }: CardIconProps) => {
|
||||
const currentWorkspaceId = useAtomValue(currentWorkspaceIdAtom)
|
||||
const iconSrc = getPluginCardIconUrl(plugin, icon, currentWorkspaceId)
|
||||
|
||||
return <Icon src={iconSrc} installed={installed} installFailed={installFailed} />
|
||||
}
|
||||
|
||||
const CardIcon = ({ icon, installFailed, installed, marketplace, plugin }: CardIconProps) => {
|
||||
if (marketplace || plugin.from === 'marketplace') {
|
||||
const iconSrc = getPluginCardIconUrl({ ...plugin, from: 'marketplace' }, icon, '')
|
||||
return <Icon src={iconSrc} installed={installed} installFailed={installFailed} />
|
||||
}
|
||||
|
||||
return (
|
||||
<WorkspaceCardIcon
|
||||
icon={icon}
|
||||
installFailed={installFailed}
|
||||
installed={installed}
|
||||
plugin={plugin}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const Card = ({
|
||||
className,
|
||||
payload,
|
||||
titleLeft,
|
||||
installed,
|
||||
installFailed,
|
||||
hideCornerMark,
|
||||
descriptionLineRows,
|
||||
footer,
|
||||
isLoading = false,
|
||||
loadingFileName,
|
||||
limitedInstall = false,
|
||||
compact = false,
|
||||
variant = 'default',
|
||||
}: Props) => {
|
||||
const locale = useGetLanguage()
|
||||
const { t } = useTranslation(['plugin'])
|
||||
const { categoriesMap } = useCategories(true)
|
||||
const { category, type, name, org, label, brief, icon, icon_dark, verified, from } = payload
|
||||
const badges = payload.badges ?? []
|
||||
const { theme } = useTheme()
|
||||
const activeIcon = theme === Theme.dark && icon_dark ? icon_dark : icon
|
||||
const pluginIdentity = { from, name, org, type }
|
||||
const getLocalizedText = (obj: Record<string, string> | undefined) =>
|
||||
obj ? renderI18nObject(obj, locale) : ''
|
||||
const isPartner = badges.includes('partner')
|
||||
const effectiveDescriptionLineRows = descriptionLineRows ?? (compact ? 1 : 2)
|
||||
const isMarketplaceVariant = variant === 'marketplace'
|
||||
const cornerMarkText = categoriesMap[type === 'bundle' ? type : category]?.label ?? ''
|
||||
|
||||
const wrapClassName = cn(
|
||||
'hover-bg-components-panel-on-panel-item-bg relative overflow-hidden rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg shadow-xs',
|
||||
isMarketplaceVariant &&
|
||||
'h-37 transition-all group-hover:bg-components-panel-on-panel-item-bg-hover group-hover:shadow-md',
|
||||
className,
|
||||
)
|
||||
if (isLoading) {
|
||||
return <Placeholder wrapClassName={wrapClassName} loadingFileName={loadingFileName!} />
|
||||
}
|
||||
|
||||
if (isMarketplaceVariant) {
|
||||
return (
|
||||
<div className={wrapClassName}>
|
||||
<div className="relative flex h-full flex-col">
|
||||
{!hideCornerMark && <CornerMark text={cornerMarkText} />}
|
||||
<div className="flex items-center gap-3 px-4 pt-4 pb-2">
|
||||
<CardIcon
|
||||
icon={activeIcon}
|
||||
installed={installed}
|
||||
installFailed={installFailed}
|
||||
marketplace
|
||||
plugin={pluginIdentity}
|
||||
/>
|
||||
<div className="flex min-w-0 flex-1 flex-col justify-center gap-0.5">
|
||||
<div className="flex h-5 min-w-0 items-center">
|
||||
<div className="truncate system-md-medium text-text-primary">
|
||||
{getLocalizedText(label)}
|
||||
</div>
|
||||
{isPartner && (
|
||||
<Partner
|
||||
className="ml-0.5 size-4"
|
||||
text={t(($) => $['marketplace.partnerTip'], { ns: 'plugin' })}
|
||||
/>
|
||||
)}
|
||||
{verified && (
|
||||
<Verified
|
||||
className="ml-0.5 size-4"
|
||||
text={t(($) => $['marketplace.verifiedTip'], { ns: 'plugin' })}
|
||||
/>
|
||||
)}
|
||||
{titleLeft}
|
||||
</div>
|
||||
<div className="flex h-4 min-w-0 items-center gap-2 system-xs-regular text-text-tertiary">
|
||||
{org && (
|
||||
<div className="flex min-w-0 items-center gap-1">
|
||||
<span className="shrink-0 lowercase">
|
||||
{t(($) => $['marketplace.by'], { ns: 'plugin' })}
|
||||
</span>
|
||||
<span className="truncate">{org}</span>
|
||||
</div>
|
||||
)}
|
||||
{org && payload.install_count !== undefined && (
|
||||
<span className="shrink-0 text-text-quaternary">·</span>
|
||||
)}
|
||||
{payload.install_count !== undefined && (
|
||||
<span className="shrink-0">
|
||||
{t(($) => $.install, {
|
||||
ns: 'plugin',
|
||||
num: formatNumber(payload.install_count),
|
||||
})}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<Description
|
||||
className="mx-4 mt-1 text-text-secondary"
|
||||
text={getLocalizedText(brief)}
|
||||
descriptionLineRows={effectiveDescriptionLineRows}
|
||||
/>
|
||||
{!!footer && <div className="px-4 pt-2 pr-5">{footer}</div>}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={wrapClassName}>
|
||||
<div className={cn(compact ? 'p-3 pb-2' : 'p-4 pb-3', limitedInstall && 'pb-1')}>
|
||||
{!hideCornerMark && <CornerMark text={cornerMarkText} />}
|
||||
{/* Header */}
|
||||
<div className="flex">
|
||||
<CardIcon
|
||||
icon={activeIcon}
|
||||
installed={installed}
|
||||
installFailed={installFailed}
|
||||
plugin={pluginIdentity}
|
||||
/>
|
||||
<div className="ml-3 w-0 grow">
|
||||
<div className="flex h-5 items-center">
|
||||
<Title title={getLocalizedText(label)} />
|
||||
{isPartner && (
|
||||
<Partner
|
||||
className="ml-0.5 size-4"
|
||||
text={t(($) => $['marketplace.partnerTip'], { ns: 'plugin' })}
|
||||
/>
|
||||
)}
|
||||
{verified && (
|
||||
<Verified
|
||||
className="ml-0.5 size-4"
|
||||
text={t(($) => $['marketplace.verifiedTip'], { ns: 'plugin' })}
|
||||
/>
|
||||
)}
|
||||
{titleLeft} {/* This can be version badge */}
|
||||
</div>
|
||||
<OrgInfo className="mt-0.5" orgName={org} packageName={name} />
|
||||
</div>
|
||||
</div>
|
||||
<Description
|
||||
className={compact ? 'mt-1' : 'mt-3'}
|
||||
text={getLocalizedText(brief)}
|
||||
descriptionLineRows={effectiveDescriptionLineRows}
|
||||
/>
|
||||
{!!footer && <div>{footer}</div>}
|
||||
</div>
|
||||
{limitedInstall && (
|
||||
<div className="relative flex h-8 items-center gap-x-2 px-3 after:absolute after:inset-0 after:bg-toast-warning-bg after:opacity-40">
|
||||
<span
|
||||
aria-hidden
|
||||
className="i-ri-alert-fill size-3 shrink-0 text-text-warning-secondary"
|
||||
/>
|
||||
<p className="z-10 grow system-xs-regular text-text-secondary">
|
||||
{t(($) => $['installModal.installWarning'], { ns: 'plugin' })}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default React.memo(Card)
|
||||
@@ -0,0 +1,36 @@
|
||||
import { PluginCategoryEnum } from './types'
|
||||
|
||||
export const tagKeys = [
|
||||
'agent',
|
||||
'rag',
|
||||
'search',
|
||||
'image',
|
||||
'videos',
|
||||
'weather',
|
||||
'finance',
|
||||
'design',
|
||||
'travel',
|
||||
'social',
|
||||
'news',
|
||||
'medical',
|
||||
'productivity',
|
||||
'education',
|
||||
'business',
|
||||
'entertainment',
|
||||
'utilities',
|
||||
'other',
|
||||
] as const
|
||||
|
||||
export type TagKey = (typeof tagKeys)[number]
|
||||
|
||||
export const categoryKeys = [
|
||||
PluginCategoryEnum.model,
|
||||
PluginCategoryEnum.tool,
|
||||
PluginCategoryEnum.datasource,
|
||||
PluginCategoryEnum.agent,
|
||||
PluginCategoryEnum.extension,
|
||||
'bundle',
|
||||
PluginCategoryEnum.trigger,
|
||||
] as const
|
||||
|
||||
export type CategoryKey = (typeof categoryKeys)[number]
|
||||
@@ -0,0 +1,148 @@
|
||||
import type { CategoryKey, TagKey } from './constants'
|
||||
import type { PluginDetail } from './types'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { useMemo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { consoleQuery } from '@/service/console'
|
||||
import { categoryKeys, tagKeys } from './constants'
|
||||
import { PluginCategoryEnum, PluginSource } from './types'
|
||||
|
||||
export type Tag = {
|
||||
name: TagKey
|
||||
label: string
|
||||
}
|
||||
|
||||
export const useTags = () => {
|
||||
const { t } = useTranslation(['pluginTags'])
|
||||
|
||||
const tags = useMemo(() => {
|
||||
return tagKeys.map((tag) => {
|
||||
return {
|
||||
name: tag,
|
||||
label: t(($) => $[`tags.${tag}`], { ns: 'pluginTags' }),
|
||||
}
|
||||
})
|
||||
}, [t])
|
||||
|
||||
const tagsMap = useMemo(() => {
|
||||
return tags.reduce(
|
||||
(acc, tag) => {
|
||||
acc[tag.name] = tag
|
||||
return acc
|
||||
},
|
||||
{} as Record<string, Tag>,
|
||||
)
|
||||
}, [tags])
|
||||
|
||||
const getTagLabel = useMemo(() => {
|
||||
return (name: string) => {
|
||||
if (!tagsMap[name]) return name
|
||||
return tagsMap[name].label
|
||||
}
|
||||
}, [tagsMap])
|
||||
|
||||
return {
|
||||
tags,
|
||||
tagsMap,
|
||||
getTagLabel,
|
||||
}
|
||||
}
|
||||
|
||||
type Category = {
|
||||
name: CategoryKey
|
||||
label: string
|
||||
}
|
||||
|
||||
export const useCategories = (isSingle?: boolean) => {
|
||||
const { t } = useTranslation(['plugin'])
|
||||
|
||||
const categories = useMemo(() => {
|
||||
return categoryKeys.map((category) => {
|
||||
if (category === PluginCategoryEnum.agent) {
|
||||
return {
|
||||
name: PluginCategoryEnum.agent,
|
||||
label: isSingle
|
||||
? t(($) => $['categorySingle.agent'], { ns: 'plugin' })
|
||||
: t(($) => $['category.agents'], { ns: 'plugin' }),
|
||||
}
|
||||
}
|
||||
return {
|
||||
name: category,
|
||||
label: isSingle
|
||||
? t(($) => $[`categorySingle.${category}`], { ns: 'plugin' })
|
||||
: t(($) => $[`category.${category}s`], { ns: 'plugin' }),
|
||||
}
|
||||
})
|
||||
}, [t, isSingle])
|
||||
|
||||
const categoriesMap = useMemo(() => {
|
||||
return categories.reduce(
|
||||
(acc, category) => {
|
||||
acc[category.name] = category
|
||||
return acc
|
||||
},
|
||||
{} as Record<string, Category>,
|
||||
)
|
||||
}, [categories])
|
||||
|
||||
return {
|
||||
categories,
|
||||
categoriesMap,
|
||||
}
|
||||
}
|
||||
|
||||
export const PLUGIN_PAGE_TABS_MAP = {
|
||||
plugins: 'plugins',
|
||||
marketplace: 'discover',
|
||||
}
|
||||
|
||||
export const usePluginPageTabs = () => {
|
||||
const { t } = useTranslation(['navigation'])
|
||||
const tabs = [
|
||||
{
|
||||
value: PLUGIN_PAGE_TABS_MAP.plugins,
|
||||
text: t(($) => $['menus.plugins'], { ns: 'navigation' }),
|
||||
},
|
||||
{
|
||||
value: PLUGIN_PAGE_TABS_MAP.marketplace,
|
||||
text: t(($) => $['menus.exploreMarketplace'], { ns: 'navigation' }),
|
||||
},
|
||||
]
|
||||
return tabs
|
||||
}
|
||||
|
||||
const EMPTY_PLUGINS: PluginDetail[] = []
|
||||
|
||||
export function usePluginsWithLatestVersion(
|
||||
plugins: PluginDetail[] = EMPTY_PLUGINS,
|
||||
): PluginDetail[] {
|
||||
const marketplacePluginIds = useMemo(
|
||||
() => plugins.filter((p) => p.source === PluginSource.marketplace).map((p) => p.plugin_id),
|
||||
[plugins],
|
||||
)
|
||||
|
||||
const { data: latestVersionData } = useQuery(
|
||||
consoleQuery.workspaces.current.plugin.list.latestVersions.post.queryOptions({
|
||||
input: { body: { plugin_ids: marketplacePluginIds } },
|
||||
enabled: !!marketplacePluginIds.length,
|
||||
}),
|
||||
)
|
||||
|
||||
return useMemo(() => {
|
||||
const versions = latestVersionData?.versions
|
||||
if (!versions) return plugins
|
||||
|
||||
return plugins.map((plugin) => {
|
||||
const info = versions[plugin.plugin_id]
|
||||
if (!info) return plugin
|
||||
return {
|
||||
...plugin,
|
||||
latest_version: info.version,
|
||||
latest_unique_identifier: info.unique_identifier,
|
||||
status: info.status,
|
||||
deprecated_reason: info.deprecated_reason,
|
||||
alternative_plugin_id: info.alternative_plugin_id,
|
||||
}
|
||||
})
|
||||
}, [plugins, latestVersionData])
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
|
||||
import { checkForUpdates, fetchReleases } from '../hooks'
|
||||
|
||||
const { mockToastError } = vi.hoisted(() => ({
|
||||
mockToastError: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/app/notifications', () => ({
|
||||
toast: {
|
||||
error: mockToastError,
|
||||
},
|
||||
}))
|
||||
|
||||
const mockFetch = vi.fn<typeof fetch>()
|
||||
|
||||
describe('install-plugin/hooks', () => {
|
||||
beforeEach(() => {
|
||||
mockFetch.mockReset()
|
||||
mockToastError.mockReset()
|
||||
vi.stubGlobal('fetch', mockFetch)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
describe('fetchReleases', () => {
|
||||
it('leaves failed responses to the business caller', async () => {
|
||||
mockFetch.mockResolvedValue(new Response(null, { status: 500 }))
|
||||
|
||||
await expect(fetchReleases('owner', 'repo')).rejects.toThrow(
|
||||
'Failed to fetch repository releases',
|
||||
)
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledOnce()
|
||||
expect(mockFetch).toHaveBeenCalledWith('https://ungh.cc/repos/owner/repo/releases')
|
||||
expect(mockToastError).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('checkForUpdates', () => {
|
||||
it('detects newer version available', () => {
|
||||
const releases = [
|
||||
{ tag_name: 'v1.0.0', assets: [] },
|
||||
{ tag_name: 'v2.0.0', assets: [] },
|
||||
]
|
||||
const { needUpdate, toastProps } = checkForUpdates(releases, 'v1.0.0')
|
||||
|
||||
expect(needUpdate).toBe(true)
|
||||
expect(toastProps.message).toContain('v2.0.0')
|
||||
})
|
||||
|
||||
it('returns no update when current is latest', () => {
|
||||
const releases = [{ tag_name: 'v1.0.0', assets: [] }]
|
||||
const { needUpdate, toastProps } = checkForUpdates(releases, 'v1.0.0')
|
||||
|
||||
expect(needUpdate).toBe(false)
|
||||
expect(toastProps.type).toBe('info')
|
||||
})
|
||||
|
||||
it('returns error for empty releases', () => {
|
||||
const { needUpdate, toastProps } = checkForUpdates([], 'v1.0.0')
|
||||
|
||||
expect(needUpdate).toBe(false)
|
||||
expect(toastProps.type).toBe('error')
|
||||
expect(toastProps.message).toContain('empty')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,217 @@
|
||||
import type { PluginDeclaration, PluginManifestInMarket } from '../../types'
|
||||
import { describe, expect, it } from 'vite-plus/test'
|
||||
import { PluginCategoryEnum } from '../../types'
|
||||
import {
|
||||
convertRepoToUrl,
|
||||
parseGitHubUrl,
|
||||
pluginDeclarationToCardPluginProps,
|
||||
pluginManifestInMarketToPluginProps,
|
||||
pluginManifestToCardPluginProps,
|
||||
toPluginText,
|
||||
} from '../utils'
|
||||
|
||||
describe('pluginManifestToCardPluginProps', () => {
|
||||
const createMockPluginDeclaration = (
|
||||
overrides?: Partial<PluginDeclaration>,
|
||||
): PluginDeclaration => ({
|
||||
plugin_unique_identifier: 'test-plugin-123',
|
||||
version: '1.0.0',
|
||||
author: 'test-author',
|
||||
icon: '/test-icon.png',
|
||||
name: 'test-plugin',
|
||||
category: PluginCategoryEnum.tool,
|
||||
label: { 'en-US': 'Test Plugin' } as Record<string, string>,
|
||||
description: { 'en-US': 'Test description' } as Record<string, string>,
|
||||
created_at: '2024-01-01',
|
||||
resource: {},
|
||||
plugins: {},
|
||||
verified: true,
|
||||
endpoint: { settings: [], endpoints: [] },
|
||||
model: {},
|
||||
tags: ['search', 'api'],
|
||||
agent_strategy: null,
|
||||
meta: { version: '1.0.0' },
|
||||
trigger: {} as PluginDeclaration['trigger'],
|
||||
...overrides,
|
||||
})
|
||||
|
||||
it('converts a package manifest into its card identity and metadata', () => {
|
||||
const manifest = createMockPluginDeclaration({
|
||||
category: PluginCategoryEnum.model,
|
||||
label: {
|
||||
...createMockPluginDeclaration().label,
|
||||
'en-US': 'My Plugin',
|
||||
'zh-Hans': '我的插件',
|
||||
},
|
||||
icon_dark: '/dark-icon.png',
|
||||
})
|
||||
expect(pluginManifestToCardPluginProps(manifest)).toEqual({
|
||||
plugin_id: 'test-plugin-123',
|
||||
type: PluginCategoryEnum.model,
|
||||
category: PluginCategoryEnum.model,
|
||||
name: 'test-plugin',
|
||||
version: '1.0.0',
|
||||
org: 'test-author',
|
||||
author: 'test-author',
|
||||
label: { 'en-US': 'My Plugin', 'zh-Hans': '我的插件' },
|
||||
brief: { 'en-US': 'Test description' },
|
||||
description: { 'en-US': 'Test description' },
|
||||
icon: '/test-icon.png',
|
||||
icon_dark: '/dark-icon.png',
|
||||
verified: true,
|
||||
latest_version: '',
|
||||
latest_package_identifier: '',
|
||||
introduction: '',
|
||||
repository: '',
|
||||
install_count: 0,
|
||||
endpoint: { settings: [] },
|
||||
tags: [{ name: 'search' }, { name: 'api' }],
|
||||
badges: [],
|
||||
verification: { authorized_category: 'langgenius' },
|
||||
from: 'package',
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps untagged package manifests untagged', () => {
|
||||
expect(pluginManifestToCardPluginProps(createMockPluginDeclaration({ tags: [] })).tags).toEqual(
|
||||
[],
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('pluginDeclarationToCardPluginProps', () => {
|
||||
const manifest = {
|
||||
author: null,
|
||||
category: 'agent-strategy',
|
||||
created_at: '2026-01-01T00:00:00Z',
|
||||
description: { en_US: 'Description', zh_Hans: null },
|
||||
icon: 'icon.svg',
|
||||
label: { en_US: 'Agent', zh_Hans: '代理' },
|
||||
meta: { minimum_dify_version: null, version: '0.0.1' },
|
||||
name: 'agent',
|
||||
plugins: {},
|
||||
resource: { memory: 0 },
|
||||
version: '1.0.0',
|
||||
} satisfies Parameters<typeof pluginDeclarationToCardPluginProps>[0]
|
||||
|
||||
it('reads the uploaded package as a card', () => {
|
||||
expect(
|
||||
pluginDeclarationToCardPluginProps(manifest, 'langgenius/agent:1.0.0@hash'),
|
||||
).toMatchObject({
|
||||
plugin_id: 'langgenius/agent:1.0.0@hash',
|
||||
type: 'agent_strategy',
|
||||
category: 'agent-strategy',
|
||||
org: '',
|
||||
author: undefined,
|
||||
label: { en_US: 'Agent', zh_Hans: '代理' },
|
||||
description: { en_US: 'Description' },
|
||||
verified: false,
|
||||
tags: [],
|
||||
})
|
||||
})
|
||||
|
||||
it('leaves untranslated locales out of card text', () => {
|
||||
expect(toPluginText({ en_US: 'Name', ja_JP: null, pt_BR: 'Nome' })).toEqual({
|
||||
en_US: 'Name',
|
||||
pt_BR: 'Nome',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('pluginManifestInMarketToPluginProps', () => {
|
||||
const createMockPluginManifestInMarket = (
|
||||
overrides?: Partial<PluginManifestInMarket>,
|
||||
): PluginManifestInMarket => ({
|
||||
plugin_unique_identifier: 'market-plugin-123',
|
||||
name: 'market-plugin',
|
||||
org: 'market-org',
|
||||
icon: '/market-icon.png',
|
||||
label: { 'en-US': 'Market Plugin' } as Record<string, string>,
|
||||
category: PluginCategoryEnum.tool,
|
||||
version: '1.0.0',
|
||||
latest_version: '1.2.0',
|
||||
brief: { 'en-US': 'Market plugin description' } as Record<string, string>,
|
||||
introduction: 'Full introduction text',
|
||||
verified: true,
|
||||
install_count: 5000,
|
||||
badges: ['partner', 'verified'],
|
||||
verification: { authorized_category: 'langgenius' },
|
||||
from: 'marketplace',
|
||||
...overrides,
|
||||
})
|
||||
|
||||
it('uses the latest marketplace version and marketplace metadata for the card', () => {
|
||||
const manifest = createMockPluginManifestInMarket({ category: PluginCategoryEnum.model })
|
||||
expect(pluginManifestInMarketToPluginProps(manifest)).toEqual({
|
||||
plugin_id: 'market-plugin-123',
|
||||
type: PluginCategoryEnum.model,
|
||||
category: PluginCategoryEnum.model,
|
||||
name: 'market-plugin',
|
||||
version: '1.2.0',
|
||||
latest_version: '1.2.0',
|
||||
org: 'market-org',
|
||||
label: { 'en-US': 'Market Plugin' },
|
||||
brief: { 'en-US': 'Market plugin description' },
|
||||
description: { 'en-US': 'Market plugin description' },
|
||||
icon: '/market-icon.png',
|
||||
verified: true,
|
||||
introduction: 'Full introduction text',
|
||||
latest_package_identifier: '',
|
||||
repository: '',
|
||||
install_count: 0,
|
||||
tags: [],
|
||||
endpoint: { settings: [] },
|
||||
badges: ['partner', 'verified'],
|
||||
verification: { authorized_category: 'langgenius' },
|
||||
from: 'marketplace',
|
||||
})
|
||||
})
|
||||
|
||||
it.each([
|
||||
[{ authorized_category: 'partner' }, { authorized_category: 'partner' }],
|
||||
[{}, { authorized_category: 'langgenius' }],
|
||||
])('normalizes marketplace verification %j', (verification, expected) => {
|
||||
expect(
|
||||
pluginManifestInMarketToPluginProps(
|
||||
createMockPluginManifestInMarket({
|
||||
verification: verification as PluginManifestInMarket['verification'],
|
||||
from: 'github',
|
||||
}),
|
||||
),
|
||||
).toMatchObject({ verification: expected, from: 'github' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('parseGitHubUrl', () => {
|
||||
it.each([
|
||||
['https://github.com/owner/repo', 'owner', 'repo'],
|
||||
['https://github.com/owner/repo/', 'owner', 'repo'],
|
||||
['https://github.com/my-org/my_repo123', 'my-org', 'my_repo123'],
|
||||
])('parses %s', (url, owner, repo) => {
|
||||
expect(parseGitHubUrl(url)).toEqual({ isValid: true, owner, repo })
|
||||
})
|
||||
|
||||
it.each([
|
||||
'https://gitlab.com/owner/repo',
|
||||
'https://github.com/owner/repo/tree/main',
|
||||
'https://github.com/owner',
|
||||
'',
|
||||
'not-a-url',
|
||||
'http://github.com/owner/repo',
|
||||
'https://www.github.com/owner/repo',
|
||||
])('rejects %s', (url) => {
|
||||
expect(parseGitHubUrl(url)).toEqual({ isValid: false })
|
||||
})
|
||||
})
|
||||
|
||||
describe('convertRepoToUrl', () => {
|
||||
it.each([
|
||||
[
|
||||
'organization_name/repository-name.js',
|
||||
'https://github.com/organization_name/repository-name.js',
|
||||
],
|
||||
['', ''],
|
||||
])('converts %s to its repository URL', (repo, expected) => {
|
||||
expect(convertRepoToUrl(repo)).toBe(expected)
|
||||
})
|
||||
})
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
|
||||
import { TaskStatus } from '../../../types'
|
||||
import checkTaskStatus from '../check-task-status'
|
||||
|
||||
const { fetchTask } = vi.hoisted(() => ({ fetchTask: vi.fn() }))
|
||||
vi.mock('@/service/plugins', () => ({ checkTaskStatus: fetchTask }))
|
||||
|
||||
const task = (status: TaskStatus) => ({
|
||||
task: {
|
||||
plugins: [
|
||||
{
|
||||
plugin_unique_identifier: 'other-plugin',
|
||||
status: TaskStatus.failed,
|
||||
message: 'Unrelated failure',
|
||||
},
|
||||
{ plugin_unique_identifier: 'test-plugin', status, message: '' },
|
||||
],
|
||||
},
|
||||
})
|
||||
const params = { taskId: 'task-1', pluginUniqueIdentifier: 'test-plugin' }
|
||||
|
||||
describe('checkTaskStatus', () => {
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks()
|
||||
vi.useFakeTimers()
|
||||
})
|
||||
|
||||
afterEach(() => vi.useRealTimers())
|
||||
|
||||
it('fails when the requested package is absent from the task', async () => {
|
||||
fetchTask.mockResolvedValue({
|
||||
task: { plugins: [{ plugin_unique_identifier: 'other-plugin', status: TaskStatus.success }] },
|
||||
})
|
||||
|
||||
await expect(checkTaskStatus().check(params)).resolves.toEqual({
|
||||
status: TaskStatus.failed,
|
||||
error: 'Plugin package not found',
|
||||
})
|
||||
})
|
||||
|
||||
it('follows the requested package through pending and running until success', async () => {
|
||||
fetchTask
|
||||
.mockResolvedValueOnce(task(TaskStatus.pending))
|
||||
.mockResolvedValueOnce(task(TaskStatus.running))
|
||||
.mockResolvedValueOnce(task(TaskStatus.success))
|
||||
const completed = vi.fn()
|
||||
const result = checkTaskStatus().check(params).then(completed)
|
||||
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(fetchTask).toHaveBeenCalledExactlyOnceWith('task-1')
|
||||
expect(completed).not.toHaveBeenCalled()
|
||||
await vi.advanceTimersByTimeAsync(10_000)
|
||||
expect(fetchTask).toHaveBeenCalledTimes(2)
|
||||
expect(completed).not.toHaveBeenCalled()
|
||||
await vi.advanceTimersByTimeAsync(10_000)
|
||||
await result
|
||||
expect(fetchTask).toHaveBeenNthCalledWith(3, 'task-1')
|
||||
expect(completed).toHaveBeenCalledExactlyOnceWith({ status: TaskStatus.success })
|
||||
})
|
||||
|
||||
it('stops one checker before its first request without stopping another installation', async () => {
|
||||
fetchTask.mockResolvedValue(task(TaskStatus.success))
|
||||
const stopped = checkTaskStatus()
|
||||
const active = checkTaskStatus()
|
||||
stopped.stop()
|
||||
|
||||
await expect(stopped.check(params)).resolves.toEqual({ status: TaskStatus.success })
|
||||
expect(fetchTask).not.toHaveBeenCalled()
|
||||
await expect(active.check({ ...params, taskId: 'task-2' })).resolves.toEqual({
|
||||
status: TaskStatus.success,
|
||||
})
|
||||
expect(fetchTask).toHaveBeenCalledExactlyOnceWith('task-2')
|
||||
})
|
||||
|
||||
it('does not fetch again when stopped during the polling interval', async () => {
|
||||
fetchTask.mockResolvedValue(task(TaskStatus.running))
|
||||
const checker = checkTaskStatus()
|
||||
const result = checker.check(params)
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
checker.stop()
|
||||
await vi.advanceTimersByTimeAsync(10_000)
|
||||
|
||||
await expect(result).resolves.toEqual({ status: TaskStatus.success })
|
||||
expect(fetchTask).toHaveBeenCalledExactlyOnceWith('task-1')
|
||||
})
|
||||
})
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
import { screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { renderWithConsoleQuery as render } from '@/test/console/query-data'
|
||||
import { createPluginDeclarationFixture } from '@/test/fixtures/plugin'
|
||||
import { PluginCategoryEnum } from '../../../types'
|
||||
import Installed from '../installed'
|
||||
|
||||
it('closes without a navigation link when installation matches the current category', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onCancel = vi.fn()
|
||||
render(
|
||||
<Installed
|
||||
payload={createPluginDeclarationFixture({ category: PluginCategoryEnum.extension })}
|
||||
installContextCategory={PluginCategoryEnum.extension}
|
||||
isFailed={false}
|
||||
onCancel={onCancel}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(
|
||||
screen.queryByRole('link', { name: 'plugin.installModal.viewDetails' }),
|
||||
).not.toBeInTheDocument()
|
||||
await user.click(screen.getByRole('button', { name: 'common.operation.close' }))
|
||||
expect(onCancel).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('links to the installed category after success but keeps failures in the current context', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onCancel = vi.fn()
|
||||
const payload = createPluginDeclarationFixture({ category: PluginCategoryEnum.extension })
|
||||
const { rerender } = render(
|
||||
<Installed
|
||||
payload={payload}
|
||||
installContextCategory={PluginCategoryEnum.trigger}
|
||||
isFailed={false}
|
||||
onCancel={onCancel}
|
||||
/>,
|
||||
)
|
||||
|
||||
const details = screen.getByRole('link', { name: 'plugin.installModal.viewDetails' })
|
||||
expect(details).toHaveAttribute('href', '/integrations/extension')
|
||||
await user.click(details)
|
||||
expect(onCancel).toHaveBeenCalledOnce()
|
||||
|
||||
rerender(
|
||||
<Installed
|
||||
payload={payload}
|
||||
installContextCategory={PluginCategoryEnum.trigger}
|
||||
isFailed
|
||||
errMsg="Package verification failed"
|
||||
onCancel={onCancel}
|
||||
/>,
|
||||
)
|
||||
expect(screen.getByText('Package verification failed')).toBeInTheDocument()
|
||||
expect(
|
||||
screen.queryByRole('link', { name: 'plugin.installModal.viewDetails' }),
|
||||
).not.toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'common.operation.close' })).toBeEnabled()
|
||||
})
|
||||
@@ -0,0 +1,61 @@
|
||||
import { checkTaskStatus as fetchCheckTaskStatus } from '@/service/plugins'
|
||||
import { sleep } from '@/utils'
|
||||
import { TaskStatus } from '../../types'
|
||||
|
||||
const INTERVAL = 10 * 1000 // 10 seconds
|
||||
const isUnfinishedStatus = (status: TaskStatus) =>
|
||||
status === TaskStatus.pending || status === TaskStatus.running
|
||||
|
||||
type Params = {
|
||||
taskId: string
|
||||
pluginUniqueIdentifier: string
|
||||
}
|
||||
|
||||
function checkTaskStatus() {
|
||||
let nextStatus: TaskStatus = TaskStatus.running
|
||||
let isStop = false
|
||||
|
||||
const doCheckStatus = async ({ taskId, pluginUniqueIdentifier }: Params) => {
|
||||
if (isStop) {
|
||||
return {
|
||||
status: TaskStatus.success,
|
||||
}
|
||||
}
|
||||
const res = await fetchCheckTaskStatus(taskId)
|
||||
const { plugins } = res.task
|
||||
const plugin = plugins.find((p) => p.plugin_unique_identifier === pluginUniqueIdentifier)
|
||||
if (!plugin) {
|
||||
nextStatus = TaskStatus.failed
|
||||
return {
|
||||
status: TaskStatus.failed,
|
||||
error: 'Plugin package not found',
|
||||
}
|
||||
}
|
||||
nextStatus = plugin.status
|
||||
if (isUnfinishedStatus(nextStatus)) {
|
||||
await sleep(INTERVAL)
|
||||
return await doCheckStatus({
|
||||
taskId,
|
||||
pluginUniqueIdentifier,
|
||||
})
|
||||
}
|
||||
if (nextStatus === TaskStatus.failed) {
|
||||
return {
|
||||
status: TaskStatus.failed,
|
||||
error: plugin.message,
|
||||
}
|
||||
}
|
||||
return {
|
||||
status: TaskStatus.success,
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
check: doCheckStatus,
|
||||
stop: () => {
|
||||
isStop = true
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export default checkTaskStatus
|
||||
@@ -0,0 +1,156 @@
|
||||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import type { Plugin, PluginDeclaration, PluginManifestInMarket } from '../../types'
|
||||
import { Button, buttonVariants } from '@langgenius/dify-ui/button'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import * as React from 'react'
|
||||
import { Trans, useTranslation } from 'react-i18next'
|
||||
import Badge from '@/app/components/base/badge/index'
|
||||
import { buildIntegrationPath } from '@/app/components/integrations/routes'
|
||||
import Link from '@/next/link'
|
||||
import Card from '../../card'
|
||||
import { PluginCategoryEnum } from '../../types'
|
||||
import { pluginManifestInMarketToPluginProps, pluginManifestToCardPluginProps } from '../utils'
|
||||
|
||||
type Props = Readonly<{
|
||||
payload?: Plugin | PluginDeclaration | PluginManifestInMarket | null
|
||||
isMarketPayload?: boolean
|
||||
isFailed: boolean
|
||||
errMsg?: string | null
|
||||
installContextCategory?: PluginCategoryEnum
|
||||
onCancel: () => void
|
||||
}>
|
||||
|
||||
type CategoryTarget = {
|
||||
labelKey:
|
||||
| 'menus.tools'
|
||||
| 'settings.agentStrategy'
|
||||
| 'settings.dataSource'
|
||||
| 'settings.extension'
|
||||
| 'settings.provider'
|
||||
| 'settings.trigger'
|
||||
path: string
|
||||
}
|
||||
|
||||
const categoryTargetMap: Partial<Record<PluginCategoryEnum, CategoryTarget>> = {
|
||||
[PluginCategoryEnum.model]: {
|
||||
labelKey: 'settings.provider',
|
||||
path: buildIntegrationPath('provider'),
|
||||
},
|
||||
[PluginCategoryEnum.tool]: {
|
||||
labelKey: 'menus.tools',
|
||||
path: buildIntegrationPath('builtin'),
|
||||
},
|
||||
[PluginCategoryEnum.datasource]: {
|
||||
labelKey: 'settings.dataSource',
|
||||
path: buildIntegrationPath('data-source'),
|
||||
},
|
||||
[PluginCategoryEnum.trigger]: {
|
||||
labelKey: 'settings.trigger',
|
||||
path: buildIntegrationPath('trigger'),
|
||||
},
|
||||
[PluginCategoryEnum.agent]: {
|
||||
labelKey: 'settings.agentStrategy',
|
||||
path: buildIntegrationPath('agent-strategy'),
|
||||
},
|
||||
[PluginCategoryEnum.extension]: {
|
||||
labelKey: 'settings.extension',
|
||||
path: buildIntegrationPath('extension'),
|
||||
},
|
||||
}
|
||||
|
||||
const Installed: FC<Props> = ({
|
||||
payload,
|
||||
isMarketPayload,
|
||||
isFailed,
|
||||
errMsg,
|
||||
installContextCategory,
|
||||
onCancel,
|
||||
}) => {
|
||||
const { t } = useTranslation(['plugin', 'common', 'navigation'])
|
||||
const installedCategory = payload?.category
|
||||
const categoryTarget =
|
||||
!isFailed && installContextCategory && installedCategory !== installContextCategory
|
||||
? categoryTargetMap[installedCategory as PluginCategoryEnum]
|
||||
: undefined
|
||||
const categoryName = categoryTarget
|
||||
? t(($) => $[categoryTarget.labelKey], { ns: 'navigation' })
|
||||
: ''
|
||||
|
||||
const handleClose = () => {
|
||||
onCancel()
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<div className="flex min-h-0 min-w-0 flex-col items-start justify-center gap-2 self-stretch overflow-x-hidden overflow-y-auto px-6 py-3">
|
||||
<p
|
||||
className={cn(
|
||||
'w-full max-w-full min-w-0 system-md-regular text-text-secondary',
|
||||
isFailed && 'wrap-anywhere whitespace-pre-wrap',
|
||||
)}
|
||||
>
|
||||
{isFailed && errMsg ? (
|
||||
errMsg
|
||||
) : categoryTarget ? (
|
||||
<Trans
|
||||
t={t}
|
||||
i18nKey={($) => $['installModal.installedSuccessfullyWithPageDesc']}
|
||||
ns="plugin"
|
||||
components={{
|
||||
categoryName: <span className="system-sm-semibold text-text-secondary" />,
|
||||
}}
|
||||
values={{ categoryName }}
|
||||
/>
|
||||
) : (
|
||||
t(
|
||||
($) =>
|
||||
$[`installModal.${isFailed ? 'installFailedDesc' : 'installedSuccessfullyDesc'}`],
|
||||
{ ns: 'plugin' },
|
||||
)
|
||||
)}
|
||||
</p>
|
||||
{payload && (
|
||||
<div className="flex flex-wrap content-start items-start gap-1 self-stretch rounded-2xl bg-background-section-burn p-2">
|
||||
<Card
|
||||
className="w-full"
|
||||
payload={
|
||||
isMarketPayload
|
||||
? pluginManifestInMarketToPluginProps(payload as PluginManifestInMarket)
|
||||
: pluginManifestToCardPluginProps(payload as PluginDeclaration)
|
||||
}
|
||||
installed={!isFailed}
|
||||
installFailed={isFailed}
|
||||
titleLeft={
|
||||
<Badge className="mx-1" size="s">
|
||||
{(payload as PluginDeclaration).version ||
|
||||
(payload as PluginManifestInMarket).latest_version}
|
||||
</Badge>
|
||||
}
|
||||
compact
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{/* Action Buttons */}
|
||||
<div className="flex shrink-0 items-center justify-end gap-2 self-stretch p-6 pt-5">
|
||||
{categoryTarget ? (
|
||||
<Link
|
||||
href={categoryTarget.path}
|
||||
className={cn(buttonVariants({ variant: 'primary' }), 'min-w-18')}
|
||||
onClick={handleClose}
|
||||
>
|
||||
<>
|
||||
<span>{t(($) => $['installModal.viewDetails'], { ns: 'plugin' })}</span>
|
||||
<span className="i-ri-arrow-right-up-line size-4 shrink-0" aria-hidden="true" />
|
||||
</>
|
||||
</Link>
|
||||
) : (
|
||||
<Button variant="primary" className="min-w-18" onClick={handleClose}>
|
||||
{t(($) => $['operation.close'], { ns: 'common' })}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
export default React.memo(Installed)
|
||||
@@ -0,0 +1,41 @@
|
||||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import { CheckboxSkeleton } from '@langgenius/dify-ui/checkbox'
|
||||
import { RiCloseLine } from '@remixicon/react'
|
||||
import * as React from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { LoadingPlaceholder } from '@/app/components/plugins/card/base/placeholder'
|
||||
|
||||
const LoadingError: FC = () => {
|
||||
const { t } = useTranslation(['plugin'])
|
||||
return (
|
||||
<div className="flex items-center space-x-2">
|
||||
<CheckboxSkeleton className="shrink-0" />
|
||||
<div className="relative grow rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg p-4 pb-3 shadow-xs">
|
||||
<div className="flex">
|
||||
<div className="relative flex h-10 w-10 items-center justify-center gap-2 rounded-[10px] border-[0.5px] border-state-destructive-border bg-state-destructive-hover p-1 backdrop-blur-xs">
|
||||
<div className="flex size-5 items-center justify-center">
|
||||
<span
|
||||
aria-hidden
|
||||
className="i-custom-vender-other-group h-4 w-3.5 text-text-quaternary"
|
||||
/>
|
||||
</div>
|
||||
<div className="absolute -right-1 -bottom-1 rounded-full border-2 border-components-panel-bg bg-state-destructive-solid">
|
||||
<RiCloseLine className="size-3 text-text-primary-on-surface" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="ml-3 grow">
|
||||
<div className="flex h-5 items-center system-md-semibold text-text-destructive">
|
||||
{t(($) => $['installModal.pluginLoadError'], { ns: 'plugin' })}
|
||||
</div>
|
||||
<div className="mt-0.5 system-xs-regular text-text-tertiary">
|
||||
{t(($) => $['installModal.pluginLoadErrorDesc'], { ns: 'plugin' })}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<LoadingPlaceholder className="mt-3 w-105" />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
export default React.memo(LoadingError)
|
||||
@@ -0,0 +1,17 @@
|
||||
'use client'
|
||||
import { CheckboxSkeleton } from '@langgenius/dify-ui/checkbox'
|
||||
import * as React from 'react'
|
||||
import Placeholder from '../../card/base/placeholder'
|
||||
|
||||
const Loading = () => {
|
||||
return (
|
||||
<div className="flex items-center space-x-2">
|
||||
<CheckboxSkeleton className="shrink-0" />
|
||||
<div className="relative grow rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg p-4 pb-3 shadow-xs">
|
||||
<Placeholder wrapClassName="w-full" />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default React.memo(Loading)
|
||||
@@ -0,0 +1,20 @@
|
||||
import { useAtomValue } from 'jotai'
|
||||
import { useCallback } from 'react'
|
||||
import { API_PREFIX } from '@/config'
|
||||
import { currentWorkspaceIdAtom } from '@/context/workspace-state'
|
||||
|
||||
const useGetIcon = () => {
|
||||
const currentWorkspaceId = useAtomValue(currentWorkspaceIdAtom)
|
||||
const getIconUrl = useCallback(
|
||||
(fileName: string) => {
|
||||
return `${API_PREFIX}/workspaces/current/plugin/icon?tenant_id=${currentWorkspaceId}&filename=${fileName}`
|
||||
},
|
||||
[currentWorkspaceId],
|
||||
)
|
||||
|
||||
return {
|
||||
getIconUrl,
|
||||
}
|
||||
}
|
||||
|
||||
export default useGetIcon
|
||||
@@ -0,0 +1,28 @@
|
||||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import type { VersionProps } from '../../types'
|
||||
import * as React from 'react'
|
||||
import Badge from '@/app/components/base/badge/index'
|
||||
|
||||
const Version: FC<VersionProps> = ({ hasInstalled, installedVersion, toInstallVersion }) => {
|
||||
return (
|
||||
<>
|
||||
{!hasInstalled ? (
|
||||
<Badge className="mx-1" size="s">
|
||||
{toInstallVersion}
|
||||
</Badge>
|
||||
) : (
|
||||
<>
|
||||
<Badge className="mx-1" size="s" variant="warning">
|
||||
{`${installedVersion} -> ${toInstallVersion}`}
|
||||
</Badge>
|
||||
{/* <div className='flex px-0.5 justify-center items-center gap-0.5'>
|
||||
<div className='text-text-warning system-xs-medium'>Used in 3 apps</div>
|
||||
<RiInformation2Line className='w-4 h-4 text-text-tertiary' />
|
||||
</div> */}
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
export default React.memo(Version)
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
'use client'
|
||||
|
||||
import type { ReactNode } from 'react'
|
||||
import { use, useEffect, useState } from 'react'
|
||||
import {
|
||||
createPluginInstallPermissionStore,
|
||||
PluginInstallPermissionContext,
|
||||
} from '../hooks/use-plugin-install-permission'
|
||||
|
||||
type PluginInstallPermissionProviderProps = {
|
||||
canInstallPlugin: boolean
|
||||
canUpdatePlugin?: boolean
|
||||
currentDifyVersion?: string
|
||||
children: ReactNode
|
||||
}
|
||||
|
||||
export const PluginInstallPermissionProvider = ({
|
||||
canInstallPlugin,
|
||||
canUpdatePlugin,
|
||||
currentDifyVersion,
|
||||
children,
|
||||
}: PluginInstallPermissionProviderProps) => {
|
||||
const [store] = useState(() =>
|
||||
createPluginInstallPermissionStore({
|
||||
canInstallPlugin,
|
||||
canUpdatePlugin,
|
||||
currentDifyVersion,
|
||||
}),
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
store.getState().setPluginInstallPermission({
|
||||
canInstallPlugin,
|
||||
canUpdatePlugin: canUpdatePlugin ?? canInstallPlugin,
|
||||
currentDifyVersion,
|
||||
})
|
||||
}, [canInstallPlugin, canUpdatePlugin, currentDifyVersion, store])
|
||||
|
||||
return <PluginInstallPermissionContext value={store}>{children}</PluginInstallPermissionContext>
|
||||
}
|
||||
|
||||
export const PluginInstallPermissionProviderGuard = ({
|
||||
canInstallPlugin,
|
||||
canUpdatePlugin,
|
||||
currentDifyVersion,
|
||||
children,
|
||||
}: PluginInstallPermissionProviderProps) => {
|
||||
const store = use(PluginInstallPermissionContext)
|
||||
|
||||
if (store) return children
|
||||
|
||||
return (
|
||||
<PluginInstallPermissionProvider
|
||||
canInstallPlugin={canInstallPlugin}
|
||||
canUpdatePlugin={canUpdatePlugin}
|
||||
currentDifyVersion={currentDifyVersion}
|
||||
>
|
||||
{children}
|
||||
</PluginInstallPermissionProvider>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import type { ToastType } from '@langgenius/dify-ui/toast'
|
||||
import type { GitHubRepoReleaseResponse } from '../types'
|
||||
import { uploadGitHub } from '@/service/plugins'
|
||||
import { compareVersion, getLatestVersion } from '@/utils/semver'
|
||||
|
||||
const normalizeAssetName = (downloadUrl: string) => {
|
||||
const parts = downloadUrl.split('/')
|
||||
return parts[parts.length - 1]
|
||||
}
|
||||
|
||||
const formatReleases = (releases: any) => {
|
||||
return releases.map((release: any) => ({
|
||||
tag_name: release.tag,
|
||||
assets: release.assets.map((asset: any) => ({
|
||||
browser_download_url: asset.downloadUrl,
|
||||
name: normalizeAssetName(asset.downloadUrl),
|
||||
})),
|
||||
}))
|
||||
}
|
||||
|
||||
export const fetchReleases = async (owner: string, repo: string) => {
|
||||
// Fetch releases without authentication from client.
|
||||
const res = await fetch(`https://ungh.cc/repos/${owner}/${repo}/releases`)
|
||||
if (!res.ok) throw new Error('Failed to fetch repository releases')
|
||||
const data = await res.json()
|
||||
return formatReleases(data.releases)
|
||||
}
|
||||
|
||||
export const checkForUpdates = (
|
||||
fetchedReleases: GitHubRepoReleaseResponse[],
|
||||
currentVersion: string,
|
||||
) => {
|
||||
let needUpdate = false
|
||||
const toastProps: { type: ToastType; message: string } = {
|
||||
type: 'info',
|
||||
message: 'No new version available',
|
||||
}
|
||||
if (fetchedReleases.length === 0) {
|
||||
toastProps.type = 'error'
|
||||
toastProps.message = 'Input releases is empty'
|
||||
return { needUpdate, toastProps }
|
||||
}
|
||||
const versions = fetchedReleases.map((release) => release.tag_name)
|
||||
const latestVersion = getLatestVersion(versions)
|
||||
try {
|
||||
needUpdate = compareVersion(latestVersion!, currentVersion) === 1
|
||||
if (needUpdate) toastProps.message = `New version available: ${latestVersion}`
|
||||
} catch {
|
||||
needUpdate = false
|
||||
toastProps.type = 'error'
|
||||
toastProps.message = 'Fail to compare versions, please check the version format'
|
||||
}
|
||||
return { needUpdate, toastProps }
|
||||
}
|
||||
|
||||
export const handleUpload = async (
|
||||
repoUrl: string,
|
||||
selectedVersion: string,
|
||||
selectedPackage: string,
|
||||
onSuccess?: (GitHubPackage: { manifest: any; unique_identifier: string }) => void,
|
||||
) => {
|
||||
const response = await uploadGitHub(repoUrl, selectedVersion, selectedPackage, { silent: true })
|
||||
const GitHubPackage = {
|
||||
manifest: response.manifest,
|
||||
unique_identifier: response.unique_identifier,
|
||||
}
|
||||
onSuccess?.(GitHubPackage)
|
||||
return GitHubPackage
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
|
||||
import createFoldAnimInto from '../create-fold-anim-into'
|
||||
|
||||
const mountModal = () => {
|
||||
const modal = document.createElement('div')
|
||||
modal.className = 'install-modal'
|
||||
vi.spyOn(modal, 'getBoundingClientRect').mockReturnValue(new DOMRect(100, 100, 400, 300))
|
||||
document.body.appendChild(modal)
|
||||
return modal
|
||||
}
|
||||
|
||||
beforeEach(() => vi.useFakeTimers())
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
vi.restoreAllMocks()
|
||||
document
|
||||
.querySelectorAll('.install-modal, #plugin-task-trigger, .plugins-nav-button')
|
||||
.forEach((element) => element.remove())
|
||||
})
|
||||
|
||||
describe('createFoldAnimInto', () => {
|
||||
it.each([false, true])(
|
||||
'closes immediately without an animation target (modal present: %s)',
|
||||
async (hasModal) => {
|
||||
if (hasModal) mountModal()
|
||||
const onClose = vi.fn()
|
||||
await createFoldAnimInto(onClose).foldIntoAnim()
|
||||
expect(onClose).toHaveBeenCalledOnce()
|
||||
},
|
||||
)
|
||||
|
||||
it.each(['task', 'navigation'])('closes after folding to the %s target', async (target) => {
|
||||
mountModal()
|
||||
const trigger = document.createElement('button')
|
||||
if (target === 'task') trigger.id = 'plugin-task-trigger'
|
||||
else trigger.className = 'plugins-nav-button'
|
||||
vi.spyOn(trigger, 'getBoundingClientRect').mockReturnValue(new DOMRect(50, 50, 40, 40))
|
||||
document.body.appendChild(trigger)
|
||||
const onClose = vi.fn()
|
||||
const pending = createFoldAnimInto(onClose).foldIntoAnim()
|
||||
|
||||
await vi.advanceTimersByTimeAsync(749)
|
||||
expect(onClose).not.toHaveBeenCalled()
|
||||
await vi.advanceTimersByTimeAsync(1)
|
||||
await pending
|
||||
expect(onClose).toHaveBeenCalledOnce()
|
||||
})
|
||||
})
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
import { act, waitFor } from '@testing-library/react'
|
||||
import { renderHookWithConsoleQuery as renderHook } from '@/test/console/query-data'
|
||||
import { createDeferred } from '@/test/deferred'
|
||||
import { createPluginEntity } from '@/test/fixtures/plugin'
|
||||
import useCheckInstalled from '../use-check-installed'
|
||||
|
||||
const request = vi.hoisted(() => vi.fn())
|
||||
vi.mock('@/service/console', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/service/console')>()
|
||||
const { withConsoleResponses } = await import('@/test/console/service-responses')
|
||||
return {
|
||||
...actual,
|
||||
consoleQuery: withConsoleResponses(actual.consoleQuery, {
|
||||
'workspaces.current.plugin.list.installations.ids.post': request,
|
||||
}),
|
||||
}
|
||||
})
|
||||
|
||||
beforeEach(() => {
|
||||
request.mockResolvedValue({ plugins: [] })
|
||||
})
|
||||
|
||||
it('waits for installed plugins and maps their server identities and versions', async () => {
|
||||
const pending = createDeferred<{ plugins: ReturnType<typeof createPluginEntity>[] }>()
|
||||
request.mockReturnValue(pending.promise)
|
||||
const plugin = createPluginEntity()
|
||||
const { result } = renderHook(() =>
|
||||
useCheckInstalled({ pluginIds: [plugin.plugin_id], enabled: true }),
|
||||
)
|
||||
expect(result.current.isLoading).toBe(true)
|
||||
expect(result.current.installedInfo).toBeUndefined()
|
||||
await act(async () => pending.resolve({ plugins: [plugin] }))
|
||||
await waitFor(() => expect(result.current.isLoading).toBe(false))
|
||||
expect(request).toHaveBeenCalledWith({ body: { plugin_ids: [plugin.plugin_id] } })
|
||||
expect(result.current.installedInfo).toEqual({
|
||||
[plugin.plugin_id]: {
|
||||
installedId: plugin.id,
|
||||
installedVersion: plugin.declaration.version,
|
||||
uniqueIdentifier: plugin.plugin_unique_identifier,
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('starts the installation lookup only after the caller enables it', async () => {
|
||||
const { result, rerender } = renderHook(
|
||||
({ enabled }) => useCheckInstalled({ pluginIds: ['plugin-1'], enabled }),
|
||||
{ initialProps: { enabled: false } },
|
||||
)
|
||||
expect(request).not.toHaveBeenCalled()
|
||||
expect(result.current.installedInfo).toBeUndefined()
|
||||
rerender({ enabled: true })
|
||||
await waitFor(() => expect(result.current.installedInfo).toEqual({}))
|
||||
expect(request).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('exposes lookup failures without manufacturing an installed result', async () => {
|
||||
const error = new Error('lookup failed')
|
||||
request.mockRejectedValue(error)
|
||||
const { result } = renderHook(() => useCheckInstalled({ pluginIds: ['plugin-1'], enabled: true }))
|
||||
await waitFor(() => expect(result.current.error).toBe(error))
|
||||
expect(result.current.installedInfo).toBeUndefined()
|
||||
expect(result.current.isLoading).toBe(false)
|
||||
})
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
import { act, renderHook } from '@testing-library/react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
|
||||
import useHideLogic from '../use-hide-logic'
|
||||
|
||||
beforeEach(() => vi.useFakeTimers())
|
||||
afterEach(() => {
|
||||
vi.clearAllTimers()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
describe('installation window lifetime', () => {
|
||||
it('cancels the pending automatic close when the user hides an ongoing installation', async () => {
|
||||
const onClose = vi.fn()
|
||||
const { result } = renderHook(() => useHideLogic(onClose))
|
||||
act(() => result.current.handleStartToInstall())
|
||||
// Without a task trigger, folding falls back to closing immediately.
|
||||
act(() => result.current.foldAnimInto())
|
||||
expect(onClose).toHaveBeenCalledOnce()
|
||||
await act(() => vi.advanceTimersByTimeAsync(15_000))
|
||||
expect(onClose).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('keeps the original countdown through rerenders and calls the latest close callback', async () => {
|
||||
const initialOnClose = vi.fn()
|
||||
const latestOnClose = vi.fn()
|
||||
const { result, rerender } = renderHook(({ onClose }) => useHideLogic(onClose), {
|
||||
initialProps: { onClose: initialOnClose },
|
||||
})
|
||||
act(() => result.current.handleStartToInstall())
|
||||
await act(() => vi.advanceTimersByTimeAsync(1_000))
|
||||
rerender({ onClose: latestOnClose })
|
||||
await act(() => vi.advanceTimersByTimeAsync(13_999))
|
||||
expect(initialOnClose).not.toHaveBeenCalled()
|
||||
expect(latestOnClose).not.toHaveBeenCalled()
|
||||
await act(() => vi.advanceTimersByTimeAsync(1))
|
||||
expect(latestOnClose).toHaveBeenCalledOnce()
|
||||
expect(initialOnClose).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps the completed installation open until the user closes it', async () => {
|
||||
const onClose = vi.fn()
|
||||
const { result } = renderHook(() => useHideLogic(onClose))
|
||||
act(() => result.current.handleStartToInstall())
|
||||
// Starting and completing installation commit separately, as the async request does.
|
||||
act(() => result.current.setIsInstalling(false))
|
||||
await act(() => vi.advanceTimersByTimeAsync(15_000))
|
||||
expect(onClose).not.toHaveBeenCalled()
|
||||
act(() => result.current.foldAnimInto())
|
||||
expect(onClose).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('cancels the automatic close when the installation window unmounts', async () => {
|
||||
const onClose = vi.fn()
|
||||
const { result, unmount } = renderHook(() => useHideLogic(onClose))
|
||||
act(() => result.current.handleStartToInstall())
|
||||
unmount()
|
||||
await act(() => vi.advanceTimersByTimeAsync(15_000))
|
||||
expect(onClose).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
import type { PluginInstallationScope } from '@dify/contracts/api/console/system-features/types.gen'
|
||||
import { zPluginInstallationScope } from '@dify/contracts/api/console/system-features/zod.gen'
|
||||
import { describe, expect, it } from 'vite-plus/test'
|
||||
import { pluginInstallLimit } from '../use-install-plugin-limit'
|
||||
|
||||
type PluginInstallCandidate = Parameters<typeof pluginInstallLimit>[0]
|
||||
type SystemFeatures = Parameters<typeof pluginInstallLimit>[1]
|
||||
|
||||
const basePlugin = {
|
||||
from: 'marketplace' as const,
|
||||
verification: { authorized_category: 'langgenius' },
|
||||
} satisfies PluginInstallCandidate
|
||||
|
||||
function makeSystemFeatures(
|
||||
scope: PluginInstallationScope,
|
||||
restrictToMarketplaceOnly = false,
|
||||
): SystemFeatures {
|
||||
return {
|
||||
plugin_installation_permission: {
|
||||
restrict_to_marketplace_only: restrictToMarketplaceOnly,
|
||||
plugin_installation_scope: scope,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
describe('pluginInstallLimit', () => {
|
||||
it('should allow all plugins when scope is ALL', () => {
|
||||
const features = makeSystemFeatures(zPluginInstallationScope.enum.all)
|
||||
|
||||
expect(pluginInstallLimit(basePlugin, features).canInstall).toBe(true)
|
||||
})
|
||||
|
||||
it('should deny all plugins when scope is NONE', () => {
|
||||
const features = makeSystemFeatures(zPluginInstallationScope.enum.none)
|
||||
|
||||
expect(pluginInstallLimit(basePlugin, features).canInstall).toBe(false)
|
||||
})
|
||||
|
||||
it('should allow langgenius plugins when scope is OFFICIAL_ONLY', () => {
|
||||
const features = makeSystemFeatures(zPluginInstallationScope.enum.official_only)
|
||||
|
||||
expect(pluginInstallLimit(basePlugin, features).canInstall).toBe(true)
|
||||
})
|
||||
|
||||
it('should deny non-official plugins when scope is OFFICIAL_ONLY', () => {
|
||||
const features = makeSystemFeatures(zPluginInstallationScope.enum.official_only)
|
||||
const plugin = {
|
||||
...basePlugin,
|
||||
verification: { authorized_category: 'community' as const },
|
||||
} satisfies PluginInstallCandidate
|
||||
|
||||
expect(pluginInstallLimit(plugin, features).canInstall).toBe(false)
|
||||
})
|
||||
|
||||
it('should allow partner plugins when scope is OFFICIAL_AND_PARTNER', () => {
|
||||
const features = makeSystemFeatures(
|
||||
zPluginInstallationScope.enum.official_and_specific_partners,
|
||||
)
|
||||
const plugin = {
|
||||
...basePlugin,
|
||||
verification: { authorized_category: 'partner' as const },
|
||||
} satisfies PluginInstallCandidate
|
||||
|
||||
expect(pluginInstallLimit(plugin, features).canInstall).toBe(true)
|
||||
})
|
||||
|
||||
it('should deny github plugins when restrict_to_marketplace_only is true', () => {
|
||||
const features = makeSystemFeatures(zPluginInstallationScope.enum.all, true)
|
||||
const plugin = { ...basePlugin, from: 'github' as const } satisfies PluginInstallCandidate
|
||||
|
||||
expect(pluginInstallLimit(plugin, features).canInstall).toBe(false)
|
||||
})
|
||||
|
||||
it('should deny package plugins when restrict_to_marketplace_only is true', () => {
|
||||
const features = makeSystemFeatures(zPluginInstallationScope.enum.all, true)
|
||||
const plugin = { ...basePlugin, from: 'package' as const } satisfies PluginInstallCandidate
|
||||
|
||||
expect(pluginInstallLimit(plugin, features).canInstall).toBe(false)
|
||||
})
|
||||
|
||||
it('should allow marketplace plugins even when restrict_to_marketplace_only is true', () => {
|
||||
const features = makeSystemFeatures(zPluginInstallationScope.enum.all, true)
|
||||
|
||||
expect(pluginInstallLimit(basePlugin, features).canInstall).toBe(true)
|
||||
})
|
||||
|
||||
it('should default to langgenius when no verification info', () => {
|
||||
const features = makeSystemFeatures(zPluginInstallationScope.enum.official_only)
|
||||
const plugin = { from: 'marketplace' as const } satisfies PluginInstallCandidate
|
||||
|
||||
expect(pluginInstallLimit(plugin, features).canInstall).toBe(true)
|
||||
})
|
||||
})
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import { renderHook } from '@testing-library/react'
|
||||
import usePluginInstallPermission, {
|
||||
createPluginInstallPermissionStore,
|
||||
PluginInstallPermissionContext,
|
||||
usePluginInstallPermissionStore,
|
||||
} from '../use-plugin-install-permission'
|
||||
|
||||
describe('usePluginInstallPermission', () => {
|
||||
// Store creation defaults update permission to install permission when not provided.
|
||||
describe('Store Defaults', () => {
|
||||
it('should default update permission from install permission', () => {
|
||||
const store = createPluginInstallPermissionStore({
|
||||
canInstallPlugin: false,
|
||||
})
|
||||
|
||||
expect(store.getState().canInstallPlugin).toBe(false)
|
||||
expect(store.getState().canUpdatePlugin).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
// Hook consumers read values from the plugin install permission context.
|
||||
describe('Context', () => {
|
||||
it('should expose plugin install permissions from context store', () => {
|
||||
const store = createPluginInstallPermissionStore({
|
||||
canInstallPlugin: true,
|
||||
canUpdatePlugin: false,
|
||||
currentDifyVersion: '1.2.3',
|
||||
})
|
||||
const wrapper = ({ children }: { children: ReactNode }) => (
|
||||
<PluginInstallPermissionContext value={store}>{children}</PluginInstallPermissionContext>
|
||||
)
|
||||
|
||||
const { result } = renderHook(() => usePluginInstallPermission(), { wrapper })
|
||||
|
||||
expect(result.current).toEqual({
|
||||
canInstallPlugin: true,
|
||||
canUpdatePlugin: false,
|
||||
currentDifyVersion: '1.2.3',
|
||||
})
|
||||
})
|
||||
|
||||
it('should throw when provider is missing', () => {
|
||||
expect(() => {
|
||||
renderHook(() => usePluginInstallPermissionStore((state) => state.canInstallPlugin))
|
||||
}).toThrow('Missing PluginInstallPermissionProvider in the tree')
|
||||
})
|
||||
})
|
||||
})
|
||||
+175
@@ -0,0 +1,175 @@
|
||||
import type { PropsWithChildren } from 'react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { act, renderHook, waitFor } from '@testing-library/react'
|
||||
import { createElement } from 'react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
|
||||
import { consoleQuery } from '@/service/console'
|
||||
import { PluginCategoryEnum } from '../../../types'
|
||||
import useRefreshPluginList from '../use-refresh-plugin-list'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
request: vi.fn<(url: string) => Promise<Response>>(),
|
||||
installed: vi.fn(),
|
||||
checkInstalled: vi.fn(),
|
||||
defaultModel: vi.fn(),
|
||||
triggers: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/service/base', () => ({ request: mocks.request }))
|
||||
vi.mock('@/service/use-plugins', () => ({
|
||||
useInvalidateCheckInstalled: () => mocks.checkInstalled,
|
||||
useInvalidateInstalledPluginList: () => mocks.installed,
|
||||
}))
|
||||
vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({
|
||||
useInvalidateDefaultModel: () => mocks.defaultModel,
|
||||
}))
|
||||
vi.mock('@/service/use-triggers', () => ({
|
||||
useInvalidateAllTriggerPlugins: () => mocks.triggers,
|
||||
}))
|
||||
|
||||
const current = consoleQuery.workspaces.current
|
||||
const strategyKeys = [
|
||||
current.agentProviders.get.queryKey(),
|
||||
current.agentProvider.byProviderName.get.queryKey({
|
||||
input: { params: { provider_name: 'langgenius/agent/react' } },
|
||||
}),
|
||||
current.agentProvider.byProviderName.get.queryKey({
|
||||
input: { params: { provider_name: 'langgenius/agent/function-calling' } },
|
||||
}),
|
||||
]
|
||||
const providerKeys = [
|
||||
current.modelProviders.summary.get.key(),
|
||||
consoleQuery.workspaces.current.modelProviders.get.key(),
|
||||
]
|
||||
const pluginVersionKeys = [
|
||||
current.plugin.list.installations.ids.post.queryKey({
|
||||
input: { body: { plugin_ids: ['langgenius/test'] } },
|
||||
}),
|
||||
current.plugin.list.latestVersions.post.queryKey({
|
||||
input: { body: { plugin_ids: ['langgenius/test'] } },
|
||||
}),
|
||||
]
|
||||
const datasourceKey = consoleQuery.rag.pipelines.datasourcePlugins.get.queryKey()
|
||||
const dataSourceAuthKey = consoleQuery.auth.plugin.datasource.list.get.queryKey()
|
||||
const toolKeys = [
|
||||
current.toolProviders.get.queryKey({ input: { query: {} } }),
|
||||
current.toolProviders.get.queryKey({ input: { query: { type: 'mcp' } } }),
|
||||
current.tools.builtin.get.queryKey(),
|
||||
consoleQuery.rag.pipelines.recommendedPlugins.get.queryKey({
|
||||
input: { query: { type: 'tool' } },
|
||||
}),
|
||||
]
|
||||
const otherRecommendedKey = consoleQuery.rag.pipelines.recommendedPlugins.get.queryKey({
|
||||
input: { query: { type: 'datasource' } },
|
||||
})
|
||||
const unrelatedKey = consoleQuery.account.profile.get.key()
|
||||
const modelTypes = ['llm', 'text-embedding', 'rerank', 'speech2text', 'tts']
|
||||
|
||||
describe('plugin installation refresh', () => {
|
||||
let client: QueryClient
|
||||
|
||||
const wrapper = ({ children }: PropsWithChildren) =>
|
||||
createElement(QueryClientProvider, { client }, children)
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
client = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false, staleTime: Infinity } },
|
||||
})
|
||||
for (const key of [...strategyKeys, ...providerKeys, ...pluginVersionKeys, unrelatedKey])
|
||||
client.setQueryData(key, { cached: true })
|
||||
client.setQueryData(datasourceKey, [])
|
||||
client.setQueryData(dataSourceAuthKey, { result: [] })
|
||||
for (const key of [...toolKeys, otherRecommendedKey]) client.setQueryData(key, [])
|
||||
for (const model_type of modelTypes) {
|
||||
client.setQueryData(
|
||||
current.models.modelTypes.byModelType.get.queryKey({ input: { params: { model_type } } }),
|
||||
{ data: [] },
|
||||
)
|
||||
}
|
||||
mocks.request.mockImplementation(async () => Response.json({ data: [] }))
|
||||
})
|
||||
|
||||
afterEach(() => client.clear())
|
||||
|
||||
it('invalidates the strategy catalog and every provider detail after an agent plugin changes', () => {
|
||||
const { result } = renderHook(useRefreshPluginList, { wrapper })
|
||||
|
||||
act(() => result.current.refreshPluginList({ category: PluginCategoryEnum.agent }))
|
||||
for (const key of pluginVersionKeys) expect(client.getQueryState(key)?.isInvalidated).toBe(true)
|
||||
|
||||
expect(mocks.installed).toHaveBeenCalledWith(PluginCategoryEnum.agent)
|
||||
expect(mocks.checkInstalled).toHaveBeenCalledOnce()
|
||||
for (const key of strategyKeys) expect(client.getQueryState(key)?.isInvalidated).toBe(true)
|
||||
for (const key of [...providerKeys, unrelatedKey])
|
||||
expect(client.getQueryState(key)?.isInvalidated).toBe(false)
|
||||
expect(mocks.request).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.each([PluginCategoryEnum.tool, PluginCategoryEnum.datasource, PluginCategoryEnum.trigger])(
|
||||
'keeps strategy caches fresh when a %s plugin changes',
|
||||
(category) => {
|
||||
const { result } = renderHook(useRefreshPluginList, { wrapper })
|
||||
|
||||
act(() => result.current.refreshPluginList({ category }))
|
||||
|
||||
expect(mocks.installed).toHaveBeenCalledWith(category)
|
||||
for (const key of strategyKeys) expect(client.getQueryState(key)?.isInvalidated).toBe(false)
|
||||
expect(client.getQueryState(datasourceKey)?.isInvalidated).toBe(
|
||||
category === PluginCategoryEnum.datasource,
|
||||
)
|
||||
for (const key of toolKeys)
|
||||
expect(client.getQueryState(key)?.isInvalidated).toBe(category === PluginCategoryEnum.tool)
|
||||
expect(client.getQueryState(otherRecommendedKey)?.isInvalidated).toBe(false)
|
||||
if (category === PluginCategoryEnum.datasource) {
|
||||
expect(client.getQueryState(datasourceKey)?.isInvalidated).toBe(true)
|
||||
expect(client.getQueryState(dataSourceAuthKey)?.isInvalidated).toBe(true)
|
||||
}
|
||||
if (category === PluginCategoryEnum.trigger) expect(mocks.triggers).toHaveBeenCalledOnce()
|
||||
},
|
||||
)
|
||||
|
||||
it.each([false, true])('refreshes model data and defaults; all categories = %s', async (all) => {
|
||||
const { result } = renderHook(useRefreshPluginList, { wrapper })
|
||||
|
||||
act(() => result.current.refreshPluginList({ category: PluginCategoryEnum.model }, all))
|
||||
|
||||
await waitFor(() => expect(mocks.request).toHaveBeenCalledTimes(modelTypes.length))
|
||||
for (const modelType of modelTypes) {
|
||||
expect(
|
||||
mocks.request.mock.calls.some(([url]) => url.endsWith(`/model-types/${modelType}`)),
|
||||
).toBe(true)
|
||||
expect(mocks.defaultModel).toHaveBeenCalledWith(modelType)
|
||||
}
|
||||
for (const key of providerKeys) expect(client.getQueryState(key)?.isInvalidated).toBe(true)
|
||||
for (const key of strategyKeys) expect(client.getQueryState(key)?.isInvalidated).toBe(all)
|
||||
expect(client.getQueryState(unrelatedKey)?.isInvalidated).toBe(false)
|
||||
expect(client.getQueryState(datasourceKey)?.isInvalidated).toBe(all)
|
||||
if (all) {
|
||||
expect(mocks.installed).toHaveBeenCalledWith()
|
||||
for (const key of toolKeys) expect(client.getQueryState(key)?.isInvalidated).toBe(true)
|
||||
expect(client.getQueryState(datasourceKey)?.isInvalidated).toBe(true)
|
||||
expect(client.getQueryState(dataSourceAuthKey)?.isInvalidated).toBe(true)
|
||||
expect(mocks.triggers).toHaveBeenCalledOnce()
|
||||
}
|
||||
})
|
||||
|
||||
it('only refreshes installation caches without a manifest', () => {
|
||||
const { result } = renderHook(useRefreshPluginList, { wrapper })
|
||||
|
||||
act(() => result.current.refreshPluginList())
|
||||
|
||||
expect(mocks.installed).toHaveBeenCalledWith()
|
||||
expect(mocks.checkInstalled).toHaveBeenCalledOnce()
|
||||
for (const key of [
|
||||
...strategyKeys,
|
||||
...providerKeys,
|
||||
...toolKeys,
|
||||
datasourceKey,
|
||||
dataSourceAuthKey,
|
||||
])
|
||||
expect(client.getQueryState(key)?.isInvalidated).toBe(false)
|
||||
expect(mocks.triggers).not.toHaveBeenCalled()
|
||||
expect(mocks.request).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
|
||||
import { createConsoleQueryWrapper } from '@/test/console/query-data'
|
||||
import { renderHook } from '@/test/console/render'
|
||||
import useWorkspacePluginInstallPermission from '../use-workspace-plugin-install-permission'
|
||||
|
||||
let mockWorkspacePermissionKeys: string[] = []
|
||||
|
||||
vi.mock('@/context/permission-state', async () => {
|
||||
const { createPermissionStateModuleMock } = await import('@/test/console/state-fixture')
|
||||
return createPermissionStateModuleMock(() => ({
|
||||
workspacePermissionKeys: mockWorkspacePermissionKeys,
|
||||
}))
|
||||
})
|
||||
|
||||
const renderPermissionHook = () => {
|
||||
const { wrapper } = createConsoleQueryWrapper({
|
||||
accountProfileMeta: { currentVersion: '1.0.0' },
|
||||
})
|
||||
return renderHook(() => useWorkspacePluginInstallPermission(), { wrapper })
|
||||
}
|
||||
|
||||
describe('useWorkspacePluginInstallPermission', () => {
|
||||
beforeEach(() => {
|
||||
mockWorkspacePermissionKeys = []
|
||||
})
|
||||
|
||||
it('should grant install and update capabilities with plugin.install', () => {
|
||||
mockWorkspacePermissionKeys = ['plugin.install']
|
||||
|
||||
const { result } = renderPermissionHook()
|
||||
|
||||
expect(result.current.canInstallPlugin).toBe(true)
|
||||
expect(result.current.canUpdatePlugin).toBe(true)
|
||||
expect(result.current.canDeletePlugin).toBe(false)
|
||||
expect(result.current.canDebugPlugin).toBe(false)
|
||||
expect(result.current.canSetPluginPreferences).toBe(false)
|
||||
})
|
||||
|
||||
it('should grant delete capability but not install or update with plugin.delete', () => {
|
||||
mockWorkspacePermissionKeys = ['plugin.delete']
|
||||
|
||||
const { result } = renderPermissionHook()
|
||||
|
||||
expect(result.current.canInstallPlugin).toBe(false)
|
||||
expect(result.current.canUpdatePlugin).toBe(false)
|
||||
expect(result.current.canDeletePlugin).toBe(true)
|
||||
expect(result.current.canDebugPlugin).toBe(false)
|
||||
expect(result.current.canSetPluginPreferences).toBe(false)
|
||||
})
|
||||
|
||||
it('should grant plugin debug capability with plugin.debug', () => {
|
||||
mockWorkspacePermissionKeys = ['plugin.debug']
|
||||
|
||||
const { result } = renderPermissionHook()
|
||||
|
||||
expect(result.current.canInstallPlugin).toBe(false)
|
||||
expect(result.current.canUpdatePlugin).toBe(false)
|
||||
expect(result.current.canDeletePlugin).toBe(false)
|
||||
expect(result.current.canDebugPlugin).toBe(true)
|
||||
expect(result.current.canSetPluginPreferences).toBe(false)
|
||||
})
|
||||
|
||||
it('should grant plugin preference setting capability with plugin.plugin_preferences', () => {
|
||||
mockWorkspacePermissionKeys = ['plugin.plugin_preferences']
|
||||
|
||||
const { result } = renderPermissionHook()
|
||||
|
||||
expect(result.current.canInstallPlugin).toBe(false)
|
||||
expect(result.current.canUpdatePlugin).toBe(false)
|
||||
expect(result.current.canDeletePlugin).toBe(false)
|
||||
expect(result.current.canDebugPlugin).toBe(false)
|
||||
expect(result.current.canSetPluginPreferences).toBe(true)
|
||||
})
|
||||
|
||||
it('should deny plugin capabilities without plugin install or manage permissions', () => {
|
||||
const { result } = renderPermissionHook()
|
||||
|
||||
expect(result.current.canInstallPlugin).toBe(false)
|
||||
expect(result.current.canUpdatePlugin).toBe(false)
|
||||
expect(result.current.canDeletePlugin).toBe(false)
|
||||
expect(result.current.canDebugPlugin).toBe(false)
|
||||
expect(result.current.canSetPluginPreferences).toBe(false)
|
||||
})
|
||||
})
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
import { sleep } from '@/utils'
|
||||
|
||||
const animTime = 750
|
||||
const modalClassName = 'install-modal'
|
||||
const COUNT_DOWN_TIME = 15000 // 15s
|
||||
|
||||
function getElemCenter(elem: HTMLElement) {
|
||||
const rect = elem.getBoundingClientRect()
|
||||
return {
|
||||
x: rect.left + rect.width / 2 + window.scrollX,
|
||||
y: rect.top + rect.height / 2 + window.scrollY,
|
||||
}
|
||||
}
|
||||
|
||||
const createFoldAnimInto = (onClose: () => void) => {
|
||||
let countDownRunId: number
|
||||
const clearCountDown = () => {
|
||||
clearTimeout(countDownRunId)
|
||||
}
|
||||
// modalElem fold into plugin install task btn
|
||||
const foldIntoAnim = async () => {
|
||||
clearCountDown()
|
||||
const modalElem = document.querySelector(`.${modalClassName}`) as HTMLElement
|
||||
const pluginTaskTriggerElem =
|
||||
document.getElementById('plugin-task-trigger') ||
|
||||
document.querySelector('.plugins-nav-button')
|
||||
|
||||
if (!modalElem || !pluginTaskTriggerElem) {
|
||||
onClose()
|
||||
return
|
||||
}
|
||||
|
||||
const modelCenter = getElemCenter(modalElem)
|
||||
const modalElemRect = modalElem.getBoundingClientRect()
|
||||
const pluginTaskTriggerCenter = getElemCenter(pluginTaskTriggerElem)
|
||||
const xDiff = pluginTaskTriggerCenter.x - modelCenter.x
|
||||
const yDiff = pluginTaskTriggerCenter.y - modelCenter.y
|
||||
const scale = 1 / Math.max(modalElemRect.width, modalElemRect.height)
|
||||
modalElem.style.transition = `all cubic-bezier(0.4, 0, 0.2, 1) ${animTime}ms`
|
||||
modalElem.style.transform = `translate(${xDiff}px, ${yDiff}px) scale(${scale})`
|
||||
await sleep(animTime)
|
||||
onClose()
|
||||
}
|
||||
|
||||
const countDownFoldIntoAnim = async () => {
|
||||
countDownRunId = window.setTimeout(() => {
|
||||
foldIntoAnim()
|
||||
}, COUNT_DOWN_TIME)
|
||||
}
|
||||
|
||||
return {
|
||||
modalClassName,
|
||||
foldIntoAnim,
|
||||
clearCountDown,
|
||||
countDownFoldIntoAnim,
|
||||
}
|
||||
}
|
||||
|
||||
export default createFoldAnimInto
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
import type { VersionInfo } from '../../types'
|
||||
import { useMemo } from 'react'
|
||||
import { useCheckInstalled as useDoCheckInstalled } from '@/service/use-plugins'
|
||||
|
||||
type Props = Readonly<{
|
||||
pluginIds: string[]
|
||||
enabled: boolean
|
||||
}>
|
||||
const useCheckInstalled = (props: Props) => {
|
||||
const { data, isLoading, error } = useDoCheckInstalled(props)
|
||||
|
||||
const installedInfo = useMemo(() => {
|
||||
if (!data) return undefined
|
||||
|
||||
const res: Record<string, VersionInfo> = {}
|
||||
data?.plugins.forEach((plugin) => {
|
||||
res[plugin.plugin_id] = {
|
||||
installedId: plugin.id,
|
||||
installedVersion: plugin.declaration.version,
|
||||
uniqueIdentifier: plugin.plugin_unique_identifier,
|
||||
}
|
||||
})
|
||||
return res
|
||||
}, [data])
|
||||
return {
|
||||
installedInfo,
|
||||
isLoading,
|
||||
error,
|
||||
}
|
||||
}
|
||||
|
||||
export default useCheckInstalled
|
||||
@@ -0,0 +1,51 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import createFoldAnimInto from './create-fold-anim-into'
|
||||
|
||||
const useHideLogic = (onClose: () => void) => {
|
||||
const onCloseRef = useRef(onClose)
|
||||
useEffect(() => {
|
||||
onCloseRef.current = onClose
|
||||
}, [onClose])
|
||||
|
||||
const [controller] = useState(() => createFoldAnimInto(() => onCloseRef.current()))
|
||||
const {
|
||||
modalClassName,
|
||||
foldIntoAnim: doFoldAnimInto,
|
||||
clearCountDown,
|
||||
countDownFoldIntoAnim,
|
||||
} = controller
|
||||
|
||||
useEffect(() => clearCountDown, [clearCountDown])
|
||||
|
||||
const [isInstalling, doSetIsInstalling] = useState(false)
|
||||
const setIsInstalling = useCallback(
|
||||
(isInstalling: boolean) => {
|
||||
if (!isInstalling) clearCountDown()
|
||||
doSetIsInstalling(isInstalling)
|
||||
},
|
||||
[clearCountDown],
|
||||
)
|
||||
|
||||
const foldAnimInto = useCallback(() => {
|
||||
if (isInstalling) {
|
||||
doFoldAnimInto()
|
||||
return
|
||||
}
|
||||
onClose()
|
||||
}, [doFoldAnimInto, isInstalling, onClose])
|
||||
|
||||
const handleStartToInstall = useCallback(() => {
|
||||
setIsInstalling(true)
|
||||
countDownFoldIntoAnim()
|
||||
}, [countDownFoldIntoAnim, setIsInstalling])
|
||||
|
||||
return {
|
||||
modalClassName,
|
||||
foldAnimInto,
|
||||
foldIntoTaskTrigger: doFoldAnimInto,
|
||||
setIsInstalling,
|
||||
handleStartToInstall,
|
||||
}
|
||||
}
|
||||
|
||||
export default useHideLogic
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
'use client'
|
||||
|
||||
import type { Dependency, PluginDeclaration, PluginManifestInMarket } from '../../types'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { parseMarketplacePluginId } from '@/app/components/plugins/plugin-routes'
|
||||
import { getMarketplacePluginIconUrl } from '@/features/marketplace/api'
|
||||
import { usePluginInstallation } from '@/hooks/use-query-params'
|
||||
import {
|
||||
fetchBundleInfoFromMarketPlace,
|
||||
fetchManifestFromMarketPlace,
|
||||
fetchPluginInfoFromMarketPlace,
|
||||
} from '@/service/plugins'
|
||||
|
||||
type MarketplaceInstall = {
|
||||
manifest: PluginDeclaration | PluginManifestInMarket
|
||||
packageId: string
|
||||
uniqueIdentifier: string
|
||||
}
|
||||
|
||||
async function resolveMarketplaceUniqueIdentifier(packageId: string) {
|
||||
const pluginId = parseMarketplacePluginId(packageId)
|
||||
if (!pluginId) return packageId
|
||||
|
||||
const { data } = await fetchPluginInfoFromMarketPlace(pluginId)
|
||||
return data.plugin.latest_package_identifier
|
||||
}
|
||||
|
||||
export type UseInstallFromMarketplaceQueryOptions = {
|
||||
canInstallPlugin: boolean
|
||||
isPermissionLoading?: boolean
|
||||
onPackageCategoryResolved?: (category: string | undefined, packageId: string) => boolean
|
||||
}
|
||||
|
||||
export const useInstallFromMarketplaceQuery = ({
|
||||
canInstallPlugin,
|
||||
isPermissionLoading = false,
|
||||
onPackageCategoryResolved,
|
||||
}: UseInstallFromMarketplaceQueryOptions) => {
|
||||
const [{ packageId, bundleInfo }, setInstallState] = usePluginInstallation()
|
||||
const [marketplaceInstall, setMarketplaceInstall] = useState<MarketplaceInstall | null>(null)
|
||||
const [dependencies, setDependencies] = useState<Dependency[]>([])
|
||||
const [isShowInstallFromMarketplace, setIsShowInstallFromMarketplace] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!packageId && !bundleInfo) return
|
||||
|
||||
if (isPermissionLoading) return
|
||||
|
||||
if (!canInstallPlugin) {
|
||||
setInstallState(null)
|
||||
return
|
||||
}
|
||||
|
||||
let ignore = false
|
||||
|
||||
const loadMarketplaceInstall = async () => {
|
||||
if (packageId) {
|
||||
try {
|
||||
const uniqueIdentifier = await resolveMarketplaceUniqueIdentifier(packageId)
|
||||
const { data } = await fetchManifestFromMarketPlace(encodeURIComponent(uniqueIdentifier))
|
||||
if (ignore) return
|
||||
|
||||
const { plugin, version } = data
|
||||
const redirected = onPackageCategoryResolved?.(plugin.category, packageId)
|
||||
if (redirected) return
|
||||
|
||||
setMarketplaceInstall({
|
||||
packageId,
|
||||
uniqueIdentifier,
|
||||
manifest: {
|
||||
...plugin,
|
||||
version: version.version,
|
||||
icon: getMarketplacePluginIconUrl(`${plugin.org}/${plugin.name}`),
|
||||
},
|
||||
})
|
||||
setIsShowInstallFromMarketplace(true)
|
||||
} catch (error) {
|
||||
if (!ignore) console.error('Failed to load marketplace plugin manifest:', error)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (bundleInfo) {
|
||||
try {
|
||||
const { data } = await fetchBundleInfoFromMarketPlace(bundleInfo)
|
||||
if (ignore) return
|
||||
|
||||
setDependencies(data.version.dependencies)
|
||||
setIsShowInstallFromMarketplace(true)
|
||||
} catch (error) {
|
||||
if (!ignore) console.error('Failed to load bundle info:', error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
loadMarketplaceInstall()
|
||||
|
||||
return () => {
|
||||
ignore = true
|
||||
}
|
||||
}, [
|
||||
bundleInfo,
|
||||
canInstallPlugin,
|
||||
isPermissionLoading,
|
||||
onPackageCategoryResolved,
|
||||
packageId,
|
||||
setInstallState,
|
||||
])
|
||||
|
||||
const hideInstallFromMarketplace = () => {
|
||||
setMarketplaceInstall(null)
|
||||
setDependencies([])
|
||||
setIsShowInstallFromMarketplace(false)
|
||||
setInstallState(null)
|
||||
}
|
||||
|
||||
return {
|
||||
bundleInfo,
|
||||
dependencies,
|
||||
hideInstallFromMarketplace,
|
||||
isShowInstallFromMarketplace,
|
||||
marketplaceInstall: marketplaceInstall?.packageId === packageId ? marketplaceInstall : null,
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
import type { GetSystemFeaturesResponse } from '@dify/contracts/api/console/system-features/types.gen'
|
||||
import type {
|
||||
PluginBundleDependencyType,
|
||||
PluginVerification,
|
||||
} from '@dify/contracts/api/console/workspaces/types.gen'
|
||||
import { zPluginInstallationScope } from '@dify/contracts/api/console/system-features/zod.gen'
|
||||
import { useSuspenseQuery } from '@tanstack/react-query'
|
||||
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
|
||||
|
||||
type PluginInstallCandidate = {
|
||||
from: PluginBundleDependencyType
|
||||
verification?: PluginVerification | null
|
||||
}
|
||||
type PluginInstallLimitResult = {
|
||||
canInstall: boolean
|
||||
}
|
||||
|
||||
function denyUnsupportedInstallationScope(_scope: never): PluginInstallLimitResult {
|
||||
return { canInstall: false }
|
||||
}
|
||||
|
||||
export function pluginInstallLimit(
|
||||
plugin: PluginInstallCandidate,
|
||||
systemFeatures: Pick<GetSystemFeaturesResponse, 'plugin_installation_permission'>,
|
||||
) {
|
||||
const permission = systemFeatures.plugin_installation_permission
|
||||
if (permission.restrict_to_marketplace_only) {
|
||||
if (plugin.from === 'github' || plugin.from === 'package') return { canInstall: false }
|
||||
}
|
||||
|
||||
const authorizedCategory = plugin.verification?.authorized_category ?? 'langgenius'
|
||||
const scope = permission.plugin_installation_scope
|
||||
|
||||
switch (scope) {
|
||||
case zPluginInstallationScope.enum.all:
|
||||
return { canInstall: true }
|
||||
case zPluginInstallationScope.enum.none:
|
||||
return { canInstall: false }
|
||||
case zPluginInstallationScope.enum.official_only:
|
||||
return { canInstall: authorizedCategory === 'langgenius' }
|
||||
case zPluginInstallationScope.enum.official_and_specific_partners:
|
||||
return {
|
||||
canInstall: authorizedCategory === 'langgenius' || authorizedCategory === 'partner',
|
||||
}
|
||||
default:
|
||||
return denyUnsupportedInstallationScope(scope)
|
||||
}
|
||||
}
|
||||
|
||||
export default function usePluginInstallLimit(
|
||||
plugin: PluginInstallCandidate,
|
||||
): PluginInstallLimitResult {
|
||||
const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
|
||||
|
||||
return pluginInstallLimit(plugin, systemFeatures)
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
import type { StoreApi } from 'zustand'
|
||||
import { createContext, use } from 'react'
|
||||
import { useStore } from 'zustand'
|
||||
import { createStore } from 'zustand/vanilla'
|
||||
|
||||
export type PluginInstallPermissionState = {
|
||||
canInstallPlugin: boolean
|
||||
canUpdatePlugin: boolean
|
||||
currentDifyVersion?: string
|
||||
}
|
||||
|
||||
type PluginInstallPermissionAction = {
|
||||
setPluginInstallPermission: (state: PluginInstallPermissionState) => void
|
||||
}
|
||||
|
||||
export type PluginInstallPermissionStoreState = PluginInstallPermissionState &
|
||||
PluginInstallPermissionAction
|
||||
|
||||
export type PluginInstallPermissionStore = StoreApi<PluginInstallPermissionStoreState>
|
||||
|
||||
const defaultPluginInstallPermissionState: PluginInstallPermissionState = {
|
||||
canInstallPlugin: true,
|
||||
canUpdatePlugin: true,
|
||||
}
|
||||
|
||||
export const createPluginInstallPermissionStore = (
|
||||
initProps?: Partial<PluginInstallPermissionState>,
|
||||
) => {
|
||||
const canInstallPlugin =
|
||||
initProps?.canInstallPlugin ?? defaultPluginInstallPermissionState.canInstallPlugin
|
||||
|
||||
return createStore<PluginInstallPermissionStoreState>()((set) => ({
|
||||
...defaultPluginInstallPermissionState,
|
||||
...initProps,
|
||||
canUpdatePlugin: initProps?.canUpdatePlugin ?? canInstallPlugin,
|
||||
setPluginInstallPermission: (state) => set(() => state),
|
||||
}))
|
||||
}
|
||||
|
||||
const fallbackPluginInstallPermissionStore = createPluginInstallPermissionStore()
|
||||
|
||||
export const PluginInstallPermissionContext = createContext<PluginInstallPermissionStore | null>(
|
||||
null,
|
||||
)
|
||||
|
||||
export const usePluginInstallPermissionStore = <T>(
|
||||
selector: (state: PluginInstallPermissionStoreState) => T,
|
||||
): T => {
|
||||
const store = use(PluginInstallPermissionContext)
|
||||
if (!store) throw new Error('Missing PluginInstallPermissionProvider in the tree')
|
||||
|
||||
return useStore(store, selector)
|
||||
}
|
||||
|
||||
const usePluginInstallPermission = () => {
|
||||
const canInstallPlugin = usePluginInstallPermissionStore((state) => state.canInstallPlugin)
|
||||
const canUpdatePlugin = usePluginInstallPermissionStore((state) => state.canUpdatePlugin)
|
||||
const currentDifyVersion = usePluginInstallPermissionStore((state) => state.currentDifyVersion)
|
||||
|
||||
return {
|
||||
canInstallPlugin,
|
||||
canUpdatePlugin,
|
||||
currentDifyVersion,
|
||||
}
|
||||
}
|
||||
|
||||
export const useOptionalPluginInstallPermission = () => {
|
||||
const store = use(PluginInstallPermissionContext) ?? fallbackPluginInstallPermissionStore
|
||||
const canInstallPlugin = useStore(store, (state) => state.canInstallPlugin)
|
||||
const canUpdatePlugin = useStore(store, (state) => state.canUpdatePlugin)
|
||||
const currentDifyVersion = useStore(store, (state) => state.currentDifyVersion)
|
||||
|
||||
return {
|
||||
canInstallPlugin,
|
||||
canUpdatePlugin,
|
||||
currentDifyVersion,
|
||||
}
|
||||
}
|
||||
|
||||
export default usePluginInstallPermission
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
import type { Plugin, PluginDeclaration, PluginManifestInMarket } from '../../types'
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
|
||||
import { useInvalidateDefaultModel } from '@/app/components/header/account-setting/model-provider-page/hooks'
|
||||
import { consoleQuery } from '@/service/console'
|
||||
import {
|
||||
useInvalidateCheckInstalled,
|
||||
useInvalidateInstalledPluginList,
|
||||
} from '@/service/use-plugins'
|
||||
import { useInvalidateAllTriggerPlugins } from '@/service/use-triggers'
|
||||
import { PluginCategoryEnum } from '../../types'
|
||||
|
||||
type PluginCategoryPayload = {
|
||||
category: PluginCategoryEnum
|
||||
}
|
||||
|
||||
const SYSTEM_MODEL_TYPES = [
|
||||
ModelTypeEnum.textGeneration,
|
||||
ModelTypeEnum.textEmbedding,
|
||||
ModelTypeEnum.rerank,
|
||||
ModelTypeEnum.speech2text,
|
||||
ModelTypeEnum.tts,
|
||||
]
|
||||
|
||||
const useRefreshPluginList = () => {
|
||||
const invalidateInstalledPluginList = useInvalidateInstalledPluginList()
|
||||
const invalidateCheckInstalled = useInvalidateCheckInstalled()
|
||||
const { refetch: refetchLLMModelList } = useQuery(
|
||||
consoleQuery.workspaces.current.models.modelTypes.byModelType.get.queryOptions({
|
||||
input: { params: { model_type: ModelTypeEnum.textGeneration } },
|
||||
}),
|
||||
)
|
||||
const { refetch: refetchEmbeddingModelList } = useQuery(
|
||||
consoleQuery.workspaces.current.models.modelTypes.byModelType.get.queryOptions({
|
||||
input: { params: { model_type: ModelTypeEnum.textEmbedding } },
|
||||
}),
|
||||
)
|
||||
const { refetch: refetchRerankModelList } = useQuery(
|
||||
consoleQuery.workspaces.current.models.modelTypes.byModelType.get.queryOptions({
|
||||
input: { params: { model_type: ModelTypeEnum.rerank } },
|
||||
}),
|
||||
)
|
||||
const { refetch: refetchSpeech2textModelList } = useQuery(
|
||||
consoleQuery.workspaces.current.models.modelTypes.byModelType.get.queryOptions({
|
||||
input: { params: { model_type: ModelTypeEnum.speech2text } },
|
||||
}),
|
||||
)
|
||||
const { refetch: refetchTTSModelList } = useQuery(
|
||||
consoleQuery.workspaces.current.models.modelTypes.byModelType.get.queryOptions({
|
||||
input: { params: { model_type: ModelTypeEnum.tts } },
|
||||
}),
|
||||
)
|
||||
const invalidateDefaultModel = useInvalidateDefaultModel()
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const invalidateAllTriggerPlugins = useInvalidateAllTriggerPlugins()
|
||||
return {
|
||||
refreshPluginList: (
|
||||
manifest?: PluginManifestInMarket | Plugin | PluginDeclaration | PluginCategoryPayload | null,
|
||||
refreshAllType?: boolean,
|
||||
) => {
|
||||
// installed list
|
||||
if (refreshAllType || !manifest) invalidateInstalledPluginList()
|
||||
else invalidateInstalledPluginList(manifest.category)
|
||||
invalidateCheckInstalled()
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: consoleQuery.workspaces.current.plugin.list.installations.ids.post.key(),
|
||||
})
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: consoleQuery.workspaces.current.plugin.list.latestVersions.post.key(),
|
||||
})
|
||||
|
||||
// tool page, tool select
|
||||
if ((manifest && PluginCategoryEnum.tool.includes(manifest.category)) || refreshAllType) {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: consoleQuery.workspaces.current.toolProviders.get.key(),
|
||||
})
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: consoleQuery.workspaces.current.tools.builtin.get.queryKey(),
|
||||
})
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: consoleQuery.rag.pipelines.recommendedPlugins.get.queryKey({
|
||||
input: { query: { type: 'tool' } },
|
||||
}),
|
||||
})
|
||||
// TODO: update suggested tools. It's a function in hook useMarketplacePlugins,handleUpdatePlugins
|
||||
}
|
||||
|
||||
if ((manifest && PluginCategoryEnum.trigger.includes(manifest.category)) || refreshAllType)
|
||||
invalidateAllTriggerPlugins()
|
||||
|
||||
if (
|
||||
(manifest && PluginCategoryEnum.datasource.includes(manifest.category)) ||
|
||||
refreshAllType
|
||||
) {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: consoleQuery.rag.pipelines.datasourcePlugins.get.key(),
|
||||
})
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: consoleQuery.auth.plugin.datasource.list.get.queryKey(),
|
||||
})
|
||||
}
|
||||
|
||||
// model select
|
||||
if ((manifest && PluginCategoryEnum.model.includes(manifest.category)) || refreshAllType) {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: consoleQuery.workspaces.current.modelProviders.summary.get.key(),
|
||||
})
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: consoleQuery.workspaces.current.modelProviders.get.key(),
|
||||
})
|
||||
refetchLLMModelList()
|
||||
refetchEmbeddingModelList()
|
||||
refetchRerankModelList()
|
||||
refetchSpeech2textModelList()
|
||||
refetchTTSModelList()
|
||||
SYSTEM_MODEL_TYPES.forEach((type) => invalidateDefaultModel(type))
|
||||
}
|
||||
|
||||
// agent select
|
||||
if ((manifest && PluginCategoryEnum.agent.includes(manifest.category)) || refreshAllType) {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: consoleQuery.workspaces.current.agentProviders.get.key(),
|
||||
})
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: consoleQuery.workspaces.current.agentProvider.byProviderName.get.key(),
|
||||
})
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export default useRefreshPluginList
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
import { useSuspenseQuery } from '@tanstack/react-query'
|
||||
import { useAtomValue } from 'jotai'
|
||||
import { useMemo } from 'react'
|
||||
import { workspacePermissionKeysAtom } from '@/context/permission-state'
|
||||
import { userProfileQueryOptions } from '@/features/account-profile/client'
|
||||
import { hasPermission } from '@/utils/permission'
|
||||
|
||||
const useWorkspacePluginInstallPermission = () => {
|
||||
const { data: currentVersion } = useSuspenseQuery({
|
||||
...userProfileQueryOptions(),
|
||||
select: (data) => data.meta.currentVersion ?? '',
|
||||
})
|
||||
const workspacePermissionKeys = useAtomValue(workspacePermissionKeysAtom)
|
||||
|
||||
const canInstallPlugin = useMemo(() => {
|
||||
return hasPermission(workspacePermissionKeys, 'plugin.install')
|
||||
}, [workspacePermissionKeys])
|
||||
|
||||
const canUpdatePlugin = useMemo(() => {
|
||||
return hasPermission(workspacePermissionKeys, 'plugin.install')
|
||||
}, [workspacePermissionKeys])
|
||||
|
||||
const canDeletePlugin = useMemo(() => {
|
||||
return hasPermission(workspacePermissionKeys, 'plugin.delete')
|
||||
}, [workspacePermissionKeys])
|
||||
|
||||
const canDebugPlugin = useMemo(() => {
|
||||
return hasPermission(workspacePermissionKeys, 'plugin.debug')
|
||||
}, [workspacePermissionKeys])
|
||||
|
||||
const canSetPluginPreferences = useMemo(() => {
|
||||
return hasPermission(workspacePermissionKeys, 'plugin.plugin_preferences')
|
||||
}, [workspacePermissionKeys])
|
||||
|
||||
return {
|
||||
canInstallPlugin,
|
||||
canUpdatePlugin,
|
||||
canDeletePlugin,
|
||||
canDebugPlugin,
|
||||
canSetPluginPreferences,
|
||||
currentDifyVersion: currentVersion,
|
||||
}
|
||||
}
|
||||
|
||||
export default useWorkspacePluginInstallPermission
|
||||
+399
@@ -0,0 +1,399 @@
|
||||
import type { Dependency, PackageDependency, Plugin } from '../../../types'
|
||||
import type { ConsoleQueryTestOptions } from '@/test/console/query-data'
|
||||
import { screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { MARKETPLACE_API_PREFIX } from '@/features/marketplace/api'
|
||||
import { renderWithConsoleQuery } from '@/test/console/query-data'
|
||||
import { createDeferred } from '@/test/deferred'
|
||||
import { createPluginDeclarationFixture, createPluginEntity } from '@/test/fixtures/plugin'
|
||||
import { PermissionType, PluginCategoryEnum, TaskStatus } from '../../../types'
|
||||
import InstallBundle from '../index'
|
||||
|
||||
const {
|
||||
marketplace,
|
||||
checkTask,
|
||||
refresh,
|
||||
installRequest,
|
||||
uploadGithub,
|
||||
installGithub,
|
||||
installPackage,
|
||||
installedPlugins,
|
||||
upgrade,
|
||||
} = vi.hoisted(() => ({
|
||||
marketplace: vi.fn(),
|
||||
checkTask: vi.fn(),
|
||||
refresh: vi.fn(),
|
||||
installRequest: vi.fn(),
|
||||
uploadGithub: vi.fn(),
|
||||
installGithub: vi.fn(),
|
||||
installPackage: vi.fn(),
|
||||
installedPlugins: vi.fn(),
|
||||
upgrade: vi.fn(),
|
||||
}))
|
||||
vi.mock('@/service/base', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('@/service/base')>()),
|
||||
postMarketplace: marketplace,
|
||||
}))
|
||||
vi.mock('@/service/plugins', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('@/service/plugins')>()),
|
||||
checkTaskStatus: checkTask,
|
||||
}))
|
||||
vi.mock('@/service/console', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/service/console')>()
|
||||
const { withConsoleResponses, withConsoleClientResponses } =
|
||||
await import('@/test/console/service-responses')
|
||||
return {
|
||||
...actual,
|
||||
consoleClient: withConsoleClientResponses(actual.consoleClient, {
|
||||
'workspaces.current.plugin.permission.fetch.get': async () => ({
|
||||
install_permission: PermissionType.everyone,
|
||||
debug_permission: PermissionType.everyone,
|
||||
}),
|
||||
'workspaces.current.plugin.tasks.get': async () => ({ tasks: [] }),
|
||||
'workspaces.current.plugin.install.marketplace.post': installRequest,
|
||||
'workspaces.current.plugin.upload.github.post': uploadGithub,
|
||||
'workspaces.current.plugin.install.github.post': installGithub,
|
||||
'workspaces.current.plugin.install.pkg.post': installPackage,
|
||||
'workspaces.current.plugin.upgrade.marketplace.post': upgrade,
|
||||
}),
|
||||
consoleQuery: withConsoleResponses(actual.consoleQuery, {
|
||||
'workspaces.current.plugin.list.installations.ids.post': installedPlugins,
|
||||
}),
|
||||
}
|
||||
})
|
||||
// Refreshing unrelated model/tool catalogs is independently covered by use-refresh-plugin-list.
|
||||
vi.mock('../../hooks/use-refresh-plugin-list', () => ({
|
||||
default: () => ({ refreshPluginList: refresh }),
|
||||
}))
|
||||
|
||||
const plugins: Plugin[] = ['finished', 'failed', 'running'].map((name) => ({
|
||||
type: 'plugin',
|
||||
org: 'test',
|
||||
name,
|
||||
plugin_id: `test/${name}`,
|
||||
version: '1.0.0',
|
||||
latest_version: '1.0.0',
|
||||
latest_package_identifier: `test/${name}:1.0.0`,
|
||||
icon: '',
|
||||
verified: true,
|
||||
label: { en_US: name },
|
||||
brief: { en_US: 'Test plugin' },
|
||||
description: { en_US: 'Test plugin' },
|
||||
introduction: '',
|
||||
repository: '',
|
||||
category: PluginCategoryEnum.tool,
|
||||
install_count: 1,
|
||||
endpoint: { settings: [] },
|
||||
tags: [],
|
||||
badges: [],
|
||||
verification: { authorized_category: 'community' },
|
||||
from: 'marketplace',
|
||||
}))
|
||||
const dependencies: Dependency[] = plugins.map((plugin) => ({
|
||||
type: 'marketplace',
|
||||
value: { marketplace_plugin_unique_identifier: plugin.latest_package_identifier },
|
||||
}))
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks()
|
||||
installedPlugins.mockResolvedValue({ plugins: [] })
|
||||
marketplace.mockResolvedValue({ data: { list: plugins.map((plugin) => ({ plugin })) } })
|
||||
})
|
||||
|
||||
const renderInstall = (
|
||||
fromDSLPayload: Dependency[] = dependencies,
|
||||
options: ConsoleQueryTestOptions = {},
|
||||
) => {
|
||||
const onInstalled = vi.fn()
|
||||
const onClose = vi.fn()
|
||||
renderWithConsoleQuery(
|
||||
<InstallBundle
|
||||
fromDSLPayload={fromDSLPayload}
|
||||
onInstallComplete={onInstalled}
|
||||
onClose={onClose}
|
||||
/>,
|
||||
{
|
||||
workspacePermissionKeys: ['plugin.install'],
|
||||
systemFeatures: {
|
||||
enable_marketplace: true,
|
||||
rbac_enabled: true,
|
||||
plugin_installation_permission: {
|
||||
plugin_installation_scope: 'all',
|
||||
restrict_to_marketplace_only: false,
|
||||
},
|
||||
},
|
||||
...options,
|
||||
},
|
||||
)
|
||||
return { onInstalled, onClose }
|
||||
}
|
||||
|
||||
it('waits for marketplace metadata before rendering imported plugin icons', async () => {
|
||||
const metadata = createDeferred<{ data: { list: { plugin: Plugin }[] } }>()
|
||||
marketplace.mockReturnValue(metadata.promise)
|
||||
renderInstall([dependencies[0]!])
|
||||
|
||||
expect(screen.queryByRole('presentation')).not.toBeInTheDocument()
|
||||
|
||||
metadata.resolve({ data: { list: [{ plugin: plugins[0]! }] } })
|
||||
|
||||
const icon = await screen.findByRole('presentation')
|
||||
expect(icon).toHaveAttribute('src', `${MARKETPLACE_API_PREFIX}/plugins/test/finished/icon`)
|
||||
expect(icon).toBeVisible()
|
||||
})
|
||||
|
||||
it('aggregates finished, failed and running installs and polls only the unfinished task', async () => {
|
||||
const user = userEvent.setup()
|
||||
const pending = createDeferred<{ all_installed: boolean; task_id: string }>()
|
||||
const install = installRequest.mockImplementation(
|
||||
async ({ body }: { body: { plugin_unique_identifiers: string[] } }) => {
|
||||
const id = body.plugin_unique_identifiers[0]
|
||||
if (id === plugins[1]!.latest_package_identifier) throw new Error('Installation rejected')
|
||||
if (id === plugins[2]!.latest_package_identifier) return pending.promise
|
||||
return { all_installed: true, task_id: '' }
|
||||
},
|
||||
)
|
||||
checkTask.mockResolvedValue({
|
||||
task: {
|
||||
plugins: [
|
||||
{
|
||||
plugin_unique_identifier: plugins[2]!.latest_package_identifier,
|
||||
status: TaskStatus.success,
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
const { onInstalled, onClose } = renderInstall()
|
||||
const button = await screen.findByRole('button', { name: 'plugin.installModal.install' })
|
||||
await waitFor(() => expect(button).toBeEnabled())
|
||||
await user.click(button)
|
||||
await screen.findByRole('button', { name: 'plugin.installModal.installing' })
|
||||
expect(
|
||||
screen.getByRole('dialog', { name: 'plugin.installModal.installPlugin' }),
|
||||
).toBeInTheDocument()
|
||||
expect(onInstalled).not.toHaveBeenCalled()
|
||||
expect(install).toHaveBeenCalledTimes(3)
|
||||
pending.resolve({ all_installed: false, task_id: 'running-task' })
|
||||
await waitFor(() => expect(onInstalled).toHaveBeenCalledOnce())
|
||||
expect(
|
||||
screen.getByRole('dialog', { name: 'plugin.installModal.installedSuccessfully' }),
|
||||
).toBeInTheDocument()
|
||||
expect(screen.queryByRole('checkbox')).not.toBeInTheDocument()
|
||||
expect(checkTask).toHaveBeenCalledExactlyOnceWith('running-task')
|
||||
expect(onInstalled).toHaveBeenCalledWith(
|
||||
expect.arrayContaining(plugins.map(({ plugin_id }) => expect.objectContaining({ plugin_id }))),
|
||||
[
|
||||
{ success: true, isFromMarketPlace: true },
|
||||
{ success: false, isFromMarketPlace: true },
|
||||
{ success: true, isFromMarketPlace: true },
|
||||
],
|
||||
plugins.map(() => ({
|
||||
hasInstalled: false,
|
||||
installedVersion: undefined,
|
||||
toInstallVersion: '1.0.0',
|
||||
})),
|
||||
)
|
||||
await user.click(screen.getAllByRole('button', { name: 'common.operation.close' }).at(-1)!)
|
||||
expect(onClose).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('reports failed requests without polling or refreshing installed plugins', async () => {
|
||||
const user = userEvent.setup()
|
||||
installRequest.mockRejectedValue(new Error('Installation rejected'))
|
||||
const { onInstalled } = renderInstall()
|
||||
const button = await screen.findByRole('button', { name: 'plugin.installModal.install' })
|
||||
await waitFor(() => expect(button).toBeEnabled())
|
||||
await user.click(button)
|
||||
await waitFor(() => expect(onInstalled).toHaveBeenCalledOnce())
|
||||
expect(onInstalled).toHaveBeenCalledWith(
|
||||
expect.any(Array),
|
||||
plugins.map(() => ({ success: false, isFromMarketPlace: true })),
|
||||
expect.any(Array),
|
||||
)
|
||||
expect(checkTask).not.toHaveBeenCalled()
|
||||
expect(refresh).not.toHaveBeenCalled()
|
||||
expect(
|
||||
screen.queryByRole('button', { name: 'plugin.installModal.install' }),
|
||||
).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('installs only selected plugins and refreshes the catalog after immediate success', async () => {
|
||||
const user = userEvent.setup()
|
||||
const install = installRequest.mockResolvedValue({ all_installed: true, task_id: '' })
|
||||
const { onInstalled } = renderInstall()
|
||||
const button = await screen.findByRole('button', { name: 'plugin.installModal.install' })
|
||||
await waitFor(() => expect(button).toBeEnabled())
|
||||
await user.click(screen.getByRole('checkbox', { name: 'common.operation.deSelectAll' }))
|
||||
expect(button).toBeDisabled()
|
||||
await user.click(screen.getByRole('checkbox', { name: 'finished' }))
|
||||
await user.click(button)
|
||||
await waitFor(() => expect(onInstalled).toHaveBeenCalledOnce())
|
||||
expect(install).toHaveBeenCalledExactlyOnceWith({
|
||||
body: { plugin_unique_identifiers: [plugins[0]!.latest_package_identifier] },
|
||||
})
|
||||
expect(refresh).toHaveBeenCalledWith(undefined, true)
|
||||
expect(checkTask).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.each(['common.operation.cancel', 'common.operation.close'])(
|
||||
'allows %s before plugin metadata is ready without starting installation',
|
||||
async (name) => {
|
||||
const user = userEvent.setup()
|
||||
marketplace.mockReturnValue(new Promise(() => {}))
|
||||
const { onClose, onInstalled } = renderInstall()
|
||||
expect(screen.getByRole('button', { name: 'plugin.installModal.install' })).toBeDisabled()
|
||||
await user.click(screen.getByRole('button', { name }))
|
||||
expect(onClose).toHaveBeenCalledOnce()
|
||||
expect(installRequest).not.toHaveBeenCalled()
|
||||
expect(onInstalled).not.toHaveBeenCalled()
|
||||
},
|
||||
)
|
||||
|
||||
const packageDependency: PackageDependency = {
|
||||
type: 'package',
|
||||
value: {
|
||||
unique_identifier: 'test/local:2.0.0',
|
||||
manifest: createPluginDeclarationFixture({
|
||||
author: 'test',
|
||||
name: 'local',
|
||||
version: '2.0.0',
|
||||
label: { ...createPluginDeclarationFixture().label, en_US: 'Local plugin' },
|
||||
}),
|
||||
},
|
||||
}
|
||||
const githubDependency: Dependency = {
|
||||
type: 'github',
|
||||
value: { repo: 'test/github', release: 'v3.0.0', packages: 'plugin.difypkg' },
|
||||
}
|
||||
|
||||
it('keeps mixed-source results and version changes aligned with their dependencies', async () => {
|
||||
const user = userEvent.setup()
|
||||
marketplace.mockResolvedValue({ data: { list: [{ plugin: plugins[0] }] } })
|
||||
const installed = createPluginEntity({
|
||||
plugin_id: 'test/finished',
|
||||
plugin_unique_identifier: 'test/finished:0.9.0',
|
||||
})
|
||||
installed.declaration.version = '0.9.0'
|
||||
installedPlugins.mockResolvedValue({ plugins: [installed] })
|
||||
uploadGithub.mockResolvedValue({
|
||||
unique_identifier: 'test/github:3.0.0',
|
||||
manifest: createPluginDeclarationFixture({
|
||||
author: 'test',
|
||||
name: 'github',
|
||||
version: '3.0.0',
|
||||
label: { ...createPluginDeclarationFixture().label, en_US: 'GitHub plugin' },
|
||||
}),
|
||||
})
|
||||
installPackage.mockResolvedValue({ all_installed: true, task_id: '' })
|
||||
upgrade.mockResolvedValue({ all_installed: true, task_id: '' })
|
||||
installGithub.mockRejectedValue(new Error('Package rejected'))
|
||||
const { onInstalled } = renderInstall([packageDependency, dependencies[0]!, githubDependency])
|
||||
const button = screen.getByRole('button', { name: 'plugin.installModal.install' })
|
||||
await waitFor(() => expect(button).toBeEnabled())
|
||||
for (const name of ['local', 'finished', 'github']) {
|
||||
expect(screen.getByRole('checkbox', { name })).toBeChecked()
|
||||
}
|
||||
await user.click(button)
|
||||
await waitFor(() => expect(onInstalled).toHaveBeenCalledOnce())
|
||||
expect(installPackage).toHaveBeenCalledExactlyOnceWith({
|
||||
body: { plugin_unique_identifiers: ['test/local:2.0.0'] },
|
||||
})
|
||||
expect(installGithub).toHaveBeenCalledExactlyOnceWith({
|
||||
body: {
|
||||
repo: 'test/github',
|
||||
version: 'v3.0.0',
|
||||
package: 'plugin.difypkg',
|
||||
plugin_unique_identifier: 'test/github:3.0.0',
|
||||
},
|
||||
})
|
||||
expect(upgrade).toHaveBeenCalledExactlyOnceWith({
|
||||
body: {
|
||||
original_plugin_unique_identifier: 'test/finished:0.9.0',
|
||||
new_plugin_unique_identifier: 'test/finished:1.0.0',
|
||||
},
|
||||
})
|
||||
expect(installRequest).not.toHaveBeenCalled()
|
||||
expect(onInstalled).toHaveBeenCalledWith(
|
||||
[
|
||||
expect.objectContaining({ name: 'local' }),
|
||||
expect.objectContaining({ name: 'finished' }),
|
||||
expect.objectContaining({ name: 'github' }),
|
||||
],
|
||||
[
|
||||
{ success: true, isFromMarketPlace: false },
|
||||
{ success: true, isFromMarketPlace: true },
|
||||
{ success: false, isFromMarketPlace: false },
|
||||
],
|
||||
[
|
||||
{ hasInstalled: false, installedVersion: undefined, toInstallVersion: '2.0.0' },
|
||||
{ hasInstalled: true, installedVersion: '0.9.0', toInstallVersion: '1.0.0' },
|
||||
{ hasInstalled: false, installedVersion: undefined, toInstallVersion: '3.0.0' },
|
||||
],
|
||||
)
|
||||
expect(screen.getByText('0.9.0 -> 1.0.0')).toBeInTheDocument()
|
||||
expect(screen.getByText('2.0.0')).toBeInTheDocument()
|
||||
expect(screen.getByText('3.0.0')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('excludes failed metadata loads from selection and installs the remaining package', async () => {
|
||||
const user = userEvent.setup()
|
||||
marketplace.mockRejectedValue(new Error('Marketplace unavailable'))
|
||||
uploadGithub.mockRejectedValue(new Error('GitHub unavailable'))
|
||||
installPackage.mockResolvedValue({ all_installed: true, task_id: '' })
|
||||
const { onInstalled } = renderInstall([dependencies[0]!, githubDependency, packageDependency])
|
||||
await waitFor(() =>
|
||||
expect(screen.getAllByText('plugin.installModal.pluginLoadError')).toHaveLength(2),
|
||||
)
|
||||
const button = screen.getByRole('button', { name: 'plugin.installModal.install' })
|
||||
await waitFor(() => expect(button).toBeEnabled())
|
||||
expect(screen.getByRole('checkbox', { name: 'local' })).toBeChecked()
|
||||
await user.click(screen.getByRole('checkbox', { name: 'common.operation.deSelectAll' }))
|
||||
expect(button).toBeDisabled()
|
||||
await user.click(screen.getByRole('checkbox', { name: 'common.operation.selectAll' }))
|
||||
await user.click(button)
|
||||
await waitFor(() => expect(onInstalled).toHaveBeenCalledOnce())
|
||||
expect(onInstalled).toHaveBeenCalledWith(
|
||||
[expect.objectContaining({ name: 'local' })],
|
||||
[{ success: true, isFromMarketPlace: false }],
|
||||
[{ hasInstalled: false, installedVersion: undefined, toInstallVersion: '2.0.0' }],
|
||||
)
|
||||
expect(installPackage).toHaveBeenCalledExactlyOnceWith({
|
||||
body: { plugin_unique_identifiers: ['test/local:2.0.0'] },
|
||||
})
|
||||
expect(installRequest).not.toHaveBeenCalled()
|
||||
expect(installGithub).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('excludes restricted plugins when selecting all and prevents selecting them individually', async () => {
|
||||
const user = userEvent.setup()
|
||||
marketplace.mockResolvedValue({
|
||||
data: {
|
||||
list: [
|
||||
{ plugin: { ...plugins[0], verification: { authorized_category: 'langgenius' } } },
|
||||
{ plugin: plugins[1] },
|
||||
],
|
||||
},
|
||||
})
|
||||
installRequest.mockResolvedValue({ all_installed: true, task_id: '' })
|
||||
const { onInstalled } = renderInstall(dependencies.slice(0, 2), {
|
||||
systemFeatures: {
|
||||
enable_marketplace: true,
|
||||
plugin_installation_permission: {
|
||||
plugin_installation_scope: 'official_only',
|
||||
restrict_to_marketplace_only: false,
|
||||
},
|
||||
},
|
||||
})
|
||||
const button = screen.getByRole('button', { name: 'plugin.installModal.install' })
|
||||
await waitFor(() => expect(button).toBeEnabled())
|
||||
const restricted = screen.getByRole('checkbox', { name: 'failed' })
|
||||
expect(restricted).toHaveAttribute('aria-disabled', 'true')
|
||||
await user.click(restricted)
|
||||
expect(restricted).not.toBeChecked()
|
||||
expect(screen.getByRole('checkbox', { name: 'finished' })).toBeChecked()
|
||||
await user.click(button)
|
||||
await waitFor(() => expect(onInstalled).toHaveBeenCalledOnce())
|
||||
expect(installRequest).toHaveBeenCalledExactlyOnceWith({
|
||||
body: { plugin_unique_identifiers: ['test/finished:1.0.0'] },
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,97 @@
|
||||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import type { Dependency, InstallStatus, Plugin, VersionProps } from '../../types'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogHeaderCloseButton,
|
||||
DialogTitle,
|
||||
} from '@langgenius/dify-ui/dialog'
|
||||
import * as React from 'react'
|
||||
import { useCallback, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { InstallStep } from '../../types'
|
||||
import useHideLogic from '../hooks/use-hide-logic'
|
||||
import ReadyToInstall from './ready-to-install'
|
||||
|
||||
const i18nPrefix = 'installModal'
|
||||
|
||||
export type InstallBundleCompleteCallback = (
|
||||
plugins: Plugin[],
|
||||
installStatus: InstallStatus[],
|
||||
versionInfo: VersionProps[],
|
||||
) => void
|
||||
|
||||
const InstallType = {
|
||||
fromLocal: 'fromLocal',
|
||||
fromMarketplace: 'fromMarketplace',
|
||||
fromDSL: 'fromDSL',
|
||||
} as const
|
||||
|
||||
type InstallType = (typeof InstallType)[keyof typeof InstallType]
|
||||
|
||||
type Props = Readonly<{
|
||||
installType?: InstallType
|
||||
fromDSLPayload: Dependency[]
|
||||
// plugins?: PluginDeclaration[]
|
||||
onClose: () => void
|
||||
onInstallComplete?: InstallBundleCompleteCallback
|
||||
}>
|
||||
|
||||
const InstallBundle: FC<Props> = ({
|
||||
installType = InstallType.fromMarketplace,
|
||||
fromDSLPayload,
|
||||
onClose,
|
||||
onInstallComplete,
|
||||
}) => {
|
||||
const { t } = useTranslation(['common', 'plugin'])
|
||||
const [step, setStep] = useState<InstallStep>(
|
||||
installType === InstallType.fromMarketplace
|
||||
? InstallStep.readyToInstall
|
||||
: InstallStep.uploading,
|
||||
)
|
||||
|
||||
const { modalClassName, foldAnimInto, setIsInstalling, handleStartToInstall } =
|
||||
useHideLogic(onClose)
|
||||
|
||||
const getTitle = useCallback(() => {
|
||||
if (step === InstallStep.uploadFailed)
|
||||
return t(($) => $[`${i18nPrefix}.uploadFailed`], { ns: 'plugin' })
|
||||
if (step === InstallStep.installed)
|
||||
return t(($) => $[`${i18nPrefix}.installedSuccessfully`], { ns: 'plugin' })
|
||||
|
||||
return t(($) => $[`${i18nPrefix}.installPlugin`], { ns: 'plugin' })
|
||||
}, [step, t])
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
onOpenChange={(open) => {
|
||||
if (!open) foldAnimInto()
|
||||
}}
|
||||
>
|
||||
<DialogContent
|
||||
backdropProps={{ forceRender: true }}
|
||||
className={cn('w-120', modalClassName, 'max-h-[calc(100dvh-48px)] min-w-140')}
|
||||
>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{getTitle()}</DialogTitle>
|
||||
<DialogHeaderCloseButton aria-label={t(($) => $['operation.close'], { ns: 'common' })} />
|
||||
</DialogHeader>
|
||||
<ReadyToInstall
|
||||
step={step}
|
||||
onStepChange={setStep}
|
||||
onStartToInstall={handleStartToInstall}
|
||||
setIsInstalling={setIsInstalling}
|
||||
allPlugins={fromDSLPayload}
|
||||
onClose={onClose}
|
||||
onInstallComplete={onInstallComplete}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
export default React.memo(InstallBundle)
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import type { GitHubItemAndMarketPlaceDependency, Plugin, VersionProps } from '../../../types'
|
||||
import * as React from 'react'
|
||||
import { useEffect } from 'react'
|
||||
import { useUploadGitHub } from '@/service/use-plugins'
|
||||
import Loading from '../../base/loading'
|
||||
import { pluginDeclarationToCardPluginProps } from '../../utils'
|
||||
import LoadedItem from './loaded-item'
|
||||
|
||||
type Props = Readonly<{
|
||||
checked: boolean
|
||||
onCheckedChange: (plugin: Plugin) => void
|
||||
dependency: GitHubItemAndMarketPlaceDependency
|
||||
versionInfo: VersionProps
|
||||
onFetchedPayload: (payload: Plugin) => void
|
||||
onFetchError: () => void
|
||||
}>
|
||||
|
||||
const Item: FC<Props> = ({
|
||||
checked,
|
||||
onCheckedChange,
|
||||
dependency,
|
||||
versionInfo,
|
||||
onFetchedPayload,
|
||||
onFetchError,
|
||||
}) => {
|
||||
const info = dependency.value
|
||||
const { data, error } = useUploadGitHub({
|
||||
repo: info.repo!,
|
||||
version: info.release! || info.version!,
|
||||
package: info.packages! || info.package!,
|
||||
})
|
||||
const [payload, setPayload] = React.useState<Plugin | null>(null)
|
||||
useEffect(() => {
|
||||
if (data) {
|
||||
const payload = {
|
||||
...pluginDeclarationToCardPluginProps(data.manifest, data.unique_identifier),
|
||||
}
|
||||
onFetchedPayload(payload)
|
||||
setPayload({ ...payload, from: dependency.type })
|
||||
}
|
||||
}, [data])
|
||||
useEffect(() => {
|
||||
if (error) onFetchError()
|
||||
}, [error])
|
||||
if (!payload) return <Loading />
|
||||
return (
|
||||
<LoadedItem
|
||||
payload={payload}
|
||||
versionInfo={versionInfo}
|
||||
checked={checked}
|
||||
onCheckedChange={onCheckedChange}
|
||||
/>
|
||||
)
|
||||
}
|
||||
export default React.memo(Item)
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import type { Plugin, VersionProps } from '../../../types'
|
||||
import { Checkbox } from '@langgenius/dify-ui/checkbox'
|
||||
import * as React from 'react'
|
||||
import { getMarketplacePluginIconUrl } from '@/features/marketplace/api'
|
||||
import Card from '../../../card'
|
||||
import useGetIcon from '../../base/use-get-icon'
|
||||
import Version from '../../base/version'
|
||||
import usePluginInstallLimit from '../../hooks/use-install-plugin-limit'
|
||||
|
||||
type Props = Readonly<{
|
||||
checked: boolean
|
||||
onCheckedChange: (plugin: Plugin) => void
|
||||
payload: Plugin
|
||||
isFromMarketPlace?: boolean
|
||||
versionInfo: VersionProps
|
||||
}>
|
||||
|
||||
const LoadedItem: FC<Props> = ({
|
||||
checked,
|
||||
onCheckedChange,
|
||||
payload,
|
||||
isFromMarketPlace,
|
||||
versionInfo: particleVersionInfo,
|
||||
}) => {
|
||||
const { getIconUrl } = useGetIcon()
|
||||
const versionInfo = {
|
||||
...particleVersionInfo,
|
||||
toInstallVersion: payload.version,
|
||||
}
|
||||
const { canInstall } = usePluginInstallLimit(payload)
|
||||
return (
|
||||
<div className="flex items-center space-x-2">
|
||||
<Checkbox
|
||||
disabled={!canInstall}
|
||||
className="shrink-0"
|
||||
checked={checked}
|
||||
aria-label={payload.name}
|
||||
onCheckedChange={() => onCheckedChange(payload)}
|
||||
/>
|
||||
<Card
|
||||
className="grow"
|
||||
payload={{
|
||||
...payload,
|
||||
icon: isFromMarketPlace
|
||||
? getMarketplacePluginIconUrl(`${payload.org}/${payload.name}`)
|
||||
: getIconUrl(payload.icon),
|
||||
}}
|
||||
titleLeft={payload.version ? <Version {...versionInfo} /> : null}
|
||||
limitedInstall={!canInstall}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default React.memo(LoadedItem)
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import type { Plugin, VersionProps } from '../../../types'
|
||||
import * as React from 'react'
|
||||
import Loading from '../../base/loading'
|
||||
import LoadedItem from './loaded-item'
|
||||
|
||||
type Props = Readonly<{
|
||||
checked: boolean
|
||||
onCheckedChange: (plugin: Plugin) => void
|
||||
payload?: Plugin
|
||||
version: string
|
||||
versionInfo: VersionProps
|
||||
}>
|
||||
|
||||
const MarketPlaceItem: FC<Props> = ({
|
||||
checked,
|
||||
onCheckedChange,
|
||||
payload,
|
||||
version,
|
||||
versionInfo,
|
||||
}) => {
|
||||
if (!payload) return <Loading />
|
||||
return (
|
||||
<LoadedItem
|
||||
checked={checked}
|
||||
onCheckedChange={onCheckedChange}
|
||||
payload={{ ...payload, version }}
|
||||
isFromMarketPlace
|
||||
versionInfo={versionInfo}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export default React.memo(MarketPlaceItem)
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import type { PackageDependency, Plugin, VersionProps } from '../../../types'
|
||||
import * as React from 'react'
|
||||
import LoadingError from '../../base/loading-error'
|
||||
import { pluginManifestToCardPluginProps } from '../../utils'
|
||||
import LoadedItem from './loaded-item'
|
||||
|
||||
type Props = Readonly<{
|
||||
checked: boolean
|
||||
onCheckedChange: (plugin: Plugin) => void
|
||||
payload: PackageDependency
|
||||
isFromMarketPlace?: boolean
|
||||
versionInfo: VersionProps
|
||||
}>
|
||||
|
||||
const PackageItem: FC<Props> = ({
|
||||
payload,
|
||||
checked,
|
||||
onCheckedChange,
|
||||
isFromMarketPlace,
|
||||
versionInfo,
|
||||
}) => {
|
||||
if (!payload.value?.manifest) return <LoadingError />
|
||||
|
||||
const plugin = pluginManifestToCardPluginProps(payload.value.manifest)
|
||||
return (
|
||||
<LoadedItem
|
||||
payload={{ ...plugin, from: payload.type }}
|
||||
checked={checked}
|
||||
onCheckedChange={onCheckedChange}
|
||||
isFromMarketPlace={isFromMarketPlace}
|
||||
versionInfo={versionInfo}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export default React.memo(PackageItem)
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import type { Dependency, InstallStatus, Plugin, VersionProps } from '../../types'
|
||||
import type { InstallBundleCompleteCallback } from './index'
|
||||
import * as React from 'react'
|
||||
import { useCallback, useState } from 'react'
|
||||
import { InstallStep } from '../../types'
|
||||
import Install from './steps/install'
|
||||
import Installed from './steps/installed'
|
||||
|
||||
type Props = Readonly<{
|
||||
step: InstallStep
|
||||
onStepChange: (step: InstallStep) => void
|
||||
onStartToInstall: () => void
|
||||
setIsInstalling: (isInstalling: boolean) => void
|
||||
allPlugins: Dependency[]
|
||||
onClose: () => void
|
||||
onInstallComplete?: InstallBundleCompleteCallback
|
||||
isFromMarketPlace?: boolean
|
||||
}>
|
||||
|
||||
const ReadyToInstall: FC<Props> = ({
|
||||
step,
|
||||
onStepChange,
|
||||
onStartToInstall,
|
||||
setIsInstalling,
|
||||
allPlugins,
|
||||
onClose,
|
||||
onInstallComplete,
|
||||
isFromMarketPlace,
|
||||
}) => {
|
||||
const [installedPlugins, setInstalledPlugins] = useState<Plugin[]>([])
|
||||
const [installStatus, setInstallStatus] = useState<InstallStatus[]>([])
|
||||
const [installedVersionInfo, setInstalledVersionInfo] = useState<VersionProps[]>([])
|
||||
const handleInstalled = useCallback(
|
||||
(plugins: Plugin[], installStatus: InstallStatus[], versionInfo: VersionProps[]) => {
|
||||
setInstallStatus(installStatus)
|
||||
setInstalledPlugins(plugins)
|
||||
setInstalledVersionInfo(versionInfo)
|
||||
onStepChange(InstallStep.installed)
|
||||
setIsInstalling(false)
|
||||
onInstallComplete?.(plugins, installStatus, versionInfo)
|
||||
},
|
||||
[onInstallComplete, onStepChange, setIsInstalling],
|
||||
)
|
||||
return (
|
||||
<>
|
||||
{step === InstallStep.readyToInstall && (
|
||||
<Install
|
||||
allPlugins={allPlugins}
|
||||
onCancel={onClose}
|
||||
onStartToInstall={onStartToInstall}
|
||||
onInstalled={handleInstalled}
|
||||
isFromMarketPlace={isFromMarketPlace}
|
||||
/>
|
||||
)}
|
||||
{step === InstallStep.installed && (
|
||||
<Installed
|
||||
list={installedPlugins}
|
||||
installStatus={installStatus}
|
||||
versionInfo={installedVersionInfo}
|
||||
onCancel={onClose}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
export default React.memo(ReadyToInstall)
|
||||
+216
@@ -0,0 +1,216 @@
|
||||
import type {
|
||||
Dependency,
|
||||
GitHubItemAndMarketPlaceDependency,
|
||||
PackageDependency,
|
||||
Plugin,
|
||||
} from '@/app/components/plugins/types'
|
||||
import { act, waitFor } from '@testing-library/react'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
|
||||
import { PluginCategoryEnum } from '@/app/components/plugins/types'
|
||||
import { renderHookWithConsoleQuery as renderHook } from '@/test/console/query-data'
|
||||
import { createDeferred } from '@/test/deferred'
|
||||
import { createPluginDeclarationFixture } from '@/test/fixtures/plugin'
|
||||
import { useInstallMultiState } from '../use-install-multi-state'
|
||||
|
||||
const requests = vi.hoisted(() => ({ marketplace: vi.fn(), installed: vi.fn() }))
|
||||
vi.mock('@/service/base', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('@/service/base')>()),
|
||||
postMarketplace: requests.marketplace,
|
||||
}))
|
||||
vi.mock('@/service/console', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/service/console')>()
|
||||
const { withConsoleResponses } = await import('@/test/console/service-responses')
|
||||
return {
|
||||
...actual,
|
||||
consoleQuery: withConsoleResponses(actual.consoleQuery, {
|
||||
'workspaces.current.plugin.list.installations.ids.post': requests.installed,
|
||||
}),
|
||||
}
|
||||
})
|
||||
|
||||
const createMockPlugin = (overrides: Partial<Plugin> = {}): Plugin => ({
|
||||
type: 'plugin',
|
||||
org: 'test-org',
|
||||
name: 'Test Plugin',
|
||||
plugin_id: 'test-plugin-id',
|
||||
version: '1.0.0',
|
||||
latest_version: '1.0.0',
|
||||
latest_package_identifier: 'test-pkg-id',
|
||||
icon: 'icon.png',
|
||||
verified: true,
|
||||
label: { 'en-US': 'Test Plugin' },
|
||||
brief: { 'en-US': 'Brief' },
|
||||
description: { 'en-US': 'Description' },
|
||||
introduction: 'Intro',
|
||||
repository: 'https://github.com/test/plugin',
|
||||
category: PluginCategoryEnum.tool,
|
||||
install_count: 100,
|
||||
endpoint: { settings: [] },
|
||||
tags: [],
|
||||
badges: [],
|
||||
verification: { authorized_category: 'community' },
|
||||
from: 'marketplace',
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const packageDependency: PackageDependency = {
|
||||
type: 'package',
|
||||
value: {
|
||||
unique_identifier: 'test/local:1.0.0',
|
||||
manifest: createPluginDeclarationFixture({ author: 'test', name: 'local' }),
|
||||
},
|
||||
}
|
||||
const githubDependency: Dependency = {
|
||||
type: 'github',
|
||||
value: { repo: 'test/github', release: 'v1.0.0', packages: 'plugin.difypkg' },
|
||||
}
|
||||
const marketplaceDependency: GitHubItemAndMarketPlaceDependency = {
|
||||
type: 'marketplace',
|
||||
value: { marketplace_plugin_unique_identifier: 'test/remote:1.0.0@hash' },
|
||||
}
|
||||
const params = (allPlugins: Dependency[]) => ({
|
||||
allPlugins,
|
||||
selectedPlugins: [] as Plugin[],
|
||||
onSelect: vi.fn(),
|
||||
onLoadedAllPlugin: vi.fn(),
|
||||
})
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
requests.installed.mockResolvedValue({ plugins: [] })
|
||||
requests.marketplace.mockResolvedValue({ data: { list: [] } })
|
||||
})
|
||||
|
||||
describe('bundle metadata', () => {
|
||||
it.each([
|
||||
{ marketplace_plugin_unique_identifier: 'test/remote:1.0.0@hash' },
|
||||
{ organization: 'test', plugin: 'remote', version: '1.0.0' },
|
||||
])('normalizes dependency %j and maps metadata back to the original slots', async (value) => {
|
||||
const remote = createMockPlugin({ org: 'test', name: 'remote', plugin_id: 'test/remote' })
|
||||
const second = createMockPlugin({
|
||||
org: 'test',
|
||||
name: 'second',
|
||||
plugin_id: 'test/second',
|
||||
version: '',
|
||||
latest_version: '2.0.0',
|
||||
})
|
||||
// For identifier dependencies, the response can arrive in a different order.
|
||||
const responseOrder =
|
||||
'marketplace_plugin_unique_identifier' in value ? [remote, second] : [second, remote]
|
||||
requests.marketplace.mockResolvedValue({
|
||||
data: { list: responseOrder.map((plugin) => ({ plugin })) },
|
||||
})
|
||||
const input = params([
|
||||
packageDependency,
|
||||
{ type: 'marketplace', value: { marketplace_plugin_unique_identifier: 'test/second:2.0.0' } },
|
||||
{ type: 'marketplace', value },
|
||||
])
|
||||
const { result } = renderHook(() => useInstallMultiState(input))
|
||||
await waitFor(() => expect(input.onLoadedAllPlugin).toHaveBeenCalledWith({}))
|
||||
expect(requests.marketplace).toHaveBeenCalledWith('/plugins/versions/batch', {
|
||||
body: {
|
||||
plugin_tuples: [
|
||||
{ org: 'test', name: 'second', version: '2.0.0' },
|
||||
{ org: 'test', name: 'remote', version: '1.0.0' },
|
||||
],
|
||||
},
|
||||
})
|
||||
expect(result.current.plugins).toMatchObject([
|
||||
{ plugin_id: 'test/local:1.0.0' },
|
||||
{ plugin_id: 'test/second', version: '2.0.0' },
|
||||
{ plugin_id: 'test/remote', version: '1.0.0' },
|
||||
])
|
||||
expect(requests.installed).toHaveBeenCalledWith({
|
||||
body: { plugin_ids: ['test/local', 'test/second', 'test/remote'] },
|
||||
})
|
||||
expect(result.current.errorIndexes).toEqual([])
|
||||
})
|
||||
|
||||
it.each(['invalid-identifier', 'test/:1.0.0', undefined])(
|
||||
'rejects malformed marketplace identifier %s without fetching it',
|
||||
async (identifier) => {
|
||||
const input = params([
|
||||
packageDependency,
|
||||
{ type: 'marketplace', value: { marketplace_plugin_unique_identifier: identifier } },
|
||||
])
|
||||
const { result } = renderHook(() => useInstallMultiState(input))
|
||||
await waitFor(() => expect(input.onLoadedAllPlugin).toHaveBeenCalledWith({}))
|
||||
expect(result.current.errorIndexes).toEqual([1])
|
||||
expect(requests.marketplace).not.toHaveBeenCalled()
|
||||
},
|
||||
)
|
||||
|
||||
it('marks only missing marketplace entries as failed', async () => {
|
||||
requests.marketplace.mockResolvedValue({
|
||||
data: { list: [{ plugin: createMockPlugin({ plugin_id: 'test/remote' }) }] },
|
||||
})
|
||||
const input = params([
|
||||
packageDependency,
|
||||
marketplaceDependency,
|
||||
{
|
||||
type: 'marketplace',
|
||||
value: { marketplace_plugin_unique_identifier: 'test/missing:1.0.0' },
|
||||
},
|
||||
])
|
||||
const { result } = renderHook(() => useInstallMultiState(input))
|
||||
await waitFor(() => expect(input.onLoadedAllPlugin).toHaveBeenCalledWith({}))
|
||||
expect(result.current.errorIndexes).toEqual([2])
|
||||
expect(result.current.plugins[0]?.plugin_id).toBe('test/local:1.0.0')
|
||||
expect(result.current.plugins[1]?.plugin_id).toBe('test/remote')
|
||||
})
|
||||
|
||||
it('waits for every source and installed lookup while preserving concurrent GitHub results and failures', async () => {
|
||||
requests.marketplace.mockRejectedValueOnce(new Error('Marketplace unavailable'))
|
||||
const installed = createDeferred<{ plugins: [] }>()
|
||||
requests.installed.mockReturnValueOnce(installed.promise)
|
||||
const input = params([
|
||||
packageDependency,
|
||||
marketplaceDependency,
|
||||
githubDependency,
|
||||
githubDependency,
|
||||
githubDependency,
|
||||
])
|
||||
const { result } = renderHook(() => useInstallMultiState(input))
|
||||
await waitFor(() => expect(result.current.errorIndexes).toEqual([1]))
|
||||
expect(input.onLoadedAllPlugin).not.toHaveBeenCalled()
|
||||
expect(requests.installed).not.toHaveBeenCalled()
|
||||
const github = createMockPlugin({ org: 'test', name: 'github', plugin_id: 'test/github' })
|
||||
act(() => {
|
||||
result.current.handleGitHubPluginFetched(2)(github)
|
||||
result.current.handleGitHubPluginFetchError(3)()
|
||||
result.current.handleGitHubPluginFetchError(4)()
|
||||
})
|
||||
await waitFor(() => expect(requests.installed).toHaveBeenCalledOnce())
|
||||
expect(input.onLoadedAllPlugin).not.toHaveBeenCalled()
|
||||
installed.resolve({ plugins: [] })
|
||||
await waitFor(() => expect(input.onLoadedAllPlugin).toHaveBeenCalledWith({}))
|
||||
expect(result.current.errorIndexes).toEqual([1, 3, 4])
|
||||
expect(result.current.plugins).toEqual([
|
||||
expect.objectContaining({ plugin_id: 'test/local:1.0.0' }),
|
||||
undefined,
|
||||
github,
|
||||
undefined,
|
||||
undefined,
|
||||
])
|
||||
})
|
||||
|
||||
it('excludes unresolved plugins from bulk selection before metadata finishes', () => {
|
||||
const input = params([packageDependency, githubDependency])
|
||||
input.selectedPlugins = [createMockPlugin({ plugin_id: 'test/local:1.0.0' })]
|
||||
const { result } = renderHook(() => useInstallMultiState(input), {
|
||||
systemFeatures: {
|
||||
plugin_installation_permission: {
|
||||
plugin_installation_scope: 'all',
|
||||
restrict_to_marketplace_only: false,
|
||||
},
|
||||
},
|
||||
})
|
||||
expect(result.current.getInstallablePlugins()).toEqual({
|
||||
installablePlugins: [expect.objectContaining({ plugin_id: 'test/local:1.0.0' })],
|
||||
selectedIndexes: [0],
|
||||
})
|
||||
expect(result.current.isPluginSelected(0)).toBe(true)
|
||||
expect(result.current.isPluginSelected(1)).toBe(false)
|
||||
expect(input.onLoadedAllPlugin).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
+292
@@ -0,0 +1,292 @@
|
||||
'use client'
|
||||
|
||||
import type {
|
||||
Dependency,
|
||||
GitHubItemAndMarketPlaceDependency,
|
||||
PackageDependency,
|
||||
Plugin,
|
||||
VersionInfo,
|
||||
} from '@/app/components/plugins/types'
|
||||
import { useSuspenseQuery } from '@tanstack/react-query'
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import useCheckInstalled from '@/app/components/plugins/install-plugin/hooks/use-check-installed'
|
||||
import { pluginInstallLimit } from '@/app/components/plugins/install-plugin/hooks/use-install-plugin-limit'
|
||||
import { getFormattedPlugin } from '@/app/components/plugins/marketplace/utils'
|
||||
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
|
||||
import { useFetchPluginsInMarketPlaceByInfo } from '@/service/use-plugins'
|
||||
|
||||
type UseInstallMultiStateParams = {
|
||||
allPlugins: Dependency[]
|
||||
selectedPlugins: Plugin[]
|
||||
onSelect: (plugin: Plugin, selectedIndex: number, allCanInstallPluginsLength: number) => void
|
||||
onLoadedAllPlugin: (installedInfo: Record<string, VersionInfo>) => void
|
||||
}
|
||||
|
||||
type MarketplacePluginInfo = {
|
||||
organization: string
|
||||
plugin: string
|
||||
version?: string
|
||||
}
|
||||
|
||||
type MarketplaceRequest = {
|
||||
dslIndex: number
|
||||
dependency: GitHubItemAndMarketPlaceDependency
|
||||
info: MarketplacePluginInfo
|
||||
}
|
||||
|
||||
export function getPluginKey(plugin: Plugin | undefined): string {
|
||||
return `${plugin?.org || plugin?.author}/${plugin?.name}`
|
||||
}
|
||||
|
||||
function parseMarketplaceIdentifier(identifier?: string): MarketplacePluginInfo | null {
|
||||
if (!identifier) return null
|
||||
|
||||
const withoutHash = identifier.split('@')[0]
|
||||
const [organization, nameAndVersionPart] = withoutHash!.split('/')
|
||||
if (!organization || !nameAndVersionPart) return null
|
||||
|
||||
const [plugin, version] = nameAndVersionPart.split(':')
|
||||
if (!plugin) return null
|
||||
|
||||
return { organization, plugin, version }
|
||||
}
|
||||
|
||||
function getMarketplacePluginInfo(
|
||||
value: GitHubItemAndMarketPlaceDependency['value'],
|
||||
): MarketplacePluginInfo | null {
|
||||
const parsedInfo = parseMarketplaceIdentifier(
|
||||
value.marketplace_plugin_unique_identifier || value.plugin_unique_identifier,
|
||||
)
|
||||
if (parsedInfo) return parsedInfo
|
||||
|
||||
if (!value.organization || !value.plugin) return null
|
||||
|
||||
return {
|
||||
organization: value.organization,
|
||||
plugin: value.plugin,
|
||||
version: value.version,
|
||||
}
|
||||
}
|
||||
|
||||
function initPluginsFromDependencies(allPlugins: Dependency[]): (Plugin | undefined)[] {
|
||||
if (!allPlugins.some((d) => d.type === 'package')) return []
|
||||
|
||||
return allPlugins.map((d) => {
|
||||
if (d.type !== 'package') return undefined
|
||||
const { manifest, unique_identifier } = (d as PackageDependency).value
|
||||
return {
|
||||
...manifest,
|
||||
plugin_id: unique_identifier,
|
||||
} as unknown as Plugin
|
||||
})
|
||||
}
|
||||
|
||||
export function useInstallMultiState({
|
||||
allPlugins,
|
||||
selectedPlugins,
|
||||
onSelect,
|
||||
onLoadedAllPlugin,
|
||||
}: UseInstallMultiStateParams) {
|
||||
const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
|
||||
|
||||
// Marketplace plugins filtering and index mapping
|
||||
const marketplacePlugins = useMemo(
|
||||
() =>
|
||||
allPlugins.filter((d): d is GitHubItemAndMarketPlaceDependency => d.type === 'marketplace'),
|
||||
[allPlugins],
|
||||
)
|
||||
|
||||
const marketPlaceInDSLIndex = useMemo(() => {
|
||||
return allPlugins.reduce<number[]>((acc, d, index) => {
|
||||
if (d.type === 'marketplace') acc.push(index)
|
||||
return acc
|
||||
}, [])
|
||||
}, [allPlugins])
|
||||
|
||||
const { marketplaceRequests, invalidMarketplaceIndexes } = useMemo(() => {
|
||||
return marketplacePlugins.reduce<{
|
||||
marketplaceRequests: MarketplaceRequest[]
|
||||
invalidMarketplaceIndexes: number[]
|
||||
}>(
|
||||
(acc, dependency, marketplaceIndex) => {
|
||||
const dslIndex = marketPlaceInDSLIndex[marketplaceIndex]
|
||||
if (dslIndex === undefined) return acc
|
||||
|
||||
const marketplaceInfo = getMarketplacePluginInfo(dependency.value)
|
||||
if (!marketplaceInfo) acc.invalidMarketplaceIndexes.push(dslIndex)
|
||||
else acc.marketplaceRequests.push({ dslIndex, dependency, info: marketplaceInfo })
|
||||
|
||||
return acc
|
||||
},
|
||||
{
|
||||
marketplaceRequests: [],
|
||||
invalidMarketplaceIndexes: [],
|
||||
},
|
||||
)
|
||||
}, [marketPlaceInDSLIndex, marketplacePlugins])
|
||||
|
||||
// Marketplace data fetching: by normalized marketplace info
|
||||
const {
|
||||
isLoading: isFetchingById,
|
||||
data: infoGetById,
|
||||
error: infoByIdError,
|
||||
} = useFetchPluginsInMarketPlaceByInfo(marketplaceRequests.map((request) => request.info))
|
||||
|
||||
// Derive marketplace plugin data and errors from API responses
|
||||
const { marketplacePluginMap, marketplaceErrorIndexes } = useMemo(() => {
|
||||
const pluginMap = new Map<number, Plugin>()
|
||||
const errorSet = new Set<number>(invalidMarketplaceIndexes)
|
||||
|
||||
// Process "by ID" response
|
||||
if (!isFetchingById && infoGetById?.data.list) {
|
||||
const payloads = infoGetById.data.list
|
||||
const pluginById = new Map(payloads.map((item) => [item.plugin.plugin_id, item.plugin]))
|
||||
|
||||
marketplaceRequests.forEach((request, requestIndex) => {
|
||||
const pluginId = (
|
||||
request.dependency.value.marketplace_plugin_unique_identifier ||
|
||||
request.dependency.value.plugin_unique_identifier
|
||||
)?.split(':')[0]
|
||||
const pluginInfo =
|
||||
(pluginId ? pluginById.get(pluginId) : undefined) || payloads[requestIndex]?.plugin
|
||||
|
||||
if (pluginInfo) {
|
||||
pluginMap.set(
|
||||
request.dslIndex,
|
||||
getFormattedPlugin({
|
||||
...pluginInfo,
|
||||
from: request.dependency.type,
|
||||
version: pluginInfo.version || pluginInfo.latest_version,
|
||||
}),
|
||||
)
|
||||
} else {
|
||||
errorSet.add(request.dslIndex)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Mark all marketplace indexes as errors on fetch failure
|
||||
if (infoByIdError) marketPlaceInDSLIndex.forEach((index) => errorSet.add(index))
|
||||
|
||||
return { marketplacePluginMap: pluginMap, marketplaceErrorIndexes: errorSet }
|
||||
}, [
|
||||
invalidMarketplaceIndexes,
|
||||
isFetchingById,
|
||||
infoGetById,
|
||||
infoByIdError,
|
||||
marketPlaceInDSLIndex,
|
||||
marketplaceRequests,
|
||||
])
|
||||
|
||||
// GitHub-fetched plugins and errors (imperative state from child callbacks)
|
||||
const [githubPluginMap, setGithubPluginMap] = useState<Map<number, Plugin>>(() => new Map())
|
||||
const [githubErrorIndexes, setGithubErrorIndexes] = useState<number[]>([])
|
||||
|
||||
// Merge all plugin sources into a single array
|
||||
const plugins = useMemo(() => {
|
||||
const initial = initPluginsFromDependencies(allPlugins)
|
||||
const result: (Plugin | undefined)[] = allPlugins.map((_, i) => initial[i])
|
||||
marketplacePluginMap.forEach((plugin, index) => {
|
||||
result[index] = plugin
|
||||
})
|
||||
githubPluginMap.forEach((plugin, index) => {
|
||||
result[index] = plugin
|
||||
})
|
||||
return result
|
||||
}, [allPlugins, marketplacePluginMap, githubPluginMap])
|
||||
|
||||
// Merge all error sources
|
||||
const errorIndexes = useMemo(() => {
|
||||
return [...marketplaceErrorIndexes, ...githubErrorIndexes]
|
||||
}, [marketplaceErrorIndexes, githubErrorIndexes])
|
||||
|
||||
// Check installed status after all data is loaded
|
||||
const isLoadedAllData = plugins.filter(Boolean).length + errorIndexes.length === allPlugins.length
|
||||
|
||||
const { installedInfo } = useCheckInstalled({
|
||||
pluginIds: plugins.filter(Boolean).map((d) => getPluginKey(d)) || [],
|
||||
enabled: isLoadedAllData,
|
||||
})
|
||||
|
||||
// Notify parent when all plugin data and install info is ready
|
||||
useEffect(() => {
|
||||
if (isLoadedAllData && installedInfo) onLoadedAllPlugin(installedInfo!)
|
||||
// oxlint-disable-next-line react/exhaustive-deps
|
||||
}, [isLoadedAllData, installedInfo])
|
||||
|
||||
// Callback: handle GitHub plugin fetch success
|
||||
const handleGitHubPluginFetched = useCallback((index: number) => {
|
||||
return (p: Plugin) => {
|
||||
setGithubPluginMap((prev) => new Map(prev).set(index, p))
|
||||
}
|
||||
}, [])
|
||||
|
||||
// Callback: handle GitHub plugin fetch error
|
||||
const handleGitHubPluginFetchError = useCallback((index: number) => {
|
||||
return () => {
|
||||
setGithubErrorIndexes((prev) => [...prev, index])
|
||||
}
|
||||
}, [])
|
||||
|
||||
// Callback: get version info for a plugin by its key
|
||||
const getVersionInfo = useCallback(
|
||||
(pluginId: string) => {
|
||||
const pluginDetail = installedInfo?.[pluginId]
|
||||
return {
|
||||
hasInstalled: !!pluginDetail,
|
||||
installedVersion: pluginDetail?.installedVersion,
|
||||
toInstallVersion: '',
|
||||
}
|
||||
},
|
||||
[installedInfo],
|
||||
)
|
||||
|
||||
// Callback: handle plugin selection
|
||||
const handleSelect = useCallback(
|
||||
(index: number) => {
|
||||
return () => {
|
||||
const canSelectPlugins = plugins.filter((p) => {
|
||||
const { canInstall } = pluginInstallLimit(p!, systemFeatures)
|
||||
return canInstall
|
||||
})
|
||||
onSelect(plugins[index]!, index, canSelectPlugins.length)
|
||||
}
|
||||
},
|
||||
[onSelect, plugins, systemFeatures],
|
||||
)
|
||||
|
||||
// Callback: check if a plugin at given index is selected
|
||||
const isPluginSelected = useCallback(
|
||||
(index: number) => {
|
||||
return !!selectedPlugins.find((p) => p.plugin_id === plugins[index]?.plugin_id)
|
||||
},
|
||||
[selectedPlugins, plugins],
|
||||
)
|
||||
|
||||
// Callback: get all installable plugins with their indexes
|
||||
const getInstallablePlugins = useCallback(() => {
|
||||
const selectedIndexes: number[] = []
|
||||
const installablePlugins: Plugin[] = []
|
||||
allPlugins.forEach((_d, index) => {
|
||||
const p = plugins[index]
|
||||
if (!p) return
|
||||
const { canInstall } = pluginInstallLimit(p, systemFeatures)
|
||||
if (canInstall) {
|
||||
selectedIndexes.push(index)
|
||||
installablePlugins.push(p)
|
||||
}
|
||||
})
|
||||
return { selectedIndexes, installablePlugins }
|
||||
}, [allPlugins, plugins, systemFeatures])
|
||||
|
||||
return {
|
||||
plugins,
|
||||
errorIndexes,
|
||||
handleGitHubPluginFetched,
|
||||
handleGitHubPluginFetchError,
|
||||
getVersionInfo,
|
||||
handleSelect,
|
||||
isPluginSelected,
|
||||
getInstallablePlugins,
|
||||
}
|
||||
}
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
'use client'
|
||||
import type {
|
||||
Dependency,
|
||||
GitHubItemAndMarketPlaceDependency,
|
||||
PackageDependency,
|
||||
Plugin,
|
||||
VersionInfo,
|
||||
} from '../../../types'
|
||||
import * as React from 'react'
|
||||
import { useImperativeHandle } from 'react'
|
||||
import LoadingError from '../../base/loading-error'
|
||||
import GithubItem from '../item/github-item'
|
||||
import MarketplaceItem from '../item/marketplace-item'
|
||||
import PackageItem from '../item/package-item'
|
||||
import { getPluginKey, useInstallMultiState } from './hooks/use-install-multi-state'
|
||||
|
||||
type Props = Readonly<{
|
||||
allPlugins: Dependency[]
|
||||
selectedPlugins: Plugin[]
|
||||
onSelect: (plugin: Plugin, selectedIndex: number, allCanInstallPluginsLength: number) => void
|
||||
onSelectAll: (plugins: Plugin[], selectedIndexes: number[]) => void
|
||||
onDeSelectAll: () => void
|
||||
onLoadedAllPlugin: (installedInfo: Record<string, VersionInfo>) => void
|
||||
isFromMarketPlace?: boolean
|
||||
ref?: React.Ref<ExposeRefs>
|
||||
}>
|
||||
|
||||
export type ExposeRefs = {
|
||||
selectAllPlugins: () => void
|
||||
deSelectAllPlugins: () => void
|
||||
}
|
||||
|
||||
const InstallByDSLList = ({
|
||||
allPlugins,
|
||||
selectedPlugins,
|
||||
onSelect,
|
||||
onSelectAll,
|
||||
onDeSelectAll,
|
||||
onLoadedAllPlugin,
|
||||
isFromMarketPlace,
|
||||
ref,
|
||||
}: Props) => {
|
||||
const {
|
||||
plugins,
|
||||
errorIndexes,
|
||||
handleGitHubPluginFetched,
|
||||
handleGitHubPluginFetchError,
|
||||
getVersionInfo,
|
||||
handleSelect,
|
||||
isPluginSelected,
|
||||
getInstallablePlugins,
|
||||
} = useInstallMultiState({
|
||||
allPlugins,
|
||||
selectedPlugins,
|
||||
onSelect,
|
||||
onLoadedAllPlugin,
|
||||
})
|
||||
|
||||
useImperativeHandle(ref, () => ({
|
||||
selectAllPlugins: () => {
|
||||
const { installablePlugins, selectedIndexes } = getInstallablePlugins()
|
||||
onSelectAll(installablePlugins, selectedIndexes)
|
||||
},
|
||||
deSelectAllPlugins: onDeSelectAll,
|
||||
}))
|
||||
|
||||
return (
|
||||
<>
|
||||
{allPlugins.map((d, index) => {
|
||||
if (errorIndexes.includes(index)) return <LoadingError key={index} />
|
||||
|
||||
const plugin = plugins[index]
|
||||
const checked = isPluginSelected(index)
|
||||
const versionInfo = getVersionInfo(getPluginKey(plugin))
|
||||
|
||||
if (d.type === 'github') {
|
||||
return (
|
||||
<GithubItem
|
||||
key={index}
|
||||
checked={checked}
|
||||
onCheckedChange={handleSelect(index)}
|
||||
dependency={d as GitHubItemAndMarketPlaceDependency}
|
||||
onFetchedPayload={handleGitHubPluginFetched(index)}
|
||||
onFetchError={handleGitHubPluginFetchError(index)}
|
||||
versionInfo={versionInfo}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
if (d.type === 'marketplace') {
|
||||
return (
|
||||
<MarketplaceItem
|
||||
key={index}
|
||||
checked={checked}
|
||||
onCheckedChange={handleSelect(index)}
|
||||
payload={plugin}
|
||||
version={
|
||||
(d as GitHubItemAndMarketPlaceDependency).value.version! || plugin?.version || ''
|
||||
}
|
||||
versionInfo={versionInfo}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<PackageItem
|
||||
key={index}
|
||||
checked={checked}
|
||||
onCheckedChange={handleSelect(index)}
|
||||
payload={d as PackageDependency}
|
||||
isFromMarketPlace={isFromMarketPlace}
|
||||
versionInfo={versionInfo}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</>
|
||||
)
|
||||
}
|
||||
export default InstallByDSLList
|
||||
+255
@@ -0,0 +1,255 @@
|
||||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import type { Dependency, InstallStatusResponse, Plugin, VersionInfo } from '../../../types'
|
||||
import type { InstallBundleCompleteCallback } from '../index'
|
||||
import type { ExposeRefs } from './install-multi'
|
||||
import { Button } from '@langgenius/dify-ui/button'
|
||||
import { Checkbox } from '@langgenius/dify-ui/checkbox'
|
||||
import { RiLoader2Line } from '@remixicon/react'
|
||||
import * as React from 'react'
|
||||
import { useCallback, useRef, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useCanInstallPluginFromMarketplace } from '@/app/components/plugins/plugin-page/use-reference-setting'
|
||||
import { useInstallOrUpdate, usePluginTaskList } from '@/service/use-plugins'
|
||||
import { TaskStatus } from '../../../types'
|
||||
import checkTaskStatus from '../../base/check-task-status'
|
||||
import useRefreshPluginList from '../../hooks/use-refresh-plugin-list'
|
||||
import { getPluginKey } from './hooks/use-install-multi-state'
|
||||
import InstallMulti from './install-multi'
|
||||
|
||||
const i18nPrefix = 'installModal'
|
||||
|
||||
type Props = Readonly<{
|
||||
allPlugins: Dependency[]
|
||||
onStartToInstall?: () => void
|
||||
onInstalled: InstallBundleCompleteCallback
|
||||
onCancel: () => void
|
||||
isFromMarketPlace?: boolean
|
||||
isHideButton?: boolean
|
||||
}>
|
||||
|
||||
const Install: FC<Props> = ({
|
||||
allPlugins,
|
||||
onStartToInstall,
|
||||
onInstalled,
|
||||
onCancel,
|
||||
isFromMarketPlace,
|
||||
isHideButton,
|
||||
}) => {
|
||||
const { t } = useTranslation(['common', 'plugin'])
|
||||
const [selectedPlugins, setSelectedPlugins] = React.useState<Plugin[]>([])
|
||||
const [selectedIndexes, setSelectedIndexes] = React.useState<number[]>([])
|
||||
const selectedPluginsNum = selectedPlugins.length
|
||||
const installMultiRef = useRef<ExposeRefs>(null)
|
||||
const { refreshPluginList } = useRefreshPluginList()
|
||||
const [isSelectAll, setIsSelectAll] = useState(false)
|
||||
const handleClickSelectAll = useCallback(() => {
|
||||
if (isSelectAll) installMultiRef.current?.deSelectAllPlugins()
|
||||
else installMultiRef.current?.selectAllPlugins()
|
||||
}, [isSelectAll])
|
||||
const [canInstall, setCanInstall] = React.useState(false)
|
||||
const [installedInfo, setInstalledInfo] = useState<Record<string, VersionInfo> | undefined>(
|
||||
undefined,
|
||||
)
|
||||
|
||||
const handleLoadedAllPlugin = useCallback(
|
||||
(installedInfo: Record<string, VersionInfo> | undefined) => {
|
||||
handleClickSelectAll()
|
||||
setInstalledInfo(installedInfo)
|
||||
setCanInstall(true)
|
||||
},
|
||||
[],
|
||||
)
|
||||
|
||||
const { check, stop } = checkTaskStatus()
|
||||
|
||||
const handleCancel = useCallback(() => {
|
||||
stop()
|
||||
onCancel()
|
||||
}, [onCancel, stop])
|
||||
|
||||
const { handleRefetch } = usePluginTaskList()
|
||||
const getSelectedVersionInfo = useCallback(() => {
|
||||
return selectedPlugins.map((plugin) => {
|
||||
const pluginDetail = installedInfo?.[getPluginKey(plugin)]
|
||||
return {
|
||||
hasInstalled: !!pluginDetail,
|
||||
installedVersion: pluginDetail?.installedVersion,
|
||||
toInstallVersion: plugin.version,
|
||||
}
|
||||
})
|
||||
}, [installedInfo, selectedPlugins])
|
||||
|
||||
// Install from marketplace and github
|
||||
const { mutate: installOrUpdate, isPending: isInstalling } = useInstallOrUpdate({
|
||||
onSuccess: async (res: InstallStatusResponse[]) => {
|
||||
const isAllSettled = res.every(
|
||||
(r) => r.status === TaskStatus.success || r.status === TaskStatus.failed,
|
||||
)
|
||||
// if all settled, return the install status
|
||||
if (isAllSettled) {
|
||||
onInstalled(
|
||||
selectedPlugins,
|
||||
res.map((r, i) => {
|
||||
return {
|
||||
success: r.status === TaskStatus.success,
|
||||
isFromMarketPlace: allPlugins[selectedIndexes[i]!]!.type === 'marketplace',
|
||||
}
|
||||
}),
|
||||
getSelectedVersionInfo(),
|
||||
)
|
||||
const hasInstallSuccess = res.some((r) => r.status === TaskStatus.success)
|
||||
if (hasInstallSuccess) {
|
||||
refreshPluginList(undefined, true)
|
||||
}
|
||||
return
|
||||
}
|
||||
// if not all settled, keep checking the status of the plugins
|
||||
handleRefetch()
|
||||
const installStatus = await Promise.all(
|
||||
res.map(async (item, index) => {
|
||||
if (item.status !== TaskStatus.running) {
|
||||
return {
|
||||
success: item.status === TaskStatus.success,
|
||||
isFromMarketPlace: allPlugins[selectedIndexes[index]!]!.type === 'marketplace',
|
||||
}
|
||||
}
|
||||
const { status } = await check({
|
||||
taskId: item.taskId,
|
||||
pluginUniqueIdentifier: item.uniqueIdentifier,
|
||||
})
|
||||
return {
|
||||
success: status === TaskStatus.success,
|
||||
isFromMarketPlace: allPlugins[selectedIndexes[index]!]!.type === 'marketplace',
|
||||
}
|
||||
}),
|
||||
)
|
||||
onInstalled(selectedPlugins, installStatus, getSelectedVersionInfo())
|
||||
},
|
||||
})
|
||||
const handleInstall = () => {
|
||||
onStartToInstall?.()
|
||||
installOrUpdate({
|
||||
payload: allPlugins.filter((_d, index) => selectedIndexes.includes(index)),
|
||||
plugin: selectedPlugins,
|
||||
installedInfo: installedInfo!,
|
||||
})
|
||||
}
|
||||
const [isIndeterminate, setIsIndeterminate] = useState(false)
|
||||
const handleSelectAll = useCallback((plugins: Plugin[], selectedIndexes: number[]) => {
|
||||
setSelectedPlugins(plugins)
|
||||
setSelectedIndexes(selectedIndexes)
|
||||
setIsSelectAll(true)
|
||||
setIsIndeterminate(false)
|
||||
}, [])
|
||||
const handleDeSelectAll = useCallback(() => {
|
||||
setSelectedPlugins([])
|
||||
setSelectedIndexes([])
|
||||
setIsSelectAll(false)
|
||||
setIsIndeterminate(false)
|
||||
}, [])
|
||||
|
||||
const handleSelect = useCallback(
|
||||
(plugin: Plugin, selectedIndex: number, allPluginsLength: number) => {
|
||||
const isSelected = !!selectedPlugins.find((p) => p.plugin_id === plugin.plugin_id)
|
||||
let nextSelectedPlugins
|
||||
if (isSelected)
|
||||
nextSelectedPlugins = selectedPlugins.filter((p) => p.plugin_id !== plugin.plugin_id)
|
||||
else nextSelectedPlugins = [...selectedPlugins, plugin]
|
||||
setSelectedPlugins(nextSelectedPlugins)
|
||||
const nextSelectedIndexes = isSelected
|
||||
? selectedIndexes.filter((i) => i !== selectedIndex)
|
||||
: [...selectedIndexes, selectedIndex]
|
||||
setSelectedIndexes(nextSelectedIndexes)
|
||||
if (nextSelectedPlugins.length === 0) {
|
||||
setIsSelectAll(false)
|
||||
setIsIndeterminate(false)
|
||||
} else if (nextSelectedPlugins.length === allPluginsLength) {
|
||||
setIsSelectAll(true)
|
||||
setIsIndeterminate(false)
|
||||
} else {
|
||||
setIsIndeterminate(true)
|
||||
setIsSelectAll(false)
|
||||
}
|
||||
},
|
||||
[selectedPlugins, selectedIndexes],
|
||||
)
|
||||
|
||||
const { canInstallPluginFromMarketplace } = useCanInstallPluginFromMarketplace()
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col self-stretch overflow-hidden">
|
||||
<div className="flex min-h-0 flex-1 flex-col items-start justify-center gap-4 self-stretch overflow-hidden px-6 py-3">
|
||||
<div className="system-md-regular text-text-secondary">
|
||||
<p>
|
||||
{t(
|
||||
($) =>
|
||||
$[
|
||||
`${i18nPrefix}.${selectedPluginsNum > 1 ? 'readyToInstallPackages' : 'readyToInstallPackage'}`
|
||||
],
|
||||
{ ns: 'plugin', num: selectedPluginsNum },
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex min-h-0 w-full flex-1 flex-col gap-1 overflow-y-auto rounded-2xl bg-background-section-burn p-2">
|
||||
<InstallMulti
|
||||
ref={installMultiRef}
|
||||
allPlugins={allPlugins}
|
||||
selectedPlugins={selectedPlugins}
|
||||
onSelect={handleSelect}
|
||||
onSelectAll={handleSelectAll}
|
||||
onDeSelectAll={handleDeSelectAll}
|
||||
onLoadedAllPlugin={handleLoadedAllPlugin}
|
||||
isFromMarketPlace={isFromMarketPlace}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{/* Action Buttons */}
|
||||
{!isHideButton && (
|
||||
<div className="flex items-center justify-between gap-2 self-stretch p-6 pt-5">
|
||||
<div className="px-2">
|
||||
{canInstall && (
|
||||
<label className="flex cursor-pointer items-center gap-x-2">
|
||||
<Checkbox
|
||||
checked={isSelectAll}
|
||||
indeterminate={isIndeterminate}
|
||||
onCheckedChange={() => handleClickSelectAll()}
|
||||
/>
|
||||
<span className="system-sm-medium text-text-secondary">
|
||||
{isSelectAll
|
||||
? t(($) => $['operation.deSelectAll'], { ns: 'common' })
|
||||
: t(($) => $['operation.selectAll'], { ns: 'common' })}
|
||||
</span>
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center justify-end gap-2 self-stretch">
|
||||
{!canInstall && (
|
||||
<Button variant="secondary" className="min-w-18" onClick={handleCancel}>
|
||||
{t(($) => $['operation.cancel'], { ns: 'common' })}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="primary"
|
||||
className="flex min-w-18"
|
||||
disabled={
|
||||
!canInstall ||
|
||||
isInstalling ||
|
||||
selectedPlugins.length === 0 ||
|
||||
!canInstallPluginFromMarketplace
|
||||
}
|
||||
onClick={handleInstall}
|
||||
>
|
||||
{isInstalling && <RiLoader2Line className="size-4 animate-spin-slow" />}
|
||||
<span>
|
||||
{t(($) => $[`${i18nPrefix}.${isInstalling ? 'installing' : 'install'}`], {
|
||||
ns: 'plugin',
|
||||
})}
|
||||
</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
export default React.memo(Install)
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import type { InstallStatus, Plugin, VersionProps } from '../../../types'
|
||||
import { Button } from '@langgenius/dify-ui/button'
|
||||
import * as React from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import Badge from '@/app/components/base/badge/index'
|
||||
import Card from '@/app/components/plugins/card'
|
||||
import { getMarketplacePluginIconUrl } from '@/features/marketplace/api'
|
||||
import useGetIcon from '../../base/use-get-icon'
|
||||
import Version from '../../base/version'
|
||||
|
||||
type Props = Readonly<{
|
||||
list: Plugin[]
|
||||
installStatus: InstallStatus[]
|
||||
versionInfo?: VersionProps[]
|
||||
onCancel: () => void
|
||||
isHideButton?: boolean
|
||||
}>
|
||||
|
||||
const Installed: FC<Props> = ({ list, installStatus, versionInfo, onCancel, isHideButton }) => {
|
||||
const { t } = useTranslation(['common', 'plugin'])
|
||||
const { getIconUrl } = useGetIcon()
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-col items-start justify-center gap-4 self-stretch px-6 py-3">
|
||||
<p className="system-md-regular text-text-secondary">
|
||||
{t(($) => $['installModal.installedSuccessfullyCountDesc'], {
|
||||
ns: 'plugin',
|
||||
num: list.length,
|
||||
})}
|
||||
</p>
|
||||
<div className="flex flex-wrap content-start items-start gap-1 space-y-1 self-stretch rounded-2xl bg-background-section-burn p-2">
|
||||
{list.map((plugin, index) => {
|
||||
const pluginVersionInfo = versionInfo?.[index]
|
||||
return (
|
||||
<Card
|
||||
key={plugin.plugin_id}
|
||||
className="w-full"
|
||||
payload={{
|
||||
...plugin,
|
||||
icon: installStatus[index]!.isFromMarketPlace
|
||||
? getMarketplacePluginIconUrl(`${plugin.org}/${plugin.name}`)
|
||||
: getIconUrl(plugin.icon),
|
||||
}}
|
||||
installed={installStatus[index]!.success}
|
||||
installFailed={!installStatus[index]!.success}
|
||||
titleLeft={
|
||||
plugin.version ? (
|
||||
pluginVersionInfo ? (
|
||||
<Version {...pluginVersionInfo} />
|
||||
) : (
|
||||
<Badge className="mx-1" size="s">
|
||||
{plugin.version}
|
||||
</Badge>
|
||||
)
|
||||
) : null
|
||||
}
|
||||
compact
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
{/* Action Buttons */}
|
||||
{!isHideButton && (
|
||||
<div className="flex items-center justify-end gap-2 self-stretch p-6 pt-5">
|
||||
<Button variant="primary" className="min-w-18" onClick={onCancel}>
|
||||
{t(($) => $['operation.close'], { ns: 'common' })}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default React.memo(Installed)
|
||||
+400
@@ -0,0 +1,400 @@
|
||||
import type { ComponentProps } from 'react'
|
||||
import { act, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { createHttpError } from '@/service/http-error'
|
||||
import { renderWithConsoleQuery } from '@/test/console/query-data'
|
||||
import { createDeferred } from '@/test/deferred'
|
||||
import { createPluginDeclarationFixture, createPluginEntity } from '@/test/fixtures/plugin'
|
||||
import { TaskStatus } from '../../../types'
|
||||
import InstallFromGitHub from '../index'
|
||||
|
||||
const { fetchReleases, upload, install, pollTask, refresh, notify, installed, upgrade } =
|
||||
vi.hoisted(() => ({
|
||||
installed: vi.fn(),
|
||||
upgrade: vi.fn(),
|
||||
fetchReleases: vi.fn(),
|
||||
upload: vi.fn(),
|
||||
install: vi.fn(),
|
||||
pollTask: vi.fn(),
|
||||
refresh: vi.fn(),
|
||||
notify: vi.fn(),
|
||||
}))
|
||||
vi.mock('@/service/plugins', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('@/service/plugins')>()),
|
||||
uploadGitHub: upload,
|
||||
updateFromGitHub: upgrade,
|
||||
checkTaskStatus: pollTask,
|
||||
}))
|
||||
vi.mock('@/service/console', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/service/console')>()
|
||||
const { withConsoleClientResponses, withConsoleResponses } =
|
||||
await import('@/test/console/service-responses')
|
||||
return {
|
||||
...actual,
|
||||
consoleQuery: withConsoleResponses(actual.consoleQuery, {
|
||||
'workspaces.current.plugin.list.installations.ids.post': installed,
|
||||
}),
|
||||
consoleClient: withConsoleClientResponses(actual.consoleClient, {
|
||||
'workspaces.current.plugin.tasks.get': async () => ({ tasks: [] }),
|
||||
'workspaces.current.plugin.install.github.post': install,
|
||||
}),
|
||||
}
|
||||
})
|
||||
// Refreshing the separate model/tool catalogs is covered by use-refresh-plugin-list.
|
||||
vi.mock('../../hooks/use-refresh-plugin-list', () => ({
|
||||
default: () => ({ refreshPluginList: refresh }),
|
||||
}))
|
||||
vi.mock('@/app/notifications', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/app/notifications')>()
|
||||
return { ...actual, toast: Object.assign(vi.fn(), actual.toast, { error: notify }) }
|
||||
})
|
||||
|
||||
const manifest = createPluginDeclarationFixture({ name: 'github' })
|
||||
const uploadedPackage = { unique_identifier: 'test/github:1.0.0', manifest }
|
||||
const releases = [
|
||||
{
|
||||
tag: 'v1.0.0',
|
||||
assets: [
|
||||
{ downloadUrl: 'https://github.com/owner/repo/releases/download/v1.0.0/plugin.difypkg' },
|
||||
],
|
||||
},
|
||||
{
|
||||
tag: 'v0.9.0',
|
||||
assets: [{ downloadUrl: 'https://github.com/owner/repo/releases/download/v0.9.0/old.difypkg' }],
|
||||
},
|
||||
]
|
||||
const renderInstaller = (props: Partial<ComponentProps<typeof InstallFromGitHub>> = {}) => {
|
||||
const onSuccess = vi.fn()
|
||||
const onClose = vi.fn()
|
||||
renderWithConsoleQuery(<InstallFromGitHub onSuccess={onSuccess} onClose={onClose} {...props} />)
|
||||
return { onSuccess, onClose }
|
||||
}
|
||||
const nextButton = () => screen.getByRole('button', { name: 'plugin.installModal.next' })
|
||||
const versionSelect = () =>
|
||||
screen.getByRole('combobox', { name: 'plugin.installFromGitHub.selectVersion' })
|
||||
const packageSelect = () =>
|
||||
screen.getByRole('combobox', { name: 'plugin.installFromGitHub.selectPackage' })
|
||||
const submitRepo = async (user: ReturnType<typeof userEvent.setup>) => {
|
||||
await user.type(
|
||||
screen.getByRole('textbox', { name: 'plugin.installFromGitHub.gitHubRepo' }),
|
||||
'https://github.com/owner/repo',
|
||||
)
|
||||
await user.keyboard('{Enter}')
|
||||
await screen.findByRole('combobox', { name: 'plugin.installFromGitHub.selectVersion' })
|
||||
}
|
||||
const selectPackage = async (user: ReturnType<typeof userEvent.setup>) => {
|
||||
await user.click(versionSelect())
|
||||
await user.click(await screen.findByRole('option', { name: 'v1.0.0' }))
|
||||
await user.click(packageSelect())
|
||||
await user.click(await screen.findByRole('option', { name: 'plugin.difypkg' }))
|
||||
}
|
||||
const loadPackage = async (user: ReturnType<typeof userEvent.setup>) => {
|
||||
await submitRepo(user)
|
||||
await selectPackage(user)
|
||||
await user.click(nextButton())
|
||||
return await screen.findByRole('button', { name: 'plugin.installModal.install' })
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks()
|
||||
installed.mockResolvedValue({ plugins: [] })
|
||||
upgrade.mockResolvedValue({ all_installed: true, task_id: '' })
|
||||
vi.stubGlobal('fetch', fetchReleases)
|
||||
fetchReleases.mockImplementation(async () => Response.json({ releases }))
|
||||
upload.mockResolvedValue(uploadedPackage)
|
||||
install.mockResolvedValue({ all_installed: true, task_id: '' })
|
||||
})
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
|
||||
it('submits the URL with Enter, installs the selected release, and waits for asynchronous completion handling', async () => {
|
||||
const user = userEvent.setup()
|
||||
const success = createDeferred<void>()
|
||||
const onSuccess = vi.fn(() => success.promise)
|
||||
const { onClose } = renderInstaller({ onSuccess })
|
||||
const input = screen.getByRole('textbox', { name: 'plugin.installFromGitHub.gitHubRepo' })
|
||||
await waitFor(() => expect(input).toHaveFocus())
|
||||
expect(nextButton()).toBeDisabled()
|
||||
const button = await loadPackage(user)
|
||||
expect(fetchReleases).toHaveBeenCalledExactlyOnceWith('https://ungh.cc/repos/owner/repo/releases')
|
||||
expect(upload).toHaveBeenCalledExactlyOnceWith('owner/repo', 'v1.0.0', 'plugin.difypkg', {
|
||||
silent: true,
|
||||
})
|
||||
await user.click(button)
|
||||
await waitFor(() => expect(onSuccess).toHaveBeenCalledOnce())
|
||||
const pendingButton = screen.getByRole('button', { name: 'plugin.installModal.installing' })
|
||||
await user.click(pendingButton)
|
||||
expect(install).toHaveBeenCalledExactlyOnceWith({
|
||||
body: {
|
||||
repo: 'owner/repo',
|
||||
version: 'v1.0.0',
|
||||
package: 'plugin.difypkg',
|
||||
plugin_unique_identifier: 'test/github:1.0.0',
|
||||
},
|
||||
})
|
||||
expect(
|
||||
screen.queryByRole('dialog', { name: 'plugin.installFromGitHub.installedSuccessfully' }),
|
||||
).not.toBeInTheDocument()
|
||||
success.resolve()
|
||||
await screen.findByRole('dialog', { name: 'plugin.installFromGitHub.installedSuccessfully' })
|
||||
expect(screen.getByText('Test Plugin')).toBeInTheDocument()
|
||||
expect(screen.queryByText('plugin.installFromGitHub.installNote')).not.toBeInTheDocument()
|
||||
expect(refresh).toHaveBeenCalledExactlyOnceWith(
|
||||
expect.objectContaining({
|
||||
name: 'github',
|
||||
icon: expect.stringContaining('filename=test-icon.png'),
|
||||
}),
|
||||
)
|
||||
await user.click(screen.getAllByRole('button', { name: 'common.operation.close' }).at(-1)!)
|
||||
expect(onClose).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('keeps URL and selections when navigating back through the real steps', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderInstaller()
|
||||
await loadPackage(user)
|
||||
await user.click(screen.getByRole('button', { name: 'plugin.installModal.back' }))
|
||||
expect(versionSelect()).toHaveTextContent('v1.0.0')
|
||||
expect(packageSelect()).toHaveTextContent('plugin.difypkg')
|
||||
await user.click(screen.getByRole('button', { name: 'plugin.installModal.back' }))
|
||||
expect(screen.getByRole('textbox', { name: 'plugin.installFromGitHub.gitHubRepo' })).toHaveValue(
|
||||
'https://github.com/owner/repo',
|
||||
)
|
||||
expect(install).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('derives the package options from the selected release and blocks upload before selection', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderInstaller()
|
||||
await submitRepo(user)
|
||||
expect(packageSelect()).toBeDisabled()
|
||||
expect(nextButton()).toBeDisabled()
|
||||
await user.click(versionSelect())
|
||||
await user.click(await screen.findByRole('option', { name: 'v0.9.0' }))
|
||||
await user.click(packageSelect())
|
||||
expect(await screen.findByRole('option', { name: 'old.difypkg' })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('option', { name: 'plugin.difypkg' })).not.toBeInTheDocument()
|
||||
await user.keyboard('{Escape}')
|
||||
expect(nextButton()).toBeDisabled()
|
||||
expect(upload).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('blocks a release without assets from proceeding to upload', async () => {
|
||||
const user = userEvent.setup()
|
||||
fetchReleases.mockImplementation(async () =>
|
||||
Response.json({ releases: [{ tag: 'v1.0.0', assets: [] }] }),
|
||||
)
|
||||
renderInstaller()
|
||||
await submitRepo(user)
|
||||
await user.click(versionSelect())
|
||||
await user.click(await screen.findByRole('option', { name: 'v1.0.0' }))
|
||||
await user.click(packageSelect())
|
||||
expect(screen.queryByRole('option')).not.toBeInTheDocument()
|
||||
await user.keyboard('{Escape}')
|
||||
expect(nextButton()).toBeDisabled()
|
||||
expect(upload).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects an invalid URL before fetching releases', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderInstaller()
|
||||
await user.type(
|
||||
screen.getByRole('textbox', { name: 'plugin.installFromGitHub.gitHubRepo' }),
|
||||
'invalid-url',
|
||||
)
|
||||
await user.click(nextButton())
|
||||
expect(notify).toHaveBeenCalledWith('plugin.error.inValidGitHubUrl')
|
||||
expect(fetchReleases).not.toHaveBeenCalled()
|
||||
expect(screen.queryByRole('combobox')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it.each(['empty', 'error'])(
|
||||
'allows retrying release lookup after an %s response',
|
||||
async (response) => {
|
||||
const user = userEvent.setup()
|
||||
if (response === 'empty') fetchReleases.mockResolvedValueOnce(Response.json({ releases: [] }))
|
||||
else fetchReleases.mockRejectedValueOnce(new Error('Release service unavailable'))
|
||||
renderInstaller()
|
||||
await user.type(
|
||||
screen.getByRole('textbox', { name: 'plugin.installFromGitHub.gitHubRepo' }),
|
||||
'https://github.com/owner/repo',
|
||||
)
|
||||
await user.click(nextButton())
|
||||
await waitFor(() =>
|
||||
expect(notify).toHaveBeenCalledExactlyOnceWith(
|
||||
response === 'empty' ? 'plugin.error.noReleasesFound' : 'plugin.error.fetchReleasesError',
|
||||
),
|
||||
)
|
||||
expect(screen.queryByRole('combobox')).not.toBeInTheDocument()
|
||||
await user.click(nextButton())
|
||||
await screen.findByRole('combobox', { name: 'plugin.installFromGitHub.selectVersion' })
|
||||
expect(fetchReleases).toHaveBeenCalledTimes(2)
|
||||
},
|
||||
)
|
||||
|
||||
it.each([
|
||||
[new Error('Package download failed'), 'Package download failed'],
|
||||
[
|
||||
createHttpError(new Response(null, { status: 500 }), { message: 'Package rejected' }),
|
||||
'Package rejected',
|
||||
],
|
||||
['Unexpected server response', 'plugin.installFromGitHub.uploadFailed'],
|
||||
])('shows upload failure %s without starting installation', async (error, message) => {
|
||||
const user = userEvent.setup()
|
||||
upload.mockRejectedValue(error)
|
||||
const { onSuccess, onClose } = renderInstaller()
|
||||
await submitRepo(user)
|
||||
await selectPackage(user)
|
||||
await user.click(nextButton())
|
||||
await screen.findByText(message)
|
||||
expect(notify).not.toHaveBeenCalled()
|
||||
expect(screen.queryByRole('combobox')).not.toBeInTheDocument()
|
||||
expect(install).not.toHaveBeenCalled()
|
||||
expect(onSuccess).not.toHaveBeenCalled()
|
||||
await user.click(screen.getAllByRole('button', { name: 'common.operation.close' }).at(-1)!)
|
||||
expect(onClose).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it.each([TaskStatus.success, TaskStatus.failed])(
|
||||
'shows the asynchronous install result: %s',
|
||||
async (status) => {
|
||||
const user = userEvent.setup()
|
||||
install.mockResolvedValue({ all_installed: false, task_id: 'github-task' })
|
||||
pollTask.mockResolvedValue({
|
||||
task: {
|
||||
plugins: [
|
||||
{
|
||||
plugin_unique_identifier: 'test/github:1.0.0',
|
||||
status,
|
||||
message: 'Plugin initialization failed',
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
const { onSuccess } = renderInstaller()
|
||||
await user.click(await loadPackage(user))
|
||||
await screen.findByRole('dialog', {
|
||||
name:
|
||||
status === TaskStatus.success
|
||||
? 'plugin.installFromGitHub.installedSuccessfully'
|
||||
: 'plugin.installFromGitHub.installFailed',
|
||||
})
|
||||
expect(pollTask).toHaveBeenCalledExactlyOnceWith('github-task')
|
||||
if (status === TaskStatus.failed) {
|
||||
expect(screen.getByText('Plugin initialization failed')).toBeInTheDocument()
|
||||
expect(onSuccess).not.toHaveBeenCalled()
|
||||
} else expect(onSuccess).toHaveBeenCalledOnce()
|
||||
expect(refresh).not.toHaveBeenCalled()
|
||||
},
|
||||
)
|
||||
|
||||
it.each([
|
||||
[new Error('Connection failed'), 'plugin.installModal.installFailedDesc'],
|
||||
['Server install error', 'Server install error'],
|
||||
])('shows the install failure for %s', async (error, message) => {
|
||||
const user = userEvent.setup()
|
||||
install.mockRejectedValue(error)
|
||||
const { onSuccess } = renderInstaller()
|
||||
await user.click(await loadPackage(user))
|
||||
await screen.findByRole('dialog', { name: 'plugin.installFromGitHub.installFailed' })
|
||||
expect(screen.getByText(message)).toBeInTheDocument()
|
||||
expect(onSuccess).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.each(['plugin.installModal.cancel', 'common.operation.close'])(
|
||||
'allows %s before selecting a repository',
|
||||
async (name) => {
|
||||
const user = userEvent.setup()
|
||||
const { onClose } = renderInstaller()
|
||||
await user.click(screen.getByRole('button', { name }))
|
||||
expect(onClose).toHaveBeenCalledOnce()
|
||||
expect(fetchReleases).not.toHaveBeenCalled()
|
||||
expect(upload).not.toHaveBeenCalled()
|
||||
},
|
||||
)
|
||||
|
||||
it('blocks repeated upload and backward navigation until the selected package finishes loading', async () => {
|
||||
const user = userEvent.setup()
|
||||
const pending = createDeferred<typeof uploadedPackage>()
|
||||
upload.mockReturnValueOnce(pending.promise)
|
||||
renderInstaller()
|
||||
await submitRepo(user)
|
||||
await selectPackage(user)
|
||||
const next = nextButton()
|
||||
await user.click(next)
|
||||
expect(next).toBeDisabled()
|
||||
const back = screen.getByRole('button', { name: 'plugin.installModal.back' })
|
||||
expect(back).toBeDisabled()
|
||||
await user.click(next)
|
||||
await user.click(back)
|
||||
expect(upload).toHaveBeenCalledExactlyOnceWith('owner/repo', 'v1.0.0', 'plugin.difypkg', {
|
||||
silent: true,
|
||||
})
|
||||
expect(
|
||||
screen.queryByRole('button', { name: 'plugin.installModal.install' }),
|
||||
).not.toBeInTheDocument()
|
||||
pending.resolve(uploadedPackage)
|
||||
expect(
|
||||
await screen.findByRole('button', { name: 'plugin.installModal.install' }),
|
||||
).toBeInTheDocument()
|
||||
expect(install).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('waits for the installed version before upgrading the package selected from GitHub', async () => {
|
||||
const user = userEvent.setup()
|
||||
const existing = createPluginEntity({
|
||||
plugin_id: 'test/github',
|
||||
plugin_unique_identifier: 'test/github:0.9.0',
|
||||
})
|
||||
existing.declaration.version = '0.9.0'
|
||||
const lookup = createDeferred<{ plugins: ReturnType<typeof createPluginEntity>[] }>()
|
||||
installed.mockReturnValueOnce(lookup.promise)
|
||||
upload.mockResolvedValueOnce({
|
||||
...uploadedPackage,
|
||||
manifest: { ...manifest, plugin_id: 'test/github' },
|
||||
})
|
||||
const { onSuccess } = renderInstaller()
|
||||
const button = await loadPackage(user)
|
||||
expect(button).toBeDisabled()
|
||||
await user.click(button)
|
||||
expect(install).not.toHaveBeenCalled()
|
||||
expect(upgrade).not.toHaveBeenCalled()
|
||||
await act(async () => lookup.resolve({ plugins: [existing] }))
|
||||
await waitFor(() => expect(button).toBeEnabled())
|
||||
expect(screen.getByText('0.9.0 -> 1.0.0')).toBeInTheDocument()
|
||||
expect(onSuccess).not.toHaveBeenCalled()
|
||||
await user.click(button)
|
||||
await screen.findByRole('dialog', { name: 'plugin.installFromGitHub.installedSuccessfully' })
|
||||
expect(upgrade).toHaveBeenCalledExactlyOnceWith(
|
||||
'owner/repo',
|
||||
'v1.0.0',
|
||||
'plugin.difypkg',
|
||||
'test/github:0.9.0',
|
||||
'test/github:1.0.0',
|
||||
)
|
||||
expect(onSuccess).toHaveBeenCalledOnce()
|
||||
expect(install).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('finishes without an install or upgrade when the selected GitHub package is already installed', async () => {
|
||||
const user = userEvent.setup()
|
||||
installed.mockResolvedValueOnce({
|
||||
plugins: [
|
||||
createPluginEntity({
|
||||
plugin_id: 'test/github',
|
||||
plugin_unique_identifier: uploadedPackage.unique_identifier,
|
||||
}),
|
||||
],
|
||||
})
|
||||
upload.mockResolvedValueOnce({
|
||||
...uploadedPackage,
|
||||
manifest: { ...manifest, plugin_id: 'test/github' },
|
||||
})
|
||||
const { onSuccess } = renderInstaller()
|
||||
await submitRepo(user)
|
||||
await selectPackage(user)
|
||||
await user.click(nextButton())
|
||||
await screen.findByRole('dialog', { name: 'plugin.installFromGitHub.installedSuccessfully' })
|
||||
expect(onSuccess).toHaveBeenCalledOnce()
|
||||
expect(upgrade).not.toHaveBeenCalled()
|
||||
expect(install).not.toHaveBeenCalled()
|
||||
})
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
import type { UpdateFromGitHubPayload } from '../../../types'
|
||||
import { screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { renderWithConsoleQuery as render } from '@/test/console/query-data'
|
||||
import { createPluginDeclarationFixture } from '@/test/fixtures/plugin'
|
||||
import InstallFromGitHub from '../index'
|
||||
|
||||
const { uploadGitHub, updateFromGitHub } = vi.hoisted(() => ({
|
||||
uploadGitHub: vi.fn(),
|
||||
updateFromGitHub: vi.fn(),
|
||||
}))
|
||||
vi.mock('@/service/plugins', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('@/service/plugins')>()),
|
||||
uploadGitHub,
|
||||
updateFromGitHub,
|
||||
}))
|
||||
vi.mock('@/service/console', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/service/console')>()
|
||||
const { withConsoleClientResponses } = await import('@/test/console/service-responses')
|
||||
return {
|
||||
...actual,
|
||||
consoleClient: withConsoleClientResponses(actual.consoleClient, {
|
||||
'workspaces.current.plugin.tasks.get': async () => ({ tasks: [] }),
|
||||
}),
|
||||
}
|
||||
})
|
||||
// Model/tool catalog refresh is covered by its own hook tests.
|
||||
vi.mock('../../hooks/use-refresh-plugin-list', () => ({
|
||||
default: () => ({ refreshPluginList: vi.fn() }),
|
||||
}))
|
||||
|
||||
const github: UpdateFromGitHubPayload = {
|
||||
originalPackageInfo: {
|
||||
id: 'github-original-id',
|
||||
repo: 'owner/repo',
|
||||
version: 'v1.0.0',
|
||||
package: 'plugin.difypkg',
|
||||
releases: [
|
||||
{
|
||||
tag_name: 'v1.0.0',
|
||||
assets: [
|
||||
{
|
||||
id: 1,
|
||||
name: 'plugin.difypkg',
|
||||
browser_download_url:
|
||||
'https://github.com/owner/repo/releases/download/v1.0.0/plugin.difypkg',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
tag_name: 'v2.0.0',
|
||||
assets: [
|
||||
{
|
||||
id: 2,
|
||||
name: 'plugin.difypkg',
|
||||
browser_download_url:
|
||||
'https://github.com/owner/repo/releases/download/v2.0.0/plugin.difypkg',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
beforeEach(() => vi.resetAllMocks())
|
||||
|
||||
it('updates a GitHub plugin using the selected release and the existing installation identifier', async () => {
|
||||
const user = userEvent.setup()
|
||||
uploadGitHub.mockResolvedValueOnce({
|
||||
unique_identifier: 'github-target-id',
|
||||
manifest: createPluginDeclarationFixture({ version: '2.0.0' }),
|
||||
})
|
||||
updateFromGitHub.mockResolvedValueOnce({ all_installed: true, task_id: '' })
|
||||
const onSave = vi.fn()
|
||||
const onCancel = vi.fn()
|
||||
render(<InstallFromGitHub updatePayload={github} onSuccess={onSave} onClose={onCancel} />)
|
||||
|
||||
await user.click(screen.getByRole('combobox', { name: 'plugin.installFromGitHub.selectVersion' }))
|
||||
expect(await screen.findByRole('option', { name: /v1\.0\.0.*INSTALLED/ })).toBeInTheDocument()
|
||||
await user.click(await screen.findByRole('option', { name: 'v2.0.0' }))
|
||||
expect(
|
||||
screen.getByRole('combobox', { name: 'plugin.installFromGitHub.selectVersion' }),
|
||||
).toHaveTextContent('v1.0.0 -> v2.0.0')
|
||||
expect(screen.queryByRole('button', { name: 'plugin.installModal.back' })).not.toBeInTheDocument()
|
||||
await user.click(screen.getByRole('combobox', { name: 'plugin.installFromGitHub.selectPackage' }))
|
||||
await user.click(await screen.findByRole('option', { name: 'plugin.difypkg' }))
|
||||
await user.click(screen.getByRole('button', { name: 'plugin.installModal.next' }))
|
||||
const install = await screen.findByRole('button', { name: 'plugin.installModal.install' })
|
||||
expect(uploadGitHub).toHaveBeenCalledExactlyOnceWith('owner/repo', 'v2.0.0', 'plugin.difypkg', {
|
||||
silent: true,
|
||||
})
|
||||
await user.click(install)
|
||||
await screen.findByRole('dialog', { name: 'plugin.installFromGitHub.installedSuccessfully' })
|
||||
|
||||
expect(updateFromGitHub).toHaveBeenCalledExactlyOnceWith(
|
||||
'owner/repo',
|
||||
'v2.0.0',
|
||||
'plugin.difypkg',
|
||||
'github-original-id',
|
||||
'github-target-id',
|
||||
)
|
||||
expect(onSave).toHaveBeenCalledOnce()
|
||||
expect(onCancel).not.toHaveBeenCalled()
|
||||
})
|
||||
+304
@@ -0,0 +1,304 @@
|
||||
'use client'
|
||||
import type { PluginCategoryEnum, PluginDeclaration, UpdateFromGitHubPayload } from '../../types'
|
||||
import type { InstallState } from '@/app/components/plugins/types'
|
||||
import { Button } from '@langgenius/dify-ui/button'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import {
|
||||
Dialog,
|
||||
DialogBody,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogHeaderCloseButton,
|
||||
DialogTitle,
|
||||
} from '@langgenius/dify-ui/dialog'
|
||||
import { Field, FieldLabel } from '@langgenius/dify-ui/field'
|
||||
import { Form } from '@langgenius/dify-ui/form'
|
||||
import { Input } from '@langgenius/dify-ui/input'
|
||||
import * as React from 'react'
|
||||
import { useCallback, useRef, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import useGetIcon from '@/app/components/plugins/install-plugin/base/use-get-icon'
|
||||
import { toast } from '@/app/notifications'
|
||||
import { InstallStepFromGitHub } from '../../types'
|
||||
import Installed from '../base/installed'
|
||||
import { fetchReleases } from '../hooks'
|
||||
import useHideLogic from '../hooks/use-hide-logic'
|
||||
import useRefreshPluginList from '../hooks/use-refresh-plugin-list'
|
||||
import { convertRepoToUrl, parseGitHubUrl } from '../utils'
|
||||
import Loaded from './steps/loaded'
|
||||
import SelectPackage from './steps/selectPackage'
|
||||
|
||||
const i18nPrefix = 'installFromGitHub'
|
||||
|
||||
type SelectOption = {
|
||||
value: string
|
||||
name: string
|
||||
}
|
||||
|
||||
type InstallFromGitHubProps = {
|
||||
updatePayload?: UpdateFromGitHubPayload
|
||||
installContextCategory?: PluginCategoryEnum
|
||||
onClose: () => void
|
||||
onSuccess: () => void | Promise<void>
|
||||
}
|
||||
|
||||
const InstallFromGitHub: React.FC<InstallFromGitHubProps> = ({
|
||||
updatePayload,
|
||||
installContextCategory,
|
||||
onClose,
|
||||
onSuccess,
|
||||
}) => {
|
||||
const repoUrlInputRef = useRef<HTMLInputElement>(null)
|
||||
const { t } = useTranslation(['common', 'plugin'])
|
||||
const { getIconUrl } = useGetIcon()
|
||||
const { refreshPluginList } = useRefreshPluginList()
|
||||
|
||||
const { modalClassName, foldAnimInto, setIsInstalling, handleStartToInstall } =
|
||||
useHideLogic(onClose)
|
||||
|
||||
const [state, setState] = useState<InstallState>({
|
||||
step: updatePayload ? InstallStepFromGitHub.selectPackage : InstallStepFromGitHub.setUrl,
|
||||
repoUrl: updatePayload?.originalPackageInfo?.repo
|
||||
? convertRepoToUrl(updatePayload.originalPackageInfo.repo)
|
||||
: '',
|
||||
selectedVersion: '',
|
||||
selectedPackage: '',
|
||||
releases: updatePayload ? updatePayload.originalPackageInfo.releases : [],
|
||||
})
|
||||
const [uniqueIdentifier, setUniqueIdentifier] = useState<string | null>(null)
|
||||
const [manifest, setManifest] = useState<PluginDeclaration | null>(null)
|
||||
const [errorMsg, setErrorMsg] = useState<string | null>(null)
|
||||
|
||||
const versions: SelectOption[] = state.releases.map((release) => ({
|
||||
value: release.tag_name,
|
||||
name: release.tag_name,
|
||||
}))
|
||||
|
||||
const packages: SelectOption[] = state.selectedVersion
|
||||
? state.releases
|
||||
.find((release) => release.tag_name === state.selectedVersion)
|
||||
?.assets.map((asset) => ({
|
||||
value: asset.name,
|
||||
name: asset.name,
|
||||
})) || []
|
||||
: []
|
||||
|
||||
const getTitle = useCallback(() => {
|
||||
if (state.step === InstallStepFromGitHub.installed)
|
||||
return t(($) => $[`${i18nPrefix}.installedSuccessfully`], { ns: 'plugin' })
|
||||
if (state.step === InstallStepFromGitHub.installFailed)
|
||||
return t(($) => $[`${i18nPrefix}.installFailed`], { ns: 'plugin' })
|
||||
|
||||
return updatePayload
|
||||
? t(($) => $[`${i18nPrefix}.updatePlugin`], { ns: 'plugin' })
|
||||
: t(($) => $[`${i18nPrefix}.installPlugin`], { ns: 'plugin' })
|
||||
}, [state.step, t, updatePayload])
|
||||
|
||||
const handleUrlSubmit = async () => {
|
||||
const { isValid, owner, repo } = parseGitHubUrl(state.repoUrl)
|
||||
if (!isValid || !owner || !repo) {
|
||||
toast.error(t(($) => $['error.inValidGitHubUrl'], { ns: 'plugin' }))
|
||||
return
|
||||
}
|
||||
try {
|
||||
const fetchedReleases = await fetchReleases(owner, repo)
|
||||
if (fetchedReleases.length > 0) {
|
||||
setState((prevState) => ({
|
||||
...prevState,
|
||||
releases: fetchedReleases,
|
||||
step: InstallStepFromGitHub.selectPackage,
|
||||
}))
|
||||
} else {
|
||||
toast.error(t(($) => $['error.noReleasesFound'], { ns: 'plugin' }))
|
||||
}
|
||||
} catch {
|
||||
toast.error(t(($) => $['error.fetchReleasesError'], { ns: 'plugin' }))
|
||||
}
|
||||
}
|
||||
|
||||
const handleError = (e: any, isInstall: boolean) => {
|
||||
const message =
|
||||
(e instanceof Error ? e.message : undefined) ||
|
||||
t(($) => $['installModal.installFailedDesc'], { ns: 'plugin' })
|
||||
setErrorMsg(message)
|
||||
setState((prevState) => ({
|
||||
...prevState,
|
||||
step: isInstall ? InstallStepFromGitHub.installFailed : InstallStepFromGitHub.uploadFailed,
|
||||
}))
|
||||
}
|
||||
|
||||
const handleUploaded = async (GitHubPackage: any) => {
|
||||
try {
|
||||
const icon = await getIconUrl(GitHubPackage.manifest.icon)
|
||||
setManifest({
|
||||
...GitHubPackage.manifest,
|
||||
icon,
|
||||
})
|
||||
setUniqueIdentifier(GitHubPackage.uniqueIdentifier)
|
||||
setState((prevState) => ({ ...prevState, step: InstallStepFromGitHub.readyToInstall }))
|
||||
} catch (e) {
|
||||
handleError(e, false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleUploadFail = useCallback((errorMsg: string) => {
|
||||
setErrorMsg(errorMsg)
|
||||
setState((prevState) => ({ ...prevState, step: InstallStepFromGitHub.uploadFailed }))
|
||||
}, [])
|
||||
|
||||
const handleInstalled = useCallback(
|
||||
async (notRefresh?: boolean) => {
|
||||
if (!notRefresh) refreshPluginList(manifest)
|
||||
await onSuccess()
|
||||
setState((prevState) => ({ ...prevState, step: InstallStepFromGitHub.installed }))
|
||||
setIsInstalling(false)
|
||||
},
|
||||
[manifest, onSuccess, refreshPluginList, setIsInstalling],
|
||||
)
|
||||
|
||||
const handleFailed = useCallback(
|
||||
(errorMsg?: string) => {
|
||||
setState((prevState) => ({ ...prevState, step: InstallStepFromGitHub.installFailed }))
|
||||
setIsInstalling(false)
|
||||
if (errorMsg) setErrorMsg(errorMsg)
|
||||
},
|
||||
[setIsInstalling],
|
||||
)
|
||||
|
||||
const handleBack = () => {
|
||||
setState((prevState) => {
|
||||
switch (prevState.step) {
|
||||
case InstallStepFromGitHub.selectPackage:
|
||||
return { ...prevState, step: InstallStepFromGitHub.setUrl }
|
||||
case InstallStepFromGitHub.readyToInstall:
|
||||
return { ...prevState, step: InstallStepFromGitHub.selectPackage }
|
||||
default:
|
||||
return prevState
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const completedSteps: InstallStepFromGitHub[] = [
|
||||
InstallStepFromGitHub.uploadFailed,
|
||||
InstallStepFromGitHub.installed,
|
||||
InstallStepFromGitHub.installFailed,
|
||||
]
|
||||
const failedSteps: InstallStepFromGitHub[] = [
|
||||
InstallStepFromGitHub.uploadFailed,
|
||||
InstallStepFromGitHub.installFailed,
|
||||
]
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
onOpenChange={(open) => {
|
||||
if (!open) foldAnimInto()
|
||||
}}
|
||||
>
|
||||
<DialogContent
|
||||
initialFocus={repoUrlInputRef}
|
||||
backdropProps={{ forceRender: true }}
|
||||
className={cn('w-140', modalClassName, 'max-h-[calc(100dvh-48px)]')}
|
||||
>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{getTitle()}</DialogTitle>
|
||||
{!completedSteps.includes(state.step) && (
|
||||
<DialogDescription>
|
||||
{t(($) => $['installFromGitHub.installNote'], { ns: 'plugin' })}
|
||||
</DialogDescription>
|
||||
)}
|
||||
<DialogHeaderCloseButton aria-label={t(($) => $['operation.close'], { ns: 'common' })} />
|
||||
</DialogHeader>
|
||||
{completedSteps.includes(state.step) ? (
|
||||
<Installed
|
||||
payload={manifest}
|
||||
isFailed={failedSteps.includes(state.step)}
|
||||
errMsg={errorMsg}
|
||||
installContextCategory={installContextCategory}
|
||||
onCancel={onClose}
|
||||
/>
|
||||
) : state.step === InstallStepFromGitHub.setUrl ? (
|
||||
<Form className="contents" onFormSubmit={handleUrlSubmit}>
|
||||
<DialogBody>
|
||||
<Field name="repoUrl" className="gap-4">
|
||||
<FieldLabel className="flex w-full flex-col items-start justify-center p-0 text-text-secondary">
|
||||
<span className="system-sm-semibold">
|
||||
{t(($) => $['installFromGitHub.gitHubRepo'], { ns: 'plugin' })}
|
||||
</span>
|
||||
</FieldLabel>
|
||||
<Input
|
||||
ref={repoUrlInputRef}
|
||||
type="text"
|
||||
inputMode="url"
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
value={state.repoUrl}
|
||||
onValueChange={(value) =>
|
||||
setState((prevState) => ({ ...prevState, repoUrl: value }))
|
||||
}
|
||||
className="flex grow items-center gap-0.5 self-stretch overflow-hidden rounded-lg border-components-input-border-active bg-components-input-bg-active p-2 text-ellipsis"
|
||||
placeholder="Please enter GitHub repo URL"
|
||||
/>
|
||||
</Field>
|
||||
</DialogBody>
|
||||
<DialogFooter>
|
||||
<Button variant="secondary" className="min-w-18" onClick={onClose}>
|
||||
{t(($) => $['installModal.cancel'], { ns: 'plugin' })}
|
||||
</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
type="submit"
|
||||
className="min-w-18"
|
||||
disabled={!state.repoUrl.trim()}
|
||||
>
|
||||
{t(($) => $['installModal.next'], { ns: 'plugin' })}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</Form>
|
||||
) : (
|
||||
<DialogBody className="flex flex-col items-start gap-4">
|
||||
{state.step === InstallStepFromGitHub.selectPackage && (
|
||||
<SelectPackage
|
||||
updatePayload={updatePayload!}
|
||||
repoUrl={state.repoUrl}
|
||||
selectedVersion={state.selectedVersion}
|
||||
versions={versions}
|
||||
onSelectVersion={(item) =>
|
||||
setState((prevState) => ({ ...prevState, selectedVersion: String(item.value) }))
|
||||
}
|
||||
selectedPackage={state.selectedPackage}
|
||||
packages={packages}
|
||||
onSelectPackage={(item) =>
|
||||
setState((prevState) => ({ ...prevState, selectedPackage: String(item.value) }))
|
||||
}
|
||||
onUploaded={handleUploaded}
|
||||
onFailed={handleUploadFail}
|
||||
onBack={handleBack}
|
||||
/>
|
||||
)}
|
||||
{state.step === InstallStepFromGitHub.readyToInstall &&
|
||||
manifest &&
|
||||
uniqueIdentifier && (
|
||||
<Loaded
|
||||
updatePayload={updatePayload!}
|
||||
uniqueIdentifier={uniqueIdentifier}
|
||||
payload={manifest}
|
||||
repoUrl={state.repoUrl}
|
||||
selectedVersion={state.selectedVersion}
|
||||
selectedPackage={state.selectedPackage}
|
||||
onBack={handleBack}
|
||||
onStartToInstall={handleStartToInstall}
|
||||
onInstalled={handleInstalled}
|
||||
onFailed={handleFailed}
|
||||
/>
|
||||
)}
|
||||
</DialogBody>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
export default InstallFromGitHub
|
||||
+184
@@ -0,0 +1,184 @@
|
||||
'use client'
|
||||
|
||||
import type { Plugin, PluginDeclaration, UpdateFromGitHubPayload } from '../../../types'
|
||||
import { Button } from '@langgenius/dify-ui/button'
|
||||
import * as React from 'react'
|
||||
import { useEffect } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import useCheckInstalled from '@/app/components/plugins/install-plugin/hooks/use-check-installed'
|
||||
import { updateFromGitHub } from '@/service/plugins'
|
||||
import { useInstallPackageFromGitHub, usePluginTaskList } from '@/service/use-plugins'
|
||||
import Card from '../../../card'
|
||||
import { TaskStatus } from '../../../types'
|
||||
import checkTaskStatus from '../../base/check-task-status'
|
||||
import Version from '../../base/version'
|
||||
import { parseGitHubUrl, pluginManifestToCardPluginProps } from '../../utils'
|
||||
|
||||
type LoadedProps = {
|
||||
updatePayload?: UpdateFromGitHubPayload
|
||||
uniqueIdentifier: string
|
||||
payload: PluginDeclaration | Plugin
|
||||
repoUrl: string
|
||||
selectedVersion: string
|
||||
selectedPackage: string
|
||||
onBack: () => void
|
||||
onStartToInstall?: () => void
|
||||
onInstalled: (notRefresh?: boolean) => void | Promise<void>
|
||||
onFailed: (message?: string) => void
|
||||
}
|
||||
|
||||
const i18nPrefix = 'installModal'
|
||||
|
||||
const Loaded: React.FC<LoadedProps> = ({
|
||||
updatePayload,
|
||||
uniqueIdentifier,
|
||||
payload,
|
||||
repoUrl,
|
||||
selectedVersion,
|
||||
selectedPackage,
|
||||
onBack,
|
||||
onStartToInstall,
|
||||
onInstalled,
|
||||
onFailed,
|
||||
}) => {
|
||||
const { t } = useTranslation(['plugin'])
|
||||
const installButtonLabelId = React.useId()
|
||||
const toInstallVersion = payload.version
|
||||
const pluginId = (payload as Plugin).plugin_id
|
||||
const { installedInfo, isLoading } = useCheckInstalled({
|
||||
pluginIds: [pluginId],
|
||||
enabled: !!pluginId,
|
||||
})
|
||||
const installedInfoPayload = installedInfo?.[pluginId]
|
||||
const installedVersion = installedInfoPayload?.installedVersion
|
||||
const hasInstalled = !!installedVersion
|
||||
|
||||
const [isInstalling, setIsInstalling] = React.useState(false)
|
||||
const { mutateAsync: installPackageFromGitHub } = useInstallPackageFromGitHub()
|
||||
const { handleInstallTaskStart } = usePluginTaskList(payload.category)
|
||||
const { check } = checkTaskStatus()
|
||||
|
||||
useEffect(() => {
|
||||
if (hasInstalled && uniqueIdentifier === installedInfoPayload.uniqueIdentifier) onInstalled()
|
||||
}, [hasInstalled])
|
||||
|
||||
const handleInstall = async () => {
|
||||
if (isInstalling) return
|
||||
setIsInstalling(true)
|
||||
onStartToInstall?.()
|
||||
|
||||
try {
|
||||
const { owner, repo } = parseGitHubUrl(repoUrl)
|
||||
let taskId
|
||||
let isInstalled
|
||||
if (updatePayload) {
|
||||
const response = await updateFromGitHub(
|
||||
`${owner}/${repo}`,
|
||||
selectedVersion,
|
||||
selectedPackage,
|
||||
updatePayload.originalPackageInfo.id,
|
||||
uniqueIdentifier,
|
||||
)
|
||||
const { all_installed, task_id } = response
|
||||
handleInstallTaskStart(response)
|
||||
|
||||
taskId = task_id
|
||||
isInstalled = all_installed
|
||||
} else {
|
||||
if (hasInstalled) {
|
||||
const response = await updateFromGitHub(
|
||||
`${owner}/${repo}`,
|
||||
selectedVersion,
|
||||
selectedPackage,
|
||||
installedInfoPayload.uniqueIdentifier,
|
||||
uniqueIdentifier,
|
||||
)
|
||||
const { all_installed, task_id } = response
|
||||
handleInstallTaskStart(response)
|
||||
taskId = task_id
|
||||
isInstalled = all_installed
|
||||
} else {
|
||||
const response = await installPackageFromGitHub({
|
||||
repoUrl: `${owner}/${repo}`,
|
||||
selectedVersion,
|
||||
selectedPackage,
|
||||
uniqueIdentifier,
|
||||
})
|
||||
const { all_installed, task_id } = response
|
||||
handleInstallTaskStart(response)
|
||||
|
||||
taskId = task_id
|
||||
isInstalled = all_installed
|
||||
}
|
||||
}
|
||||
if (isInstalled) {
|
||||
await onInstalled()
|
||||
return
|
||||
}
|
||||
|
||||
const { status, error } = await check({
|
||||
taskId,
|
||||
pluginUniqueIdentifier: uniqueIdentifier,
|
||||
})
|
||||
if (status === TaskStatus.failed) {
|
||||
onFailed(error)
|
||||
return
|
||||
}
|
||||
await onInstalled(true)
|
||||
} catch (e) {
|
||||
if (typeof e === 'string') {
|
||||
onFailed(e)
|
||||
return
|
||||
}
|
||||
onFailed()
|
||||
} finally {
|
||||
setIsInstalling(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="system-md-regular text-text-secondary">
|
||||
<p>{t(($) => $[`${i18nPrefix}.readyToInstall`], { ns: 'plugin' })}</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap content-start items-start gap-1 self-stretch rounded-2xl bg-background-section-burn p-2">
|
||||
<Card
|
||||
className="w-full"
|
||||
payload={pluginManifestToCardPluginProps(payload as PluginDeclaration)}
|
||||
titleLeft={
|
||||
!isLoading && (
|
||||
<Version
|
||||
hasInstalled={hasInstalled}
|
||||
installedVersion={installedVersion}
|
||||
toInstallVersion={toInstallVersion}
|
||||
/>
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="mt-4 flex items-center justify-end gap-2 self-stretch">
|
||||
{!isInstalling && (
|
||||
<Button variant="secondary" className="min-w-18" onClick={onBack}>
|
||||
{t(($) => $['installModal.back'], { ns: 'plugin' })}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="primary"
|
||||
className="min-w-18"
|
||||
onClick={handleInstall}
|
||||
disabled={isLoading}
|
||||
loading={isInstalling}
|
||||
aria-labelledby={installButtonLabelId}
|
||||
>
|
||||
<span id={installButtonLabelId}>
|
||||
{t(($) => $[`${i18nPrefix}.${isInstalling ? 'installing' : 'install'}`], {
|
||||
ns: 'plugin',
|
||||
})}
|
||||
</span>
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default Loaded
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
'use client'
|
||||
|
||||
import type { PluginDeclaration, UpdateFromGitHubPayload } from '../../../types'
|
||||
import { Button } from '@langgenius/dify-ui/button'
|
||||
import { Field } from '@langgenius/dify-ui/field'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectItemIndicator,
|
||||
SelectItemText,
|
||||
SelectLabel,
|
||||
SelectTrigger,
|
||||
} from '@langgenius/dify-ui/select'
|
||||
import * as React from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import Badge from '@/app/components/base/badge'
|
||||
import { handleUpload } from '../../hooks'
|
||||
|
||||
const i18nPrefix = 'installFromGitHub'
|
||||
|
||||
type SelectOption = {
|
||||
value: string
|
||||
name: string
|
||||
}
|
||||
|
||||
type SelectPackageProps = {
|
||||
updatePayload: UpdateFromGitHubPayload
|
||||
repoUrl: string
|
||||
selectedVersion: string
|
||||
versions: SelectOption[]
|
||||
onSelectVersion: (item: SelectOption) => void
|
||||
selectedPackage: string
|
||||
packages: SelectOption[]
|
||||
onSelectPackage: (item: SelectOption) => void
|
||||
onUploaded: (result: { uniqueIdentifier: string; manifest: PluginDeclaration }) => void
|
||||
onFailed: (errorMsg: string) => void
|
||||
onBack: () => void
|
||||
}
|
||||
|
||||
const SelectPackage: React.FC<SelectPackageProps> = ({
|
||||
updatePayload,
|
||||
repoUrl,
|
||||
selectedVersion,
|
||||
versions,
|
||||
onSelectVersion,
|
||||
selectedPackage,
|
||||
packages,
|
||||
onSelectPackage,
|
||||
onUploaded,
|
||||
onFailed,
|
||||
onBack,
|
||||
}) => {
|
||||
const { t } = useTranslation(['plugin'])
|
||||
const isEdit = Boolean(updatePayload)
|
||||
const [isUploading, setIsUploading] = React.useState(false)
|
||||
const selectedVersionOption = versions.find((item) => item.value === selectedVersion) ?? null
|
||||
const selectedPackageOption = packages.find((item) => item.value === selectedPackage) ?? null
|
||||
|
||||
const handleUploadPackage = async () => {
|
||||
if (isUploading) return
|
||||
setIsUploading(true)
|
||||
try {
|
||||
const repo = repoUrl.replace('https://github.com/', '')
|
||||
await handleUpload(repo, selectedVersion, selectedPackage, (GitHubPackage) => {
|
||||
onUploaded({
|
||||
uniqueIdentifier: GitHubPackage.unique_identifier,
|
||||
manifest: GitHubPackage.manifest,
|
||||
})
|
||||
})
|
||||
} catch (e) {
|
||||
if (e instanceof Error && e.message) onFailed(e.message)
|
||||
else onFailed(t(($) => $[`${i18nPrefix}.uploadFailed`], { ns: 'plugin' }))
|
||||
} finally {
|
||||
setIsUploading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Field name="version" className="gap-4 self-stretch">
|
||||
<Select
|
||||
value={selectedVersionOption?.value ?? null}
|
||||
onValueChange={(value) => {
|
||||
if (value == null) return
|
||||
const selectedItem = versions.find((item) => item.value === value)
|
||||
if (selectedItem) onSelectVersion(selectedItem)
|
||||
}}
|
||||
>
|
||||
<SelectLabel className="flex w-full flex-col items-start justify-center p-0 text-text-secondary">
|
||||
<span className="system-sm-semibold">
|
||||
{t(($) => $[`${i18nPrefix}.selectVersion`], { ns: 'plugin' })}
|
||||
</span>
|
||||
</SelectLabel>
|
||||
<SelectTrigger className="h-9 text-components-input-text-filled">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className="truncate">
|
||||
{selectedVersionOption?.name ??
|
||||
t(($) => $[`${i18nPrefix}.selectVersionPlaceholder`], { ns: 'plugin' }) ??
|
||||
''}
|
||||
</span>
|
||||
{!!(
|
||||
updatePayload?.originalPackageInfo.version &&
|
||||
selectedVersionOption &&
|
||||
selectedVersionOption.value !== updatePayload.originalPackageInfo.version
|
||||
) && (
|
||||
<Badge>
|
||||
{updatePayload.originalPackageInfo.version} {'->'} {selectedVersionOption.value}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</SelectTrigger>
|
||||
<SelectContent className="w-lg">
|
||||
{versions.map((item) => (
|
||||
<SelectItem key={item.value} value={item.value}>
|
||||
<SelectItemText>{item.name}</SelectItemText>
|
||||
{item.value === updatePayload?.originalPackageInfo.version && (
|
||||
<Badge uppercase={true} className="ml-1 shrink-0">
|
||||
INSTALLED
|
||||
</Badge>
|
||||
)}
|
||||
<SelectItemIndicator />
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
<Field name="package" className="gap-4 self-stretch">
|
||||
<Select
|
||||
value={selectedPackageOption?.value ?? null}
|
||||
disabled={!selectedVersion}
|
||||
onValueChange={(value) => {
|
||||
if (value == null) return
|
||||
const selectedItem = packages.find((item) => item.value === value)
|
||||
if (selectedItem) onSelectPackage(selectedItem)
|
||||
}}
|
||||
>
|
||||
<SelectLabel className="flex w-full flex-col items-start justify-center p-0 text-text-secondary">
|
||||
<span className="system-sm-semibold">
|
||||
{t(($) => $[`${i18nPrefix}.selectPackage`], { ns: 'plugin' })}
|
||||
</span>
|
||||
</SelectLabel>
|
||||
<SelectTrigger className="h-9 text-components-input-text-filled">
|
||||
{selectedPackageOption?.name ??
|
||||
t(($) => $[`${i18nPrefix}.selectPackagePlaceholder`], { ns: 'plugin' }) ??
|
||||
''}
|
||||
</SelectTrigger>
|
||||
<SelectContent className="w-lg">
|
||||
{packages.map((item) => (
|
||||
<SelectItem key={item.value} value={item.value}>
|
||||
<SelectItemText>{item.name}</SelectItemText>
|
||||
<SelectItemIndicator />
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
<div className="mt-4 flex items-center justify-end gap-2 self-stretch">
|
||||
{!isEdit && (
|
||||
<Button variant="secondary" className="min-w-18" onClick={onBack} disabled={isUploading}>
|
||||
{t(($) => $['installModal.back'], { ns: 'plugin' })}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="primary"
|
||||
className="min-w-18"
|
||||
onClick={handleUploadPackage}
|
||||
disabled={!selectedVersion || !selectedPackage || isUploading}
|
||||
>
|
||||
{t(($) => $['installModal.next'], { ns: 'plugin' })}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default SelectPackage
|
||||
+312
@@ -0,0 +1,312 @@
|
||||
import type { PluginInstallTaskStartResponse } from '@dify/contracts/api/console/workspaces/types.gen'
|
||||
import type { ConsoleQueryTestOptions } from '@/test/console/query-data'
|
||||
import { screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { API_PREFIX } from '@/config'
|
||||
import { createHttpError } from '@/service/http-error'
|
||||
import { renderWithConsoleQuery } from '@/test/console/query-data'
|
||||
import { createDeferred } from '@/test/deferred'
|
||||
import { createPluginDeclarationFixture, createPluginEntity } from '@/test/fixtures/plugin'
|
||||
import { PermissionType, TaskStatus } from '../../../types'
|
||||
import InstallFromLocalPackage from '../index'
|
||||
|
||||
const { upload, install, installedPlugins, uninstall, pollTask, refresh } = vi.hoisted(() => ({
|
||||
upload: vi.fn(),
|
||||
install: vi.fn(),
|
||||
installedPlugins: vi.fn(),
|
||||
uninstall: vi.fn(),
|
||||
pollTask: vi.fn(),
|
||||
refresh: vi.fn(),
|
||||
}))
|
||||
vi.mock('@/service/plugins', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('@/service/plugins')>()),
|
||||
uploadFile: upload,
|
||||
uninstallPlugin: uninstall,
|
||||
checkTaskStatus: pollTask,
|
||||
}))
|
||||
vi.mock('@/service/console', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/service/console')>()
|
||||
const { withConsoleResponses, withConsoleClientResponses } =
|
||||
await import('@/test/console/service-responses')
|
||||
return {
|
||||
...actual,
|
||||
consoleClient: withConsoleClientResponses(actual.consoleClient, {
|
||||
'workspaces.current.plugin.permission.fetch.get': async () => ({
|
||||
install_permission: PermissionType.everyone,
|
||||
debug_permission: PermissionType.everyone,
|
||||
}),
|
||||
'workspaces.current.plugin.tasks.get': async () => ({ tasks: [] }),
|
||||
'workspaces.current.plugin.install.pkg.post': install,
|
||||
}),
|
||||
consoleQuery: withConsoleResponses(actual.consoleQuery, {
|
||||
'workspaces.current.plugin.list.installations.ids.post': installedPlugins,
|
||||
}),
|
||||
}
|
||||
})
|
||||
// Refreshing the separate model/tool catalogs is covered by use-refresh-plugin-list.
|
||||
vi.mock('../../hooks/use-refresh-plugin-list', () => ({
|
||||
default: () => ({ refreshPluginList: refresh }),
|
||||
}))
|
||||
|
||||
const manifest = createPluginDeclarationFixture({
|
||||
author: 'test',
|
||||
name: 'local',
|
||||
label: { ...createPluginDeclarationFixture().label, en_US: 'Local plugin' },
|
||||
})
|
||||
const uploadedPackage = { unique_identifier: 'test/local:1.0.0', manifest }
|
||||
const file = new File(['package'], 'local.difypkg', { type: 'application/octet-stream' })
|
||||
const renderInstaller = (selectedFile = file, options: ConsoleQueryTestOptions = {}) => {
|
||||
const onClose = vi.fn()
|
||||
renderWithConsoleQuery(
|
||||
<InstallFromLocalPackage file={selectedFile} onClose={onClose} onSuccess={vi.fn()} />,
|
||||
{
|
||||
accountProfileMeta: { currentVersion: '1.0.0' },
|
||||
currentWorkspace: { id: 'local-install-workspace' },
|
||||
workspacePermissionKeys: ['plugin.install'],
|
||||
systemFeatures: {
|
||||
enable_marketplace: true,
|
||||
rbac_enabled: true,
|
||||
plugin_installation_permission: {
|
||||
plugin_installation_scope: 'all',
|
||||
restrict_to_marketplace_only: false,
|
||||
},
|
||||
},
|
||||
...options,
|
||||
},
|
||||
)
|
||||
return { onClose }
|
||||
}
|
||||
const installButton = () => screen.getByRole('button', { name: 'plugin.installModal.install' })
|
||||
const startInstall = async (user: ReturnType<typeof userEvent.setup>) => {
|
||||
await screen.findByText('plugin.installModal.readyToInstall')
|
||||
await waitFor(() => expect(installButton()).toBeEnabled())
|
||||
await user.click(installButton())
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks()
|
||||
upload.mockResolvedValue(uploadedPackage)
|
||||
installedPlugins.mockResolvedValue({ plugins: [] })
|
||||
install.mockResolvedValue({ all_installed: true, task_id: '' })
|
||||
uninstall.mockResolvedValue({})
|
||||
})
|
||||
|
||||
it('uploads the file, prevents duplicate installs while pending, and shows the completed package', async () => {
|
||||
const user = userEvent.setup()
|
||||
const uploaded = createDeferred<typeof uploadedPackage>()
|
||||
const started = createDeferred<PluginInstallTaskStartResponse>()
|
||||
upload.mockReturnValue(uploaded.promise)
|
||||
install.mockReturnValue(started.promise)
|
||||
const { onClose } = renderInstaller()
|
||||
expect(screen.getByText(/plugin.installModal.uploadingPackage/)).toHaveTextContent(
|
||||
'local.difypkg',
|
||||
)
|
||||
expect(installButton()).toBeDisabled()
|
||||
expect(upload).toHaveBeenCalledExactlyOnceWith(file, false)
|
||||
uploaded.resolve(uploadedPackage)
|
||||
await startInstall(user)
|
||||
expect(screen.queryByText(/plugin.installModal.uploadingPackage/)).not.toBeInTheDocument()
|
||||
const pendingButton = screen.getByRole('button', { name: 'plugin.installModal.installing' })
|
||||
expect(pendingButton).toBeDisabled()
|
||||
expect(screen.queryByRole('button', { name: 'common.operation.cancel' })).not.toBeInTheDocument()
|
||||
await user.click(pendingButton)
|
||||
expect(install).toHaveBeenCalledExactlyOnceWith({
|
||||
body: { plugin_unique_identifiers: ['test/local:1.0.0'] },
|
||||
})
|
||||
started.resolve({ all_installed: true, task_id: '' })
|
||||
await screen.findByRole('dialog', { name: 'plugin.installModal.installedSuccessfully' })
|
||||
expect(screen.getByText('Local plugin')).toBeInTheDocument()
|
||||
expect(screen.getByText('1.0.0')).toBeInTheDocument()
|
||||
expect(refresh).toHaveBeenCalledExactlyOnceWith(
|
||||
expect.objectContaining({
|
||||
name: 'local',
|
||||
icon: `${API_PREFIX}/workspaces/current/plugin/icon?tenant_id=local-install-workspace&filename=test-icon.png`,
|
||||
}),
|
||||
)
|
||||
expect(pollTask).not.toHaveBeenCalled()
|
||||
await user.click(screen.getAllByRole('button', { name: 'common.operation.close' }).at(-1)!)
|
||||
expect(onClose).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it.each(['common.operation.cancel', 'common.operation.close'])(
|
||||
'allows %s while upload is pending without installing',
|
||||
async (name) => {
|
||||
const user = userEvent.setup()
|
||||
upload.mockReturnValue(new Promise(() => {}))
|
||||
const { onClose } = renderInstaller()
|
||||
await user.click(screen.getByRole('button', { name }))
|
||||
expect(onClose).toHaveBeenCalledOnce()
|
||||
expect(install).not.toHaveBeenCalled()
|
||||
},
|
||||
)
|
||||
|
||||
it.each([
|
||||
{
|
||||
reason: 'server error',
|
||||
error: createHttpError(new Response(null, { status: 413 }), { message: 'File too large' }),
|
||||
message: 'File too large',
|
||||
},
|
||||
{
|
||||
reason: 'transport error',
|
||||
error: new TypeError('Failed to fetch'),
|
||||
message: 'plugin.installModal.uploadFailed',
|
||||
},
|
||||
])('shows $reason from upload and allows closing the failure', async ({ error, message }) => {
|
||||
const user = userEvent.setup()
|
||||
upload.mockRejectedValue(error)
|
||||
const { onClose } = renderInstaller()
|
||||
await screen.findByRole('dialog', { name: 'plugin.installModal.uploadFailed' })
|
||||
expect(screen.getAllByText(message).length).toBeGreaterThan(0)
|
||||
expect(
|
||||
screen.queryByRole('button', { name: 'plugin.installModal.install' }),
|
||||
).not.toBeInTheDocument()
|
||||
expect(install).not.toHaveBeenCalled()
|
||||
await user.click(screen.getAllByRole('button', { name: 'common.operation.close' }).at(-1)!)
|
||||
expect(onClose).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it.each(['local.difypkg', 'local.difybndl'])(
|
||||
'rejects an invalid upload response for %s before installing',
|
||||
async (name) => {
|
||||
upload.mockResolvedValue({})
|
||||
renderInstaller(new File(['invalid'], name))
|
||||
await screen.findByRole('dialog', { name: 'plugin.installModal.uploadFailed' })
|
||||
expect(
|
||||
screen.queryByRole('button', { name: 'plugin.installModal.install' }),
|
||||
).not.toBeInTheDocument()
|
||||
expect(install).not.toHaveBeenCalled()
|
||||
},
|
||||
)
|
||||
|
||||
it('waits for installed-version lookup, then preserves credentials before replacing the package', async () => {
|
||||
const user = userEvent.setup()
|
||||
const previous = createPluginEntity({
|
||||
id: 'old-installation',
|
||||
plugin_id: 'test/local',
|
||||
plugin_unique_identifier: 'test/local:0.9.0',
|
||||
})
|
||||
previous.declaration.version = '0.9.0'
|
||||
const lookup = createDeferred<{ plugins: (typeof previous)[] }>()
|
||||
const removal = createDeferred<void>()
|
||||
installedPlugins.mockReturnValue(lookup.promise)
|
||||
uninstall.mockReturnValue(removal.promise)
|
||||
renderInstaller()
|
||||
await screen.findByText('plugin.installModal.readyToInstall')
|
||||
expect(installButton()).toBeDisabled()
|
||||
lookup.resolve({ plugins: [previous] })
|
||||
await screen.findByText('0.9.0 -> 1.0.0')
|
||||
await startInstall(user)
|
||||
expect(uninstall).toHaveBeenCalledExactlyOnceWith('old-installation', {
|
||||
preserveCredentials: true,
|
||||
})
|
||||
expect(install).not.toHaveBeenCalled()
|
||||
removal.resolve()
|
||||
await screen.findByRole('dialog', { name: 'plugin.installModal.installedSuccessfully' })
|
||||
expect(install).toHaveBeenCalledExactlyOnceWith({
|
||||
body: { plugin_unique_identifiers: ['test/local:1.0.0'] },
|
||||
})
|
||||
})
|
||||
|
||||
it('skips reinstalling an identical package', async () => {
|
||||
installedPlugins.mockResolvedValue({
|
||||
plugins: [
|
||||
createPluginEntity({ plugin_id: 'test/local', plugin_unique_identifier: 'test/local:1.0.0' }),
|
||||
],
|
||||
})
|
||||
renderInstaller()
|
||||
await screen.findByRole('dialog', { name: 'plugin.installModal.installedSuccessfully' })
|
||||
expect(install).not.toHaveBeenCalled()
|
||||
expect(uninstall).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.each([TaskStatus.success, TaskStatus.failed])(
|
||||
'shows the asynchronous task result: %s',
|
||||
async (status) => {
|
||||
const user = userEvent.setup()
|
||||
const task = createDeferred<{
|
||||
task: { plugins: { plugin_unique_identifier: string; status: TaskStatus; message: string }[] }
|
||||
}>()
|
||||
install.mockResolvedValue({ all_installed: false, task_id: 'install-task' })
|
||||
pollTask.mockReturnValue(task.promise)
|
||||
renderInstaller()
|
||||
await startInstall(user)
|
||||
await waitFor(() => expect(pollTask).toHaveBeenCalledExactlyOnceWith('install-task'))
|
||||
expect(screen.getByRole('button', { name: 'plugin.installModal.installing' })).toBeDisabled()
|
||||
task.resolve({
|
||||
task: {
|
||||
plugins: [
|
||||
{
|
||||
plugin_unique_identifier: 'test/local:1.0.0',
|
||||
status,
|
||||
message: 'Dependency unavailable',
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
await screen.findByRole('dialog', {
|
||||
name:
|
||||
status === TaskStatus.success
|
||||
? 'plugin.installModal.installedSuccessfully'
|
||||
: 'plugin.installModal.installFailed',
|
||||
})
|
||||
if (status === TaskStatus.failed)
|
||||
expect(screen.getByText('Dependency unavailable')).toBeInTheDocument()
|
||||
expect(refresh).not.toHaveBeenCalled()
|
||||
},
|
||||
)
|
||||
|
||||
it('shows a generic installation failure when the install request rejects', async () => {
|
||||
const user = userEvent.setup()
|
||||
install.mockRejectedValue(new Error('Connection failed'))
|
||||
renderInstaller()
|
||||
await startInstall(user)
|
||||
await screen.findByRole('dialog', { name: 'plugin.installModal.installFailed' })
|
||||
expect(screen.getByText('plugin.installModal.installFailedDesc')).toBeInTheDocument()
|
||||
expect(refresh).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('uploads a bundle and installs its returned package dependency', async () => {
|
||||
const user = userEvent.setup()
|
||||
const bundle = new File(['bundle'], 'local.difybndl')
|
||||
upload.mockResolvedValue(
|
||||
['bundled'].map((name) => ({
|
||||
type: 'package',
|
||||
value: {
|
||||
unique_identifier: `test/${name}:1.0.0`,
|
||||
manifest: createPluginDeclarationFixture({ author: 'test', name }),
|
||||
},
|
||||
})),
|
||||
)
|
||||
renderInstaller(bundle)
|
||||
await waitFor(() => expect(installButton()).toBeEnabled())
|
||||
await user.click(installButton())
|
||||
await screen.findByRole('dialog', { name: 'plugin.installModal.installedSuccessfully' })
|
||||
expect(upload).toHaveBeenCalledExactlyOnceWith(bundle, true)
|
||||
expect(install).toHaveBeenCalledExactlyOnceWith({
|
||||
body: { plugin_unique_identifiers: ['test/bundled:1.0.0'] },
|
||||
})
|
||||
expect(
|
||||
screen.getByText('plugin.installModal.installedSuccessfullyCountDesc:{"num":1}'),
|
||||
).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it.each([
|
||||
{ currentVersion: '1.0.0', minimum: '0.8.0', warns: false },
|
||||
{ currentVersion: '1.0.0', minimum: '2.0.0', warns: true },
|
||||
{ currentVersion: '1.0.0', minimum: undefined, warns: false },
|
||||
{ currentVersion: null, minimum: '2.0.0', warns: false },
|
||||
])(
|
||||
'warns about compatibility for Dify $currentVersion and minimum $minimum without blocking installation',
|
||||
async ({ currentVersion, minimum, warns }) => {
|
||||
upload.mockResolvedValue({
|
||||
...uploadedPackage,
|
||||
manifest: { ...manifest, meta: { version: '1.0.0', minimum_dify_version: minimum } },
|
||||
})
|
||||
renderInstaller(file, { accountProfileMeta: { currentVersion } })
|
||||
await screen.findByText('plugin.installModal.readyToInstall')
|
||||
await waitFor(() => expect(installButton()).toBeEnabled())
|
||||
if (warns)
|
||||
expect(screen.getByText(/plugin.difyVersionNotCompatible/)).toHaveTextContent('2.0.0')
|
||||
else expect(screen.queryByText(/plugin.difyVersionNotCompatible/)).not.toBeInTheDocument()
|
||||
},
|
||||
)
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
'use client'
|
||||
import type { Dependency, PluginCategoryEnum, PluginDeclaration } from '../../types'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogHeaderCloseButton,
|
||||
DialogTitle,
|
||||
} from '@langgenius/dify-ui/dialog'
|
||||
import * as React from 'react'
|
||||
import { useCallback, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import useGetIcon from '@/app/components/plugins/install-plugin/base/use-get-icon'
|
||||
import { InstallStep } from '../../types'
|
||||
import useHideLogic from '../hooks/use-hide-logic'
|
||||
import ReadyToInstallBundle from '../install-bundle/ready-to-install'
|
||||
import ReadyToInstallPackage from './ready-to-install'
|
||||
import Uploading from './steps/uploading'
|
||||
|
||||
const i18nPrefix = 'installModal'
|
||||
|
||||
type InstallFromLocalPackageProps = {
|
||||
file: File
|
||||
installContextCategory?: PluginCategoryEnum
|
||||
onSuccess: () => void
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
const InstallFromLocalPackage: React.FC<InstallFromLocalPackageProps> = ({
|
||||
file,
|
||||
installContextCategory,
|
||||
onClose,
|
||||
}) => {
|
||||
const { t } = useTranslation(['common', 'plugin'])
|
||||
// uploading -> !uploadFailed -> readyToInstall -> installed/failed
|
||||
const [step, setStep] = useState<InstallStep>(InstallStep.uploading)
|
||||
const [uniqueIdentifier, setUniqueIdentifier] = useState<string | null>(null)
|
||||
const [manifest, setManifest] = useState<PluginDeclaration | null>(null)
|
||||
const [errorMsg, setErrorMsg] = useState<string | null>(null)
|
||||
const isBundle = file.name.endsWith('.difybndl')
|
||||
const [dependencies, setDependencies] = useState<Dependency[]>([])
|
||||
|
||||
const { modalClassName, foldAnimInto, setIsInstalling, handleStartToInstall } =
|
||||
useHideLogic(onClose)
|
||||
|
||||
const getTitle = useCallback(() => {
|
||||
if (step === InstallStep.uploadFailed)
|
||||
return t(($) => $[`${i18nPrefix}.uploadFailed`], { ns: 'plugin' })
|
||||
if (isBundle && step === InstallStep.installed)
|
||||
return t(($) => $[`${i18nPrefix}.installedSuccessfully`], { ns: 'plugin' })
|
||||
if (step === InstallStep.installed)
|
||||
return t(($) => $[`${i18nPrefix}.installedSuccessfully`], { ns: 'plugin' })
|
||||
if (step === InstallStep.installFailed)
|
||||
return t(($) => $[`${i18nPrefix}.installFailed`], { ns: 'plugin' })
|
||||
|
||||
return t(($) => $[`${i18nPrefix}.installPlugin`], { ns: 'plugin' })
|
||||
}, [isBundle, step, t])
|
||||
|
||||
const { getIconUrl } = useGetIcon()
|
||||
|
||||
const handlePackageUploaded = useCallback(
|
||||
async (result: { uniqueIdentifier: string; manifest: PluginDeclaration }) => {
|
||||
const { manifest, uniqueIdentifier } = result
|
||||
const icon = await getIconUrl(manifest!.icon)
|
||||
const iconDark = manifest.icon_dark ? await getIconUrl(manifest.icon_dark) : undefined
|
||||
setUniqueIdentifier(uniqueIdentifier)
|
||||
setManifest({
|
||||
...manifest,
|
||||
icon,
|
||||
icon_dark: iconDark,
|
||||
})
|
||||
setStep(InstallStep.readyToInstall)
|
||||
},
|
||||
[getIconUrl],
|
||||
)
|
||||
|
||||
const handleBundleUploaded = useCallback((result: Dependency[]) => {
|
||||
setDependencies(result)
|
||||
setStep(InstallStep.readyToInstall)
|
||||
}, [])
|
||||
|
||||
const handleUploadFail = useCallback((errorMsg: string) => {
|
||||
setErrorMsg(errorMsg)
|
||||
setStep(InstallStep.uploadFailed)
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
onOpenChange={(open) => {
|
||||
if (!open) foldAnimInto()
|
||||
}}
|
||||
>
|
||||
<DialogContent
|
||||
backdropProps={{ forceRender: true }}
|
||||
className={cn('w-140', modalClassName, 'max-h-[calc(100dvh-48px)]')}
|
||||
>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{getTitle()}</DialogTitle>
|
||||
<DialogHeaderCloseButton aria-label={t(($) => $['operation.close'], { ns: 'common' })} />
|
||||
</DialogHeader>
|
||||
{step === InstallStep.uploading && (
|
||||
<Uploading
|
||||
isBundle={isBundle}
|
||||
file={file}
|
||||
onCancel={onClose}
|
||||
onPackageUploaded={handlePackageUploaded}
|
||||
onBundleUploaded={handleBundleUploaded}
|
||||
onFailed={handleUploadFail}
|
||||
/>
|
||||
)}
|
||||
{isBundle ? (
|
||||
<ReadyToInstallBundle
|
||||
step={step}
|
||||
onStepChange={setStep}
|
||||
onStartToInstall={handleStartToInstall}
|
||||
setIsInstalling={setIsInstalling}
|
||||
onClose={onClose}
|
||||
allPlugins={dependencies}
|
||||
/>
|
||||
) : (
|
||||
<ReadyToInstallPackage
|
||||
step={step}
|
||||
onStepChange={setStep}
|
||||
onStartToInstall={handleStartToInstall}
|
||||
setIsInstalling={setIsInstalling}
|
||||
onClose={onClose}
|
||||
uniqueIdentifier={uniqueIdentifier}
|
||||
manifest={manifest}
|
||||
errorMsg={errorMsg}
|
||||
installContextCategory={installContextCategory}
|
||||
onError={setErrorMsg}
|
||||
/>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
export default InstallFromLocalPackage
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import type { PluginCategoryEnum, PluginDeclaration } from '../../types'
|
||||
import * as React from 'react'
|
||||
import { useCallback } from 'react'
|
||||
import { InstallStep } from '../../types'
|
||||
import Installed from '../base/installed'
|
||||
import useRefreshPluginList from '../hooks/use-refresh-plugin-list'
|
||||
import Install from './steps/install'
|
||||
|
||||
type Props = Readonly<{
|
||||
step: InstallStep
|
||||
onStepChange: (step: InstallStep) => void
|
||||
onStartToInstall: () => void
|
||||
setIsInstalling: (isInstalling: boolean) => void
|
||||
onClose: () => void
|
||||
uniqueIdentifier: string | null
|
||||
manifest: PluginDeclaration | null
|
||||
errorMsg: string | null
|
||||
installContextCategory?: PluginCategoryEnum
|
||||
onError: (errorMsg: string) => void
|
||||
}>
|
||||
|
||||
const ReadyToInstall: FC<Props> = ({
|
||||
step,
|
||||
onStepChange,
|
||||
onStartToInstall,
|
||||
setIsInstalling,
|
||||
onClose,
|
||||
uniqueIdentifier,
|
||||
manifest,
|
||||
errorMsg,
|
||||
installContextCategory,
|
||||
onError,
|
||||
}) => {
|
||||
const { refreshPluginList } = useRefreshPluginList()
|
||||
|
||||
const handleInstalled = useCallback(
|
||||
(notRefresh?: boolean) => {
|
||||
onStepChange(InstallStep.installed)
|
||||
if (!notRefresh) refreshPluginList(manifest)
|
||||
setIsInstalling(false)
|
||||
},
|
||||
[manifest, onStepChange, refreshPluginList, setIsInstalling],
|
||||
)
|
||||
|
||||
const handleFailed = useCallback(
|
||||
(errorMsg?: string) => {
|
||||
onStepChange(InstallStep.installFailed)
|
||||
setIsInstalling(false)
|
||||
if (errorMsg) onError(errorMsg)
|
||||
},
|
||||
[onError, onStepChange, setIsInstalling],
|
||||
)
|
||||
|
||||
const completedSteps: InstallStep[] = [
|
||||
InstallStep.uploadFailed,
|
||||
InstallStep.installed,
|
||||
InstallStep.installFailed,
|
||||
]
|
||||
const failedSteps: InstallStep[] = [InstallStep.uploadFailed, InstallStep.installFailed]
|
||||
|
||||
return (
|
||||
<>
|
||||
{step === InstallStep.readyToInstall && (
|
||||
<Install
|
||||
uniqueIdentifier={uniqueIdentifier!}
|
||||
payload={manifest!}
|
||||
onCancel={onClose}
|
||||
onInstalled={handleInstalled}
|
||||
onFailed={handleFailed}
|
||||
onStartToInstall={onStartToInstall}
|
||||
/>
|
||||
)}
|
||||
{completedSteps.includes(step) && (
|
||||
<Installed
|
||||
payload={manifest}
|
||||
isFailed={failedSteps.includes(step)}
|
||||
errMsg={errorMsg}
|
||||
installContextCategory={installContextCategory}
|
||||
onCancel={onClose}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
export default React.memo(ReadyToInstall)
|
||||
+174
@@ -0,0 +1,174 @@
|
||||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import type { PluginDeclaration } from '../../../types'
|
||||
import { Button } from '@langgenius/dify-ui/button'
|
||||
import { RiLoader2Line } from '@remixicon/react'
|
||||
import { useSuspenseQuery } from '@tanstack/react-query'
|
||||
import * as React from 'react'
|
||||
import { useEffect, useMemo } from 'react'
|
||||
import { Trans, useTranslation } from 'react-i18next'
|
||||
import useCheckInstalled from '@/app/components/plugins/install-plugin/hooks/use-check-installed'
|
||||
import { userProfileQueryOptions } from '@/features/account-profile/client'
|
||||
import { uninstallPlugin } from '@/service/plugins'
|
||||
import { useInstallPackageFromLocal, usePluginTaskList } from '@/service/use-plugins'
|
||||
import { isEqualOrLaterThanVersion } from '@/utils/semver'
|
||||
import Card from '../../../card'
|
||||
import { TaskStatus } from '../../../types'
|
||||
import checkTaskStatus from '../../base/check-task-status'
|
||||
import Version from '../../base/version'
|
||||
import { pluginManifestToCardPluginProps } from '../../utils'
|
||||
|
||||
const i18nPrefix = 'installModal'
|
||||
|
||||
type Props = Readonly<{
|
||||
uniqueIdentifier: string
|
||||
payload: PluginDeclaration
|
||||
onCancel: () => void
|
||||
onStartToInstall?: () => void
|
||||
onInstalled: (notRefresh?: boolean) => void
|
||||
onFailed: (message?: string) => void
|
||||
}>
|
||||
|
||||
const Installed: FC<Props> = ({
|
||||
uniqueIdentifier,
|
||||
payload,
|
||||
onCancel,
|
||||
onStartToInstall,
|
||||
onInstalled,
|
||||
onFailed,
|
||||
}) => {
|
||||
const { t } = useTranslation(['common', 'plugin'])
|
||||
const toInstallVersion = payload.version
|
||||
const pluginId = `${payload.author}/${payload.name}`
|
||||
const { installedInfo, isLoading } = useCheckInstalled({
|
||||
pluginIds: [pluginId],
|
||||
enabled: !!pluginId,
|
||||
})
|
||||
const installedInfoPayload = installedInfo?.[pluginId]
|
||||
const installedVersion = installedInfoPayload?.installedVersion
|
||||
const hasInstalled = !!installedVersion
|
||||
|
||||
useEffect(() => {
|
||||
if (hasInstalled && uniqueIdentifier === installedInfoPayload.uniqueIdentifier) onInstalled()
|
||||
}, [hasInstalled])
|
||||
|
||||
const [isInstalling, setIsInstalling] = React.useState(false)
|
||||
const { mutateAsync: installPackageFromLocal } = useInstallPackageFromLocal()
|
||||
|
||||
const { check, stop } = checkTaskStatus()
|
||||
|
||||
const handleCancel = () => {
|
||||
stop()
|
||||
onCancel()
|
||||
}
|
||||
|
||||
const { handleInstallTaskStart } = usePluginTaskList(payload.category)
|
||||
const handleInstall = async () => {
|
||||
if (isInstalling) return
|
||||
setIsInstalling(true)
|
||||
onStartToInstall?.()
|
||||
|
||||
try {
|
||||
if (hasInstalled) {
|
||||
await uninstallPlugin(installedInfoPayload.installedId, { preserveCredentials: true })
|
||||
}
|
||||
|
||||
const response = await installPackageFromLocal(uniqueIdentifier)
|
||||
const { all_installed, task_id } = response
|
||||
handleInstallTaskStart(response)
|
||||
const taskId = task_id
|
||||
const isInstalled = all_installed
|
||||
|
||||
if (isInstalled) {
|
||||
onInstalled()
|
||||
return
|
||||
}
|
||||
const { status, error } = await check({
|
||||
taskId,
|
||||
pluginUniqueIdentifier: uniqueIdentifier,
|
||||
})
|
||||
if (status === TaskStatus.failed) {
|
||||
onFailed(error)
|
||||
return
|
||||
}
|
||||
onInstalled(true)
|
||||
} catch (e) {
|
||||
if (typeof e === 'string') {
|
||||
onFailed(e)
|
||||
return
|
||||
}
|
||||
onFailed()
|
||||
}
|
||||
}
|
||||
|
||||
const { data: currentVersion } = useSuspenseQuery({
|
||||
...userProfileQueryOptions(),
|
||||
select: (data) => data.meta.currentVersion ?? '',
|
||||
})
|
||||
const isDifyVersionCompatible = useMemo(() => {
|
||||
if (!currentVersion) return true
|
||||
return isEqualOrLaterThanVersion(currentVersion, payload.meta.minimum_dify_version ?? '0.0.0')
|
||||
}, [currentVersion, payload.meta.minimum_dify_version])
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-col items-start justify-center gap-2 self-stretch px-6 py-3">
|
||||
<div className="system-md-regular text-text-secondary">
|
||||
<p>{t(($) => $[`${i18nPrefix}.readyToInstall`], { ns: 'plugin' })}</p>
|
||||
<p>
|
||||
<Trans
|
||||
i18nKey={($) => $[`${i18nPrefix}.fromTrustSource`]}
|
||||
ns="plugin"
|
||||
components={{ trustSource: <span className="system-md-semibold" /> }}
|
||||
/>
|
||||
</p>
|
||||
{!isDifyVersionCompatible && (
|
||||
<p className="flex items-center gap-1 system-md-regular text-text-warning">
|
||||
{t(($) => $.difyVersionNotCompatible, {
|
||||
ns: 'plugin',
|
||||
minimalDifyVersion: payload.meta.minimum_dify_version ?? '0.0.0',
|
||||
})}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex flex-wrap content-start items-start gap-1 self-stretch rounded-2xl bg-background-section-burn p-2">
|
||||
<Card
|
||||
className="w-full"
|
||||
payload={pluginManifestToCardPluginProps(payload)}
|
||||
titleLeft={
|
||||
!isLoading && (
|
||||
<Version
|
||||
hasInstalled={hasInstalled}
|
||||
installedVersion={installedVersion}
|
||||
toInstallVersion={toInstallVersion}
|
||||
/>
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{/* Action Buttons */}
|
||||
<div className="flex items-center justify-end gap-2 self-stretch p-6 pt-5">
|
||||
{!isInstalling && (
|
||||
<Button variant="secondary" className="min-w-18" onClick={handleCancel}>
|
||||
{t(($) => $['operation.cancel'], { ns: 'common' })}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="primary"
|
||||
className="flex min-w-18"
|
||||
disabled={isInstalling || isLoading}
|
||||
onClick={handleInstall}
|
||||
>
|
||||
{isInstalling && <RiLoader2Line className="size-4 animate-spin-slow" />}
|
||||
<span>
|
||||
{t(($) => $[`${i18nPrefix}.${isInstalling ? 'installing' : 'install'}`], {
|
||||
ns: 'plugin',
|
||||
})}
|
||||
</span>
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
export default React.memo(Installed)
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
'use client'
|
||||
import type { FC } from 'react'
|
||||
import type { Dependency, Plugin, PluginDeclaration } from '../../../types'
|
||||
import { Button } from '@langgenius/dify-ui/button'
|
||||
import { ORPCError } from '@orpc/client'
|
||||
import * as React from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { uploadFile } from '@/service/plugins'
|
||||
import Card from '../../../card'
|
||||
|
||||
const i18nPrefix = 'installModal'
|
||||
|
||||
type PackageUploadResponse = {
|
||||
unique_identifier: string
|
||||
manifest: PluginDeclaration
|
||||
}
|
||||
|
||||
function isObject(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null
|
||||
}
|
||||
|
||||
function isPackageUploadResponse(value: unknown): value is PackageUploadResponse {
|
||||
if (!isObject(value)) return false
|
||||
|
||||
return typeof value.unique_identifier === 'string' && isObject(value.manifest)
|
||||
}
|
||||
|
||||
type Props = Readonly<{
|
||||
isBundle: boolean
|
||||
file: File
|
||||
onCancel: () => void
|
||||
onPackageUploaded: (result: { uniqueIdentifier: string; manifest: PluginDeclaration }) => void
|
||||
onBundleUploaded: (result: Dependency[]) => void
|
||||
onFailed: (errorMsg: string) => void
|
||||
}>
|
||||
|
||||
const Uploading: FC<Props> = ({
|
||||
isBundle,
|
||||
file,
|
||||
onCancel,
|
||||
onPackageUploaded,
|
||||
onBundleUploaded,
|
||||
onFailed,
|
||||
}) => {
|
||||
const { t } = useTranslation(['common', 'plugin'])
|
||||
const fileName = file.name
|
||||
const handleUploadedResponse = React.useCallback(
|
||||
(response: unknown) => {
|
||||
if (isBundle) {
|
||||
if (Array.isArray(response)) {
|
||||
onBundleUploaded(response)
|
||||
return
|
||||
}
|
||||
onFailed(t(($) => $[`${i18nPrefix}.uploadFailed`], { ns: 'plugin' }))
|
||||
return
|
||||
}
|
||||
|
||||
if (!isPackageUploadResponse(response)) {
|
||||
onFailed(t(($) => $[`${i18nPrefix}.uploadFailed`], { ns: 'plugin' }))
|
||||
return
|
||||
}
|
||||
|
||||
onPackageUploaded({
|
||||
uniqueIdentifier: response.unique_identifier,
|
||||
manifest: response.manifest,
|
||||
})
|
||||
},
|
||||
[isBundle, onBundleUploaded, onFailed, onPackageUploaded, t],
|
||||
)
|
||||
|
||||
const handleUpload = React.useCallback(async () => {
|
||||
try {
|
||||
handleUploadedResponse(await uploadFile(file, isBundle))
|
||||
} catch (error: unknown) {
|
||||
// Only server answers carry a user-facing message; transport errors use the localized fallback.
|
||||
const message = error instanceof ORPCError ? error.message : undefined
|
||||
if (message) {
|
||||
onFailed(message)
|
||||
return
|
||||
}
|
||||
onFailed(t(($) => $[`${i18nPrefix}.uploadFailed`], { ns: 'plugin' }))
|
||||
}
|
||||
}, [file, handleUploadedResponse, isBundle, onFailed, t])
|
||||
|
||||
React.useEffect(() => {
|
||||
handleUpload()
|
||||
}, [handleUpload])
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-col items-start justify-center gap-2 self-stretch px-6 py-3">
|
||||
<div className="flex items-center gap-1 self-stretch">
|
||||
<span className="i-ri-loader-2-line size-4 animate-spin-slow text-text-accent" />
|
||||
<div className="system-md-regular text-text-secondary">
|
||||
{t(($) => $[`${i18nPrefix}.uploadingPackage`], {
|
||||
ns: 'plugin',
|
||||
packageName: fileName,
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap content-start items-start gap-1 self-stretch rounded-2xl bg-background-section-burn p-2">
|
||||
<Card
|
||||
className="w-full"
|
||||
payload={{ name: fileName } as Plugin}
|
||||
isLoading
|
||||
loadingFileName={fileName}
|
||||
installed={false}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Action Buttons */}
|
||||
<div className="flex items-center justify-end gap-2 self-stretch p-6 pt-5">
|
||||
<Button variant="secondary" className="min-w-18" onClick={onCancel}>
|
||||
{t(($) => $['operation.cancel'], { ns: 'common' })}
|
||||
</Button>
|
||||
<Button variant="primary" className="min-w-18" disabled>
|
||||
{t(($) => $[`${i18nPrefix}.install`], { ns: 'plugin' })}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default React.memo(Uploading)
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
'use client'
|
||||
|
||||
import type { PluginCategoryEnum, PluginManifestInMarket } from '../types'
|
||||
import type { UseInstallFromMarketplaceQueryOptions } from './hooks/use-install-from-marketplace-query'
|
||||
import { useInstallFromMarketplaceQuery as useInstallFromMarketplaceQueryHook } from './hooks/use-install-from-marketplace-query'
|
||||
import InstallFromMarketplace from './install-from-marketplace'
|
||||
|
||||
type InstallFromMarketplaceQueryProps = UseInstallFromMarketplaceQueryOptions & {
|
||||
installContextCategory?: PluginCategoryEnum
|
||||
}
|
||||
|
||||
const InstallFromMarketplaceQuery = ({
|
||||
installContextCategory,
|
||||
...options
|
||||
}: InstallFromMarketplaceQueryProps) => {
|
||||
const {
|
||||
bundleInfo,
|
||||
dependencies,
|
||||
hideInstallFromMarketplace,
|
||||
isShowInstallFromMarketplace,
|
||||
marketplaceInstall,
|
||||
} = useInstallFromMarketplaceQueryHook(options)
|
||||
|
||||
if (!isShowInstallFromMarketplace) return null
|
||||
|
||||
if (!marketplaceInstall && !bundleInfo) return null
|
||||
|
||||
return (
|
||||
<InstallFromMarketplace
|
||||
manifest={marketplaceInstall?.manifest as PluginManifestInMarket}
|
||||
uniqueIdentifier={marketplaceInstall?.uniqueIdentifier ?? ''}
|
||||
isBundle={!!bundleInfo}
|
||||
dependencies={dependencies}
|
||||
installContextCategory={installContextCategory}
|
||||
onClose={hideInstallFromMarketplace}
|
||||
onSuccess={hideInstallFromMarketplace}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export default InstallFromMarketplaceQuery
|
||||
+400
@@ -0,0 +1,400 @@
|
||||
import type { PluginInstallTaskStartResponse } from '@dify/contracts/api/console/workspaces/types.gen'
|
||||
import type { ComponentProps } from 'react'
|
||||
import type { Dependency, Plugin, PluginManifestInMarket } from '../../../types'
|
||||
import type { ConsoleQueryTestOptions } from '@/test/console/query-data'
|
||||
import { act, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { renderWithConsoleQuery } from '@/test/console/query-data'
|
||||
import { createDeferred } from '@/test/deferred'
|
||||
import { createPluginDeclarationFixture, createPluginEntity } from '@/test/fixtures/plugin'
|
||||
import { PermissionType, PluginCategoryEnum, TaskStatus } from '../../../types'
|
||||
import InstallFromMarketplace from '../index'
|
||||
|
||||
const { install, upgrade, installedPlugins, declaration, pollTask, marketplace, refresh } =
|
||||
vi.hoisted(() => ({
|
||||
install: vi.fn(),
|
||||
upgrade: vi.fn(),
|
||||
installedPlugins: vi.fn(),
|
||||
declaration: vi.fn(),
|
||||
pollTask: vi.fn(),
|
||||
marketplace: vi.fn(),
|
||||
refresh: vi.fn(),
|
||||
}))
|
||||
vi.mock('@/service/base', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('@/service/base')>()),
|
||||
postMarketplace: marketplace,
|
||||
}))
|
||||
vi.mock('@/service/plugins', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('@/service/plugins')>()),
|
||||
checkTaskStatus: pollTask,
|
||||
}))
|
||||
vi.mock('@/service/console', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/service/console')>()
|
||||
const { withConsoleResponses, withConsoleClientResponses } =
|
||||
await import('@/test/console/service-responses')
|
||||
return {
|
||||
...actual,
|
||||
consoleClient: withConsoleClientResponses(actual.consoleClient, {
|
||||
'workspaces.current.plugin.permission.fetch.get': async () => ({
|
||||
install_permission: PermissionType.everyone,
|
||||
debug_permission: PermissionType.everyone,
|
||||
}),
|
||||
'workspaces.current.plugin.tasks.get': async () => ({ tasks: [] }),
|
||||
'workspaces.current.plugin.marketplace.pkg.get': declaration,
|
||||
'workspaces.current.plugin.install.marketplace.post': install,
|
||||
'workspaces.current.plugin.upgrade.marketplace.post': upgrade,
|
||||
}),
|
||||
consoleQuery: withConsoleResponses(actual.consoleQuery, {
|
||||
'workspaces.current.plugin.list.installations.ids.post': installedPlugins,
|
||||
}),
|
||||
}
|
||||
})
|
||||
// Catalog refresh is independently covered by use-refresh-plugin-list.
|
||||
vi.mock('../../hooks/use-refresh-plugin-list', () => ({
|
||||
default: () => ({ refreshPluginList: refresh }),
|
||||
}))
|
||||
|
||||
const createMockManifest = (
|
||||
overrides: Partial<PluginManifestInMarket> = {},
|
||||
): PluginManifestInMarket => ({
|
||||
plugin_unique_identifier: 'test-unique-identifier',
|
||||
name: 'test-plugin',
|
||||
org: 'test-org',
|
||||
icon: 'test-icon.png',
|
||||
label: { en_US: 'Test Plugin' } as PluginManifestInMarket['label'],
|
||||
category: PluginCategoryEnum.tool,
|
||||
version: '1.0.0',
|
||||
latest_version: '1.0.0',
|
||||
brief: { en_US: 'A test plugin' } as PluginManifestInMarket['brief'],
|
||||
introduction: 'Introduction text',
|
||||
verified: true,
|
||||
install_count: 100,
|
||||
badges: [],
|
||||
verification: { authorized_category: 'community' },
|
||||
from: 'marketplace',
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const createMockPlugin = (overrides: Partial<Plugin> = {}): Plugin => ({
|
||||
type: 'plugin',
|
||||
org: 'test-org',
|
||||
name: 'test-plugin',
|
||||
plugin_id: 'test-plugin-id',
|
||||
version: '1.0.0',
|
||||
latest_version: '1.0.0',
|
||||
latest_package_identifier: 'test-package-id',
|
||||
icon: 'test-icon.png',
|
||||
verified: true,
|
||||
label: { en_US: 'Test Plugin' },
|
||||
brief: { en_US: 'A test plugin' },
|
||||
description: { en_US: 'A test plugin description' },
|
||||
introduction: 'Introduction text',
|
||||
repository: 'https://github.com/test/plugin',
|
||||
category: PluginCategoryEnum.tool,
|
||||
install_count: 100,
|
||||
endpoint: { settings: [] },
|
||||
tags: [],
|
||||
badges: [],
|
||||
verification: { authorized_category: 'community' },
|
||||
from: 'marketplace',
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const renderInstaller = (
|
||||
props: Partial<ComponentProps<typeof InstallFromMarketplace>> = {},
|
||||
options: ConsoleQueryTestOptions = {},
|
||||
) => {
|
||||
const onClose = vi.fn()
|
||||
const onSuccess = vi.fn()
|
||||
const manifest = createMockManifest()
|
||||
const rendered = renderWithConsoleQuery(
|
||||
<InstallFromMarketplace
|
||||
uniqueIdentifier="test-unique-identifier"
|
||||
manifest={manifest}
|
||||
onClose={onClose}
|
||||
onSuccess={onSuccess}
|
||||
{...props}
|
||||
/>,
|
||||
{
|
||||
accountProfileMeta: { currentVersion: '1.0.0' },
|
||||
workspacePermissionKeys: ['plugin.install'],
|
||||
systemFeatures: {
|
||||
enable_marketplace: true,
|
||||
rbac_enabled: true,
|
||||
plugin_installation_permission: {
|
||||
plugin_installation_scope: 'all',
|
||||
restrict_to_marketplace_only: false,
|
||||
},
|
||||
},
|
||||
...options,
|
||||
},
|
||||
)
|
||||
return { ...rendered, onClose, onSuccess, manifest }
|
||||
}
|
||||
|
||||
const installButton = () => screen.getByRole('button', { name: 'plugin.installModal.install' })
|
||||
const successDialog = () =>
|
||||
screen.findByRole('dialog', { name: 'plugin.installModal.installedSuccessfully' })
|
||||
// The footer and the dialog dismiss button share a name; the footer is the visible text action.
|
||||
const closeResult = (user: ReturnType<typeof userEvent.setup>) =>
|
||||
user.click(screen.getByText('common.operation.close'))
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetAllMocks()
|
||||
install.mockResolvedValue({ all_installed: true, task_id: '' })
|
||||
upgrade.mockResolvedValue({ all_installed: true, task_id: '' })
|
||||
installedPlugins.mockResolvedValue({ plugins: [] })
|
||||
declaration.mockResolvedValue({ manifest: createPluginDeclarationFixture() })
|
||||
pollTask.mockResolvedValue({
|
||||
task: {
|
||||
plugins: [{ plugin_unique_identifier: 'test-unique-identifier', status: TaskStatus.success }],
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('installs the displayed version once while pending, refreshes the catalog and completes on close', async () => {
|
||||
const user = userEvent.setup()
|
||||
const pending = createDeferred<PluginInstallTaskStartResponse>()
|
||||
install.mockReturnValueOnce(pending.promise)
|
||||
const { onSuccess, onClose, manifest } = renderInstaller({
|
||||
uniqueIdentifier: 'selected-version-id',
|
||||
})
|
||||
expect(
|
||||
screen.getByRole('dialog', { name: 'plugin.installModal.installPlugin' }),
|
||||
).toBeInTheDocument()
|
||||
expect(screen.getByText('Test Plugin')).toBeInTheDocument()
|
||||
expect(screen.getByText('1.0.0')).toBeInTheDocument()
|
||||
|
||||
await user.click(installButton())
|
||||
const installing = await screen.findByRole('button', { name: 'plugin.installModal.installing' })
|
||||
expect(installing).toBeDisabled()
|
||||
expect(screen.queryByRole('button', { name: 'common.operation.cancel' })).not.toBeInTheDocument()
|
||||
await user.click(installing)
|
||||
expect(install).toHaveBeenCalledOnce()
|
||||
expect(onSuccess).not.toHaveBeenCalled()
|
||||
expect(refresh).not.toHaveBeenCalled()
|
||||
await act(async () => pending.resolve({ all_installed: true, task_id: '' }))
|
||||
await successDialog()
|
||||
|
||||
expect(install).toHaveBeenCalledExactlyOnceWith({
|
||||
body: { plugin_unique_identifiers: ['selected-version-id'] },
|
||||
})
|
||||
expect(upgrade).not.toHaveBeenCalled()
|
||||
expect(pollTask).not.toHaveBeenCalled()
|
||||
expect(refresh).toHaveBeenCalledExactlyOnceWith(manifest)
|
||||
expect(onSuccess).not.toHaveBeenCalled()
|
||||
expect(
|
||||
screen.queryByRole('button', { name: 'plugin.installModal.install' }),
|
||||
).not.toBeInTheDocument()
|
||||
await closeResult(user)
|
||||
expect(onSuccess).toHaveBeenCalledOnce()
|
||||
expect(onClose).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.each(['common.operation.cancel', 'common.operation.close'])(
|
||||
'dismisses before installation through %s',
|
||||
async (name) => {
|
||||
const user = userEvent.setup()
|
||||
const { onClose, onSuccess } = renderInstaller()
|
||||
await user.click(screen.getByRole('button', { name }))
|
||||
expect(onClose).toHaveBeenCalledOnce()
|
||||
expect(onSuccess).not.toHaveBeenCalled()
|
||||
expect(install).not.toHaveBeenCalled()
|
||||
},
|
||||
)
|
||||
|
||||
it('waits for a legacy task result without refreshing the catalog a second time', async () => {
|
||||
const user = userEvent.setup()
|
||||
const pending = createDeferred<{
|
||||
task: { plugins: { plugin_unique_identifier: string; status: TaskStatus }[] }
|
||||
}>()
|
||||
install.mockResolvedValueOnce({ all_installed: false, task_id: 'task-123' })
|
||||
pollTask.mockReturnValueOnce(pending.promise)
|
||||
renderInstaller()
|
||||
await user.click(installButton())
|
||||
await waitFor(() => expect(pollTask).toHaveBeenCalledExactlyOnceWith('task-123'))
|
||||
expect(
|
||||
screen.queryByRole('dialog', { name: 'plugin.installModal.installedSuccessfully' }),
|
||||
).not.toBeInTheDocument()
|
||||
await act(async () =>
|
||||
pending.resolve({
|
||||
task: {
|
||||
plugins: [
|
||||
{ plugin_unique_identifier: 'test-unique-identifier', status: TaskStatus.success },
|
||||
],
|
||||
},
|
||||
}),
|
||||
)
|
||||
await successDialog()
|
||||
expect(refresh).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('hands a started task to the task list and closes without claiming installation succeeded', async () => {
|
||||
const user = userEvent.setup()
|
||||
const task: NonNullable<PluginInstallTaskStartResponse['task']> = {
|
||||
id: 'task-123',
|
||||
created_at: '2026-06-05T03:34:59Z',
|
||||
updated_at: '2026-06-05T03:34:59Z',
|
||||
status: TaskStatus.running,
|
||||
total_plugins: 1,
|
||||
completed_plugins: 0,
|
||||
plugins: [
|
||||
{
|
||||
plugin_unique_identifier: 'test-unique-identifier',
|
||||
plugin_id: 'test-plugin-id',
|
||||
source: 'marketplace',
|
||||
status: TaskStatus.pending,
|
||||
message: '',
|
||||
icon: 'test-icon.png',
|
||||
labels: { en_US: 'Test Plugin' },
|
||||
},
|
||||
],
|
||||
}
|
||||
install.mockResolvedValueOnce({ all_installed: false, task_id: task.id, task })
|
||||
const { onClose, onSuccess, queryClient } = renderInstaller()
|
||||
await user.click(installButton())
|
||||
await waitFor(() => expect(onClose).toHaveBeenCalledOnce())
|
||||
expect(queryClient.getQueryData(['plugins', 'pluginTaskList'])).toEqual({
|
||||
tasks: [expect.objectContaining({ id: task.id, status: TaskStatus.running })],
|
||||
})
|
||||
expect(pollTask).not.toHaveBeenCalled()
|
||||
expect(onSuccess).not.toHaveBeenCalled()
|
||||
expect(refresh).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('shows a failed task message and allows closing the result', async () => {
|
||||
const user = userEvent.setup()
|
||||
install.mockResolvedValueOnce({ all_installed: false, task_id: 'failed-task' })
|
||||
pollTask.mockResolvedValueOnce({
|
||||
task: {
|
||||
plugins: [
|
||||
{
|
||||
plugin_unique_identifier: 'test-unique-identifier',
|
||||
status: TaskStatus.failed,
|
||||
message: 'Package verification failed',
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
const { onSuccess } = renderInstaller()
|
||||
await user.click(installButton())
|
||||
await screen.findByRole('dialog', { name: 'plugin.installModal.installFailed' })
|
||||
expect(screen.getByText('Package verification failed')).toBeInTheDocument()
|
||||
expect(refresh).not.toHaveBeenCalled()
|
||||
await closeResult(user)
|
||||
expect(onSuccess).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it.each([
|
||||
['Request rejected', 'Request rejected'],
|
||||
[new Error('Request rejected'), 'plugin.installModal.installFailedDesc'],
|
||||
])('shows an installation request failure: %s', async (error, message) => {
|
||||
const user = userEvent.setup()
|
||||
install.mockRejectedValueOnce(error)
|
||||
renderInstaller()
|
||||
await user.click(installButton())
|
||||
await screen.findByRole('dialog', { name: 'plugin.installModal.installFailed' })
|
||||
expect(screen.getByText(message)).toBeInTheDocument()
|
||||
expect(refresh).not.toHaveBeenCalled()
|
||||
expect(pollTask).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('waits for installed-version lookup, then upgrades the existing plugin', async () => {
|
||||
const user = userEvent.setup()
|
||||
const pending = createDeferred<{ plugins: ReturnType<typeof createPluginEntity>[] }>()
|
||||
installedPlugins.mockReturnValueOnce(pending.promise)
|
||||
renderInstaller({ manifest: createMockPlugin() })
|
||||
expect(installButton()).toBeDisabled()
|
||||
await user.click(installButton())
|
||||
expect(install).not.toHaveBeenCalled()
|
||||
const existingPlugin = createPluginEntity({
|
||||
plugin_id: 'test-plugin-id',
|
||||
plugin_unique_identifier: 'previous-version-id',
|
||||
})
|
||||
existingPlugin.declaration.version = '0.9.0'
|
||||
await act(async () => pending.resolve({ plugins: [existingPlugin] }))
|
||||
await waitFor(() => expect(installButton()).toBeEnabled())
|
||||
expect(screen.getByText('0.9.0 -> 1.0.0')).toBeInTheDocument()
|
||||
await user.click(installButton())
|
||||
await successDialog()
|
||||
expect(upgrade).toHaveBeenCalledExactlyOnceWith({
|
||||
body: {
|
||||
original_plugin_unique_identifier: 'previous-version-id',
|
||||
new_plugin_unique_identifier: 'test-unique-identifier',
|
||||
},
|
||||
})
|
||||
expect(install).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('recognizes an already installed package without submitting it again', async () => {
|
||||
installedPlugins.mockResolvedValueOnce({
|
||||
plugins: [
|
||||
createPluginEntity({
|
||||
plugin_id: 'test-plugin-id',
|
||||
plugin_unique_identifier: 'test-unique-identifier',
|
||||
}),
|
||||
],
|
||||
})
|
||||
renderInstaller({ manifest: createMockPlugin() })
|
||||
await successDialog()
|
||||
expect(install).not.toHaveBeenCalled()
|
||||
expect(upgrade).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('blocks installation when the workspace scope disallows the plugin', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderInstaller(
|
||||
{},
|
||||
{ systemFeatures: { plugin_installation_permission: { plugin_installation_scope: 'none' } } },
|
||||
)
|
||||
expect(installButton()).toBeDisabled()
|
||||
await user.click(installButton())
|
||||
expect(install).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.each([
|
||||
['2.0.0', true],
|
||||
['0.9.0', false],
|
||||
])('compares Dify 1.0.0 against the minimum version %s', async (minimumVersion, warns) => {
|
||||
const response = {
|
||||
manifest: createPluginDeclarationFixture({
|
||||
meta: { version: '1.0.0', minimum_dify_version: minimumVersion },
|
||||
}),
|
||||
}
|
||||
declaration.mockResolvedValueOnce(response)
|
||||
const { queryClient } = renderInstaller()
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
queryClient.getQueryData(['plugins', 'pluginDeclaration', 'test-unique-identifier']),
|
||||
).toEqual(response),
|
||||
)
|
||||
if (warns) expect(await screen.findByText(/plugin.difyVersionNotCompatible/)).toBeInTheDocument()
|
||||
else expect(screen.queryByText(/plugin.difyVersionNotCompatible/)).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('installs marketplace bundle dependencies through the real bundle flow', async () => {
|
||||
const user = userEvent.setup()
|
||||
const plugin = createMockPlugin({
|
||||
name: 'bundle-plugin',
|
||||
plugin_id: 'test-org/bundle-plugin',
|
||||
latest_package_identifier: 'test-org/bundle-plugin:1.0.0',
|
||||
})
|
||||
const dependencies: Dependency[] = [
|
||||
{
|
||||
type: 'marketplace',
|
||||
value: { marketplace_plugin_unique_identifier: plugin.latest_package_identifier },
|
||||
},
|
||||
]
|
||||
marketplace.mockResolvedValueOnce({ data: { list: [{ plugin }] } })
|
||||
const { onClose, onSuccess } = renderInstaller({ isBundle: true, dependencies })
|
||||
await waitFor(() => expect(installButton()).toBeEnabled())
|
||||
await user.click(installButton())
|
||||
await successDialog()
|
||||
expect(install).toHaveBeenCalledExactlyOnceWith({
|
||||
body: { plugin_unique_identifiers: [plugin.latest_package_identifier] },
|
||||
})
|
||||
expect(refresh).toHaveBeenCalledWith(undefined, true)
|
||||
await closeResult(user)
|
||||
expect(onClose).toHaveBeenCalledOnce()
|
||||
expect(onSuccess).not.toHaveBeenCalled()
|
||||
})
|
||||
+146
@@ -0,0 +1,146 @@
|
||||
'use client'
|
||||
import type { Dependency, Plugin, PluginCategoryEnum, PluginManifestInMarket } from '../../types'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { Dialog, DialogClose, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
|
||||
import { IconButton } from '@langgenius/dify-ui/icon-button'
|
||||
import * as React from 'react'
|
||||
import { useCallback, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { InstallStep } from '../../types'
|
||||
import Installed from '../base/installed'
|
||||
import useHideLogic from '../hooks/use-hide-logic'
|
||||
import useRefreshPluginList from '../hooks/use-refresh-plugin-list'
|
||||
import ReadyToInstallBundle from '../install-bundle/ready-to-install'
|
||||
import Install from './steps/install'
|
||||
|
||||
const i18nPrefix = 'installModal'
|
||||
|
||||
type InstallFromMarketplaceProps = {
|
||||
uniqueIdentifier: string
|
||||
manifest: PluginManifestInMarket | Plugin
|
||||
isBundle?: boolean
|
||||
dependencies?: Dependency[]
|
||||
installContextCategory?: PluginCategoryEnum
|
||||
onSuccess: () => void
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
const InstallFromMarketplace: React.FC<InstallFromMarketplaceProps> = ({
|
||||
uniqueIdentifier,
|
||||
manifest,
|
||||
isBundle,
|
||||
dependencies,
|
||||
installContextCategory,
|
||||
onSuccess,
|
||||
onClose,
|
||||
}) => {
|
||||
const { t } = useTranslation(['common', 'plugin'])
|
||||
// readyToInstall -> check installed -> installed/failed
|
||||
const [step, setStep] = useState<InstallStep>(InstallStep.readyToInstall)
|
||||
const [errorMsg, setErrorMsg] = useState<string | null>(null)
|
||||
const { refreshPluginList } = useRefreshPluginList()
|
||||
|
||||
const {
|
||||
modalClassName,
|
||||
foldAnimInto,
|
||||
foldIntoTaskTrigger,
|
||||
setIsInstalling,
|
||||
handleStartToInstall,
|
||||
} = useHideLogic(onClose)
|
||||
|
||||
const getTitle = useCallback(() => {
|
||||
if (isBundle && step === InstallStep.installed)
|
||||
return t(($) => $[`${i18nPrefix}.installedSuccessfully`], { ns: 'plugin' })
|
||||
if (step === InstallStep.installed)
|
||||
return t(($) => $[`${i18nPrefix}.installedSuccessfully`], { ns: 'plugin' })
|
||||
if (step === InstallStep.installFailed)
|
||||
return t(($) => $[`${i18nPrefix}.installFailed`], { ns: 'plugin' })
|
||||
return t(($) => $[`${i18nPrefix}.installPlugin`], { ns: 'plugin' })
|
||||
}, [isBundle, step, t])
|
||||
|
||||
const handleInstalled = useCallback(
|
||||
(notRefresh?: boolean) => {
|
||||
setStep(InstallStep.installed)
|
||||
if (!notRefresh) refreshPluginList(manifest)
|
||||
setIsInstalling(false)
|
||||
},
|
||||
[manifest, refreshPluginList, setIsInstalling],
|
||||
)
|
||||
|
||||
const handleFailed = useCallback(
|
||||
(errorMsg?: string) => {
|
||||
setStep(InstallStep.installFailed)
|
||||
setIsInstalling(false)
|
||||
if (errorMsg) setErrorMsg(errorMsg)
|
||||
},
|
||||
[setIsInstalling],
|
||||
)
|
||||
|
||||
const completedSteps: InstallStep[] = [InstallStep.installed, InstallStep.installFailed]
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
onOpenChange={(open) => {
|
||||
if (!open) foldAnimInto()
|
||||
}}
|
||||
>
|
||||
<DialogContent
|
||||
backdropProps={{ forceRender: true }}
|
||||
className={cn('max-h-[calc(100dvh-48px)] w-140', modalClassName)}
|
||||
>
|
||||
<div className="flex shrink-0 items-start gap-2 self-stretch pt-6 pr-14 pb-3 pl-6">
|
||||
<DialogTitle>{getTitle()}</DialogTitle>
|
||||
</div>
|
||||
{isBundle ? (
|
||||
<ReadyToInstallBundle
|
||||
step={step}
|
||||
onStepChange={setStep}
|
||||
onStartToInstall={handleStartToInstall}
|
||||
setIsInstalling={setIsInstalling}
|
||||
onClose={onClose}
|
||||
allPlugins={dependencies!}
|
||||
isFromMarketPlace
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
{step === InstallStep.readyToInstall && (
|
||||
<Install
|
||||
uniqueIdentifier={uniqueIdentifier}
|
||||
payload={manifest!}
|
||||
onCancel={onClose}
|
||||
onInstalled={handleInstalled}
|
||||
onFailed={handleFailed}
|
||||
onStartToInstall={handleStartToInstall}
|
||||
onTaskStarted={foldIntoTaskTrigger}
|
||||
/>
|
||||
)}
|
||||
{completedSteps.includes(step) && (
|
||||
<Installed
|
||||
payload={manifest!}
|
||||
isMarketPayload
|
||||
isFailed={step === InstallStep.installFailed}
|
||||
errMsg={errorMsg}
|
||||
installContextCategory={installContextCategory}
|
||||
onCancel={onSuccess}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<DialogClose
|
||||
render={
|
||||
<IconButton
|
||||
aria-label={t(($) => $['operation.close'], { ns: 'common' })}
|
||||
size="lg"
|
||||
className="absolute inset-e-6 top-6"
|
||||
>
|
||||
<span aria-hidden className="i-ri-close-line size-4" />
|
||||
</IconButton>
|
||||
}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
export default InstallFromMarketplace
|
||||
+203
@@ -0,0 +1,203 @@
|
||||
'use client'
|
||||
import type { PluginInstallTaskStartResponse } from '@dify/contracts/api/console/workspaces/types.gen'
|
||||
import type { FC } from 'react'
|
||||
import type { Plugin, PluginManifestInMarket } from '../../../types'
|
||||
import { Button } from '@langgenius/dify-ui/button'
|
||||
import { RiLoader2Line } from '@remixicon/react'
|
||||
import { useSuspenseQuery } from '@tanstack/react-query'
|
||||
import * as React from 'react'
|
||||
import { useEffect, useMemo } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import useCheckInstalled from '@/app/components/plugins/install-plugin/hooks/use-check-installed'
|
||||
import { userProfileQueryOptions } from '@/features/account-profile/client'
|
||||
import {
|
||||
useInstallPackageFromMarketPlace,
|
||||
usePluginDeclarationFromMarketPlace,
|
||||
usePluginTaskList,
|
||||
useUpdatePackageFromMarketPlace,
|
||||
} from '@/service/use-plugins'
|
||||
import { isEqualOrLaterThanVersion } from '@/utils/semver'
|
||||
import Card from '../../../card'
|
||||
// import { RiInformation2Line } from '@remixicon/react'
|
||||
import { TaskStatus } from '../../../types'
|
||||
import checkTaskStatus from '../../base/check-task-status'
|
||||
import Version from '../../base/version'
|
||||
import useInstallPluginLimit from '../../hooks/use-install-plugin-limit'
|
||||
import { pluginManifestInMarketToPluginProps } from '../../utils'
|
||||
|
||||
const i18nPrefix = 'installModal'
|
||||
|
||||
type Props = Readonly<{
|
||||
uniqueIdentifier: string
|
||||
payload: PluginManifestInMarket | Plugin
|
||||
onCancel: () => void
|
||||
onStartToInstall?: () => void
|
||||
onTaskStarted: () => void
|
||||
onInstalled: (notRefresh?: boolean) => void
|
||||
onFailed: (message?: string) => void
|
||||
}>
|
||||
|
||||
const Installed: FC<Props> = ({
|
||||
uniqueIdentifier,
|
||||
payload,
|
||||
onCancel,
|
||||
onStartToInstall,
|
||||
onTaskStarted,
|
||||
onInstalled,
|
||||
onFailed,
|
||||
}) => {
|
||||
const { t } = useTranslation(['common', 'plugin'])
|
||||
const toInstallVersion = payload.version || payload.latest_version
|
||||
const pluginId = (payload as Plugin).plugin_id
|
||||
const { installedInfo, isLoading } = useCheckInstalled({
|
||||
pluginIds: [pluginId],
|
||||
enabled: !!pluginId,
|
||||
})
|
||||
const installedInfoPayload = installedInfo?.[pluginId]
|
||||
const installedVersion = installedInfoPayload?.installedVersion
|
||||
const hasInstalled = !!installedVersion
|
||||
|
||||
const { mutateAsync: installPackageFromMarketPlace } = useInstallPackageFromMarketPlace()
|
||||
const { mutateAsync: updatePackageFromMarketPlace } = useUpdatePackageFromMarketPlace()
|
||||
const [isInstalling, setIsInstalling] = React.useState(false)
|
||||
const { check, stop } = checkTaskStatus()
|
||||
const { handleInstallTaskStart } = usePluginTaskList(payload.category)
|
||||
|
||||
useEffect(() => {
|
||||
if (hasInstalled && uniqueIdentifier === installedInfoPayload.uniqueIdentifier) onInstalled()
|
||||
}, [hasInstalled])
|
||||
|
||||
const handleCancel = () => {
|
||||
stop()
|
||||
onCancel()
|
||||
}
|
||||
|
||||
const handleInstall = async () => {
|
||||
if (isInstalling) return
|
||||
onStartToInstall?.()
|
||||
setIsInstalling(true)
|
||||
try {
|
||||
let taskId
|
||||
let isInstalled
|
||||
let installResponse: PluginInstallTaskStartResponse | undefined
|
||||
if (hasInstalled) {
|
||||
const response = await updatePackageFromMarketPlace({
|
||||
original_plugin_unique_identifier: installedInfoPayload.uniqueIdentifier,
|
||||
new_plugin_unique_identifier: uniqueIdentifier,
|
||||
})
|
||||
installResponse = response
|
||||
const { all_installed, task_id } = response
|
||||
handleInstallTaskStart(response)
|
||||
taskId = task_id
|
||||
isInstalled = all_installed
|
||||
} else {
|
||||
const response = await installPackageFromMarketPlace(uniqueIdentifier)
|
||||
installResponse = response
|
||||
const { all_installed, task_id } = response
|
||||
handleInstallTaskStart(response)
|
||||
taskId = task_id
|
||||
isInstalled = all_installed
|
||||
}
|
||||
|
||||
if (isInstalled) {
|
||||
onInstalled()
|
||||
return
|
||||
}
|
||||
|
||||
if (installResponse?.task) {
|
||||
onTaskStarted()
|
||||
return
|
||||
}
|
||||
|
||||
const { status, error } = await check({
|
||||
taskId,
|
||||
pluginUniqueIdentifier: uniqueIdentifier,
|
||||
})
|
||||
if (status === TaskStatus.failed) {
|
||||
onFailed(error)
|
||||
return
|
||||
}
|
||||
onInstalled(true)
|
||||
} catch (e) {
|
||||
if (typeof e === 'string') {
|
||||
onFailed(e)
|
||||
return
|
||||
}
|
||||
onFailed()
|
||||
}
|
||||
}
|
||||
|
||||
const { data: currentVersion } = useSuspenseQuery({
|
||||
...userProfileQueryOptions(),
|
||||
select: (data) => data.meta.currentVersion ?? '',
|
||||
})
|
||||
const { data: pluginDeclaration } = usePluginDeclarationFromMarketPlace(uniqueIdentifier)
|
||||
const isDifyVersionCompatible = useMemo(() => {
|
||||
if (!pluginDeclaration || !currentVersion) return true
|
||||
return isEqualOrLaterThanVersion(
|
||||
currentVersion,
|
||||
pluginDeclaration?.manifest.meta.minimum_dify_version ?? '0.0.0',
|
||||
)
|
||||
}, [currentVersion, pluginDeclaration])
|
||||
|
||||
const { canInstall } = useInstallPluginLimit({
|
||||
...payload,
|
||||
from: 'marketplace',
|
||||
})
|
||||
return (
|
||||
<>
|
||||
<div className="flex flex-col items-start justify-center gap-4 self-stretch px-6 py-3">
|
||||
<div className="system-md-regular text-text-secondary">
|
||||
<p>{t(($) => $[`${i18nPrefix}.readyToInstall`], { ns: 'plugin' })}</p>
|
||||
{!isDifyVersionCompatible && (
|
||||
<p className="system-md-regular text-text-warning">
|
||||
{t(($) => $.difyVersionNotCompatible, {
|
||||
ns: 'plugin',
|
||||
minimalDifyVersion:
|
||||
pluginDeclaration?.manifest.meta.minimum_dify_version ?? '0.0.0',
|
||||
})}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex flex-wrap content-start items-start gap-1 self-stretch rounded-2xl bg-background-section-burn p-2">
|
||||
<Card
|
||||
className="w-full"
|
||||
payload={pluginManifestInMarketToPluginProps(payload as PluginManifestInMarket)}
|
||||
titleLeft={
|
||||
!isLoading && (
|
||||
<Version
|
||||
hasInstalled={hasInstalled}
|
||||
installedVersion={installedVersion}
|
||||
toInstallVersion={toInstallVersion}
|
||||
/>
|
||||
)
|
||||
}
|
||||
limitedInstall={!canInstall}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{/* Action Buttons */}
|
||||
<div className="flex items-center justify-end gap-2 self-stretch p-6 pt-5">
|
||||
{!isInstalling && (
|
||||
<Button variant="secondary" className="min-w-18" onClick={handleCancel}>
|
||||
{t(($) => $['operation.cancel'], { ns: 'common' })}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="primary"
|
||||
className="flex min-w-18"
|
||||
disabled={isInstalling || isLoading || !canInstall}
|
||||
onClick={handleInstall}
|
||||
>
|
||||
{isInstalling && <RiLoader2Line className="size-4 animate-spin-slow" />}
|
||||
<span>
|
||||
{t(($) => $[`${i18nPrefix}.${isInstalling ? 'installing' : 'install'}`], {
|
||||
ns: 'plugin',
|
||||
})}
|
||||
</span>
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
export default React.memo(Installed)
|
||||
@@ -0,0 +1,119 @@
|
||||
import type {
|
||||
I18nObject,
|
||||
PluginDeclarationResponse,
|
||||
} from '@dify/contracts/api/console/workspaces/types.gen'
|
||||
import type { GitHubUrlInfo, Plugin, PluginDeclaration, PluginManifestInMarket } from '../types'
|
||||
import { isEmpty } from 'es-toolkit/compat'
|
||||
|
||||
export const pluginManifestToCardPluginProps = (pluginManifest: PluginDeclaration): Plugin => {
|
||||
return {
|
||||
plugin_id: pluginManifest.plugin_unique_identifier,
|
||||
type: pluginManifest.category as Plugin['type'],
|
||||
category: pluginManifest.category,
|
||||
name: pluginManifest.name,
|
||||
version: pluginManifest.version,
|
||||
latest_version: '',
|
||||
latest_package_identifier: '',
|
||||
org: pluginManifest.author,
|
||||
author: pluginManifest.author,
|
||||
label: pluginManifest.label,
|
||||
brief: pluginManifest.description,
|
||||
description: pluginManifest.description,
|
||||
icon: pluginManifest.icon,
|
||||
icon_dark: pluginManifest.icon_dark,
|
||||
verified: pluginManifest.verified,
|
||||
introduction: '',
|
||||
repository: '',
|
||||
install_count: 0,
|
||||
endpoint: {
|
||||
settings: [],
|
||||
},
|
||||
tags: pluginManifest.tags.map((tag) => ({ name: tag })),
|
||||
badges: [],
|
||||
verification: { authorized_category: 'langgenius' },
|
||||
from: 'package',
|
||||
}
|
||||
}
|
||||
|
||||
/** Plugin card text from a translated object; untranslated locales are left out. */
|
||||
export const toPluginText = ({ en_US, zh_Hans, ja_JP, pt_BR }: I18nObject): Plugin['label'] => ({
|
||||
en_US,
|
||||
...(zh_Hans != null && { zh_Hans }),
|
||||
...(ja_JP != null && { ja_JP }),
|
||||
...(pt_BR != null && { pt_BR }),
|
||||
})
|
||||
|
||||
/** Card props for the manifest of a package the console has just uploaded. */
|
||||
export const pluginDeclarationToCardPluginProps = (
|
||||
manifest: PluginDeclarationResponse,
|
||||
uniqueIdentifier: string,
|
||||
): Plugin => ({
|
||||
plugin_id: uniqueIdentifier,
|
||||
type: manifest.category === 'agent-strategy' ? 'agent_strategy' : manifest.category,
|
||||
category: manifest.category,
|
||||
name: manifest.name,
|
||||
version: manifest.version,
|
||||
latest_version: '',
|
||||
latest_package_identifier: '',
|
||||
// A manifest without an author shows no organization.
|
||||
org: manifest.author ?? '',
|
||||
author: manifest.author ?? undefined,
|
||||
label: toPluginText(manifest.label),
|
||||
brief: toPluginText(manifest.description),
|
||||
description: toPluginText(manifest.description),
|
||||
icon: manifest.icon,
|
||||
icon_dark: manifest.icon_dark ?? undefined,
|
||||
verified: manifest.verified ?? false,
|
||||
introduction: '',
|
||||
repository: '',
|
||||
install_count: 0,
|
||||
endpoint: {
|
||||
settings: [],
|
||||
},
|
||||
tags: (manifest.tags ?? []).map((tag) => ({ name: tag })),
|
||||
badges: [],
|
||||
verification: { authorized_category: 'langgenius' },
|
||||
from: 'package',
|
||||
})
|
||||
|
||||
export const pluginManifestInMarketToPluginProps = (
|
||||
pluginManifest: PluginManifestInMarket,
|
||||
): Plugin => {
|
||||
return {
|
||||
plugin_id: pluginManifest.plugin_unique_identifier,
|
||||
type: pluginManifest.category as Plugin['type'],
|
||||
category: pluginManifest.category,
|
||||
name: pluginManifest.name,
|
||||
version: pluginManifest.latest_version,
|
||||
latest_version: pluginManifest.latest_version,
|
||||
latest_package_identifier: '',
|
||||
org: pluginManifest.org,
|
||||
label: pluginManifest.label,
|
||||
brief: pluginManifest.brief,
|
||||
description: pluginManifest.brief,
|
||||
icon: pluginManifest.icon,
|
||||
verified: true,
|
||||
introduction: pluginManifest.introduction,
|
||||
repository: '',
|
||||
install_count: 0,
|
||||
endpoint: {
|
||||
settings: [],
|
||||
},
|
||||
tags: [],
|
||||
badges: pluginManifest.badges,
|
||||
verification: isEmpty(pluginManifest.verification)
|
||||
? { authorized_category: 'langgenius' }
|
||||
: pluginManifest.verification,
|
||||
from: pluginManifest.from,
|
||||
}
|
||||
}
|
||||
|
||||
export const parseGitHubUrl = (url: string): GitHubUrlInfo => {
|
||||
const githubUrlRegex = /^https:\/\/github\.com\/([^/]+)\/([^/]+)\/?$/
|
||||
const match = githubUrlRegex.exec(url)
|
||||
return match ? { isValid: true, owner: match[1], repo: match[2] } : { isValid: false }
|
||||
}
|
||||
|
||||
export const convertRepoToUrl = (repo: string) => {
|
||||
return repo ? `https://github.com/${repo}` : ''
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import { act, renderHook, waitFor } from '@testing-library/react'
|
||||
import { Provider as JotaiProvider } from 'jotai'
|
||||
import { createNuqsTestWrapper } from '@/test/nuqs-testing'
|
||||
import {
|
||||
useMarketplaceMoreClick,
|
||||
useMarketplaceSearchMode,
|
||||
useMarketplaceSort,
|
||||
useMarketplaceSortValue,
|
||||
useSearchPluginText,
|
||||
} from '../atoms'
|
||||
import { DEFAULT_SORT } from '../constants'
|
||||
|
||||
const createWrapper = (searchParams = '') => {
|
||||
const { wrapper: NuqsWrapper, onUrlUpdate } = createNuqsTestWrapper({ searchParams })
|
||||
const wrapper = ({ children }: { children: ReactNode }) => (
|
||||
<JotaiProvider>
|
||||
<NuqsWrapper>{children}</NuqsWrapper>
|
||||
</JotaiProvider>
|
||||
)
|
||||
return { wrapper, onUrlUpdate }
|
||||
}
|
||||
|
||||
it.each([
|
||||
['?category=all', false],
|
||||
['?q=test&category=all', true],
|
||||
['?tags=search&category=all', true],
|
||||
['?category=model', true],
|
||||
['?category=tool', false],
|
||||
] as const)('derives search mode from %s', (params, expected) => {
|
||||
const { wrapper } = createWrapper(params)
|
||||
const { result } = renderHook(() => useMarketplaceSearchMode(), { wrapper })
|
||||
expect(result.current).toBe(expected)
|
||||
})
|
||||
|
||||
it('uses the debounced query override before switching from collections to search', () => {
|
||||
const { wrapper } = createWrapper('?q=typing&category=tool')
|
||||
const { result, rerender } = renderHook(
|
||||
({ query }) => useMarketplaceSearchMode(undefined, query),
|
||||
{
|
||||
wrapper,
|
||||
initialProps: { query: '' },
|
||||
},
|
||||
)
|
||||
expect(result.current).toBe(false)
|
||||
rerender({ query: 'typing' })
|
||||
expect(result.current).toBe(true)
|
||||
})
|
||||
|
||||
it('applies a collection query and sort while preserving unrelated URL filters', async () => {
|
||||
const { wrapper, onUrlUpdate } = createWrapper('?category=tool&tags=search')
|
||||
const { result } = renderHook(
|
||||
() => ({
|
||||
more: useMarketplaceMoreClick(),
|
||||
sort: useMarketplaceSortValue(),
|
||||
query: useSearchPluginText()[0],
|
||||
}),
|
||||
{ wrapper },
|
||||
)
|
||||
await act(async () => {
|
||||
result.current.more({ query: 'collection search', sort_by: 'created_at', sort_order: 'ASC' })
|
||||
})
|
||||
expect(result.current.sort).toEqual({ sortBy: 'created_at', sortOrder: 'ASC' })
|
||||
expect(result.current.query).toBe('collection search')
|
||||
await waitFor(() => expect(onUrlUpdate).toHaveBeenCalled())
|
||||
const params = onUrlUpdate.mock.lastCall![0].searchParams
|
||||
expect(params.get('q')).toBe('collection search')
|
||||
expect(params.get('category')).toBe('tool')
|
||||
expect(params.get('tags')).toBe('search')
|
||||
})
|
||||
|
||||
it('clears the previous query and sort but keeps search active for an unfiltered collection', async () => {
|
||||
const { wrapper, onUrlUpdate } = createWrapper('?q=previous&category=tool')
|
||||
const { result } = renderHook(
|
||||
() => ({
|
||||
more: useMarketplaceMoreClick(),
|
||||
sort: useMarketplaceSort(),
|
||||
query: useSearchPluginText()[0],
|
||||
searchMode: useMarketplaceSearchMode(),
|
||||
}),
|
||||
{ wrapper },
|
||||
)
|
||||
act(() => result.current.sort[1]({ sortBy: 'created_at', sortOrder: 'ASC' }))
|
||||
await act(async () => result.current.more({}))
|
||||
expect(result.current.sort[0]).toEqual(DEFAULT_SORT)
|
||||
expect(result.current.query).toBe('')
|
||||
expect(result.current.searchMode).toBe(true)
|
||||
await waitFor(() => expect(onUrlUpdate).toHaveBeenCalled())
|
||||
expect(onUrlUpdate.mock.lastCall![0].searchParams.has('q')).toBe(false)
|
||||
})
|
||||
@@ -0,0 +1,155 @@
|
||||
import type { PluginBanner } from '@dify/contracts/marketplace'
|
||||
import type { ReactNode } from 'react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
|
||||
|
||||
const mockFetchPluginBanners = vi.fn()
|
||||
|
||||
vi.mock('#i18n', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('#i18n')>()),
|
||||
useLocale: () => 'zh-Hans',
|
||||
}))
|
||||
|
||||
vi.mock('../home/banners', async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import('../home/banners')>()
|
||||
|
||||
return {
|
||||
...original,
|
||||
fetchPluginBanners: (...args: unknown[]) => mockFetchPluginBanners(...args),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../view', () => ({
|
||||
MarketplaceView: ({
|
||||
banners,
|
||||
showInstallButton,
|
||||
}: {
|
||||
banners: PluginBanner[]
|
||||
showInstallButton: boolean
|
||||
}) => (
|
||||
<div>
|
||||
<p>Trending banners: {banners.length}</p>
|
||||
<p>{showInstallButton ? 'Install enabled' : 'Install disabled'}</p>
|
||||
</div>
|
||||
),
|
||||
}))
|
||||
|
||||
let queryClient: QueryClient
|
||||
|
||||
function Wrapper({ children }: { children: ReactNode }) {
|
||||
return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
}
|
||||
|
||||
describe('EmbeddedMarketplace', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
retry: false,
|
||||
gcTime: 0,
|
||||
},
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('loads homepage banners on the client for the active locale', async () => {
|
||||
mockFetchPluginBanners.mockResolvedValue([
|
||||
{
|
||||
id: 'banner-1',
|
||||
title: 'Trending',
|
||||
sort: 1,
|
||||
language: 'zh-Hans',
|
||||
style_type: 'blog',
|
||||
content: {
|
||||
blog_title: 'Dify update',
|
||||
link: 'https://dify.ai/blog',
|
||||
link_target_type: 'blog',
|
||||
},
|
||||
},
|
||||
] satisfies PluginBanner[])
|
||||
|
||||
const { EmbeddedMarketplace } = await import('../embedded')
|
||||
|
||||
render(<EmbeddedMarketplace showInstallButton variant="home" />, { wrapper: Wrapper })
|
||||
|
||||
expect(await screen.findByText('Trending banners: 1')).toBeInTheDocument()
|
||||
expect(screen.getByText('Install enabled')).toBeInTheDocument()
|
||||
expect(mockFetchPluginBanners).toHaveBeenCalledWith('zh-Hans')
|
||||
})
|
||||
|
||||
it('uses server-rendered homepage banners without requesting them again on hydration', async () => {
|
||||
const initialBanners = [
|
||||
{
|
||||
id: 'banner-1',
|
||||
title: 'Trending',
|
||||
sort: 1,
|
||||
language: 'zh-Hans',
|
||||
style_type: 'blog',
|
||||
content: {
|
||||
blog_title: 'Dify update',
|
||||
link: 'https://dify.ai/blog',
|
||||
link_target_type: 'blog',
|
||||
},
|
||||
},
|
||||
] satisfies PluginBanner[]
|
||||
|
||||
const { EmbeddedMarketplace } = await import('../embedded')
|
||||
|
||||
render(
|
||||
<EmbeddedMarketplace
|
||||
initialBanners={initialBanners}
|
||||
initialLocale="zh-Hans"
|
||||
showInstallButton
|
||||
variant="home"
|
||||
/>,
|
||||
{ wrapper: Wrapper },
|
||||
)
|
||||
|
||||
expect(screen.getByText('Trending banners: 1')).toBeInTheDocument()
|
||||
expect(mockFetchPluginBanners).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('refetches banners when the client locale differs from the server-rendered locale', async () => {
|
||||
const initialBanners = [
|
||||
{
|
||||
id: 'banner-en',
|
||||
title: 'Trending',
|
||||
sort: 1,
|
||||
language: 'en-US',
|
||||
style_type: 'blog',
|
||||
content: {
|
||||
blog_title: 'Dify update',
|
||||
link: 'https://dify.ai/blog',
|
||||
link_target_type: 'blog',
|
||||
},
|
||||
},
|
||||
] satisfies PluginBanner[]
|
||||
mockFetchPluginBanners.mockResolvedValue([])
|
||||
|
||||
const { EmbeddedMarketplace } = await import('../embedded')
|
||||
|
||||
render(
|
||||
<EmbeddedMarketplace
|
||||
initialBanners={initialBanners}
|
||||
initialLocale="en-US"
|
||||
showInstallButton
|
||||
variant="home"
|
||||
/>,
|
||||
{ wrapper: Wrapper },
|
||||
)
|
||||
|
||||
expect(await screen.findByText('Trending banners: 0')).toBeInTheDocument()
|
||||
expect(mockFetchPluginBanners).toHaveBeenCalledWith('zh-Hans')
|
||||
})
|
||||
|
||||
it('does not request homepage banners for the default catalog variant', async () => {
|
||||
const { EmbeddedMarketplace } = await import('../embedded')
|
||||
|
||||
render(<EmbeddedMarketplace variant="default" />, { wrapper: Wrapper })
|
||||
|
||||
expect(screen.getByText('Trending banners: 0')).toBeInTheDocument()
|
||||
expect(mockFetchPluginBanners).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,231 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import type { Plugin } from '@/app/components/plugins/types'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { act, renderHook, waitFor } from '@testing-library/react'
|
||||
import { PluginCategoryEnum } from '@/app/components/plugins/types'
|
||||
|
||||
const getMarketplacePluginsByCollectionId = vi.hoisted(() => vi.fn())
|
||||
const getMarketplaceCollectionsAndPlugins = vi.hoisted(() => vi.fn())
|
||||
|
||||
vi.mock('@/service/base', () => ({
|
||||
postMarketplace: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../utils', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('../utils')>()),
|
||||
getMarketplaceCollectionsAndPlugins,
|
||||
getMarketplacePluginsByCollectionId,
|
||||
}))
|
||||
|
||||
const createWrapper = () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
},
|
||||
})
|
||||
const Wrapper = ({ children }: { children: ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
)
|
||||
|
||||
return { Wrapper, queryClient }
|
||||
}
|
||||
|
||||
describe('useMarketplacePluginsByCollectionId', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should show loading while the first collection request is pending', async () => {
|
||||
getMarketplacePluginsByCollectionId.mockImplementation(() => new Promise(() => {}))
|
||||
const { useMarketplacePluginsByCollectionId } = await import('../hooks')
|
||||
const { Wrapper } = createWrapper()
|
||||
const { result } = renderHook(
|
||||
() => useMarketplacePluginsByCollectionId('__model-settings-pinned-models'),
|
||||
{ wrapper: Wrapper },
|
||||
)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(getMarketplacePluginsByCollectionId).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
expect(result.current.isLoading).toBe(true)
|
||||
})
|
||||
|
||||
it('should retain collection results while refreshing cached data', async () => {
|
||||
let resolveRefresh: (() => void) | undefined
|
||||
getMarketplacePluginsByCollectionId
|
||||
.mockResolvedValueOnce([{ plugin_id: 'cached-plugin', type: 'plugin' }])
|
||||
.mockImplementationOnce(
|
||||
() =>
|
||||
new Promise<{ plugin_id: string; type: string }[]>((resolve) => {
|
||||
resolveRefresh = () => resolve([{ plugin_id: 'refreshed-plugin', type: 'plugin' }])
|
||||
}),
|
||||
)
|
||||
|
||||
const { useMarketplacePluginsByCollectionId } = await import('../hooks')
|
||||
const { Wrapper, queryClient } = createWrapper()
|
||||
const { result } = renderHook(
|
||||
() => useMarketplacePluginsByCollectionId('__model-settings-pinned-models'),
|
||||
{ wrapper: Wrapper },
|
||||
)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.plugins).toEqual([{ plugin_id: 'cached-plugin', type: 'plugin' }])
|
||||
})
|
||||
|
||||
act(() => {
|
||||
void queryClient.invalidateQueries({ queryKey: ['marketplaceCollectionPlugins'] })
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(getMarketplacePluginsByCollectionId).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
expect(result.current.plugins).toEqual([{ plugin_id: 'cached-plugin', type: 'plugin' }])
|
||||
expect(result.current.isLoading).toBe(false)
|
||||
|
||||
await act(async () => {
|
||||
resolveRefresh?.()
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.plugins).toEqual([{ plugin_id: 'refreshed-plugin', type: 'plugin' }])
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('useMarketplaceCollectionsAndPlugins', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should retain collection results while refreshing cached data', async () => {
|
||||
let resolveRefresh: (() => void) | undefined
|
||||
getMarketplaceCollectionsAndPlugins
|
||||
.mockResolvedValueOnce({
|
||||
marketplaceCollections: [{ id: 'cached-collection' }],
|
||||
marketplaceCollectionPluginsMap: {},
|
||||
})
|
||||
.mockImplementationOnce(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
resolveRefresh = () =>
|
||||
resolve({
|
||||
marketplaceCollections: [{ id: 'refreshed-collection' }],
|
||||
marketplaceCollectionPluginsMap: {},
|
||||
})
|
||||
}),
|
||||
)
|
||||
|
||||
const { useMarketplaceCollectionsAndPlugins } = await import('../hooks')
|
||||
const { Wrapper, queryClient } = createWrapper()
|
||||
const { result } = renderHook(() => useMarketplaceCollectionsAndPlugins(), {
|
||||
wrapper: Wrapper,
|
||||
})
|
||||
|
||||
act(() => {
|
||||
result.current.queryMarketplaceCollectionsAndPlugins()
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.marketplaceCollections).toEqual([{ id: 'cached-collection' }])
|
||||
})
|
||||
|
||||
act(() => {
|
||||
void queryClient.invalidateQueries({ queryKey: ['marketplaceCollectionsAndPlugins'] })
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(getMarketplaceCollectionsAndPlugins).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
expect(result.current.marketplaceCollections).toEqual([{ id: 'cached-collection' }])
|
||||
expect(result.current.isLoading).toBe(false)
|
||||
|
||||
await act(async () => {
|
||||
resolveRefresh?.()
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.marketplaceCollections).toEqual([{ id: 'refreshed-collection' }])
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
const createPlugin = (pluginID: string, category: PluginCategoryEnum) =>
|
||||
({
|
||||
plugin_id: pluginID,
|
||||
type: 'plugin',
|
||||
category,
|
||||
name: pluginID,
|
||||
org: 'dify',
|
||||
}) as Plugin
|
||||
|
||||
const createInfiniteData = (plugin: Plugin, pageSize: number) => ({
|
||||
pages: [
|
||||
{
|
||||
plugins: [plugin],
|
||||
total: 1,
|
||||
page: 1,
|
||||
page_size: pageSize,
|
||||
},
|
||||
],
|
||||
pageParams: [1],
|
||||
})
|
||||
|
||||
const createWrapperWithQueryClient = (queryClient: QueryClient) =>
|
||||
function Wrapper({ children }: { children: ReactNode }) {
|
||||
return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
}
|
||||
|
||||
describe('useMarketplacePlugins', () => {
|
||||
it('should reset local query params without removing marketplace plugin caches', async () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false, gcTime: Infinity },
|
||||
},
|
||||
})
|
||||
const toolPlugin = createPlugin('tool-plugin', PluginCategoryEnum.tool)
|
||||
const modelPlugin = createPlugin('model-plugin', PluginCategoryEnum.model)
|
||||
const toolParams = {
|
||||
query: 'search',
|
||||
category: PluginCategoryEnum.tool,
|
||||
type: 'plugin' as const,
|
||||
page_size: 40,
|
||||
}
|
||||
const modelParams = {
|
||||
query: '',
|
||||
category: PluginCategoryEnum.model,
|
||||
type: 'plugin' as const,
|
||||
page_size: 1000,
|
||||
}
|
||||
const toolQueryKey = ['marketplacePlugins', toolParams]
|
||||
const modelQueryKey = ['marketplacePlugins', modelParams]
|
||||
const toolQueryData = createInfiniteData(toolPlugin, toolParams.page_size)
|
||||
const modelQueryData = createInfiniteData(modelPlugin, modelParams.page_size)
|
||||
|
||||
queryClient.setQueryData(toolQueryKey, toolQueryData)
|
||||
queryClient.setQueryData(modelQueryKey, modelQueryData)
|
||||
|
||||
const { useMarketplacePlugins } = await import('../hooks')
|
||||
const { result } = renderHook(() => useMarketplacePlugins(), {
|
||||
wrapper: createWrapperWithQueryClient(queryClient),
|
||||
})
|
||||
|
||||
act(() => {
|
||||
result.current.queryPlugins(toolParams)
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.plugins).toEqual([toolPlugin])
|
||||
})
|
||||
|
||||
act(() => {
|
||||
result.current.resetQueryParams()
|
||||
})
|
||||
|
||||
expect(result.current.plugins).toBeUndefined()
|
||||
expect(queryClient.getQueryData(toolQueryKey)).toEqual(toolQueryData)
|
||||
expect(queryClient.getQueryData(modelQueryKey)).toEqual(modelQueryData)
|
||||
})
|
||||
})
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
|
||||
import { marketplaceQuery } from '@/service/marketplace'
|
||||
|
||||
vi.mock('@/config', () => ({
|
||||
API_PREFIX: '/api',
|
||||
APP_VERSION: '1.0.0',
|
||||
IS_MARKETPLACE: false,
|
||||
}))
|
||||
vi.mock('@/env', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/env')>()
|
||||
return {
|
||||
...actual,
|
||||
env: {
|
||||
...actual.env,
|
||||
NEXT_PUBLIC_MARKETPLACE_API_PREFIX: 'https://marketplace.dify.ai/api/v1',
|
||||
NEXT_PUBLIC_MARKETPLACE_URL_PREFIX: 'https://marketplace.dify.ai',
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
const mockCollections = vi.fn()
|
||||
const mockCollectionPlugins = vi.fn()
|
||||
const mockSearchAdvanced = vi.fn()
|
||||
|
||||
vi.mock('@/service/marketplace', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('@/service/marketplace')>()),
|
||||
marketplaceClient: {
|
||||
collections: (...args: unknown[]) => mockCollections(...args),
|
||||
collectionPlugins: (...args: unknown[]) => mockCollectionPlugins(...args),
|
||||
searchAdvanced: (...args: unknown[]) => mockSearchAdvanced(...args),
|
||||
},
|
||||
}))
|
||||
|
||||
let queryClient: QueryClient
|
||||
|
||||
vi.mock('@/app/get-query-client', () => {
|
||||
return {
|
||||
getQueryClient: () => queryClient,
|
||||
}
|
||||
})
|
||||
|
||||
describe('HydrateQueryClient', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false, gcTime: 0 } },
|
||||
})
|
||||
mockCollections.mockResolvedValue({
|
||||
data: { collections: [] },
|
||||
})
|
||||
mockCollectionPlugins.mockResolvedValue({
|
||||
data: { plugins: [] },
|
||||
})
|
||||
mockSearchAdvanced.mockResolvedValue({
|
||||
data: { plugins: [], total: 0 },
|
||||
})
|
||||
})
|
||||
|
||||
it('renders the shell without fetching when search parameters are absent', async () => {
|
||||
const { HydrateQueryClient } = await import('../hydration-server')
|
||||
const element = await HydrateQueryClient({
|
||||
searchParams: undefined,
|
||||
children: <div>Child Content</div>,
|
||||
})
|
||||
render(<QueryClientProvider client={new QueryClient()}>{element}</QueryClientProvider>)
|
||||
expect(screen.getByText('Child Content')).toBeInTheDocument()
|
||||
expect(mockCollections).not.toHaveBeenCalled()
|
||||
expect(mockSearchAdvanced).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('hydrates the prefetched collection data into the client cache', async () => {
|
||||
const { HydrateQueryClient } = await import('../hydration-server')
|
||||
const element = await HydrateQueryClient({
|
||||
searchParams: Promise.resolve({ category: 'all' }),
|
||||
children: <div>Child</div>,
|
||||
})
|
||||
const renderClient = new QueryClient()
|
||||
render(<QueryClientProvider client={renderClient}>{element}</QueryClientProvider>)
|
||||
expect(mockCollections).toHaveBeenCalledOnce()
|
||||
expect(
|
||||
renderClient.getQueryData(marketplaceQuery.collections.queryKey({ input: { query: {} } })),
|
||||
).toEqual({
|
||||
marketplaceCollections: [],
|
||||
marketplaceCollectionPluginsMap: {},
|
||||
})
|
||||
})
|
||||
|
||||
it('should prefetch when category has collections (tool)', async () => {
|
||||
const { HydrateQueryClient } = await import('../hydration-server')
|
||||
|
||||
await HydrateQueryClient({
|
||||
searchParams: Promise.resolve({ category: 'tool' }),
|
||||
children: <div>Child</div>,
|
||||
})
|
||||
|
||||
expect(mockCollections).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should prefetch plugin search when q is present', async () => {
|
||||
const { HydrateQueryClient } = await import('../hydration-server')
|
||||
|
||||
await HydrateQueryClient({
|
||||
searchParams: Promise.resolve({ category: 'all', q: 'openai' }),
|
||||
children: <div>Child</div>,
|
||||
})
|
||||
|
||||
expect(mockCollections).not.toHaveBeenCalled()
|
||||
expect(mockSearchAdvanced).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
params: { kind: 'plugins' },
|
||||
body: expect.objectContaining({
|
||||
page: 1,
|
||||
query: 'openai',
|
||||
}),
|
||||
}),
|
||||
expect.any(Object),
|
||||
)
|
||||
})
|
||||
|
||||
it('should prefetch when category does not have collections (model)', async () => {
|
||||
const { HydrateQueryClient } = await import('../hydration-server')
|
||||
|
||||
await HydrateQueryClient({
|
||||
searchParams: Promise.resolve({ category: 'model' }),
|
||||
children: <div>Child</div>,
|
||||
})
|
||||
|
||||
expect(mockCollections).not.toHaveBeenCalled()
|
||||
expect(mockSearchAdvanced).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should prefetch when category does not have collections (bundle)', async () => {
|
||||
const { HydrateQueryClient } = await import('../hydration-server')
|
||||
|
||||
await HydrateQueryClient({
|
||||
searchParams: Promise.resolve({ category: 'bundle' }),
|
||||
children: <div>Child</div>,
|
||||
})
|
||||
|
||||
expect(mockCollections).not.toHaveBeenCalled()
|
||||
expect(mockSearchAdvanced).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should keep the catalog shell when collections prefetch fails', async () => {
|
||||
mockCollections.mockRejectedValue(new Error('collections unavailable'))
|
||||
const { HydrateQueryClient } = await import('../hydration-server')
|
||||
|
||||
const element = await HydrateQueryClient({
|
||||
searchParams: Promise.resolve({ category: 'all' }),
|
||||
children: <div>Child</div>,
|
||||
})
|
||||
|
||||
const renderClient = new QueryClient()
|
||||
const { getByText } = render(
|
||||
<QueryClientProvider client={renderClient}>{element}</QueryClientProvider>,
|
||||
)
|
||||
expect(getByText('Child')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should keep the catalog shell when plugin search prefetch fails', async () => {
|
||||
mockSearchAdvanced.mockRejectedValue(new Error('search unavailable'))
|
||||
const { HydrateQueryClient } = await import('../hydration-server')
|
||||
|
||||
const element = await HydrateQueryClient({
|
||||
searchParams: Promise.resolve({ category: 'all', q: 'openai' }),
|
||||
children: <div>Child</div>,
|
||||
})
|
||||
|
||||
const renderClient = new QueryClient()
|
||||
const { getByText } = render(
|
||||
<QueryClientProvider client={renderClient}>{element}</QueryClientProvider>,
|
||||
)
|
||||
expect(getByText('Child')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
import type { ComponentProps, ReactNode } from 'react'
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { Provider as JotaiProvider } from 'jotai'
|
||||
import { describe, expect, it, vi } from 'vite-plus/test'
|
||||
import { createNuqsTestWrapper } from '@/test/nuqs-testing'
|
||||
import PluginTypeSwitch from '../plugin-type-switch'
|
||||
|
||||
vi.mock('#i18n', async () => {
|
||||
const { withSelectorKey } = await import('@/test/i18n-mock')
|
||||
return {
|
||||
useTranslation: () => ({ t: withSelectorKey((key: string) => key) }),
|
||||
}
|
||||
})
|
||||
|
||||
const renderSwitch = (searchParams = '', props?: ComponentProps<typeof PluginTypeSwitch>) => {
|
||||
const { wrapper: NuqsWrapper, onUrlUpdate } = createNuqsTestWrapper({ searchParams })
|
||||
const Wrapper = ({ children }: { children: ReactNode }) => (
|
||||
<JotaiProvider>
|
||||
<NuqsWrapper>{children}</NuqsWrapper>
|
||||
</JotaiProvider>
|
||||
)
|
||||
|
||||
return { ...render(<PluginTypeSwitch {...props} />, { wrapper: Wrapper }), onUrlUpdate }
|
||||
}
|
||||
|
||||
describe('PluginTypeSwitch', () => {
|
||||
it('renders every supported plugin category', () => {
|
||||
renderSwitch()
|
||||
|
||||
expect(screen.getByRole('button', { name: 'category.all' })).toHaveAttribute(
|
||||
'aria-pressed',
|
||||
'true',
|
||||
)
|
||||
expect(screen.getByRole('button', { name: 'category.models' })).toHaveAttribute(
|
||||
'aria-pressed',
|
||||
'false',
|
||||
)
|
||||
expect(screen.getByRole('button', { name: 'category.tools' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'category.datasources' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'category.agents' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'category.triggers' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'category.extensions' })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: 'category.bundles' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('updates the category in the URL when selected', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { onUrlUpdate } = renderSwitch('?category=all')
|
||||
|
||||
const modelsButton = screen.getByRole('button', { name: 'category.models' })
|
||||
modelsButton.focus()
|
||||
await user.keyboard('{Enter}')
|
||||
|
||||
await waitFor(() => expect(onUrlUpdate).toHaveBeenCalled())
|
||||
expect(onUrlUpdate.mock.calls.at(-1)?.[0].searchParams.get('category')).toBe('model')
|
||||
expect(modelsButton).toHaveAttribute('aria-pressed', 'true')
|
||||
})
|
||||
|
||||
it('exposes the selected category and updates the URL in the home variant', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { onUrlUpdate } = renderSwitch('?category=all', { variant: 'home' })
|
||||
|
||||
const activeCategory = screen.getByRole('button', { name: 'category.all' })
|
||||
|
||||
expect(activeCategory).toHaveAttribute('aria-pressed', 'true')
|
||||
expect(screen.getByRole('button', { name: 'categorySingle.datasource' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'categorySingle.agent' })).toBeInTheDocument()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'category.models' }))
|
||||
|
||||
await waitFor(() => expect(onUrlUpdate).toHaveBeenCalled())
|
||||
const update = onUrlUpdate.mock.calls.at(-1)?.[0]
|
||||
expect(update?.searchParams.get('category')).toBe('model')
|
||||
expect(update?.options.scroll).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,214 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import type { marketplaceClient } from '@/service/marketplace'
|
||||
import { QueryClientProvider } from '@tanstack/react-query'
|
||||
import { act, renderHook, waitFor } from '@testing-library/react'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
|
||||
import { MARKETPLACE_API_PREFIX } from '@/features/marketplace/api'
|
||||
import { createMarketplacePluginFixture } from '@/test/fixtures/plugin'
|
||||
import { createTestQueryClient } from '@/test/query-client'
|
||||
import { useMarketplaceCollectionsAndPlugins, useMarketplacePlugins } from '../query'
|
||||
|
||||
const { mockCollections, mockCollectionPlugins, mockSearchAdvanced } = vi.hoisted(() => ({
|
||||
mockCollections: vi.fn<typeof marketplaceClient.collections>(),
|
||||
mockCollectionPlugins: vi.fn<typeof marketplaceClient.collectionPlugins>(),
|
||||
mockSearchAdvanced: vi.fn<typeof marketplaceClient.searchAdvanced>(),
|
||||
}))
|
||||
|
||||
vi.mock('@/service/marketplace', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('@/service/marketplace')>()),
|
||||
marketplaceClient: {
|
||||
collections: mockCollections,
|
||||
collectionPlugins: mockCollectionPlugins,
|
||||
searchAdvanced: mockSearchAdvanced,
|
||||
},
|
||||
}))
|
||||
|
||||
const createWrapper = () => {
|
||||
const queryClient = createTestQueryClient()
|
||||
const Wrapper = ({ children }: { children: ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
)
|
||||
return { Wrapper, queryClient }
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
mockCollections.mockReset()
|
||||
mockCollectionPlugins.mockReset()
|
||||
mockSearchAdvanced.mockReset()
|
||||
})
|
||||
|
||||
describe('useMarketplaceCollectionsAndPlugins', () => {
|
||||
it('should fetch collections and plugins data', async () => {
|
||||
const mockCollectionData = [
|
||||
{
|
||||
name: 'col-1',
|
||||
label: { en_US: 'Featured' },
|
||||
description: {},
|
||||
rule: '',
|
||||
created_at: '2026-06-01T00:00:00Z',
|
||||
updated_at: '2026-06-01T00:00:00Z',
|
||||
},
|
||||
]
|
||||
const mockPluginData = [createMarketplacePluginFixture({ org: 'test', name: 'plugin1' })]
|
||||
|
||||
mockCollections.mockResolvedValue({ data: { collections: mockCollectionData } })
|
||||
mockCollectionPlugins.mockResolvedValue({ data: { plugins: mockPluginData } })
|
||||
|
||||
const { Wrapper } = createWrapper()
|
||||
const { result } = renderHook(
|
||||
() => useMarketplaceCollectionsAndPlugins({ condition: 'category=tool', type: 'plugin' }),
|
||||
{ wrapper: Wrapper },
|
||||
)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.data).toBeDefined()
|
||||
})
|
||||
|
||||
expect(result.current.data?.marketplaceCollections).toEqual(mockCollectionData)
|
||||
expect(result.current.data?.marketplaceCollectionPluginsMap['col-1']).toEqual([
|
||||
expect.objectContaining({
|
||||
name: 'plugin1',
|
||||
icon: `${MARKETPLACE_API_PREFIX}/plugins/test/plugin1/icon`,
|
||||
}),
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('useMarketplacePlugins', () => {
|
||||
it('should not fetch when queryParams is undefined', async () => {
|
||||
const { Wrapper } = createWrapper()
|
||||
const { result } = renderHook(() => useMarketplacePlugins(undefined), { wrapper: Wrapper })
|
||||
|
||||
// enabled is false, so should not fetch
|
||||
expect(result.current.data).toBeUndefined()
|
||||
expect(mockSearchAdvanced).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should fetch plugins when queryParams is provided', async () => {
|
||||
mockSearchAdvanced.mockResolvedValue({
|
||||
data: {
|
||||
plugins: [createMarketplacePluginFixture({ org: 'test', name: 'p1' })],
|
||||
total: 1,
|
||||
},
|
||||
})
|
||||
|
||||
const { Wrapper } = createWrapper()
|
||||
const { result } = renderHook(
|
||||
() =>
|
||||
useMarketplacePlugins({
|
||||
query: 'test',
|
||||
sort_by: 'install_count',
|
||||
sort_order: 'DESC',
|
||||
category: 'tool',
|
||||
tags: [],
|
||||
type: 'plugin',
|
||||
}),
|
||||
{ wrapper: Wrapper },
|
||||
)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.data).toBeDefined()
|
||||
})
|
||||
|
||||
expect(result.current.data?.pages).toHaveLength(1)
|
||||
expect(result.current.data?.pages[0]?.plugins).toEqual([
|
||||
expect.objectContaining({
|
||||
name: 'p1',
|
||||
icon: `${MARKETPLACE_API_PREFIX}/plugins/test/p1/icon`,
|
||||
}),
|
||||
])
|
||||
expect(mockSearchAdvanced).toHaveBeenCalledExactlyOnceWith(
|
||||
{
|
||||
params: { kind: 'plugins' },
|
||||
body: {
|
||||
page: 1,
|
||||
page_size: 40,
|
||||
query: 'test',
|
||||
sort_by: 'install_count',
|
||||
sort_order: 'DESC',
|
||||
category: 'tool',
|
||||
tags: [],
|
||||
},
|
||||
},
|
||||
{ signal: expect.any(AbortSignal) },
|
||||
)
|
||||
})
|
||||
|
||||
it('should handle bundle type in query params', async () => {
|
||||
mockSearchAdvanced.mockResolvedValue({
|
||||
data: {
|
||||
plugins: [],
|
||||
bundles: [createMarketplacePluginFixture({ type: 'bundle', org: 'test', name: 'b1' })],
|
||||
total: 1,
|
||||
},
|
||||
})
|
||||
|
||||
const { Wrapper } = createWrapper()
|
||||
const { result } = renderHook(
|
||||
() =>
|
||||
useMarketplacePlugins({
|
||||
query: 'bundle',
|
||||
type: 'bundle',
|
||||
}),
|
||||
{ wrapper: Wrapper },
|
||||
)
|
||||
|
||||
await waitFor(() => expect(result.current.isSuccess).toBe(true))
|
||||
expect(result.current.data?.pages[0]?.plugins).toEqual([
|
||||
expect.objectContaining({ name: 'b1', type: 'bundle' }),
|
||||
])
|
||||
expect(mockSearchAdvanced).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ params: { kind: 'bundles' } }),
|
||||
expect.any(Object),
|
||||
)
|
||||
})
|
||||
|
||||
it('should surface API errors instead of an empty success', async () => {
|
||||
mockSearchAdvanced.mockRejectedValue(new Error('Network error'))
|
||||
|
||||
const { Wrapper } = createWrapper()
|
||||
const { result } = renderHook(
|
||||
() =>
|
||||
useMarketplacePlugins({
|
||||
query: 'fail',
|
||||
}),
|
||||
{ wrapper: Wrapper },
|
||||
)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isError).toBe(true)
|
||||
})
|
||||
|
||||
// No synthesized page: an empty success let a backend outage render as
|
||||
// "no plugins found", suppressed retries, and permanently disabled
|
||||
// getNextPageParam for this key.
|
||||
expect(result.current.data).toBeUndefined()
|
||||
expect(result.current.error).toEqual(new Error('Network error'))
|
||||
})
|
||||
|
||||
it('requests the next page and stops when the reported total is reached', async () => {
|
||||
const plugin = (name: string) => createMarketplacePluginFixture({ org: 'test', name })
|
||||
mockSearchAdvanced
|
||||
.mockResolvedValueOnce({ data: { plugins: [plugin('p1'), plugin('p2')], total: 3 } })
|
||||
.mockResolvedValueOnce({ data: { plugins: [plugin('p3')], total: 3 } })
|
||||
const { Wrapper } = createWrapper()
|
||||
const { result } = renderHook(
|
||||
() => useMarketplacePlugins({ query: 'paginated', page_size: 2 }),
|
||||
{ wrapper: Wrapper },
|
||||
)
|
||||
await waitFor(() => expect(result.current.hasNextPage).toBe(true))
|
||||
await act(async () => {
|
||||
await result.current.fetchNextPage()
|
||||
})
|
||||
await waitFor(() => expect(result.current.hasNextPage).toBe(false))
|
||||
expect(
|
||||
result.current.data?.pages.flatMap((page) => page.plugins.map((item) => item.name)),
|
||||
).toEqual(['p1', 'p2', 'p3'])
|
||||
expect(mockSearchAdvanced).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({
|
||||
body: expect.objectContaining({ page: 2, page_size: 2, query: 'paginated' }),
|
||||
}),
|
||||
expect.any(Object),
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,36 @@
|
||||
import { screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { describe, expect, it, vi } from 'vite-plus/test'
|
||||
import { renderWithNuqs } from '@/test/nuqs-testing'
|
||||
import { MarketplacePluginSearch } from '../search-input'
|
||||
|
||||
const markFilter = vi.hoisted(() => vi.fn())
|
||||
vi.mock('@/utils/marketplace-site-track', () => ({
|
||||
markMarketplaceSiteFilter: markFilter,
|
||||
}))
|
||||
|
||||
describe('MarketplacePluginSearch', () => {
|
||||
it('clears the query and tags independently in the URL and tracks tag changes', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { onUrlUpdate } = renderWithNuqs(<MarketplacePluginSearch />, {
|
||||
searchParams: '?q=agent&tags=rag',
|
||||
})
|
||||
await user.click(screen.getByRole('button', { name: /^plugin\.clearSearch/ }))
|
||||
await waitFor(() => {
|
||||
const params = onUrlUpdate.mock.calls.at(-1)?.[0].searchParams
|
||||
expect(params?.get('q')).toBeNull()
|
||||
expect(params?.get('tags')).toBe('rag')
|
||||
})
|
||||
expect(markFilter).not.toHaveBeenCalled()
|
||||
await user.click(screen.getByRole('button', { name: /^pluginTags\.clearSelectedTags/ }))
|
||||
await waitFor(() => {
|
||||
expect(onUrlUpdate.mock.calls.at(-1)?.[0].searchParams.get('tags')).toBeNull()
|
||||
})
|
||||
expect(markFilter).toHaveBeenCalledExactlyOnceWith({
|
||||
filter_type: 'category',
|
||||
selection_mode: 'multi',
|
||||
filter_value: 'rag',
|
||||
selected_values: [],
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,34 @@
|
||||
import { createLoader } from 'nuqs/server'
|
||||
import { describe, expect, it } from 'vite-plus/test'
|
||||
import { PLUGIN_TYPE_SEARCH_MAP } from '../constants'
|
||||
import { marketplaceSearchParamsParsers } from '../search-params'
|
||||
|
||||
const loadSearchParams = createLoader(marketplaceSearchParamsParsers)
|
||||
|
||||
describe('marketplace search params', () => {
|
||||
it('applies the expected default values', () => {
|
||||
expect(loadSearchParams({})).toEqual({
|
||||
category: PLUGIN_TYPE_SEARCH_MAP.all,
|
||||
q: '',
|
||||
tags: [],
|
||||
languages: [],
|
||||
})
|
||||
})
|
||||
|
||||
it('parses supported query values with the configured parsers', () => {
|
||||
expect(
|
||||
loadSearchParams({
|
||||
category: PLUGIN_TYPE_SEARCH_MAP.tool,
|
||||
q: 'keyword',
|
||||
tags: 'rag,search',
|
||||
languages: 'en,zh-Hans',
|
||||
}),
|
||||
).toEqual({
|
||||
category: PLUGIN_TYPE_SEARCH_MAP.tool,
|
||||
q: 'keyword',
|
||||
tags: ['rag', 'search'],
|
||||
languages: ['en', 'zh-Hans'],
|
||||
})
|
||||
expect(loadSearchParams({ category: 'unsupported' }).category).toBe(PLUGIN_TYPE_SEARCH_MAP.all)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,95 @@
|
||||
import type { PluginBanner } from '@dify/contracts/marketplace'
|
||||
import type { ReactNode } from 'react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
|
||||
|
||||
const { mockFetchPluginBanners, mockGetLocaleOnServer } = vi.hoisted(() => ({
|
||||
mockFetchPluginBanners: vi.fn(),
|
||||
mockGetLocaleOnServer: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/i18n/server', () => ({
|
||||
getLocaleOnServer: mockGetLocaleOnServer,
|
||||
}))
|
||||
|
||||
vi.mock('../home/banners', async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import('../home/banners')>()
|
||||
|
||||
return {
|
||||
...original,
|
||||
fetchPluginBanners: mockFetchPluginBanners,
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../hydration-server', () => ({
|
||||
HydrateQueryClient: ({ children }: { children: ReactNode }) => children,
|
||||
}))
|
||||
|
||||
vi.mock('../prefetch-marketplace-dehydrated-state', () => ({
|
||||
prefetchMarketplaceDehydratedState: vi.fn().mockResolvedValue(undefined),
|
||||
}))
|
||||
|
||||
vi.mock('../view', () => ({
|
||||
MarketplaceView: ({ banners }: { banners: PluginBanner[] }) => (
|
||||
<p>Server banners: {banners.length}</p>
|
||||
),
|
||||
}))
|
||||
|
||||
describe('Marketplace server entry', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('prefetches localized homepage banners before rendering the standalone view', async () => {
|
||||
mockGetLocaleOnServer.mockResolvedValue('en-US')
|
||||
mockFetchPluginBanners.mockResolvedValue([
|
||||
{
|
||||
id: 'banner-1',
|
||||
title: 'Trending',
|
||||
sort: 1,
|
||||
language: 'en-US',
|
||||
style_type: 'blog',
|
||||
content: {
|
||||
blog_title: 'Dify update',
|
||||
link: 'https://dify.ai/blog',
|
||||
link_target_type: 'blog',
|
||||
},
|
||||
},
|
||||
] satisfies PluginBanner[])
|
||||
|
||||
const { default: Marketplace } = await import('../index')
|
||||
const element = await Marketplace({ variant: 'home' })
|
||||
|
||||
render(<QueryClientProvider client={new QueryClient()}>{element}</QueryClientProvider>)
|
||||
|
||||
expect(screen.getByText('Server banners: 1')).toBeInTheDocument()
|
||||
expect(mockGetLocaleOnServer).toHaveBeenCalledOnce()
|
||||
expect(mockFetchPluginBanners).toHaveBeenCalledWith('en-US')
|
||||
})
|
||||
|
||||
it('starts catalog prefetch without waiting for banners to finish', async () => {
|
||||
const { prefetchMarketplaceDehydratedState } =
|
||||
await import('../prefetch-marketplace-dehydrated-state')
|
||||
let resolveBanners: (banners: PluginBanner[]) => void = () => {}
|
||||
mockGetLocaleOnServer.mockResolvedValue('en-US')
|
||||
mockFetchPluginBanners.mockImplementation(
|
||||
() =>
|
||||
new Promise<PluginBanner[]>((resolve) => {
|
||||
resolveBanners = resolve
|
||||
}),
|
||||
)
|
||||
vi.mocked(prefetchMarketplaceDehydratedState).mockResolvedValue(undefined)
|
||||
|
||||
const { default: Marketplace } = await import('../index')
|
||||
const renderPromise = Marketplace({ variant: 'home', searchParams: Promise.resolve({}) })
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(prefetchMarketplaceDehydratedState).toHaveBeenCalled()
|
||||
})
|
||||
expect(mockFetchPluginBanners).toHaveBeenCalledWith('en-US')
|
||||
|
||||
resolveBanners([])
|
||||
await renderPromise
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,248 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { act, fireEvent, renderHook, waitFor } from '@testing-library/react'
|
||||
import { Provider as JotaiProvider } from 'jotai'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
|
||||
import { createNuqsTestWrapper } from '@/test/nuqs-testing'
|
||||
import { PLUGIN_TYPE_SEARCH_MAP } from '../constants'
|
||||
|
||||
vi.mock('@/config', () => ({
|
||||
API_PREFIX: '/api',
|
||||
APP_VERSION: '1.0.0',
|
||||
IS_MARKETPLACE: false,
|
||||
}))
|
||||
vi.mock('@/env', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/env')>()
|
||||
return {
|
||||
...actual,
|
||||
env: {
|
||||
...actual.env,
|
||||
NEXT_PUBLIC_MARKETPLACE_API_PREFIX: 'https://marketplace.dify.ai/api/v1',
|
||||
NEXT_PUBLIC_MARKETPLACE_URL_PREFIX: 'https://marketplace.dify.ai',
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
const mockCollections = vi.fn()
|
||||
const mockCollectionPlugins = vi.fn()
|
||||
const mockSearchAdvanced = vi.fn()
|
||||
|
||||
vi.mock('@/service/marketplace', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/service/marketplace')>()
|
||||
return {
|
||||
...actual,
|
||||
marketplaceClient: {
|
||||
...actual.marketplaceClient,
|
||||
collections: (...args: unknown[]) => mockCollections(...args),
|
||||
collectionPlugins: (...args: unknown[]) => mockCollectionPlugins(...args),
|
||||
searchAdvanced: (...args: unknown[]) => mockSearchAdvanced(...args),
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
const createWrapper = (searchParams = '') => {
|
||||
const { wrapper: NuqsWrapper } = createNuqsTestWrapper({ searchParams })
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false, gcTime: 0 },
|
||||
},
|
||||
})
|
||||
const Wrapper = ({ children }: { children: ReactNode }) => (
|
||||
<JotaiProvider>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<NuqsWrapper>{children}</NuqsWrapper>
|
||||
</QueryClientProvider>
|
||||
</JotaiProvider>
|
||||
)
|
||||
return { Wrapper, queryClient }
|
||||
}
|
||||
|
||||
describe('useMarketplaceData', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
|
||||
mockCollections.mockResolvedValue({
|
||||
data: {
|
||||
collections: [
|
||||
{ name: 'col-1', label: {}, description: {}, rule: '', created_at: '', updated_at: '' },
|
||||
],
|
||||
},
|
||||
})
|
||||
mockCollectionPlugins.mockResolvedValue({
|
||||
data: {
|
||||
plugins: [{ type: 'plugin', org: 'test', name: 'p1', tags: [] }],
|
||||
},
|
||||
})
|
||||
mockSearchAdvanced.mockResolvedValue({
|
||||
data: {
|
||||
plugins: [{ type: 'plugin', org: 'test', name: 'p2', tags: [] }],
|
||||
total: 1,
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => document.getElementById('marketplace-container')?.remove())
|
||||
|
||||
it('loads collection contents without issuing a search', async () => {
|
||||
const { useMarketplaceData } = await import('../state')
|
||||
const { Wrapper } = createWrapper('?category=all')
|
||||
const { result } = renderHook(() => useMarketplaceData(), { wrapper: Wrapper })
|
||||
await waitFor(() => expect(result.current.isLoading).toBe(false))
|
||||
expect(result.current.marketplaceCollections).toEqual([
|
||||
expect.objectContaining({ name: 'col-1' }),
|
||||
])
|
||||
expect(result.current.marketplaceCollectionPluginsMap).toMatchObject({
|
||||
'col-1': [{ name: 'p1' }],
|
||||
})
|
||||
expect(result.current.plugins).toBeUndefined()
|
||||
expect(mockSearchAdvanced).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.each([
|
||||
['?category=all&q=test', { query: 'test' }],
|
||||
['?category=model', { category: 'model' }],
|
||||
['?category=all&tags=search', { tags: ['search'] }],
|
||||
])('loads search results for %s without fetching collections', async (searchParams, body) => {
|
||||
const { useMarketplaceData } = await import('../state')
|
||||
const { Wrapper } = createWrapper(searchParams)
|
||||
const { result } = renderHook(() => useMarketplaceData(), { wrapper: Wrapper })
|
||||
await waitFor(() => expect(result.current.isLoading).toBe(false))
|
||||
expect(result.current.plugins).toEqual([expect.objectContaining({ name: 'p2' })])
|
||||
expect(result.current.pluginsTotal).toBe(1)
|
||||
expect(mockSearchAdvanced).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ body: expect.objectContaining(body) }),
|
||||
expect.any(Object),
|
||||
)
|
||||
expect(mockCollections).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('restores collections and clears pending results when switching Models back to All', async () => {
|
||||
const { useMarketplaceData } = await import('../state')
|
||||
const { useActivePluginType } = await import('../atoms')
|
||||
const { Wrapper } = createWrapper('?category=model')
|
||||
const { result } = renderHook(
|
||||
() => ({
|
||||
data: useMarketplaceData(),
|
||||
setCategory: useActivePluginType()[1],
|
||||
}),
|
||||
{ wrapper: Wrapper },
|
||||
)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.data.plugins).toHaveLength(1)
|
||||
})
|
||||
|
||||
await act(async () => {
|
||||
await result.current.setCategory(PLUGIN_TYPE_SEARCH_MAP.all)
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.data.marketplaceCollections).toHaveLength(1)
|
||||
expect(result.current.data.plugins).toBeUndefined()
|
||||
expect(result.current.data.pluginsTotal).toBeUndefined()
|
||||
expect(result.current.data.isRefreshing).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
it('should use the server route category for hydrated standalone search', async () => {
|
||||
const { useMarketplaceData } = await import('../state')
|
||||
const { Wrapper } = createWrapper('?q=openai')
|
||||
|
||||
const { result } = renderHook(() => useMarketplaceData(PLUGIN_TYPE_SEARCH_MAP.model), {
|
||||
wrapper: Wrapper,
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isLoading).toBe(false)
|
||||
})
|
||||
|
||||
expect(mockSearchAdvanced).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
body: expect.objectContaining({
|
||||
category: 'model',
|
||||
query: 'openai',
|
||||
}),
|
||||
}),
|
||||
expect.any(Object),
|
||||
)
|
||||
})
|
||||
|
||||
it('appends a scrolled page, deduplicates overlapping results and stops at the total', async () => {
|
||||
const plugin = (index: number) => ({ type: 'plugin', org: 'test', name: `p${index}`, tags: [] })
|
||||
mockSearchAdvanced
|
||||
.mockResolvedValueOnce({
|
||||
data: { plugins: Array.from({ length: 40 }, (_, index) => plugin(index)), total: 42 },
|
||||
})
|
||||
.mockResolvedValueOnce({ data: { plugins: [plugin(39), plugin(40)], total: 42 } })
|
||||
const { useMarketplaceData } = await import('../state')
|
||||
const { Wrapper } = createWrapper('?category=model')
|
||||
const container = document.createElement('div')
|
||||
container.id = 'marketplace-container'
|
||||
document.body.appendChild(container)
|
||||
Object.defineProperties(container, {
|
||||
scrollTop: { value: 900, configurable: true },
|
||||
scrollHeight: { value: 1000, configurable: true },
|
||||
clientHeight: { value: 200, configurable: true },
|
||||
})
|
||||
const { result } = renderHook(() => useMarketplaceData(), { wrapper: Wrapper })
|
||||
await waitFor(() => expect(result.current.plugins).toHaveLength(40))
|
||||
fireEvent.scroll(container)
|
||||
await waitFor(() => expect(result.current.page).toBe(2))
|
||||
expect(result.current.plugins?.map((item) => item.name)).toEqual(
|
||||
Array.from({ length: 41 }, (_, index) => `p${index}`),
|
||||
)
|
||||
expect(mockSearchAdvanced).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({ body: expect.objectContaining({ page: 2 }) }),
|
||||
expect.any(Object),
|
||||
)
|
||||
await act(async () => {
|
||||
fireEvent.scroll(container)
|
||||
await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()))
|
||||
})
|
||||
expect(mockSearchAdvanced).toHaveBeenCalledTimes(2)
|
||||
expect(result.current.isFetchingNextPage).toBe(false)
|
||||
})
|
||||
|
||||
// Regression: `isSearchMode` was derived from the raw URL value while the
|
||||
// request body used the 500ms-debounced one. Keystroke #1 therefore flipped
|
||||
// the hook into search mode with an empty query, firing a full search for ''
|
||||
// whose generic top-plugins results rendered until the real ones replaced
|
||||
// them — the wrong-results flash at the start of every search session.
|
||||
it('should never issue an empty-query search when typing starts', async () => {
|
||||
const { useMarketplaceData } = await import('../state')
|
||||
const { useSearchPluginText } = await import('../atoms')
|
||||
const { Wrapper } = createWrapper('?category=all')
|
||||
|
||||
const { result } = renderHook(
|
||||
() => ({
|
||||
data: useMarketplaceData(),
|
||||
setSearch: useSearchPluginText()[1],
|
||||
}),
|
||||
{ wrapper: Wrapper },
|
||||
)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.data.isLoading).toBe(false)
|
||||
})
|
||||
|
||||
await act(async () => {
|
||||
await result.current.setSearch('openai')
|
||||
})
|
||||
|
||||
await waitFor(
|
||||
() => {
|
||||
expect(mockSearchAdvanced).toHaveBeenCalled()
|
||||
},
|
||||
{ timeout: 3000 },
|
||||
)
|
||||
|
||||
expect(mockSearchAdvanced).not.toHaveBeenCalledWith(
|
||||
expect.objectContaining({ body: expect.objectContaining({ query: '' }) }),
|
||||
expect.anything(),
|
||||
)
|
||||
expect(mockSearchAdvanced).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ body: expect.objectContaining({ query: 'openai' }) }),
|
||||
expect.anything(),
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,454 @@
|
||||
import type { Plugin } from '@/app/components/plugins/types'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
|
||||
import { PluginCategoryEnum } from '@/app/components/plugins/types'
|
||||
import { PLUGIN_TYPE_SEARCH_MAP } from '../constants'
|
||||
|
||||
vi.mock('@/env', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/env')>()
|
||||
return {
|
||||
...actual,
|
||||
env: {
|
||||
...actual.env,
|
||||
NEXT_PUBLIC_MARKETPLACE_API_PREFIX: 'https://marketplace.dify.ai/api/v1',
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
// Mock marketplace client
|
||||
const mockCollectionPlugins = vi.fn()
|
||||
const mockCollections = vi.fn()
|
||||
const mockSearchAdvanced = vi.fn()
|
||||
|
||||
vi.mock('@/service/marketplace', () => ({
|
||||
marketplaceClient: {
|
||||
collections: (...args: unknown[]) => mockCollections(...args),
|
||||
collectionPlugins: (...args: unknown[]) => mockCollectionPlugins(...args),
|
||||
searchAdvanced: (...args: unknown[]) => mockSearchAdvanced(...args),
|
||||
},
|
||||
}))
|
||||
|
||||
// Factory for creating mock plugins
|
||||
const createMockPlugin = (overrides?: Partial<Plugin>): Plugin => ({
|
||||
type: 'plugin',
|
||||
org: 'test-org',
|
||||
name: 'test-plugin',
|
||||
plugin_id: 'plugin-1',
|
||||
version: '1.0.0',
|
||||
latest_version: '1.0.0',
|
||||
latest_package_identifier: 'test-org/test-plugin:1.0.0',
|
||||
icon: '/icon.png',
|
||||
verified: true,
|
||||
label: { 'en-US': 'Test Plugin' },
|
||||
brief: { 'en-US': 'Test plugin brief' },
|
||||
description: { 'en-US': 'Test plugin description' },
|
||||
introduction: 'Test plugin introduction',
|
||||
repository: 'https://github.com/test/plugin',
|
||||
category: PluginCategoryEnum.tool,
|
||||
install_count: 1000,
|
||||
endpoint: { settings: [] },
|
||||
tags: [{ name: 'search' }],
|
||||
badges: [],
|
||||
verification: { authorized_category: 'community' },
|
||||
from: 'marketplace',
|
||||
...overrides,
|
||||
})
|
||||
|
||||
describe('plugin and bundle icons', () => {
|
||||
it.each([
|
||||
{ type: 'plugin' as const, collection: 'plugins' },
|
||||
{ type: 'bundle' as const, collection: 'bundles' },
|
||||
])('builds $type icons and formats card data', async ({ type, collection }) => {
|
||||
const { getPluginIconInMarketplace, getFormattedPlugin } = await import('../utils')
|
||||
const plugin = { ...createMockPlugin({ type }), labels: { en_US: 'Bundle label' } }
|
||||
const icon = `https://marketplace.dify.ai/api/v1/${collection}/test-org/test-plugin/icon`
|
||||
expect(getPluginIconInMarketplace(plugin)).toBe(icon)
|
||||
expect(getFormattedPlugin(plugin)).toEqual({
|
||||
...plugin,
|
||||
icon,
|
||||
...(type === 'bundle' ? { brief: plugin.description, label: plugin.labels } : {}),
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('catalog filters', () => {
|
||||
it.each([
|
||||
[PLUGIN_TYPE_SEARCH_MAP.tool, 'category=tool', 'plugin'],
|
||||
[PLUGIN_TYPE_SEARCH_MAP.model, 'category=model', 'plugin'],
|
||||
[PLUGIN_TYPE_SEARCH_MAP.agent, 'category=agent-strategy', 'plugin'],
|
||||
[PLUGIN_TYPE_SEARCH_MAP.datasource, 'category=datasource', 'plugin'],
|
||||
[PLUGIN_TYPE_SEARCH_MAP.trigger, 'category=trigger', 'plugin'],
|
||||
[PLUGIN_TYPE_SEARCH_MAP.extension, 'category=endpoint', 'plugin'],
|
||||
[PLUGIN_TYPE_SEARCH_MAP.bundle, 'type=bundle', 'bundle'],
|
||||
[PLUGIN_TYPE_SEARCH_MAP.all, '', undefined],
|
||||
] as const)('maps %s into collection request filters', async (category, condition, type) => {
|
||||
const { getMarketplaceListCondition, getMarketplaceListFilterType, getCollectionsParams } =
|
||||
await import('../utils')
|
||||
expect(getMarketplaceListCondition(category)).toBe(condition)
|
||||
expect(getMarketplaceListFilterType(category)).toBe(type)
|
||||
expect(getCollectionsParams(category)).toEqual(
|
||||
category === 'all' ? {} : { category, condition, type },
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('getMarketplacePluginsByCollectionId', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('forwards collection filters and cancellation and returns formatted cards', async () => {
|
||||
const plugin = createMockPlugin()
|
||||
mockCollectionPlugins.mockResolvedValueOnce({ data: { plugins: [plugin] } })
|
||||
const controller = new AbortController()
|
||||
const filters = { category: 'tool', exclude: ['excluded-plugin'], type: 'plugin' as const }
|
||||
const { getMarketplacePluginsByCollectionId } = await import('../utils')
|
||||
const result = await getMarketplacePluginsByCollectionId('test-collection', filters, {
|
||||
signal: controller.signal,
|
||||
})
|
||||
expect(mockCollectionPlugins).toHaveBeenCalledExactlyOnceWith(
|
||||
{ params: { collectionId: 'test-collection' }, body: filters },
|
||||
{ signal: controller.signal },
|
||||
)
|
||||
expect(result).toEqual([
|
||||
{
|
||||
...plugin,
|
||||
icon: 'https://marketplace.dify.ai/api/v1/plugins/test-org/test-plugin/icon',
|
||||
introduction: '',
|
||||
endpoint: { settings: [] },
|
||||
},
|
||||
])
|
||||
})
|
||||
|
||||
it('should propagate fetch errors', async () => {
|
||||
mockCollectionPlugins.mockRejectedValueOnce(new Error('Network error'))
|
||||
|
||||
const { getMarketplacePluginsByCollectionId } = await import('../utils')
|
||||
|
||||
await expect(getMarketplacePluginsByCollectionId('test-collection')).rejects.toThrow(
|
||||
'Network error',
|
||||
)
|
||||
})
|
||||
|
||||
it('should omit a preview limit when query is omitted', async () => {
|
||||
mockCollectionPlugins.mockResolvedValueOnce({
|
||||
data: { plugins: [] },
|
||||
})
|
||||
|
||||
const { getMarketplacePluginsByCollectionId } = await import('../utils')
|
||||
await getMarketplacePluginsByCollectionId('test-collection')
|
||||
|
||||
expect(mockCollectionPlugins).toHaveBeenCalledWith(
|
||||
{
|
||||
params: {
|
||||
collectionId: 'test-collection',
|
||||
},
|
||||
body: {},
|
||||
},
|
||||
expect.objectContaining({
|
||||
signal: undefined,
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('getMarketplaceCollectionsAndPlugins', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should fetch collections and plugins successfully', async () => {
|
||||
const mockCollectionData = [
|
||||
{ name: 'collection1', label: {}, description: {}, rule: '', created_at: '', updated_at: '' },
|
||||
]
|
||||
const mockPluginData = [{ type: 'plugin', org: 'test', name: 'plugin1' }]
|
||||
|
||||
mockCollections.mockResolvedValueOnce({ data: { collections: mockCollectionData } })
|
||||
mockCollectionPlugins.mockResolvedValue({ data: { plugins: mockPluginData } })
|
||||
|
||||
const { getMarketplaceCollectionsAndPlugins } = await import('../utils')
|
||||
const result = await getMarketplaceCollectionsAndPlugins({
|
||||
condition: 'category=tool',
|
||||
type: 'plugin',
|
||||
})
|
||||
|
||||
expect(result.marketplaceCollections).toEqual(mockCollectionData)
|
||||
expect(result.marketplaceCollectionPluginsMap).toEqual({
|
||||
collection1: [
|
||||
expect.objectContaining({
|
||||
org: 'test',
|
||||
name: 'plugin1',
|
||||
icon: 'https://marketplace.dify.ai/api/v1/plugins/test/plugin1/icon',
|
||||
}),
|
||||
],
|
||||
})
|
||||
expect(mockCollections).toHaveBeenCalledWith(
|
||||
{ query: { condition: 'category=tool', type: 'plugin', page: 1, page_size: 100 } },
|
||||
{ signal: undefined },
|
||||
)
|
||||
expect(mockCollectionPlugins).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
params: { collectionId: 'collection1' },
|
||||
body: {
|
||||
condition: 'category=tool',
|
||||
type: 'plugin',
|
||||
},
|
||||
}),
|
||||
expect.any(Object),
|
||||
)
|
||||
})
|
||||
|
||||
it('posts without a preview limit when the catalog has no extra filters', async () => {
|
||||
mockCollections.mockResolvedValueOnce({
|
||||
data: {
|
||||
collections: [
|
||||
{
|
||||
name: 'featured',
|
||||
label: {},
|
||||
description: {},
|
||||
rule: '',
|
||||
created_at: '',
|
||||
updated_at: '',
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
mockCollectionPlugins.mockResolvedValue({ data: { plugins: [] } })
|
||||
|
||||
const { getMarketplaceCollectionsAndPlugins } = await import('../utils')
|
||||
await getMarketplaceCollectionsAndPlugins()
|
||||
|
||||
expect(mockCollectionPlugins).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
params: { collectionId: 'featured' },
|
||||
body: {},
|
||||
}),
|
||||
expect.any(Object),
|
||||
)
|
||||
})
|
||||
|
||||
it('should propagate a failing collections request', async () => {
|
||||
mockCollections.mockRejectedValueOnce(new Error('Network error'))
|
||||
|
||||
const { getMarketplaceCollectionsAndPlugins } = await import('../utils')
|
||||
|
||||
// Resolving an empty catalog here made a backend outage indistinguishable
|
||||
// from "no collections", cached as a success for the whole staleTime.
|
||||
await expect(getMarketplaceCollectionsAndPlugins()).rejects.toThrow('Network error')
|
||||
})
|
||||
|
||||
it('should keep the catalog when a single collection fails', async () => {
|
||||
mockCollections.mockResolvedValueOnce({
|
||||
data: {
|
||||
collections: [
|
||||
{ name: 'ok', label: {}, description: {}, rule: '', created_at: '', updated_at: '' },
|
||||
{ name: 'broken', label: {}, description: {}, rule: '', created_at: '', updated_at: '' },
|
||||
],
|
||||
},
|
||||
})
|
||||
mockCollectionPlugins
|
||||
.mockResolvedValueOnce({ data: { plugins: [{ type: 'plugin', org: 'a', name: 'b' }] } })
|
||||
.mockRejectedValueOnce(new Error('collection down'))
|
||||
|
||||
const { getMarketplaceCollectionsAndPlugins } = await import('../utils')
|
||||
const result = await getMarketplaceCollectionsAndPlugins()
|
||||
|
||||
expect(result.marketplaceCollections).toHaveLength(2)
|
||||
expect(result.marketplaceCollectionPluginsMap.ok).toHaveLength(1)
|
||||
expect(result.marketplaceCollectionPluginsMap.broken).toEqual([])
|
||||
})
|
||||
|
||||
it('propagates cancellation instead of resolving empty carousels', async () => {
|
||||
const controller = new AbortController()
|
||||
mockCollections.mockResolvedValueOnce({
|
||||
data: {
|
||||
collections: [
|
||||
{ name: 'ok', label: {}, description: {}, rule: '', created_at: '', updated_at: '' },
|
||||
{ name: 'slow', label: {}, description: {}, rule: '', created_at: '', updated_at: '' },
|
||||
],
|
||||
},
|
||||
})
|
||||
mockCollectionPlugins
|
||||
.mockResolvedValueOnce({ data: { plugins: [{ type: 'plugin', org: 'a', name: 'b' }] } })
|
||||
.mockImplementationOnce(async () => {
|
||||
controller.abort()
|
||||
const error = new Error('Aborted')
|
||||
error.name = 'AbortError'
|
||||
throw error
|
||||
})
|
||||
|
||||
const { getMarketplaceCollectionsAndPlugins } = await import('../utils')
|
||||
|
||||
await expect(
|
||||
getMarketplaceCollectionsAndPlugins({}, { signal: controller.signal }),
|
||||
).rejects.toMatchObject({ name: 'AbortError' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('toListPlugin', () => {
|
||||
it('keeps card fields and drops list-unused payload', async () => {
|
||||
const { toListPlugin } = await import('../utils')
|
||||
const plugin = {
|
||||
...createMockPlugin({
|
||||
introduction: 'A very long readme that must not enter the catalog RSC payload',
|
||||
}),
|
||||
resource: { memory: 256 },
|
||||
plugins: { tools: ['x'] },
|
||||
tool: { identity: { name: 'search' } },
|
||||
model: { provider: 'openai' },
|
||||
agent_strategy: { features: ['a'] },
|
||||
data_sources: { items: [] },
|
||||
triggers: { events: [] },
|
||||
privacy_policy: 'https://example.com/privacy',
|
||||
privacy_options: 'all',
|
||||
readme_meta: { available_languages: ['en_US'] },
|
||||
endpoint: { settings: [{ name: 'api_key' }] },
|
||||
} as unknown as Plugin
|
||||
|
||||
const listed = toListPlugin(plugin)
|
||||
|
||||
expect(listed).toEqual({ ...createMockPlugin(), introduction: '', endpoint: { settings: [] } })
|
||||
})
|
||||
})
|
||||
|
||||
describe('getMarketplacePlugins', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should return empty result when queryParams is undefined', async () => {
|
||||
const { getMarketplacePlugins } = await import('../utils')
|
||||
const result = await getMarketplacePlugins(undefined, 1)
|
||||
|
||||
expect(result).toEqual({
|
||||
plugins: [],
|
||||
total: 0,
|
||||
page: 1,
|
||||
page_size: 40,
|
||||
})
|
||||
expect(mockSearchAdvanced).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('forwards filters, pagination and cancellation to plugin search', async () => {
|
||||
const plugin = createMockPlugin()
|
||||
mockSearchAdvanced.mockResolvedValueOnce({ data: { plugins: [plugin], total: 45 } })
|
||||
const controller = new AbortController()
|
||||
const body = {
|
||||
query: 'test',
|
||||
sort_by: 'install_count' as const,
|
||||
sort_order: 'DESC' as const,
|
||||
category: 'tool',
|
||||
tags: ['search'],
|
||||
page_size: 20,
|
||||
page: 2,
|
||||
}
|
||||
const { getMarketplacePlugins } = await import('../utils')
|
||||
const result = await getMarketplacePlugins({ ...body, type: 'plugin' }, 2, controller.signal)
|
||||
expect(mockSearchAdvanced).toHaveBeenCalledExactlyOnceWith(
|
||||
{ params: { kind: 'plugins' }, body },
|
||||
{ signal: controller.signal },
|
||||
)
|
||||
expect(result).toEqual({
|
||||
plugins: [
|
||||
{ ...plugin, icon: 'https://marketplace.dify.ai/api/v1/plugins/test-org/test-plugin/icon' },
|
||||
],
|
||||
total: 45,
|
||||
page: 2,
|
||||
page_size: 20,
|
||||
})
|
||||
})
|
||||
|
||||
it('should use bundles endpoint when type is bundle', async () => {
|
||||
mockSearchAdvanced.mockResolvedValueOnce({
|
||||
data: {
|
||||
bundles: [
|
||||
{ type: 'bundle', org: 'test', name: 'b1', tags: [], description: 'desc', labels: {} },
|
||||
],
|
||||
total: 1,
|
||||
},
|
||||
})
|
||||
|
||||
const { getMarketplacePlugins } = await import('../utils')
|
||||
const result = await getMarketplacePlugins(
|
||||
{
|
||||
query: 'bundle',
|
||||
type: 'bundle',
|
||||
},
|
||||
1,
|
||||
)
|
||||
|
||||
expect(result.plugins).toHaveLength(1)
|
||||
const call = mockSearchAdvanced.mock.calls[0]
|
||||
expect(call![0].params.kind).toBe('bundles')
|
||||
})
|
||||
|
||||
it('should use empty category when category is all', async () => {
|
||||
mockSearchAdvanced.mockResolvedValueOnce({
|
||||
data: { plugins: [], total: 0 },
|
||||
})
|
||||
|
||||
const { getMarketplacePlugins } = await import('../utils')
|
||||
const result = await getMarketplacePlugins(
|
||||
{
|
||||
query: 'test',
|
||||
category: 'all',
|
||||
},
|
||||
1,
|
||||
)
|
||||
|
||||
const call = mockSearchAdvanced.mock.calls[0]
|
||||
expect(call![0].body).toMatchObject({ category: '', page: 1, page_size: 40 })
|
||||
expect(result).toEqual({ plugins: [], total: 0, page: 1, page_size: 40 })
|
||||
})
|
||||
|
||||
it('should propagate API errors instead of synthesizing an empty page', async () => {
|
||||
mockSearchAdvanced.mockRejectedValueOnce(new Error('API error'))
|
||||
|
||||
const { getMarketplacePlugins } = await import('../utils')
|
||||
|
||||
// A synthesized `{ plugins: [], total: 0 }` resolved as a *success*: no
|
||||
// isError, no retry, a cached empty result, and getNextPageParam saw
|
||||
// total 0 and killed pagination for that key permanently.
|
||||
await expect(getMarketplacePlugins({ query: 'fail' }, 2)).rejects.toThrow('API error')
|
||||
})
|
||||
|
||||
it('should handle response with bundles fallback to plugins fallback to empty', async () => {
|
||||
// No bundles and no plugins in response
|
||||
mockSearchAdvanced.mockResolvedValueOnce({
|
||||
data: { total: 0 },
|
||||
})
|
||||
|
||||
const { getMarketplacePlugins } = await import('../utils')
|
||||
const result = await getMarketplacePlugins({ query: 'test' }, 1)
|
||||
|
||||
expect(result.plugins).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('missing collection data', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should handle collectionPlugins returning undefined plugins', async () => {
|
||||
mockCollectionPlugins.mockResolvedValueOnce({
|
||||
data: { plugins: undefined },
|
||||
})
|
||||
|
||||
const { getMarketplacePluginsByCollectionId } = await import('../utils')
|
||||
const result = await getMarketplacePluginsByCollectionId('test-collection')
|
||||
|
||||
expect(result).toEqual([])
|
||||
})
|
||||
|
||||
it('should handle collections returning undefined collections list', async () => {
|
||||
mockCollections.mockResolvedValueOnce({
|
||||
data: { collections: undefined },
|
||||
})
|
||||
|
||||
const { getMarketplaceCollectionsAndPlugins } = await import('../utils')
|
||||
const result = await getMarketplaceCollectionsAndPlugins()
|
||||
|
||||
// undefined || [] evaluates to [], so empty array is expected
|
||||
expect(result.marketplaceCollections).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,94 @@
|
||||
import type { PluginsSort, SearchParamsFromCollection } from '@dify/contracts/marketplace'
|
||||
import type { ActivePluginType } from './constants'
|
||||
import { atom, useAtom, useAtomValue, useSetAtom } from 'jotai'
|
||||
import { useQueryState } from 'nuqs'
|
||||
import { useCallback, useEffect } from 'react'
|
||||
import { DEFAULT_SORT } from './constants'
|
||||
import { marketplaceSearchParamsParsers, shouldSearchMarketplacePlugins } from './search-params'
|
||||
|
||||
const marketplaceSortAtom = atom<PluginsSort>(DEFAULT_SORT)
|
||||
export function useMarketplaceSort() {
|
||||
return useAtom(marketplaceSortAtom)
|
||||
}
|
||||
export function useMarketplaceSortValue() {
|
||||
return useAtomValue(marketplaceSortAtom)
|
||||
}
|
||||
export function useSearchPluginText() {
|
||||
return useQueryState('q', marketplaceSearchParamsParsers.q)
|
||||
}
|
||||
export function useActivePluginType() {
|
||||
return useQueryState('category', marketplaceSearchParamsParsers.category)
|
||||
}
|
||||
export function useFilterPluginTags() {
|
||||
return useQueryState('tags', marketplaceSearchParamsParsers.tags)
|
||||
}
|
||||
export function useFilterTemplateLanguages() {
|
||||
return useQueryState('languages', marketplaceSearchParamsParsers.languages)
|
||||
}
|
||||
|
||||
/**
|
||||
* Not all categories have collections, so we need to
|
||||
* force the search mode for those categories.
|
||||
*/
|
||||
export const searchModeAtom = atom<true | null>(null)
|
||||
|
||||
export function useMarketplaceSearchMode(
|
||||
activePluginTypeOverride?: ActivePluginType,
|
||||
// Callers that debounce the query text MUST pass the debounced value here.
|
||||
// Deciding "are we searching?" from the raw URL value while the request body
|
||||
// carries the debounced one flips this hook true on keystroke #1, firing a
|
||||
// wasted empty-query search whose generic top-plugins list renders for the
|
||||
// debounce window before the real results replace it. '' is a meaningful
|
||||
// override, so this is `??`, not `||`.
|
||||
searchPluginTextOverride?: string,
|
||||
) {
|
||||
const [searchPluginTextFromUrl] = useSearchPluginText()
|
||||
const searchPluginText = searchPluginTextOverride ?? searchPluginTextFromUrl
|
||||
const [filterPluginTags] = useFilterPluginTags()
|
||||
const [activePluginTypeFromUrl] = useActivePluginType()
|
||||
const activePluginType = activePluginTypeOverride ?? activePluginTypeFromUrl
|
||||
|
||||
const searchMode = useAtomValue(searchModeAtom)
|
||||
const isSearchMode =
|
||||
searchMode === true ||
|
||||
shouldSearchMarketplacePlugins({
|
||||
category: activePluginType,
|
||||
q: searchPluginText,
|
||||
tags: filterPluginTags,
|
||||
})
|
||||
return isSearchMode
|
||||
}
|
||||
|
||||
/**
|
||||
* The forced search mode lives in the app-wide Jotai store, so a "View More"
|
||||
* click would otherwise leak into the next visit of the plugin catalog after
|
||||
* navigating away (e.g. to /templates) and back, rendering empty-query search
|
||||
* results instead of the prefetched collections. Reset it when the catalog
|
||||
* route mounts; URL-owned state (q, tags, category) is not affected.
|
||||
*/
|
||||
export function useResetMarketplaceSearchModeOnMount() {
|
||||
const setSearchMode = useSetAtom(searchModeAtom)
|
||||
|
||||
useEffect(() => {
|
||||
setSearchMode(null)
|
||||
}, [setSearchMode])
|
||||
}
|
||||
|
||||
export function useMarketplaceMoreClick() {
|
||||
const [, setQ] = useSearchPluginText()
|
||||
const setSort = useSetAtom(marketplaceSortAtom)
|
||||
const setSearchMode = useSetAtom(searchModeAtom)
|
||||
|
||||
return useCallback(
|
||||
(searchParams?: SearchParamsFromCollection) => {
|
||||
if (!searchParams) return
|
||||
setQ(searchParams?.query || '')
|
||||
setSort({
|
||||
sortBy: searchParams?.sort_by || DEFAULT_SORT.sortBy,
|
||||
sortOrder: searchParams?.sort_order || DEFAULT_SORT.sortOrder,
|
||||
})
|
||||
setSearchMode(true)
|
||||
},
|
||||
[setQ, setSort, setSearchMode],
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { PluginCategoryEnum } from '../types'
|
||||
|
||||
export const DEFAULT_SORT = {
|
||||
sortBy: 'install_count',
|
||||
sortOrder: 'DESC',
|
||||
}
|
||||
|
||||
/**
|
||||
* DOM id of the marketplace scroll container. The route components render it
|
||||
* and the scroll/viewport observers below the marketplace tree look it up.
|
||||
*/
|
||||
export const MARKETPLACE_CONTAINER_ID = 'marketplace-container'
|
||||
|
||||
export const SCROLL_BOTTOM_THRESHOLD = 100
|
||||
|
||||
export const PLUGIN_TYPE_SEARCH_MAP = {
|
||||
all: 'all',
|
||||
model: PluginCategoryEnum.model,
|
||||
tool: PluginCategoryEnum.tool,
|
||||
agent: PluginCategoryEnum.agent,
|
||||
extension: PluginCategoryEnum.extension,
|
||||
datasource: PluginCategoryEnum.datasource,
|
||||
trigger: PluginCategoryEnum.trigger,
|
||||
bundle: 'bundle',
|
||||
} as const
|
||||
|
||||
type ValueOf<T> = T[keyof T]
|
||||
|
||||
export type ActivePluginType = ValueOf<typeof PLUGIN_TYPE_SEARCH_MAP>
|
||||
|
||||
export const PLUGIN_CATEGORY_WITH_COLLECTIONS = new Set<ActivePluginType>([
|
||||
PLUGIN_TYPE_SEARCH_MAP.all,
|
||||
PLUGIN_TYPE_SEARCH_MAP.tool,
|
||||
])
|
||||
@@ -0,0 +1,16 @@
|
||||
import { useSyncExternalStore } from 'react'
|
||||
import { getCreatorCenterUrl } from '@/features/marketplace/links'
|
||||
|
||||
const subscribe = () => () => {}
|
||||
|
||||
/**
|
||||
* Prefer the current page origin when this is the standalone Marketplace, so a
|
||||
* .dev deployment cannot inherit a baked-in .ai Creator Center URL.
|
||||
*/
|
||||
export const useCreatorCenterUrl = () => {
|
||||
return useSyncExternalStore(
|
||||
subscribe,
|
||||
() => getCreatorCenterUrl(window.location.origin),
|
||||
() => getCreatorCenterUrl(),
|
||||
)
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
import type { CreatorCreation } from '../model'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { describe, expect, it, vi } from 'vite-plus/test'
|
||||
import CreationCard from '../creation-card'
|
||||
|
||||
vi.mock('@/app/components/base/app-icon', () => ({
|
||||
default: () => <span data-testid="creation-icon" />,
|
||||
}))
|
||||
|
||||
const creation: CreatorCreation = {
|
||||
id: 'plugin:dify/search',
|
||||
kind: 'plugin',
|
||||
title: 'Search',
|
||||
description: 'Search the web.',
|
||||
target: { type: 'plugin', pluginType: 'plugin', org: 'dify', name: 'search' },
|
||||
icon: { type: 'emoji', value: '🔎' },
|
||||
dependencyIcons: ['/one.png', '/two.png'],
|
||||
dependencyCount: 4,
|
||||
updatedAt: 1,
|
||||
createdAt: 1,
|
||||
popularity: 1,
|
||||
}
|
||||
|
||||
describe('CreationCard', () => {
|
||||
it('renders a host link without selecting', () => {
|
||||
render(
|
||||
<CreationCard
|
||||
creation={creation}
|
||||
action={{ type: 'link', href: '/plugin/dify/search?language=en-US' }}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByRole('link', { name: 'Search' })).toHaveAttribute(
|
||||
'href',
|
||||
'/plugin/dify/search?language=en-US',
|
||||
)
|
||||
expect(screen.getByText('+2')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('selects in Dify without rendering a navigation target', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onSelect = vi.fn()
|
||||
render(<CreationCard creation={creation} action={{ type: 'select', onSelect }} />)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Search' }))
|
||||
expect(onSelect).toHaveBeenCalledOnce()
|
||||
expect(screen.queryByRole('link')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
import type { CreatorCreation } from '../model'
|
||||
import { screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { describe, expect, it, vi } from 'vite-plus/test'
|
||||
import { renderWithNuqs } from '@/test/nuqs-testing'
|
||||
import CreatorContent from '../creator-content'
|
||||
|
||||
const publisherMocks = vi.hoisted(() => ({
|
||||
fetchPublisherPluginPage: vi.fn(),
|
||||
fetchPublisherTemplatePage: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../publisher', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../publisher')>()
|
||||
return {
|
||||
...actual,
|
||||
fetchPublisherPluginPage: publisherMocks.fetchPublisherPluginPage,
|
||||
fetchPublisherTemplatePage: publisherMocks.fetchPublisherTemplatePage,
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('#i18n', async () => {
|
||||
const { withSelectorKey } = await import('@/test/i18n-mock')
|
||||
const translations: Record<string, string> = {
|
||||
'marketplace.creatorProfile.creations': 'Creations',
|
||||
'marketplace.creatorProfile.sortBy': 'Sort by',
|
||||
'marketplace.creatorProfile.sort.updatedAt': 'Recently updated',
|
||||
'marketplace.creatorProfile.sort.createdAt': 'Recently created',
|
||||
'marketplace.creatorProfile.sort.popularity': 'Most popular',
|
||||
'marketplace.creatorProfile.sort.asc': 'Sort ascending',
|
||||
'marketplace.creatorProfile.sort.desc': 'Sort descending',
|
||||
'marketplace.creatorProfile.type.plugin': 'Plugin',
|
||||
'marketplace.creatorProfile.type.template': 'Template',
|
||||
'marketplace.creatorProfile.loadMore': 'Load more',
|
||||
'marketplace.creatorProfile.loadMoreFailed': "Couldn't load more creations.",
|
||||
}
|
||||
|
||||
return {
|
||||
useTranslation: () => ({
|
||||
t: withSelectorKey((key: string) => translations[key] ?? key),
|
||||
}),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@/app/components/base/app-icon', () => ({
|
||||
default: () => <span aria-hidden />,
|
||||
}))
|
||||
|
||||
const createCreation = (
|
||||
id: string,
|
||||
title: string,
|
||||
updatedAt: number,
|
||||
createdAt: number,
|
||||
popularity: number,
|
||||
): CreatorCreation => ({
|
||||
id,
|
||||
kind: 'plugin',
|
||||
title,
|
||||
description: `${title} description`,
|
||||
target: { type: 'plugin', pluginType: 'plugin', org: 'dify', name: id },
|
||||
icon: { type: 'emoji', value: 'P' },
|
||||
dependencyIcons: [],
|
||||
dependencyCount: 0,
|
||||
updatedAt,
|
||||
createdAt,
|
||||
popularity,
|
||||
})
|
||||
|
||||
const creations = [
|
||||
createCreation('alpha', 'Alpha', 2, 3, 1),
|
||||
createCreation('bravo', 'Bravo', 3, 1, 2),
|
||||
createCreation('charlie', 'Charlie', 1, 2, 3),
|
||||
]
|
||||
|
||||
const cardNames = () => screen.getAllByRole('link').map((link) => link.getAttribute('aria-label'))
|
||||
|
||||
describe('CreatorContent', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('writes sort into the URL and reorders the current cards', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { onUrlUpdate } = renderWithNuqs(
|
||||
<CreatorContent
|
||||
creations={creations}
|
||||
getCreationAction={(creation) => ({ type: 'link', href: `/creation/${creation.id}` })}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(cardNames()).toEqual(['Bravo', 'Alpha', 'Charlie'])
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Sort by Recently updated' }))
|
||||
const recentlyUpdatedOption = screen.getByRole('menuitemradio', {
|
||||
name: 'Recently updated',
|
||||
})
|
||||
const mostPopularOption = screen.getByRole('menuitemradio', { name: 'Most popular' })
|
||||
expect(recentlyUpdatedOption).toHaveAttribute('aria-checked', 'true')
|
||||
expect(mostPopularOption).toHaveAttribute('aria-checked', 'false')
|
||||
|
||||
await user.click(mostPopularOption)
|
||||
await waitFor(() => {
|
||||
expect(cardNames()).toEqual(['Charlie', 'Bravo', 'Alpha'])
|
||||
expect(onUrlUpdate.mock.calls.at(-1)?.[0].searchParams.get('sort_by')).toBe('popularity')
|
||||
})
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Sort ascending' }))
|
||||
await waitFor(() => {
|
||||
expect(cardNames()).toEqual(['Alpha', 'Bravo', 'Charlie'])
|
||||
expect(onUrlUpdate.mock.calls.at(-1)?.[0].searchParams.get('sort_order')).toBe('asc')
|
||||
expect(onUrlUpdate.mock.calls.at(-1)?.[0].searchParams.get('sort_by')).toBe('popularity')
|
||||
})
|
||||
})
|
||||
|
||||
it('loads the next publisher pages when more creations exist', async () => {
|
||||
const user = userEvent.setup()
|
||||
publisherMocks.fetchPublisherPluginPage.mockResolvedValue({
|
||||
items: [
|
||||
{
|
||||
type: 'plugin',
|
||||
org: 'dify',
|
||||
name: 'delta',
|
||||
labels: { 'en-US': 'Delta' },
|
||||
brief: { 'en-US': 'Delta plugin' },
|
||||
install_count: 4,
|
||||
created_at: '2026-01-04T00:00:00Z',
|
||||
updated_at: '2026-02-04T00:00:00Z',
|
||||
},
|
||||
],
|
||||
hasMore: false,
|
||||
})
|
||||
publisherMocks.fetchPublisherTemplatePage.mockResolvedValue({ items: [], hasMore: false })
|
||||
|
||||
renderWithNuqs(
|
||||
<CreatorContent
|
||||
creations={creations}
|
||||
locale="en-US"
|
||||
inventory={{
|
||||
uniqueHandle: 'scarlettmao',
|
||||
pluginHasMore: true,
|
||||
templateHasMore: false,
|
||||
pluginNextPage: 2,
|
||||
templateNextPage: 2,
|
||||
}}
|
||||
getCreationAction={(creation) => ({ type: 'link', href: `/creation/${creation.id}` })}
|
||||
/>,
|
||||
)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Load more' }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(cardNames()).toContain('Delta')
|
||||
})
|
||||
expect(publisherMocks.fetchPublisherPluginPage).toHaveBeenCalledWith({
|
||||
uniqueHandle: 'scarlettmao',
|
||||
page: 2,
|
||||
sortField: 'updatedAt',
|
||||
sortOrder: 'desc',
|
||||
})
|
||||
expect(publisherMocks.fetchPublisherTemplatePage).not.toHaveBeenCalled()
|
||||
expect(screen.queryByRole('button', { name: 'Load more' })).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
+279
@@ -0,0 +1,279 @@
|
||||
import type { MarketplacePlugin, MarketplaceTemplate } from '@dify/contracts/marketplace'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
|
||||
import { loadCreatorProfile } from '../data.server'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
creatorDetail: vi.fn(),
|
||||
organizationDetail: vi.fn(),
|
||||
publisherPlugins: vi.fn(),
|
||||
publisherTemplates: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
vi.mock('@/env', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/env')>()
|
||||
return {
|
||||
...actual,
|
||||
env: {
|
||||
...actual.env,
|
||||
NEXT_PUBLIC_MARKETPLACE_API_PREFIX: 'https://marketplace.example/api/v1',
|
||||
},
|
||||
}
|
||||
})
|
||||
vi.mock('@/service/marketplace', () => ({ marketplaceClient: mocks }))
|
||||
|
||||
const plugin = {
|
||||
type: 'plugin',
|
||||
org: 'dify',
|
||||
name: 'search',
|
||||
plugin_id: 'dify/search',
|
||||
label: { en_US: 'Search' },
|
||||
brief: { en_US: 'Search the web.' },
|
||||
tags: [],
|
||||
} as unknown as MarketplacePlugin
|
||||
|
||||
const template = {
|
||||
id: 'template-one',
|
||||
template_name: 'Template one',
|
||||
overview: 'Build an app.',
|
||||
icon: '📄',
|
||||
icon_background: '#fff',
|
||||
icon_file_key: '',
|
||||
usage_count: 1,
|
||||
categories: [],
|
||||
} as MarketplaceTemplate
|
||||
|
||||
describe('loadCreatorProfile', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.creatorDetail.mockResolvedValue({
|
||||
data: {
|
||||
creator: {
|
||||
unique_handle: 'creator',
|
||||
display_name: 'Creator',
|
||||
social_links: [],
|
||||
},
|
||||
},
|
||||
})
|
||||
mocks.organizationDetail.mockResolvedValue({ data: {} })
|
||||
mocks.publisherPlugins.mockResolvedValue({ data: { plugins: [plugin] } })
|
||||
mocks.publisherTemplates.mockResolvedValue({ data: { templates: [template] } })
|
||||
})
|
||||
|
||||
it('loads individual data through all publisher contracts', async () => {
|
||||
const loaded = await loadCreatorProfile({
|
||||
uniqueHandle: 'evanz',
|
||||
locale: 'en-US',
|
||||
})
|
||||
|
||||
expect(mocks.creatorDetail).toHaveBeenCalledWith({
|
||||
params: { uniqueHandle: 'evanz' },
|
||||
})
|
||||
expect(mocks.publisherPlugins).toHaveBeenCalledWith({
|
||||
params: { uniqueHandle: 'evanz' },
|
||||
query: { page: 1, page_size: 40, sort_by: 'version_updated_at', sort_order: 'DESC' },
|
||||
})
|
||||
expect(mocks.publisherTemplates).toHaveBeenCalledWith({
|
||||
params: { uniqueHandle: 'evanz' },
|
||||
query: { page: 1, page_size: 40, sort_by: 'updated_at', sort_order: 'DESC' },
|
||||
})
|
||||
expect(loaded?.viewModel.creations).toHaveLength(2)
|
||||
expect(loaded?.pluginsByCreationId['plugin:dify/search']).toBeDefined()
|
||||
expect(loaded?.viewModel.profile.backgroundUrl).toBe('')
|
||||
expect(loaded?.viewModel.profile.avatarUrl).toBe('')
|
||||
})
|
||||
|
||||
it('only emits the remote background URL when the API reports an uploaded background', async () => {
|
||||
mocks.creatorDetail.mockResolvedValue({
|
||||
data: {
|
||||
creator: {
|
||||
unique_handle: 'creator-with-background',
|
||||
display_name: 'Creator with background',
|
||||
background_image: 'creator/background.png',
|
||||
social_links: [],
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const loaded = await loadCreatorProfile({
|
||||
uniqueHandle: 'creator-with-background',
|
||||
locale: 'en-US',
|
||||
})
|
||||
|
||||
expect(loaded?.viewModel.profile.backgroundUrl).toBe(
|
||||
'https://marketplace.example/api/v1/creators/creator-with-background/background-image',
|
||||
)
|
||||
})
|
||||
|
||||
it('only emits the remote avatar URL when the API reports an uploaded avatar', async () => {
|
||||
mocks.creatorDetail.mockResolvedValue({
|
||||
data: {
|
||||
creator: {
|
||||
unique_handle: 'creator-with-avatar',
|
||||
display_name: 'Creator with avatar',
|
||||
avatar: 'creator/avatar.png',
|
||||
social_links: [],
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const loaded = await loadCreatorProfile({
|
||||
uniqueHandle: 'creator-with-avatar',
|
||||
locale: 'en-US',
|
||||
})
|
||||
|
||||
expect(loaded?.viewModel.profile.avatarUrl).toBe(
|
||||
'https://marketplace.example/api/v1/creators/creator-with-avatar/avatar',
|
||||
)
|
||||
})
|
||||
|
||||
it('forwards popularity sort to each publisher API column', async () => {
|
||||
await loadCreatorProfile({
|
||||
uniqueHandle: 'creator-one',
|
||||
locale: 'en-US',
|
||||
sortBy: 'popularity',
|
||||
sortOrder: 'asc',
|
||||
})
|
||||
|
||||
expect(mocks.publisherPlugins).toHaveBeenCalledWith({
|
||||
params: { uniqueHandle: 'creator-one' },
|
||||
query: { page: 1, page_size: 40, sort_by: 'install_count', sort_order: 'ASC' },
|
||||
})
|
||||
expect(mocks.publisherTemplates).toHaveBeenCalledWith({
|
||||
params: { uniqueHandle: 'creator-one' },
|
||||
query: { page: 1, page_size: 40, sort_by: 'usage_count', sort_order: 'ASC' },
|
||||
})
|
||||
})
|
||||
|
||||
it('merge-sorts mixed creations after the publisher responses return', async () => {
|
||||
mocks.publisherPlugins.mockResolvedValue({
|
||||
data: {
|
||||
plugins: [{ ...plugin, install_count: 2, created_at: '2026-01-01T00:00:00Z' }],
|
||||
},
|
||||
})
|
||||
mocks.publisherTemplates.mockResolvedValue({
|
||||
data: {
|
||||
templates: [{ ...template, usage_count: 5, created_at: '2026-01-02T00:00:00Z' }],
|
||||
},
|
||||
})
|
||||
|
||||
const loaded = await loadCreatorProfile({
|
||||
uniqueHandle: 'creator-one',
|
||||
locale: 'en-US',
|
||||
sortBy: 'popularity',
|
||||
sortOrder: 'desc',
|
||||
})
|
||||
|
||||
expect(loaded?.viewModel.creations.map(({ kind }) => kind)).toEqual(['template', 'plugin'])
|
||||
})
|
||||
|
||||
it('loads only the first publisher page and reports remaining inventory', async () => {
|
||||
mocks.publisherPlugins.mockResolvedValue({
|
||||
data: {
|
||||
plugins: Array.from({ length: 40 }, (_, index) => ({ ...plugin, name: `p-${index}` })),
|
||||
total: 90,
|
||||
},
|
||||
})
|
||||
mocks.publisherTemplates.mockResolvedValue({
|
||||
data: { templates: [template], total: 1 },
|
||||
})
|
||||
|
||||
const loaded = await loadCreatorProfile({
|
||||
uniqueHandle: 'paged-creator',
|
||||
locale: 'en-US',
|
||||
})
|
||||
|
||||
expect(mocks.publisherPlugins).toHaveBeenCalledOnce()
|
||||
expect(mocks.publisherPlugins).toHaveBeenCalledWith({
|
||||
params: { uniqueHandle: 'paged-creator' },
|
||||
query: { page: 1, page_size: 40, sort_by: 'version_updated_at', sort_order: 'DESC' },
|
||||
})
|
||||
expect(loaded?.inventory).toMatchObject({
|
||||
uniqueHandle: 'paged-creator',
|
||||
pluginHasMore: true,
|
||||
templateHasMore: false,
|
||||
pluginNextPage: 2,
|
||||
})
|
||||
expect(loaded?.viewModel.creations).toHaveLength(41)
|
||||
})
|
||||
|
||||
it('does not treat a full first page as the complete inventory when total is missing', async () => {
|
||||
mocks.publisherPlugins.mockResolvedValue({
|
||||
data: {
|
||||
plugins: Array.from({ length: 40 }, (_, index) => ({ ...plugin, name: `p-${index}` })),
|
||||
},
|
||||
})
|
||||
|
||||
const loaded = await loadCreatorProfile({
|
||||
uniqueHandle: 'uncounted-creator',
|
||||
locale: 'en-US',
|
||||
})
|
||||
|
||||
expect(mocks.publisherPlugins).toHaveBeenCalledOnce()
|
||||
expect(loaded?.inventory.pluginHasMore).toBe(true)
|
||||
})
|
||||
|
||||
it('keeps successful creations when one publisher request fails', async () => {
|
||||
mocks.publisherPlugins.mockRejectedValue(new Error('plugin request failed'))
|
||||
|
||||
const loaded = await loadCreatorProfile({
|
||||
uniqueHandle: 'creator-partial',
|
||||
locale: 'en-US',
|
||||
})
|
||||
|
||||
expect(loaded?.viewModel.creations.map(({ kind }) => kind)).toEqual(['template'])
|
||||
})
|
||||
|
||||
it('returns null when the primary creator does not exist', async () => {
|
||||
mocks.creatorDetail.mockResolvedValue({ data: {} })
|
||||
|
||||
await expect(
|
||||
loadCreatorProfile({ uniqueHandle: 'missing-creator', locale: 'en-US' }),
|
||||
).resolves.toBeNull()
|
||||
})
|
||||
|
||||
it('rethrows when the primary creator request fails', async () => {
|
||||
mocks.creatorDetail.mockRejectedValue(new Error('creator request timed out'))
|
||||
|
||||
await expect(
|
||||
loadCreatorProfile({ uniqueHandle: 'slow-creator', locale: 'en-US' }),
|
||||
).rejects.toThrow('creator request timed out')
|
||||
})
|
||||
|
||||
it('rethrows when the organization request fails', async () => {
|
||||
mocks.organizationDetail.mockRejectedValue(new Error('organization request timed out'))
|
||||
|
||||
await expect(
|
||||
loadCreatorProfile({
|
||||
uniqueHandle: 'slow-org',
|
||||
publisherType: 'organization',
|
||||
locale: 'en-US',
|
||||
}),
|
||||
).rejects.toThrow('organization request timed out')
|
||||
})
|
||||
|
||||
it('maps organizations to the shared creator profile shape', async () => {
|
||||
mocks.organizationDetail.mockResolvedValue({
|
||||
data: {
|
||||
organization: {
|
||||
id: 'org-id',
|
||||
unique_handle: 'dify-org',
|
||||
display_name: 'Dify Org',
|
||||
social_links: [],
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const loaded = await loadCreatorProfile({
|
||||
uniqueHandle: 'dify-org',
|
||||
publisherType: 'organization',
|
||||
locale: 'en-US',
|
||||
})
|
||||
|
||||
expect(mocks.organizationDetail).toHaveBeenCalledWith({ params: { id: 'dify-org' } })
|
||||
expect(loaded?.viewModel.profile).toMatchObject({
|
||||
kind: 'organization',
|
||||
displayName: 'Dify Org',
|
||||
})
|
||||
})
|
||||
})
|
||||
+292
@@ -0,0 +1,292 @@
|
||||
import type { MarketplaceTemplate } from '@dify/contracts/marketplace'
|
||||
import type { ReactElement } from 'react'
|
||||
import type { LoadedCreatorProfile } from '../model'
|
||||
import type { Plugin } from '@/app/components/plugins/types'
|
||||
import { fireEvent, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
|
||||
import { renderWithConsoleQuery } from '@/test/console/query-data'
|
||||
import { createNuqsTestWrapper } from '@/test/nuqs-testing'
|
||||
import DifyCreatorProfile from '../dify-profile'
|
||||
|
||||
const deploymentState = vi.hoisted(() => ({
|
||||
deploymentEdition: 'CLOUD' as 'CLOUD' | 'COMMUNITY' | 'ENTERPRISE',
|
||||
}))
|
||||
|
||||
vi.mock('@/features/system-features/state', async () => {
|
||||
const { createSystemFeaturesStateModuleMock } = await import('@/test/console/state-fixture')
|
||||
return createSystemFeaturesStateModuleMock(() => deploymentState)
|
||||
})
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
push: vi.fn(),
|
||||
searchPlugins: vi.fn(),
|
||||
searchTemplates: vi.fn(),
|
||||
installedInfo: { 'dify/deep_research': { version: '0.0.1' } },
|
||||
}))
|
||||
|
||||
const deepResearchPlugin = {
|
||||
type: 'plugin',
|
||||
org: 'dify',
|
||||
name: 'deep_research',
|
||||
plugin_id: 'dify/deep_research',
|
||||
latest_package_identifier: 'dify/deep_research:0.0.1@test',
|
||||
label: { 'en-US': 'Deep Research' },
|
||||
brief: { 'en-US': 'Research the web.' },
|
||||
} as unknown as Plugin
|
||||
|
||||
const searchPlugin = {
|
||||
...deepResearchPlugin,
|
||||
name: 'search_result',
|
||||
plugin_id: 'dify/search_result',
|
||||
latest_package_identifier: 'dify/search_result:0.0.1@test',
|
||||
label: { 'en-US': 'Search result' },
|
||||
} as Plugin
|
||||
|
||||
const template: MarketplaceTemplate = {
|
||||
id: 'template-one',
|
||||
template_name: 'Research Template',
|
||||
overview: 'Build a research app.',
|
||||
icon: 'R',
|
||||
icon_background: '#fff',
|
||||
icon_file_key: '',
|
||||
publisher_unique_handle: 'dify',
|
||||
usage_count: 1,
|
||||
categories: [],
|
||||
}
|
||||
|
||||
const loadedProfile: LoadedCreatorProfile = {
|
||||
viewModel: {
|
||||
profile: {
|
||||
kind: 'individual',
|
||||
displayName: 'Creator',
|
||||
handle: 'creator',
|
||||
avatarUrl: '',
|
||||
backgroundUrl: '',
|
||||
badges: [],
|
||||
socialLinks: [],
|
||||
},
|
||||
creations: [
|
||||
{
|
||||
id: 'plugin:dify/deep_research',
|
||||
kind: 'plugin',
|
||||
title: 'Deep Research',
|
||||
description: 'Research the web.',
|
||||
target: {
|
||||
type: 'plugin',
|
||||
pluginType: 'plugin',
|
||||
org: 'dify',
|
||||
name: 'deep_research',
|
||||
},
|
||||
icon: { type: 'emoji', value: 'R' },
|
||||
dependencyIcons: [],
|
||||
dependencyCount: 0,
|
||||
updatedAt: 1,
|
||||
createdAt: 1,
|
||||
popularity: 1,
|
||||
},
|
||||
{
|
||||
id: 'template:template-one',
|
||||
kind: 'template',
|
||||
title: 'Research Template',
|
||||
description: 'Build a research app.',
|
||||
target: {
|
||||
type: 'template',
|
||||
id: 'template-one',
|
||||
publisher: 'dify',
|
||||
templateName: 'Research Template',
|
||||
},
|
||||
icon: { type: 'emoji', value: 'R' },
|
||||
dependencyIcons: [],
|
||||
dependencyCount: 0,
|
||||
updatedAt: 1,
|
||||
createdAt: 1,
|
||||
popularity: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
pluginsByCreationId: {
|
||||
'plugin:dify/deep_research': deepResearchPlugin,
|
||||
},
|
||||
templatesByCreationId: {
|
||||
'template:template-one': template,
|
||||
},
|
||||
inventory: {
|
||||
uniqueHandle: 'creator',
|
||||
pluginHasMore: false,
|
||||
templateHasMore: false,
|
||||
pluginNextPage: 2,
|
||||
templateNextPage: 2,
|
||||
},
|
||||
}
|
||||
|
||||
vi.mock('#i18n', async () => {
|
||||
const { withSelectorKey } = await import('@/test/i18n-mock')
|
||||
return {
|
||||
useLocale: () => 'en-US',
|
||||
useTranslation: () => ({
|
||||
t: withSelectorKey((key: string) => key),
|
||||
}),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@/next/navigation', () => ({
|
||||
useRouter: () => ({ push: mocks.push }),
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/base/app-icon', () => ({
|
||||
default: () => <span aria-hidden />,
|
||||
}))
|
||||
|
||||
vi.mock('@/app/components/plugins/install-plugin/hooks/use-check-installed', () => ({
|
||||
default: () => ({ installedInfo: mocks.installedInfo }),
|
||||
}))
|
||||
|
||||
vi.mock('../../detail-dialog/use-silent-install', () => ({
|
||||
useSilentMarketplaceInstall: () => ({ install: vi.fn() }),
|
||||
}))
|
||||
// Exercise real dialog/frame message handling without loading external documents.
|
||||
vi.mock('@/features/marketplace/links', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/features/marketplace/links')>()
|
||||
const toBlank = (url: string) =>
|
||||
`about:blank${new URL(url, 'https://marketplace.example.test').search}`
|
||||
return {
|
||||
...actual,
|
||||
marketplaceLinks: {
|
||||
...actual.marketplaceLinks,
|
||||
plugin: (...args: Parameters<typeof actual.marketplaceLinks.plugin>) =>
|
||||
toBlank(actual.marketplaceLinks.plugin(...args)),
|
||||
template: (...args: Parameters<typeof actual.marketplaceLinks.template>) =>
|
||||
toBlank(actual.marketplaceLinks.template(...args)),
|
||||
},
|
||||
}
|
||||
})
|
||||
vi.mock('@/service/marketplace', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/service/marketplace')>()
|
||||
return {
|
||||
...actual,
|
||||
marketplaceQuery: {
|
||||
...actual.marketplaceQuery,
|
||||
searchAdvanced: {
|
||||
...actual.marketplaceQuery.searchAdvanced,
|
||||
queryOptions: (
|
||||
options: Parameters<typeof actual.marketplaceQuery.searchAdvanced.queryOptions>[0],
|
||||
) => ({
|
||||
...actual.marketplaceQuery.searchAdvanced.queryOptions(options),
|
||||
queryFn: () => mocks.searchPlugins(),
|
||||
}),
|
||||
},
|
||||
templateSearch: {
|
||||
...actual.marketplaceQuery.templateSearch,
|
||||
queryOptions: (
|
||||
options: Parameters<typeof actual.marketplaceQuery.templateSearch.queryOptions>[0],
|
||||
) => ({
|
||||
...actual.marketplaceQuery.templateSearch.queryOptions(options),
|
||||
queryFn: () => mocks.searchTemplates(),
|
||||
}),
|
||||
},
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
const renderWithNuqs = (element: ReactElement) => {
|
||||
const { wrapper: UrlState, onUrlUpdate } = createNuqsTestWrapper()
|
||||
const result = renderWithConsoleQuery(<UrlState>{element}</UrlState>)
|
||||
return { ...result, onUrlUpdate }
|
||||
}
|
||||
const searchInput = () =>
|
||||
screen.getByPlaceholderText('marketplace.creatorProfile.searchPlaceholder')
|
||||
|
||||
describe('DifyCreatorProfile', () => {
|
||||
beforeEach(() => {
|
||||
deploymentState.deploymentEdition = 'CLOUD'
|
||||
vi.clearAllMocks()
|
||||
mocks.searchPlugins.mockResolvedValue({ data: { plugins: [searchPlugin], total: 1 } })
|
||||
mocks.searchTemplates.mockResolvedValue({ data: { templates: [template], total: 1 } })
|
||||
})
|
||||
|
||||
it('opens the existing plugin detail flow with installed state', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderWithNuqs(<DifyCreatorProfile loadedProfile={loadedProfile} locale="en-US" />)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Deep Research' }))
|
||||
|
||||
await screen.findByRole('dialog', { name: /Deep Research/ })
|
||||
const src = screen.getByTitle(/^Deep Research/).getAttribute('src')!
|
||||
expect(new URL(src).searchParams.get('installed')).toBe('true')
|
||||
})
|
||||
|
||||
it('opens a template detail and imports it inside Dify', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderWithNuqs(<DifyCreatorProfile loadedProfile={loadedProfile} locale="en-US" />)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Research Template' }))
|
||||
await screen.findByRole('dialog', { name: /Research Template/ })
|
||||
const frame = screen.getByTitle(/^Research Template/) as HTMLIFrameElement
|
||||
fireEvent(
|
||||
window,
|
||||
new MessageEvent('message', {
|
||||
data: { type: 'dify-marketplace:install-template', templateId: 'template-one' },
|
||||
origin: 'null',
|
||||
source: frame.contentWindow,
|
||||
}),
|
||||
)
|
||||
expect(mocks.push).toHaveBeenCalledExactlyOnceWith('/apps?template-id=template-one')
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
|
||||
})
|
||||
|
||||
it('opens search results in the same plugin dialog controller', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderWithNuqs(<DifyCreatorProfile loadedProfile={loadedProfile} locale="en-US" />)
|
||||
|
||||
await user.type(searchInput(), 'search')
|
||||
await user.click(await screen.findByRole('option', { name: /Search result/ }))
|
||||
|
||||
await screen.findByRole('dialog', { name: /Search result/ })
|
||||
const src = screen.getByTitle(/^Search result/).getAttribute('src')!
|
||||
expect(new URL(src).searchParams.get('installed')).toBe('false')
|
||||
})
|
||||
it.each(['COMMUNITY', 'ENTERPRISE'] as const)(
|
||||
'links %s creator inventory to official details',
|
||||
(edition) => {
|
||||
deploymentState.deploymentEdition = edition
|
||||
renderWithNuqs(<DifyCreatorProfile loadedProfile={loadedProfile} locale="en-US" />)
|
||||
for (const name of ['Deep Research', 'Research Template']) {
|
||||
const link = screen.getByRole('link', { name })
|
||||
const url = new URL(link.getAttribute('href')!)
|
||||
expect(url.origin).toBe('https://marketplace.dify.ai')
|
||||
expect(url.searchParams.get('source')).toBe(window.location.origin)
|
||||
expect(link).toHaveAttribute('target', '_blank')
|
||||
expect(link).toHaveAttribute('rel', 'noopener noreferrer')
|
||||
}
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
|
||||
},
|
||||
)
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it.each(['COMMUNITY', 'ENTERPRISE'] as const)(
|
||||
'opens %s creator search results externally',
|
||||
async (edition) => {
|
||||
deploymentState.deploymentEdition = edition
|
||||
const open = vi.spyOn(window, 'open').mockReturnValue(null)
|
||||
const user = userEvent.setup()
|
||||
const { onUrlUpdate } = renderWithNuqs(
|
||||
<DifyCreatorProfile loadedProfile={loadedProfile} locale="en-US" />,
|
||||
)
|
||||
await user.type(searchInput(), 'search')
|
||||
await user.click(await screen.findByRole('option', { name: /Search result/ }))
|
||||
expect(open).toHaveBeenCalledTimes(1)
|
||||
expect(new URL(String(open.mock.calls[0]![0])).pathname).toBe('/plugin/dify/search_result')
|
||||
await user.clear(searchInput())
|
||||
await user.type(searchInput(), 'template')
|
||||
await user.click(await screen.findByRole('option', { name: /Research Template/ }))
|
||||
expect(open).toHaveBeenCalledTimes(2)
|
||||
expect(new URL(String(open.mock.calls[1]![0])).pathname).toBe('/template/dify/template-one')
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
|
||||
expect(onUrlUpdate).not.toHaveBeenCalled()
|
||||
},
|
||||
)
|
||||
})
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { describe, expect, it, vi } from 'vite-plus/test'
|
||||
import CreatorProfileHeader from '../header'
|
||||
|
||||
vi.mock('#i18n', async () => {
|
||||
const { withSelectorKey } = await import('@/test/i18n-mock')
|
||||
const translations: Record<string, string> = {
|
||||
'marketplace.home.plugins': 'Plugins',
|
||||
'marketplace.home.templates': 'Templates',
|
||||
'marketplace.creatorProfile.searchPlaceholder': 'Search plugins or templates',
|
||||
'mainNav.marketplace': 'Marketplace',
|
||||
}
|
||||
|
||||
return {
|
||||
useTranslation: () => ({
|
||||
t: withSelectorKey((key: string) => translations[key] ?? key),
|
||||
}),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../../home/home-guide', () => ({
|
||||
default: () => <div data-testid="marketplace-guide" />,
|
||||
}))
|
||||
|
||||
vi.mock('../../home/marketplace-search-autocomplete', () => ({
|
||||
MarketplaceSearchAutocomplete: () => <div data-testid="marketplace-search" />,
|
||||
}))
|
||||
|
||||
describe('CreatorProfileHeader', () => {
|
||||
it('returns to the native Marketplace without marking a catalog tab active', () => {
|
||||
render(<CreatorProfileHeader locale="en-US" onSuggestionSelect={vi.fn()} />)
|
||||
|
||||
const pluginsLink = screen.getByRole('link', { name: 'Plugins' })
|
||||
const templatesLink = screen.getByRole('link', { name: 'Templates' })
|
||||
|
||||
expect(pluginsLink).toHaveAttribute('href', '/marketplace')
|
||||
expect(pluginsLink).not.toHaveAttribute('aria-current')
|
||||
expect(templatesLink).not.toHaveAttribute('aria-current')
|
||||
})
|
||||
})
|
||||
+229
@@ -0,0 +1,229 @@
|
||||
import type {
|
||||
MarketplaceCreator,
|
||||
MarketplacePlugin,
|
||||
MarketplaceTemplate,
|
||||
} from '@dify/contracts/marketplace'
|
||||
import { describe, expect, it } from 'vite-plus/test'
|
||||
import {
|
||||
adaptCreations,
|
||||
adaptCreatorProfile,
|
||||
getStandaloneCreationHref,
|
||||
normalizeCreatorSocialLink,
|
||||
parseCreatorSortField,
|
||||
parseCreatorSortOrder,
|
||||
sortCreatorCreations,
|
||||
toPublisherSortQuery,
|
||||
} from '../model'
|
||||
|
||||
const creator: MarketplaceCreator = {
|
||||
unique_handle: 'evanz',
|
||||
display_name: 'Evan.Z',
|
||||
social_links: ['github.com/evanz', 'javascript:alert(1)'],
|
||||
badges: ['partner'],
|
||||
verified: true,
|
||||
}
|
||||
|
||||
const plugin = {
|
||||
type: 'bundle',
|
||||
org: 'dify',
|
||||
name: 'research',
|
||||
labels: { en_US: 'Research bundle' },
|
||||
description: { en_US: 'Research reliably.' },
|
||||
install_count: 20,
|
||||
created_at: '2026-01-01T00:00:00Z',
|
||||
updated_at: '2026-02-01T00:00:00Z',
|
||||
} as unknown as MarketplacePlugin
|
||||
|
||||
const template = {
|
||||
id: 'template/one',
|
||||
template_name: 'Research template',
|
||||
overview: 'Start a research app.',
|
||||
icon: '📄',
|
||||
icon_background: '#fff',
|
||||
icon_file_key: '',
|
||||
publisher_unique_handle: 'dify',
|
||||
publisher_handle: 'Dify Display Name',
|
||||
usage_count: 10,
|
||||
categories: [],
|
||||
deps_plugins: ['dify/search'],
|
||||
created_at: '2026-01-02T00:00:00Z',
|
||||
updated_at: '2026-02-02T00:00:00Z',
|
||||
} as MarketplaceTemplate
|
||||
|
||||
describe('creator profile model', () => {
|
||||
it('normalizes DTOs into host-neutral creation targets and safe social links', () => {
|
||||
const viewModel = adaptCreatorProfile({
|
||||
creator,
|
||||
kind: 'organization',
|
||||
locale: 'en-US',
|
||||
avatarUrl: '/avatar',
|
||||
backgroundUrl: '/background',
|
||||
plugins: [plugin],
|
||||
templates: [template],
|
||||
resolvePluginIcon: () => '/plugin-icon',
|
||||
resolveTemplateIcon: () => '',
|
||||
resolveDependencyIcon: (id) => `/dependency/${id}`,
|
||||
})
|
||||
|
||||
expect(viewModel.profile.badges).toEqual(['partner', 'verified'])
|
||||
expect(viewModel.profile.socialLinks).toEqual([
|
||||
expect.objectContaining({ platform: 'github', href: 'https://github.com/evanz' }),
|
||||
])
|
||||
expect(viewModel.creations[0]).toMatchObject({
|
||||
title: 'Research bundle',
|
||||
target: { type: 'plugin', pluginType: 'bundle', org: 'dify', name: 'research' },
|
||||
})
|
||||
expect(viewModel.creations[1]).toMatchObject({
|
||||
target: {
|
||||
type: 'template',
|
||||
id: 'template/one',
|
||||
publisher: 'dify',
|
||||
templateName: 'Research template',
|
||||
},
|
||||
dependencyCount: 1,
|
||||
})
|
||||
})
|
||||
|
||||
it('builds standalone plugin, bundle, and template URLs outside the shared model', () => {
|
||||
const viewModel = adaptCreatorProfile({
|
||||
creator,
|
||||
kind: 'individual',
|
||||
locale: 'en-US',
|
||||
avatarUrl: '',
|
||||
backgroundUrl: '',
|
||||
plugins: [plugin],
|
||||
templates: [template],
|
||||
resolvePluginIcon: () => '',
|
||||
resolveTemplateIcon: () => '',
|
||||
resolveDependencyIcon: () => '',
|
||||
})
|
||||
|
||||
expect(getStandaloneCreationHref(viewModel.creations[0]!, 'zh-Hans')).toBe(
|
||||
'/bundles/dify/research?language=zh-Hans',
|
||||
)
|
||||
expect(getStandaloneCreationHref(viewModel.creations[1]!, 'zh-Hans')).toBe(
|
||||
'/template/dify/template%2Fone?language=zh-Hans',
|
||||
)
|
||||
expect(getStandaloneCreationHref(viewModel.creations[1]!)).toBe('/template/dify/template%2Fone')
|
||||
})
|
||||
|
||||
it('uses stable template links for publisher handle fallbacks without exposing creator email', () => {
|
||||
const creations = adaptCreations({
|
||||
locale: 'en-US',
|
||||
plugins: [],
|
||||
templates: [
|
||||
{ ...template, publisher_unique_handle: '', publisher_handle: '研究 / Team' },
|
||||
{
|
||||
...template,
|
||||
publisher_unique_handle: '',
|
||||
publisher_handle: '',
|
||||
creator_email: 'private@example.com',
|
||||
},
|
||||
{ ...template, template_name: 'Renamed research template' },
|
||||
],
|
||||
resolvePluginIcon: () => '',
|
||||
resolveTemplateIcon: () => '',
|
||||
resolveDependencyIcon: () => '',
|
||||
})
|
||||
|
||||
expect(creations.map((creation) => getStandaloneCreationHref(creation))).toEqual([
|
||||
'/template/%E7%A0%94%E7%A9%B6%20%2F%20Team/template%2Fone',
|
||||
'/template/template/template%2Fone',
|
||||
'/template/dify/template%2Fone',
|
||||
])
|
||||
})
|
||||
|
||||
it('normalizes Unix-second, Unix-millisecond, and ISO timestamps', () => {
|
||||
const unixSeconds = 1_767_225_600
|
||||
const unixMilliseconds = 1_767_225_700_000
|
||||
const viewModel = adaptCreatorProfile({
|
||||
creator,
|
||||
kind: 'individual',
|
||||
locale: 'en-US',
|
||||
avatarUrl: '',
|
||||
backgroundUrl: '',
|
||||
plugins: [
|
||||
{
|
||||
...plugin,
|
||||
created_at: unixSeconds,
|
||||
version_updated_at: unixSeconds + 100,
|
||||
},
|
||||
],
|
||||
templates: [
|
||||
{
|
||||
...template,
|
||||
created_at: '2026-01-02T00:00:00Z',
|
||||
updated_at: unixMilliseconds,
|
||||
},
|
||||
],
|
||||
resolvePluginIcon: () => '',
|
||||
resolveTemplateIcon: () => '',
|
||||
resolveDependencyIcon: () => '',
|
||||
})
|
||||
|
||||
expect(viewModel.creations[0]).toMatchObject({
|
||||
createdAt: unixSeconds * 1000,
|
||||
updatedAt: (unixSeconds + 100) * 1000,
|
||||
})
|
||||
expect(viewModel.creations[1]).toMatchObject({
|
||||
createdAt: Date.parse('2026-01-02T00:00:00Z'),
|
||||
updatedAt: unixMilliseconds,
|
||||
})
|
||||
})
|
||||
|
||||
it('maps each UI sort onto the matching plugin and template API columns', () => {
|
||||
expect(toPublisherSortQuery('updatedAt', 'desc')).toEqual({
|
||||
plugins: { sort_by: 'version_updated_at', sort_order: 'DESC' },
|
||||
templates: { sort_by: 'updated_at', sort_order: 'DESC' },
|
||||
})
|
||||
expect(toPublisherSortQuery('createdAt', 'asc')).toEqual({
|
||||
plugins: { sort_by: 'created_at', sort_order: 'ASC' },
|
||||
templates: { sort_by: 'created_at', sort_order: 'ASC' },
|
||||
})
|
||||
expect(toPublisherSortQuery('popularity', 'desc')).toEqual({
|
||||
plugins: { sort_by: 'install_count', sort_order: 'DESC' },
|
||||
templates: { sort_by: 'usage_count', sort_order: 'DESC' },
|
||||
})
|
||||
})
|
||||
|
||||
it('falls back to recently updated descending for unknown URL sort values', () => {
|
||||
expect(parseCreatorSortField('garbage')).toBe('updatedAt')
|
||||
expect(parseCreatorSortField(undefined)).toBe('updatedAt')
|
||||
expect(parseCreatorSortOrder('sideways')).toBe('desc')
|
||||
expect(parseCreatorSortOrder('ASC')).toBe('asc')
|
||||
})
|
||||
|
||||
it('sorts update time, creation time and popularity while preserving equal-value order', () => {
|
||||
const creations = [
|
||||
{ id: 'first', updatedAt: 1, createdAt: 3, popularity: 2 },
|
||||
{ id: 'second', updatedAt: 1, createdAt: 2, popularity: 3 },
|
||||
{ id: 'third', updatedAt: 2, createdAt: 1, popularity: 1 },
|
||||
] as ReturnType<typeof adaptCreatorProfile>['creations']
|
||||
|
||||
expect(sortCreatorCreations(creations, 'updatedAt', 'asc').map(({ id }) => id)).toEqual([
|
||||
'first',
|
||||
'second',
|
||||
'third',
|
||||
])
|
||||
expect(sortCreatorCreations(creations, 'createdAt', 'desc').map(({ id }) => id)).toEqual([
|
||||
'first',
|
||||
'second',
|
||||
'third',
|
||||
])
|
||||
expect(sortCreatorCreations(creations, 'popularity', 'desc').map(({ id }) => id)).toEqual([
|
||||
'second',
|
||||
'first',
|
||||
'third',
|
||||
])
|
||||
})
|
||||
|
||||
it('rejects unsafe URL schemes', () => {
|
||||
expect(normalizeCreatorSocialLink('data:text/html,bad')).toBeNull()
|
||||
expect(normalizeCreatorSocialLink('mailto:test@example.com')).toBeNull()
|
||||
})
|
||||
|
||||
it('ignores non-string values at the social-link normalization boundary', () => {
|
||||
expect(normalizeCreatorSocialLink({ href: 'https://x.com/x' })).toBeNull()
|
||||
expect(normalizeCreatorSocialLink(null)).toBeNull()
|
||||
})
|
||||
})
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
import type { CreatorProfileViewModel } from '../model'
|
||||
import { fireEvent, render, screen, within } from '@testing-library/react'
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { describe, expect, it, vi } from 'vite-plus/test'
|
||||
import CreatorProfileView from '../view'
|
||||
|
||||
vi.mock('#i18n', async () => {
|
||||
const { withSelectorKey } = await import('@/test/i18n-mock')
|
||||
return {
|
||||
useTranslation: () => ({
|
||||
t: withSelectorKey((key: string) => key),
|
||||
}),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../creator-content', () => ({
|
||||
default: () => <section>Creator content</section>,
|
||||
}))
|
||||
|
||||
const profile: CreatorProfileViewModel = {
|
||||
profile: {
|
||||
kind: 'individual',
|
||||
displayName: 'Creator',
|
||||
handle: 'creator',
|
||||
avatarUrl: '/creator-avatar.png',
|
||||
backgroundUrl: '/creator-background.png',
|
||||
badges: [],
|
||||
socialLinks: [],
|
||||
},
|
||||
creations: [],
|
||||
}
|
||||
|
||||
describe('CreatorProfileView SSR background', () => {
|
||||
it('keeps the creator profile within the parent main landmark', () => {
|
||||
render(
|
||||
<main>
|
||||
<CreatorProfileView
|
||||
profile={profile}
|
||||
homeHref="/marketplace"
|
||||
isMarketplacePlatform
|
||||
getCreationAction={() => ({ type: 'link', href: '/' })}
|
||||
/>
|
||||
</main>,
|
||||
)
|
||||
|
||||
const main = screen.getByRole('main')
|
||||
expect(within(main).getByRole('heading', { level: 1, name: 'Creator' })).toBeInTheDocument()
|
||||
expect(
|
||||
within(main).getByRole('navigation', { name: 'marketplace.creatorProfile.breadcrumbLabel' }),
|
||||
).toBeInTheDocument()
|
||||
expect(screen.queryByRole('complementary')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('includes the default background in server markup before the remote background loads', () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<CreatorProfileView
|
||||
profile={profile}
|
||||
homeHref="/"
|
||||
isMarketplacePlatform={false}
|
||||
getCreationAction={() => ({ type: 'link', href: '/' })}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(markup).toContain('default-background.png')
|
||||
expect(markup).toContain('src="/creator-background.png"')
|
||||
})
|
||||
|
||||
it('server-renders only the default background when the profile has no background', () => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<CreatorProfileView
|
||||
profile={{
|
||||
...profile,
|
||||
profile: { ...profile.profile, backgroundUrl: '' },
|
||||
}}
|
||||
homeHref="/"
|
||||
isMarketplacePlatform={false}
|
||||
getCreationAction={() => ({ type: 'link', href: '/' })}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(markup).toContain('default-background.png')
|
||||
expect(markup).not.toContain('src="/creator-background.png"')
|
||||
})
|
||||
|
||||
it('hides a stale remote image after a loading failure', () => {
|
||||
const { container } = render(
|
||||
<CreatorProfileView
|
||||
profile={profile}
|
||||
homeHref="/"
|
||||
isMarketplacePlatform={false}
|
||||
getCreationAction={() => ({ type: 'link', href: '/' })}
|
||||
/>,
|
||||
)
|
||||
const remoteBackground = container.querySelector<HTMLImageElement>(
|
||||
'img[src="/creator-background.png"]',
|
||||
)!
|
||||
|
||||
fireEvent.error(remoteBackground)
|
||||
|
||||
expect(remoteBackground).toHaveAttribute('hidden')
|
||||
})
|
||||
})
|
||||
Loaded 100 of 15831 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user