Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

refactor(web): route marketplace links through a gated module (#45027)

yyha641dfc6d624
diff --git a/packages/tooling/lint.config.ts b/packages/tooling/lint.config.ts
index 4418b3afa65..d0864232ca5 100644
--- a/packages/tooling/lint.config.ts
+++ b/packages/tooling/lint.config.ts
@@ -116,6 +116,16 @@ const webRestrictedImports = [
},
] satisfies NonNullable<OxlintConfig['rules']>[string]
+const marketplaceBoundaryFiles = [
+ 'web/env.ts',
+ 'web/proxy.ts',
+ 'web/service/**',
+ 'web/features/marketplace/**',
+ 'web/app/components/plugins/marketplace/**',
+ 'web/app/components/plugins/plugin-page/nav-operations.tsx',
+ 'web/app/components/workflow/block-selector/marketplace-plugin/**',
+]
+
const serviceRestrictedImports = [
'error',
{
@@ -1771,5 +1781,12 @@ export const lintConfig = {
],
},
},
+ {
+ ...handwrittenApiScope,
+ excludeFiles: [...handwrittenApiScope.excludeFiles, ...marketplaceBoundaryFiles],
+ rules: {
+ 'dify/marketplace-boundary': 'error',
+ },
+ },
],
} satisfies OxlintConfig
diff --git a/packages/tooling/plugins/eslint/index.ts b/packages/tooling/plugins/eslint/index.ts
index 9e4e4f3ca62..57c081d4916 100644
--- a/packages/tooling/plugins/eslint/index.ts
+++ b/packages/tooling/plugins/eslint/index.ts
@@ -1,6 +1,7 @@
import type { ESLint } from 'eslint'
import consistentPlaceholders from './rules/consistent-placeholders.ts'
import i18nFlatKey from './rules/i18n-flat-key.ts'
+import marketplaceBoundary from './rules/marketplace-boundary.ts'
import noExtraKeys from './rules/no-extra-keys.ts'
import noFileWideDisable from './rules/no-file-wide-disable.ts'
import preferTailwindIcons from './rules/prefer-tailwind-icons.ts'
@@ -17,6 +18,7 @@ const plugin: ESLint.Plugin = {
rules: {
'consistent-placeholders': consistentPlaceholders,
'i18n-flat-key': i18nFlatKey,
+ 'marketplace-boundary': marketplaceBoundary,
'no-extra-keys': noExtraKeys,
'no-file-wide-disable': noFileWideDisable,
'prefer-tailwind-icons': preferTailwindIcons,
diff --git a/packages/tooling/plugins/eslint/rules/marketplace-boundary.test.ts b/packages/tooling/plugins/eslint/rules/marketplace-boundary.test.ts
new file mode 100644
index 00000000000..3b02bf01e49
--- /dev/null
+++ b/packages/tooling/plugins/eslint/rules/marketplace-boundary.test.ts
@@ -0,0 +1,59 @@
+import { spawnSync } from 'node:child_process'
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { createRequire } from 'node:module'
+import { tmpdir } from 'node:os'
+import { dirname, join } from 'node:path'
+import { expect, it } from 'vite-plus/test'
+
+function lintFixture(source: string) {
+ const require = createRequire(import.meta.url)
+ const viteRequire = createRequire(require.resolve('vite-plus/package.json'))
+ const oxlintBin = join(dirname(dirname(viteRequire.resolve('oxlint'))), 'bin', 'oxlint')
+ const directory = mkdtempSync(join(tmpdir(), 'dify-marketplace-boundary-'))
+ try {
+ writeFileSync(
+ join(directory, 'plugin.mjs'),
+ `export { default } from ${JSON.stringify(require.resolve('../index.ts'))};`,
+ )
+ writeFileSync(
+ join(directory, '.oxlintrc.json'),
+ JSON.stringify({
+ categories: { correctness: 'off' },
+ jsPlugins: ['./plugin.mjs'],
+ rules: { 'dify/marketplace-boundary': 'error' },
+ }),
+ )
+ writeFileSync(join(directory, 'fixture.ts'), source)
+ const result = spawnSync(
+ process.execPath,
+ [oxlintBin, '--config', join(directory, '.oxlintrc.json'), '--format', 'json', 'fixture.ts'],
+ { cwd: directory, encoding: 'utf8' },
+ )
+ expect(result.error).toBeUndefined()
+ expect([0, 1], result.stderr + result.stdout).toContain(result.status)
+ return (
+ JSON.parse(result.stdout).diagnostics as Array<{ labels: { span: { line: number } }[] }>
+ ).map((diagnostic) => diagnostic.labels[0]!.span.line)
+ } finally {
+ rmSync(directory, { recursive: true, force: true })
+ }
+}
+
+it('reports Marketplace links, data and availability read outside the Marketplace module', () => {
+ const lines = lintFixture(
+ [
+ "import { marketplaceQuery } from '@/service/marketplace'",
+ "import { getPluginDetailPath, marketplaceLinks } from '@/features/marketplace/links'",
+ "import { MARKETPLACE_API_PREFIX, getMarketplaceApiUrl } from '@/features/marketplace/api'",
+ "import type { MarketplaceLinks } from '@/features/marketplace/links'",
+ 'const enabled = systemFeatures.enable_marketplace',
+ 'const { enable_marketplace } = systemFeatures',
+ 'const prefix = env.NEXT_PUBLIC_MARKETPLACE_URL_PREFIX',
+ "const page = 'https://marketplace.dify.ai/plugins'",
+ 'const creators = `https://creators-staging.dify.dev/` + path',
+ "const docs = 'https://docs.dify.ai/marketplace'",
+ ].join('\n'),
+ )
+
+ expect(lines).toEqual([1, 2, 3, 5, 6, 7, 8, 9])
+})
diff --git a/packages/tooling/plugins/eslint/rules/marketplace-boundary.ts b/packages/tooling/plugins/eslint/rules/marketplace-boundary.ts
new file mode 100644
index 00000000000..46e2898bb7c
--- /dev/null
+++ b/packages/tooling/plugins/eslint/rules/marketplace-boundary.ts
@@ -0,0 +1,91 @@
+import type { Rule } from 'eslint'
+
+const restrictedImports: Record<string, string[] | 'all'> = {
+ '@/service/marketplace': 'all',
+ '@/features/marketplace/links': ['marketplaceLinks'],
+ '@/features/marketplace/api': ['MARKETPLACE_API_PREFIX'],
+}
+
+const restrictedProperties = new Set([
+ 'enable_marketplace',
+ 'NEXT_PUBLIC_MARKETPLACE_URL_PREFIX',
+ 'NEXT_PUBLIC_MARKETPLACE_API_PREFIX',
+])
+
+const marketplaceHost = /\b(?:marketplace|creators)(?:-[\w-]+)?\.dify\.(?:ai|dev)\b/
+
+type TypeOnly = { importKind?: 'type' | 'value' }
+
+const rule: Rule.RuleModule = {
+ meta: {
+ type: 'problem',
+ docs: {
+ description:
+ 'Keep Marketplace links, data and availability behind @/features/marketplace/client.',
+ },
+ schema: [],
+ messages: {
+ import:
+ 'Do not import {{name}} here. Get Marketplace links and data from @/features/marketplace/client, which is off when Marketplace is disabled.',
+ property:
+ 'Do not read {{name}} here. Use useMarketplace() from @/features/marketplace/client.',
+ url: 'Do not hand-write Marketplace URLs. Build them from useMarketplace() in @/features/marketplace/client.',
+ },
+ },
+ create(context) {
+ const reportProperty = (node: Rule.Node, name: string) => {
+ if (restrictedProperties.has(name))
+ context.report({ node, messageId: 'property', data: { name } })
+ }
+
+ return {
+ ImportDeclaration(node) {
+ if ((node as TypeOnly).importKind === 'type') return
+ const restricted = restrictedImports[String(node.source.value)]
+ if (!restricted) return
+ if (restricted === 'all') {
+ context.report({
+ node,
+ messageId: 'import',
+ data: { name: String(node.source.value) },
+ })
+ return
+ }
+ for (const specifier of node.specifiers) {
+ if (
+ specifier.type === 'ImportSpecifier' &&
+ (specifier as TypeOnly).importKind !== 'type' &&
+ specifier.imported.type === 'Identifier' &&
+ restricted.includes(specifier.imported.name)
+ )
+ context.report({
+ node: specifier,
+ messageId: 'import',
+ data: { name: specifier.imported.name },
+ })
+ }
+ },
+ MemberExpression(node) {
+ if (!node.computed && node.property.type === 'Identifier')
+ reportProperty(node.property as Rule.Node, node.property.name)
+ },
+ Property(node) {
+ if (
+ node.parent.type === 'ObjectPattern' &&
+ !node.computed &&
+ node.key.type === 'Identifier'
+ )
+ reportProperty(node.key as Rule.Node, node.key.name)
+ },
+ Literal(node) {
+ if (typeof node.value === 'string' && marketplaceHost.test(node.value))
+ context.report({ node, messageId: 'url' })
+ },
+ TemplateElement(node) {
+ if (marketplaceHost.test(node.value.raw)) context.report({ node, messageId: 'url' })
+ },
+ }
+ },
+}
+
+export default rule
diff --git a/web/app/(commonLayout)/plugins/page.spec.tsx b/web/app/(commonLayout)/plugins/page.spec.tsx
index 57b321ce1b4..4f52ef22b8f 100644
--- a/web/app/(commonLayout)/plugins/page.spec.tsx
+++ b/web/app/(commonLayout)/plugins/page.spec.tsx
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
-import { MARKETPLACE_API_PREFIX } from '@/config'
+import { MARKETPLACE_API_PREFIX } from '@/features/marketplace/api'
const mocks = vi.hoisted(() => ({
fetch: vi.fn(),
diff --git a/web/app/(commonLayout)/plugins/page.tsx b/web/app/(commonLayout)/plugins/page.tsx
index e26fc91ca28..de4220ef50a 100644
--- a/web/app/(commonLayout)/plugins/page.tsx
+++ b/web/app/(commonLayout)/plugins/page.tsx
@@ -7,7 +7,7 @@ import {
parseMarketplacePluginId,
shouldResolveInstallCategoryRedirect,
} from '@/app/components/plugins/plugin-routes'
-import { MARKETPLACE_API_PREFIX } from '@/config'
+import { getMarketplaceApiUrl } from '@/features/marketplace/api'
import { redirect } from '@/next/navigation'
type PluginListProps = {
@@ -28,7 +28,7 @@ const fetchPluginCategoryFromMarketplace = async (packageId: string) => {
const path = pluginId
? `/plugins/${encodeURIComponent(pluginId.org)}/${encodeURIComponent(pluginId.name)}`
: `/plugins/identifier?unique_identifier=${encodeURIComponent(packageId)}`
- const response = await fetch(`${MARKETPLACE_API_PREFIX}${path}`, { cache: 'no-store' })
+ const response = await fetch(getMarketplaceApiUrl(path), { cache: 'no-store' })
if (!response.ok) return undefined
diff --git a/web/app/components/apps/import-from-marketplace-template-modal.tsx b/web/app/components/apps/import-from-marketplace-template-modal.tsx
index 98f31cacc4f..5b476e02837 100644
--- a/web/app/components/apps/import-from-marketplace-template-modal.tsx
+++ b/web/app/components/apps/import-from-marketplace-template-modal.tsx
@@ -14,7 +14,7 @@ import { useCallback, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import AppIcon from '@/app/components/base/app-icon'
import { toast } from '@/app/notifications'
-import { MARKETPLACE_API_PREFIX } from '@/config'
+import { getMarketplaceTemplateIconUrl } from '@/features/marketplace/api'
import {
fetchMarketplaceTemplateDSL,
useMarketplaceTemplateDetail,
@@ -111,7 +111,7 @@ const ImportFromMarketplaceTemplateModal = ({
icon_type: template.icon_file_key ? 'image' : 'emoji',
icon: template.icon || 'page_facing_up',
icon_url: template.icon_file_key
- ? `${MARKETPLACE_API_PREFIX}/templates/${template.id}/icon`
+ ? getMarketplaceTemplateIconUrl(template.id)
: undefined,
icon_background: template.icon_file_key ? undefined : template.icon_background,
}}
diff --git a/web/app/components/base/markdown-blocks/__tests__/plugin-assets.browser.spec.tsx b/web/app/components/base/markdown-blocks/__tests__/plugin-assets.browser.spec.tsx
index f1c8bc0579e..433e5b47b27 100644
--- a/web/app/components/base/markdown-blocks/__tests__/plugin-assets.browser.spec.tsx
+++ b/web/app/components/base/markdown-blocks/__tests__/plugin-assets.browser.spec.tsx
@@ -6,11 +6,17 @@ const { request } = vi.hoisted(() => ({ request: vi.fn<() => Promise<Response>>(
vi.mock('@/service/base', () => ({ request }))
// Keep the unrelated marketplace image fallback local; all asset bytes still go
// through the generated Console client and the browser's real image decoder.
-vi.mock('@/config', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@/config')>()),
- MARKETPLACE_API_PREFIX:
- 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7#',
-}))
+vi.mock('@/env', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/env')>()
+ return {
+ ...actual,
+ env: {
+ ...actual.env,
+ NEXT_PUBLIC_MARKETPLACE_API_PREFIX:
+ 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7#',
+ },
+ }
+})
async function pngResponse(width: number, height: number) {
const canvas = document.createElement('canvas')
diff --git a/web/app/components/base/markdown-blocks/__tests__/utils.spec.ts b/web/app/components/base/markdown-blocks/__tests__/utils.spec.ts
index 54d390219e1..c605f16cc5d 100644
--- a/web/app/components/base/markdown-blocks/__tests__/utils.spec.ts
+++ b/web/app/components/base/markdown-blocks/__tests__/utils.spec.ts
@@ -2,8 +2,14 @@ import { getMarkdownImageURL, isValidUrl } from '../utils'
vi.mock('@/config', () => ({
ALLOW_UNSAFE_DATA_SCHEME: false,
- MARKETPLACE_API_PREFIX: '/api/marketplace',
}))
+vi.mock('@/env', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/env')>()
+ return {
+ ...actual,
+ env: { ...actual.env, NEXT_PUBLIC_MARKETPLACE_API_PREFIX: '/api/marketplace' },
+ }
+})
afterEach(() => {
vi.doUnmock('@/config')
@@ -58,7 +64,6 @@ describe('utils', () => {
vi.resetModules()
vi.doMock('@/config', () => ({
ALLOW_UNSAFE_DATA_SCHEME: true,
- MARKETPLACE_API_PREFIX: '/api/marketplace',
}))
})
@@ -105,10 +110,13 @@ describe('utils', () => {
describe('getMarkdownImageURL with trailing slash prefix', () => {
beforeEach(() => {
vi.resetModules()
- vi.doMock('@/config', () => ({
- ALLOW_UNSAFE_DATA_SCHEME: false,
- MARKETPLACE_API_PREFIX: '/api/marketplace/',
- }))
+ vi.doMock('@/env', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/env')>()
+ return {
+ ...actual,
+ env: { ...actual.env, NEXT_PUBLIC_MARKETPLACE_API_PREFIX: '/api/marketplace/' },
+ }
+ })
})
it('should not add extra slash when prefix ends with slash', async () => {
diff --git a/web/app/components/base/markdown-blocks/utils.ts b/web/app/components/base/markdown-blocks/utils.ts
index b0202b3e058..84d79c40d9c 100644
--- a/web/app/components/base/markdown-blocks/utils.ts
+++ b/web/app/components/base/markdown-blocks/utils.ts
@@ -1,5 +1,6 @@
import type { ExtraProps } from 'streamdown'
-import { ALLOW_UNSAFE_DATA_SCHEME, MARKETPLACE_API_PREFIX } from '@/config'
+import { ALLOW_UNSAFE_DATA_SCHEME } from '@/config'
+import { getMarketplaceApiUrl } from '@/features/marketplace/api'
export const hasImageChild = (
children: NonNullable<ExtraProps['node']>['children'] | undefined,
@@ -21,6 +22,6 @@ export const isValidUrl = (url: string): boolean => {
export const getMarkdownImageURL = (url: string, pathname?: string) => {
const regex = /^(?:\.\/|\/)?_assets(?=\/)/
if (regex.test(url))
- return `${MARKETPLACE_API_PREFIX}${MARKETPLACE_API_PREFIX.endsWith('/') ? '' : '/'}plugins/${pathname ?? ''}${url.replace(regex, '/_assets')}`
+ return getMarketplaceApiUrl(`plugins/${pathname ?? ''}${url.replace(regex, '/_assets')}`)
return url
}
diff --git a/web/app/components/datasets/create-from-pipeline/list/built-in-pipeline-list.tsx b/web/app/components/datasets/create-from-pipeline/list/built-in-pipeline-list.tsx
index f1cc9614ccb..82ddc997b69 100644
--- a/web/app/components/datasets/create-from-pipeline/list/built-in-pipeline-list.tsx
+++ b/web/app/components/datasets/create-from-pipeline/list/built-in-pipeline-list.tsx
@@ -1,8 +1,8 @@
-import { useQuery, useSuspenseQuery } from '@tanstack/react-query'
+import { useQuery } from '@tanstack/react-query'
import { useMemo } from 'react'
import { useLocale } from '#i18n'
import { selectPipelineTemplateList } from '@/app/components/rag-pipeline/utils/query-select'
-import { systemFeaturesQueryOptions } from '@/features/system-features/client'
+import { useMarketplace } from '@/features/marketplace/client'
import { LanguagesSupported } from '@/i18n/language'
import { consoleQuery } from '@/service/console'
import CreateCard from './create-card'
@@ -14,10 +14,7 @@ const BuiltInPipelineList = () => {
if (['zh-Hans', 'ja-JP'].includes(locale)) return locale
return LanguagesSupported[0]
}, [locale])
- const { data: enableMarketplace } = useSuspenseQuery({
- ...systemFeaturesQueryOptions(),
- select: (s) => s.enable_marketplace,
- })
+ const enableMarketplace = useMarketplace() !== null
const { data: pipelineList, isLoading } = useQuery(
consoleQuery.rag.pipeline.templates.get.queryOptions({
input: { query: { type: 'built-in', language } },
diff --git a/web/app/components/explore/try-app/app-info/__tests__/index.spec.tsx b/web/app/components/explore/try-app/app-info/__tests__/index.spec.tsx
index 72a8056c766..5f0efca82a7 100644
--- a/web/app/components/explore/try-app/app-info/__tests__/index.spec.tsx
+++ b/web/app/components/explore/try-app/app-info/__tests__/index.spec.tsx
@@ -2,7 +2,7 @@ import type { ComponentProps } from 'react'
import type { consoleClient } from '@/service/console'
import { act, fireEvent, screen, within } from '@testing-library/react'
import { BlockEnum } from '@/app/components/workflow/types'
-import { MARKETPLACE_API_PREFIX } from '@/config'
+import { MARKETPLACE_API_PREFIX } from '@/features/marketplace/api'
import { renderWithConsoleQuery as render } from '@/test/console/query-data'
import { createDeferred } from '@/test/deferred'
import { createTrialAppDetailFixture } from '@/test/fixtures/app'
diff --git a/web/app/components/explore/try-app/app-info/use-get-requirements.ts b/web/app/components/explore/try-app/app-info/use-get-requirements.ts
index 2425e4b21e3..ef51cfcd04b 100644
--- a/web/app/components/explore/try-app/app-info/use-get-requirements.ts
+++ b/web/app/components/explore/try-app/app-info/use-get-requirements.ts
@@ -6,7 +6,7 @@ import type { AgentTool } from '@/types/app'
import { useQuery } from '@tanstack/react-query'
import { uniqBy } from 'es-toolkit/compat'
import { BlockEnum } from '@/app/components/workflow/types'
-import { MARKETPLACE_API_PREFIX } from '@/config'
+import { getMarketplacePluginIconUrl } from '@/features/marketplace/api'
import { consoleQuery } from '@/service/console'
type Params = {
@@ -64,9 +64,9 @@ const getIconUrl = (providerId: string, type: ProviderType) => {
const parsed = parseProviderId(providerId)
if (!parsed) return ''
- const organization = encodeURIComponent(parsed.organization)
- const pluginName = encodeURIComponent(getPluginName(parsed.providerName, type))
- return `${MARKETPLACE_API_PREFIX}/plugins/${organization}/${pluginName}/icon`
+ return getMarketplacePluginIconUrl(
+ `${parsed.organization}/${getPluginName(parsed.providerName, type)}`,
+ )
}
const isRecord = (value: unknown): value is Record<string, unknown> => {
diff --git a/web/app/components/goto-anything/__tests__/index.spec.tsx b/web/app/components/goto-anything/__tests__/index.spec.tsx
index 74589388795..baf64a072ef 100644
--- a/web/app/components/goto-anything/__tests__/index.spec.tsx
+++ b/web/app/components/goto-anything/__tests__/index.spec.tsx
@@ -138,6 +138,7 @@ function setup({ datasetOperator = false, enableSkill = true, canInstall = true
accountProfileMeta: { currentVersion: '1.0.0' },
workspacePermissionKeys: canInstall ? ['plugin.install'] : [],
systemFeatures: {
+ enable_marketplace: true,
rbac_enabled: true,
plugin_installation_permission: {
plugin_installation_scope: 'all',
diff --git a/web/app/components/goto-anything/actions/__tests__/index.spec.ts b/web/app/components/goto-anything/actions/__tests__/index.spec.ts
index ebce2fa7241..ff7a49ab796 100644
--- a/web/app/components/goto-anything/actions/__tests__/index.spec.ts
+++ b/web/app/components/goto-anything/actions/__tests__/index.spec.ts
@@ -13,8 +13,19 @@ describe('getActionSearchTerm', () => {
})
})
+describe('createActions', () => {
+ it('offers plugin search only when Marketplace is available', () => {
+ expect(
+ createActions(slash, false, false, { agents: false, plugins: true, skills: false }),
+ ).toHaveProperty('plugin')
+ expect(
+ createActions(slash, false, false, { agents: false, plugins: false, skills: false }),
+ ).not.toHaveProperty('plugin')
+ })
+})
+
describe('matchAction', () => {
- const actions = createActions(slash, false, false, { agents: true, skills: true })
+ const actions = createActions(slash, false, false, { agents: true, plugins: true, skills: true })
it.each([
['@app query', '@app'],
diff --git a/web/app/components/goto-anything/actions/index.ts b/web/app/components/goto-anything/actions/index.ts
index 97264caeebe..dbb2388adee 100644
--- a/web/app/components/goto-anything/actions/index.ts
+++ b/web/app/components/goto-anything/actions/index.ts
@@ -10,16 +10,17 @@ import { workflowNodesAction } from './workflow-nodes'
const defaultActions = {
app: appAction,
knowledge: knowledgeAction,
- plugin: pluginAction,
} satisfies Record<string, ActionItem>
type ActionAvailability = {
agents: boolean
+ plugins: boolean
skills: boolean
}
const defaultAvailability: ActionAvailability = {
agents: false,
+ plugins: true,
skills: true,
}
@@ -32,6 +33,7 @@ export function createActions(
const availableActions = {
...defaultActions,
slash,
+ ...(availability.plugins ? { plugin: pluginAction } : {}),
...(availability.skills ? { skill: skillAction } : {}),
...(availability.agents ? { agent: agentAction } : {}),
}
diff --git a/web/app/components/goto-anything/actions/plugin.tsx b/web/app/components/goto-anything/actions/plugin.tsx
index abb5ac22085..49c5c093a87 100644
--- a/web/app/components/goto-anything/actions/plugin.tsx
+++ b/web/app/components/goto-anything/actions/plugin.tsx
@@ -1,11 +1,12 @@
import type { Plugin } from '../../plugins/types'
-import type { ActionItem, PluginSearchResult, SearchQueryOptions } from './types'
+import type { ActionItem, PluginSearchResult } from './types'
import { renderI18nObject } from '@/i18n/metadata'
-import { marketplaceQuery } from '@/service/marketplace'
import Icon from '../../plugins/card/base/card-icon'
-import { getFormattedPlugin } from '../../plugins/marketplace/utils'
-const parser = (plugins: Plugin[], locale: string): PluginSearchResult[] => {
+export const parsePluginSearchResults = (
+ plugins: Plugin[],
+ locale: string,
+): PluginSearchResult[] => {
return plugins.map((plugin) => {
return {
id: plugin.name,
@@ -25,29 +26,3 @@ export const pluginAction: ActionItem = {
description: 'Search and navigate to your plugins',
source: 'remote',
}
-
-export function pluginSearchQueryOptions(
- searchTerm: string,
- locale: string,
- options: SearchQueryOptions = {},
-) {
- return marketplaceQuery.searchAdvanced.queryOptions({
- input: {
- params: { kind: 'plugins' },
- body: {
- page: 1,
- page_size: 10,
- query: searchTerm,
- },
- },
- retry: false,
- ...options,
- select: (response) => {
- const plugins = response.data?.plugins ?? []
- return parser(
- plugins.map((plugin) => getFormattedPlugin(plugin)),
- locale,
- )
- },
- })
-}
diff --git a/web/app/components/goto-anything/index.tsx b/web/app/components/goto-anything/index.tsx
index c417d7c3ac2..5fdd079b43c 100644
--- a/web/app/components/goto-anything/index.tsx
+++ b/web/app/components/goto-anything/index.tsx
@@ -29,6 +29,7 @@ import { selectWorkflowNode } from '@/app/components/workflow/utils/node-navigat
import { useGetLanguage } from '@/context/i18n'
import { isCurrentWorkspaceDatasetOperatorAtom } from '@/context/workspace-state'
import { isAgentV2Enabled } from '@/features/agent-v2/feature-flag'
+import { useMarketplace, useMarketplacePluginSearch } from '@/features/marketplace/client'
import { usePathname, useRouter } from '@/next/navigation'
import { consoleQuery } from '@/service/console'
import { PluginInstallPermissionProvider } from '../plugins/install-plugin/components/plugin-install-permission-provider'
@@ -41,7 +42,7 @@ import { slashCommandRegistry } from './actions/commands/catalog'
import { createSlashAction } from './actions/commands/slash'
import { useCommandContext } from './actions/commands/use-command-context'
import { knowledgeSearchQueryOptions } from './actions/knowledge'
-import { pluginSearchQueryOptions } from './actions/plugin'
+import { parsePluginSearchResults } from './actions/plugin'
import { skillSearchQueryOptions } from './actions/skill'
import { isCommandOption, useCommandOptions } from './command-options'
import { EmptyState } from './components/empty-state'
@@ -153,6 +154,7 @@ export function GotoAnything() {
)
const agentsAvailable = isAgentV2Enabled()
const skillsAvailable = enableSkill === true && !isCurrentWorkspaceDatasetOperator
+ const pluginsAvailable = useMarketplace() !== null
const isWorkflowPage =
appWorkflowPathPattern.test(pathname) || sharedWorkflowPathPattern.test(pathname)
const isRagPipelinePage = ragPipelinePathPattern.test(pathname)
@@ -167,9 +169,17 @@ export function GotoAnything() {
() =>
createActions(createSlashAction(commandContext), isWorkflowPage, isRagPipelinePage, {
agents: agentsAvailable,
+ plugins: pluginsAvailable,
skills: skillsAvailable,
}),
- [agentsAvailable, commandContext, isWorkflowPage, isRagPipelinePage, skillsAvailable],
+ [
+ agentsAvailable,
+ commandContext,
+ isWorkflowPage,
+ isRagPipelinePage,
+ pluginsAvailable,
+ skillsAvailable,
+ ],
)
const { commandOptions, scopeOptions } = useCommandOptions(actions, searchQuery, commandContext)
const trimmedSearchQuery = searchQuery.trim()
@@ -190,7 +200,9 @@ export function GotoAnything() {
const knowledgeSearchEnabled =
remoteSearchEnabled && (!debouncedAction || debouncedAction.key === '@knowledge')
const pluginSearchEnabled =
- remoteSearchEnabled && (!debouncedAction || debouncedAction.key === '@plugin')
+ remoteSearchEnabled &&
+ pluginsAvailable &&
+ (!debouncedAction || debouncedAction.key === '@plugin')
const skillSearchEnabled =
remoteSearchEnabled && skillsAvailable && (!debouncedAction || debouncedAction.key === '@skill')
const agentSearchEnabled =
@@ -209,12 +221,10 @@ export function GotoAnything() {
placeholderData: keepPreviousData,
}),
)
- const pluginSearchQuery = useQuery(
- pluginSearchQueryOptions(debouncedSearchTerm, defaultLocale, {
- enabled: pluginSearchEnabled,
- placeholderData: keepPreviousData,
- }),
- )
+ const pluginSearchQuery = useMarketplacePluginSearch(debouncedSearchTerm, {
+ enabled: pluginSearchEnabled,
+ select: (plugins) => parsePluginSearchResults(plugins, defaultLocale),
+ })
const skillSearchQuery = useQuery(
skillSearchQueryOptions(debouncedSearchTerm, {
enabled: skillSearchEnabled,
diff --git a/web/app/components/header/account-setting/data-source-page-new/index.tsx b/web/app/components/header/account-setting/data-source-page-new/index.tsx
index c0e10dccd14..814e9a5240b 100644
--- a/web/app/components/header/account-setting/data-source-page-new/index.tsx
+++ b/web/app/components/header/account-setting/data-source-page-new/index.tsx
@@ -1,5 +1,5 @@
import type { ReactNode } from 'react'
-import { useQuery, useQueryClient, useSuspenseQuery } from '@tanstack/react-query'
+import { useQuery, useQueryClient } from '@tanstack/react-query'
import { memo, useCallback, useMemo, useState } from 'react'
import { Trans, useTranslation } from 'react-i18next'
import { SearchInput } from '@/app/components/base/search-input'
@@ -8,7 +8,7 @@ import { usePluginsWithLatestVersion } from '@/app/components/plugins/hooks'
import { usePluginSettingsAccess } from '@/app/components/plugins/plugin-page/use-reference-setting'
import { PluginCategoryEnum } from '@/app/components/plugins/types'
import { STEP_BY_STEP_TOUR_TARGETS } from '@/app/components/step-by-step-tour/target-registry'
-import { systemFeaturesQueryOptions } from '@/features/system-features/client'
+import { useMarketplace } from '@/features/marketplace/client'
import { useRenderI18nObject } from '@/hooks/use-i18n'
import { consoleQuery } from '@/service/console'
import { useInstalledPluginList, useInvalidateInstalledPluginList } from '@/service/use-plugins'
@@ -58,10 +58,7 @@ const DataSourcePage = ({ layout, onOpenMarketplace, stickyToolbar }: DataSource
const renderI18nObject = useRenderI18nObject()
const [searchText, setSearchText] = useState('')
const { canSetPluginPreferences } = usePluginSettingsAccess()
- const { data: enable_marketplace } = useSuspenseQuery({
- ...systemFeaturesQueryOptions(),
- select: (s) => s.enable_marketplace,
- })
+ const marketplace = useMarketplace()
const { data, isLoading: isDataSourceListLoading } = useQuery(
consoleQuery.auth.plugin.datasource.list.get.queryOptions(),
)
@@ -179,8 +176,9 @@ const DataSourcePage = ({ layout, onOpenMarketplace, stickyToolbar }: DataSource
})}
</div>
)}
- {!isDataSourceListLoading && enable_marketplace && (
+ {!isDataSourceListLoading && marketplace && (
<InstallFromMarketplace
+ marketplace={marketplace}
providers={dataSources}
searchText={searchText}
onOpenMarketplace={onOpenMarketplace}
diff --git a/web/app/components/header/account-setting/data-source-page-new/install-from-marketplace.tsx b/web/app/components/header/account-setting/data-source-page-new/install-from-marketplace.tsx
index 8d28beca4c3..32762833130 100644
--- a/web/app/components/header/account-setting/data-source-page-new/install-from-marketplace.tsx
+++ b/web/app/components/header/account-setting/data-source-page-new/install-from-marketplace.tsx
@@ -1,5 +1,6 @@
import type { DatasourceProviderAuthResponse } from '@dify/contracts/api/console/auth/types.gen'
import type { Plugin } from '@/app/components/plugins/types'
+import type { MarketplaceLinks } from '@/features/marketplace/links'
import { cn } from '@langgenius/dify-ui/cn'
import { Separator } from '@langgenius/dify-ui/separator'
import { useTheme } from 'next-themes'
@@ -7,7 +8,6 @@ import { memo, useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
import List from '@/app/components/plugins/marketplace/list'
-import { getMarketplaceCategoryUrl } from '@/app/components/plugins/marketplace/utils'
import { usePluginSettingsAccess } from '@/app/components/plugins/plugin-page/use-reference-setting'
import ProviderCard from '@/app/components/plugins/provider-card'
import { PluginCategoryEnum } from '@/app/components/plugins/types'
@@ -15,11 +15,13 @@ import Link from '@/next/link'
import { useMarketplaceAllPlugins } from './hooks'
type InstallFromMarketplaceProps = {
+ marketplace: MarketplaceLinks
onOpenMarketplace?: () => void
providers: DatasourceProviderAuthResponse[]
searchText: string
}
const InstallFromMarketplace = ({
+ marketplace,
onOpenMarketplace,
providers,
searchText,
@@ -33,11 +35,21 @@ const InstallFromMarketplace = ({
searchText,
)
- const cardRender = useCallback((plugin: Plugin) => {
- if (plugin.type === 'bundle') return null
+ const cardRender = useCallback(
+ (plugin: Plugin) => {
+ if (plugin.type === 'bundle') return null
- return <ProviderCard key={plugin.plugin_id} className="h-36.5" payload={plugin} />
- }, [])
+ return (
+ <ProviderCard
+ key={plugin.plugin_id}
+ className="h-36.5"
+ marketplace={marketplace}
+ payload={plugin}
+ />
+ )
+ },
+ [marketplace],
+ )
return (
<div className="mb-2">
@@ -75,7 +87,7 @@ const InstallFromMarketplace = ({
<Link
target="_blank"
rel="noopener noreferrer"
- href={getMarketplaceCategoryUrl(PluginCategoryEnum.datasource, { theme })}
+ href={marketplace.category(PluginCategoryEnum.datasource, { theme })}
className="inline-flex items-center system-sm-medium text-text-accent"
>
{t(($) => $['marketplace.difyMarketplace'], { ns: 'plugin' })}
diff --git a/web/app/components/header/account-setting/data-source-page-new/plugin-actions.tsx b/web/app/components/header/account-setting/data-source-page-new/plugin-actions.tsx
index 82f9dd74969..0f1a982ad62 100644
--- a/web/app/components/header/account-setting/data-source-page-new/plugin-actions.tsx
+++ b/web/app/components/header/account-setting/data-source-page-new/plugin-actions.tsx
@@ -12,10 +12,8 @@ import {
MenuTrigger,
} from '@langgenius/dify-ui/menu'
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
-import { skipToken, useQuery } from '@tanstack/react-query'
import { memo, useId } from 'react'
import { useTranslation } from 'react-i18next'
-import { useLocale } from '#i18n'
import Badge from '@/app/components/base/badge'
import { HeaderModals } from '@/app/components/plugins/plugin-detail-panel/detail-header/components'
import {
@@ -25,43 +23,27 @@ import {
import { OperationMenu } from '@/app/components/plugins/plugin-detail-panel/operation-menu'
import { usePluginSettingsAccess } from '@/app/components/plugins/plugin-page/use-reference-setting'
import { useReadmePanelStore } from '@/app/components/plugins/readme-panel/store'
-import { PluginSource } from '@/app/components/plugins/types'
+import { useMarketplace, useMarketplacePluginVersions } from '@/features/marketplace/client'
import { useRenderI18nObject } from '@/hooks/use-i18n'
-import useTheme from '@/hooks/use-theme'
import useTimestamp from '@/hooks/use-timestamp'
-import { marketplaceQuery } from '@/service/marketplace'
import { isEarlierThanVersion } from '@/utils/semver'
-import { getMarketplaceUrl } from '@/utils/var'
type Props = {
detail: PluginDetail
onUpdate?: (isDelete?: boolean) => void
}
-const getDetailUrl = (detail: PluginDetail, locale: string, theme: string) => {
- const { source, meta } = detail
- const { author, name } = detail.declaration || detail
-
- if (source === PluginSource.github) return meta?.repo ? `https://github.com/${meta.repo}` : ''
-
- if (source === PluginSource.marketplace)
- return getMarketplaceUrl(`/plugins/${author}/${name}`, { language: locale, theme })
-
- return ''
-}
-
const DataSourcePluginActions = ({ detail, onUpdate }: Props) => {
const { t } = useTranslation(['common', 'plugin', 'appLog'])
const versionMenuLabelId = useId()
const { formatDate } = useTimestamp()
const dateFormat = t(($) => $.dateTimeFormat, { ns: 'appLog' }).split(' ')[0]!
- const { theme } = useTheme()
- const locale = useLocale()
const renderI18nObject = useRenderI18nObject()
const readmeTriggerId = useId()
const openReadmePanel = useReadmePanelStore((s) => s.openReadmePanel)
const { canDeletePlugin, canUpdatePlugin } = usePluginSettingsAccess()
const detailHeaderState = useDetailHeaderState(detail)
+ const marketplace = useMarketplace()
const {
modalStates,
versionPicker,
@@ -82,16 +64,10 @@ const DataSourcePluginActions = ({ detail, onUpdate }: Props) => {
const displayVersion = isFromGitHub ? (detail.meta?.version ?? detail.version) : detail.version
const pluginLabel = renderI18nObject(detail.declaration.label) || detail.name
- const [organization, pluginName] = detail.plugin_id.split('/')
- const versionsQuery = useQuery(
- marketplaceQuery.pluginVersions.queryOptions({
- input:
- organization && pluginName
- ? { params: { organization, pluginName }, query: { page: 1, page_size: 100 } }
- : skipToken,
- enabled: versionPicker.isShow && canUpdatePlugin && isFromMarketplace,
- retry: false,
- }),
+ const canChangeVersion = canUpdatePlugin && isFromMarketplace && marketplace !== null
+ const versionsQuery = useMarketplacePluginVersions(
+ detail.plugin_id,
+ versionPicker.isShow && canChangeVersion,
)
const loadingVersions =
versionPicker.isShow && (versionsQuery.isPending || autoUpgradeSettings.isPending)
@@ -127,13 +103,7 @@ const DataSourcePluginActions = ({ detail, onUpdate }: Props) => {
return (
<div className="flex shrink-0 items-center gap-1">
<Menu
- open={
- !!displayVersion &&
- versionPicker.isShow &&
- canUpdatePlugin &&
- isFromMarketplace &&
- !loadingVersions
- }
+ open={!!displayVersion && versionPicker.isShow && canChangeVersion && !loadingVersions}
onOpenChange={versionPicker.setIsShow}
>
{!!displayVersion && (
@@ -142,7 +112,7 @@ const DataSourcePluginActions = ({ detail, onUpdate }: Props) => {
<Button
variant="ghost"
size="small"
- disabled={!canUpdatePlugin || !isFromMarketplace}
+ disabled={!canChangeVersion}
loading={loadingVersions}
aria-label={`${t(($) => $['detailPanel.switchVersion'], { ns: 'plugin' })} ${pluginLabel} ${displayVersion}`}
className="relative h-5 overflow-visible rounded-[5px] border border-divider-deep px-1.5 system-xs-medium text-text-tertiary"
@@ -151,7 +121,7 @@ const DataSourcePluginActions = ({ detail, onUpdate }: Props) => {
<span className="absolute -inset-e-0.5 -top-0.5 size-1.5 rounded-xs border border-components-badge-status-light-error-border-inner bg-components-badge-status-light-error-bg shadow-sm" />
)}
<span>{displayVersion}</span>
- {canUpdatePlugin && isFromMarketplace && !loadingVersions && (
+ {canChangeVersion && !loadingVersions && (
<span aria-hidden className="i-ri-arrow-left-right-line size-3" />
)}
</Button>
@@ -228,7 +198,8 @@ const DataSourcePluginActions = ({ detail, onUpdate }: Props) => {
onCheckVersion={handleUpdate}
onRemove={modalStates.showDeleteConfirm}
onViewReadme={detail.plugin_unique_identifier ? handleViewReadme : undefined}
- detailUrl={getDetailUrl(detail, locale, theme || 'light')}
+ marketplacePlugin={{ org: detail.declaration.author, name: detail.declaration.name }}
+ repo={detail.meta?.repo}
triggerSize="xs"
showCheckVersion={canUpdatePlugin}
showRemove={canDeletePlugin}
diff --git a/web/app/components/header/account-setting/model-provider-page/index.tsx b/web/app/components/header/account-setting/model-provider-page/index.tsx
index 1a74e1c3005..772231fdedd 100644
--- a/web/app/components/header/account-setting/model-provider-page/index.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/index.tsx
@@ -4,7 +4,7 @@ import type {
ModelProviderSummaryResponse,
} from '@dify/contracts/api/console/workspaces/types.gen'
import type { ReactNode } from 'react'
-import { useQuery, useSuspenseQuery } from '@tanstack/react-query'
+import { useQuery } from '@tanstack/react-query'
import { useDebounce } from 'ahooks'
import { noop } from 'es-toolkit/function'
import { useMemo } from 'react'
@@ -12,7 +12,7 @@ import { useTranslation } from 'react-i18next'
import { SearchInput } from '@/app/components/base/search-input'
import { usePluginSettingsAccess } from '@/app/components/plugins/plugin-page/use-reference-setting'
import { PluginCategoryEnum } from '@/app/components/plugins/types'
-import { systemFeaturesQueryOptions } from '@/features/system-features/client'
+import { useMarketplace } from '@/features/marketplace/client'
import { consoleQuery } from '@/service/console'
import { UpdateSettingDialog } from '../update-setting-dialog'
import { ModelTypeEnum } from './declarations'
@@ -76,7 +76,6 @@ const ModelProviderPage = ({
)
const providers = providerSummary?.data ?? EMPTY_MODEL_PROVIDERS
const modelProviderPlugins = providerSummary?.plugins ?? EMPTY_MODEL_PROVIDER_PLUGINS
- const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
const marketplacePluginIds = useMemo(
() =>
@@ -103,7 +102,7 @@ const ModelProviderPage = ({
}
return map
}, [latestVersionData, modelProviderPlugins])
- const enableMarketplace = systemFeatures.enable_marketplace
+ const marketplace = useMarketplace()
const isDefaultModelLoading =
isTextGenerationDefaultModelLoading ||
isEmbeddingsDefaultModelLoading ||
@@ -201,7 +200,6 @@ const ModelProviderPage = ({
const showConfiguredProviders = !isLoadingModelProviders && !!filteredConfiguredProviders?.length
const showNotConfiguredProviders =
!isLoadingModelProviders && !!filteredNotConfiguredProviders?.length
- const showMarketplace = !isLoadingModelProviders && enableMarketplace
const toolbar = (
<div
className={
@@ -263,8 +261,7 @@ const ModelProviderPage = ({
showEmptyProvider={showEmptyProvider}
showConfiguredProviders={showConfiguredProviders}
showNotConfiguredProviders={showNotConfiguredProviders}
- showMarketplace={showMarketplace}
- enableMarketplace={enableMarketplace}
+ marketplace={marketplace}
searchText={searchText}
pluginSummaryMap={pluginSummaryMap}
onOpenMarketplace={onOpenMarketplace}
diff --git a/web/app/components/header/account-setting/model-provider-page/install-from-marketplace.tsx b/web/app/components/header/account-setting/model-provider-page/install-from-marketplace.tsx
index dc427a3389a..850c6dd02fc 100644
--- a/web/app/components/header/account-setting/model-provider-page/install-from-marketplace.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/install-from-marketplace.tsx
@@ -1,4 +1,5 @@
import type { Plugin } from '@/app/components/plugins/types'
+import type { MarketplaceLinks } from '@/features/marketplace/links'
import { cn } from '@langgenius/dify-ui/cn'
import { Separator } from '@langgenius/dify-ui/separator'
import { useQuery } from '@tanstack/react-query'
@@ -7,7 +8,6 @@ import { useCallback, useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
import List from '@/app/components/plugins/marketplace/list'
-import { getMarketplaceCategoryUrl } from '@/app/components/plugins/marketplace/utils'
import { usePluginSettingsAccess } from '@/app/components/plugins/plugin-page/use-reference-setting'
import ProviderCard from '@/app/components/plugins/provider-card'
import { PluginCategoryEnum } from '@/app/components/plugins/types'
@@ -16,11 +16,13 @@ import { consoleQuery } from '@/service/console'
import { useMarketplaceAllPlugins } from './hooks'
type InstallFromMarketplaceProps = {
+ marketplace: MarketplaceLinks
onOpenMarketplace?: () => void
searchText: string
stepByStepTourTarget?: string
}
const InstallFromMarketplace = ({
+ marketplace,
onOpenMarketplace,
searchText,
stepByStepTourTarget,
@@ -68,11 +70,21 @@ const InstallFromMarketplace = ({
})
}
- const cardRender = useCallback((plugin: Plugin) => {
- if (plugin.type === 'bundle') return null
+ const cardRender = useCallback(
+ (plugin: Plugin) => {
+ if (plugin.type === 'bundle') return null
- return <ProviderCard key={plugin.plugin_id} className="h-36.5" payload={plugin} />
- }, [])
+ return (
+ <ProviderCard
+ key={plugin.plugin_id}
+ className="h-36.5"
+ marketplace={marketplace}
+ payload={plugin}
+ />
+ )
+ },
+ [marketplace],
+ )
return (
<div
@@ -122,7 +134,7 @@ const InstallFromMarketplace = ({
<Link
target="_blank"
rel="noopener noreferrer"
- href={getMarketplaceCategoryUrl(PluginCategoryEnum.model, { theme })}
+ href={marketplace.category(PluginCategoryEnum.model, { theme })}
className="inline-flex items-center system-sm-medium text-text-accent"
>
{t(($) => $['marketplace.difyMarketplace'], { ns: 'plugin' })}
diff --git a/web/app/components/header/account-setting/model-provider-page/model-provider-page-body.tsx b/web/app/components/header/account-setting/model-provider-page/model-provider-page-body.tsx
index 078dfdf9585..b267862f41e 100644
--- a/web/app/components/header/account-setting/model-provider-page/model-provider-page-body.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/model-provider-page-body.tsx
@@ -1,6 +1,7 @@
import type { ModelProviderSummaryResponse } from '@dify/contracts/api/console/workspaces/types.gen'
import type { FC } from 'react'
import type { ModelProviderPluginSummary } from './index'
+import type { MarketplaceLinks } from '@/features/marketplace/links'
import { useSuspenseQuery } from '@tanstack/react-query'
import { Trans, useTranslation } from 'react-i18next'
import { SkeletonContainer, SkeletonRectangle, SkeletonRow } from '@/app/components/base/skeleton'
@@ -18,8 +19,7 @@ type ModelProviderPageBodyProps = {
showEmptyProvider: boolean
showConfiguredProviders: boolean
showNotConfiguredProviders: boolean
- showMarketplace: boolean
- enableMarketplace: boolean
+ marketplace: MarketplaceLinks | null
searchText: string
pluginSummaryMap: Map<string, ModelProviderPluginSummary>
onOpenMarketplace?: () => void
@@ -162,8 +162,7 @@ const ModelProviderPageBody: FC<ModelProviderPageBodyProps> = ({
showEmptyProvider,
showConfiguredProviders,
showNotConfiguredProviders,
- showMarketplace,
- enableMarketplace,
+ marketplace,
searchText,
pluginSummaryMap,
onOpenMarketplace,
@@ -190,7 +189,7 @@ const ModelProviderPageBody: FC<ModelProviderPageBodyProps> = ({
)}
{showEmptyProvider && (
<EmptyProviderState
- enableMarketplace={enableMarketplace}
+ enableMarketplace={marketplace !== null}
stepByStepTourTarget={
!showConfiguredProviders && !showNotConfiguredProviders
? STEP_BY_STEP_TOUR_TARGETS.integrationModelProviderProduction
@@ -222,9 +221,10 @@ const ModelProviderPageBody: FC<ModelProviderPageBodyProps> = ({
/>
</div>
)}
- {showMarketplace && (
+ {!isLoadingModelProviders && marketplace && (
<div>
<InstallFromMarketplace
+ marketplace={marketplace}
searchText={searchText}
onOpenMarketplace={onOpenMarketplace}
stepByStepTourTarget={STEP_BY_STEP_TOUR_TARGETS.integrationModelProviderInstall}
diff --git a/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/marketplace-section.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/marketplace-section.spec.tsx
index d356202d72c..0937db6da78 100644
--- a/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/marketplace-section.spec.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/marketplace-section.spec.tsx
@@ -1,5 +1,6 @@
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { marketplaceLinks } from '@/features/marketplace/links'
import { ModelProviderQuotaGetPaid } from '@/types/model-provider'
import MarketplaceSection from '../marketplace-section'
@@ -15,7 +16,9 @@ const defaultProps = {
describe('MarketplaceSection', () => {
it('keeps the install action named and focused while preventing repeat installation', async () => {
const user = userEvent.setup()
- const { rerender } = render(<MarketplaceSection {...defaultProps} />)
+ const { rerender } = render(
+ <MarketplaceSection marketplace={marketplaceLinks} {...defaultProps} />,
+ )
const installButton = screen.getByRole('button', {
name: 'modelProvider.modelProvider.selector.install OpenAI',
})
@@ -29,6 +32,7 @@ describe('MarketplaceSection', () => {
rerender(
<MarketplaceSection
+ marketplace={marketplaceLinks}
{...defaultProps}
installingProvider={ModelProviderQuotaGetPaid.OPENAI}
/>,
diff --git a/web/app/components/header/account-setting/model-provider-page/model-selector/marketplace-section.tsx b/web/app/components/header/account-setting/model-provider-page/model-selector/marketplace-section.tsx
index b6246351fb9..cfe14c58314 100644
--- a/web/app/components/header/account-setting/model-provider-page/model-selector/marketplace-section.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/model-selector/marketplace-section.tsx
@@ -1,14 +1,15 @@
+import type { MarketplaceLinks } from '@/features/marketplace/links'
import type { ModelProviderQuotaGetPaid } from '@/types/model-provider'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from '@langgenius/dify-ui/collapsible'
import { useId } from 'react'
import { useTranslation } from 'react-i18next'
-import { getMarketplaceCategoryUrl } from '@/app/components/plugins/marketplace/utils'
import { PluginCategoryEnum } from '@/app/components/plugins/types'
import { modelNameMap, providerLogoMap } from '../utils'
type MarketplaceSectionProps = {
+ marketplace: MarketplaceLinks
marketplaceProviders: ModelProviderQuotaGetPaid[]
marketplaceCollapsed: boolean
installingProvider: ModelProviderQuotaGetPaid | null
@@ -20,6 +21,7 @@ type MarketplaceSectionProps = {
}
function MarketplaceSection({
+ marketplace,
marketplaceProviders,
marketplaceCollapsed,
installingProvider,
@@ -135,7 +137,7 @@ function MarketplaceSection({
) : (
<a
className="flex cursor-pointer items-center gap-0.5 rounded-md px-3 py-1.5 outline-hidden focus-visible:ring-2 focus-visible:ring-state-accent-solid"
- href={getMarketplaceCategoryUrl(PluginCategoryEnum.model, { theme })}
+ href={marketplace.category(PluginCategoryEnum.model, { theme })}
target="_blank"
rel="noopener noreferrer"
>
diff --git a/web/app/components/header/account-setting/model-provider-page/model-selector/popup.tsx b/web/app/components/header/account-setting/model-provider-page/model-selector/popup.tsx
index e9e07a06871..233909abe87 100644
--- a/web/app/components/header/account-setting/model-provider-page/model-selector/popup.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/model-selector/popup.tsx
@@ -20,6 +20,7 @@ import checkTaskStatus from '@/app/components/plugins/install-plugin/base/check-
import useRefreshPluginList from '@/app/components/plugins/install-plugin/hooks/use-refresh-plugin-list'
import useWorkspacePluginInstallPermission from '@/app/components/plugins/install-plugin/hooks/use-workspace-plugin-install-permission'
import { PluginCategoryEnum, TaskStatus } from '@/app/components/plugins/types'
+import { useMarketplace } from '@/features/marketplace/client'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import { renderI18nObject } from '@/i18n/metadata'
import { consoleQuery } from '@/service/console'
@@ -93,10 +94,7 @@ function Popup({
)
const modelProviders = providerSummary?.data ?? EMPTY_MODEL_PROVIDERS
const modelProviderPlugins = providerSummary?.plugins ?? EMPTY_MODEL_PROVIDER_PLUGINS
- const { data: enableMarketplace } = useSuspenseQuery({
- ...systemFeaturesQueryOptions(),
- select: (systemFeatures) => systemFeatures.enable_marketplace,
- })
+ const marketplace = useMarketplace()
const { data: deploymentEdition } = useSuspenseQuery({
...systemFeaturesQueryOptions(),
select: ({ deployment_edition }) => deployment_edition,
@@ -119,16 +117,16 @@ function Popup({
[modelProviders],
)
const aiCreditVisibleProviders = useMemo(() => {
- if (!enableMarketplace || isCreditsExhausted) return new Set<string>()
+ if (!marketplace || isCreditsExhausted) return new Set<string>()
return new Set(
modelProviders
.filter((provider) => providerSupportsCredits(provider, trialModels, deploymentEdition))
.map((provider) => provider.provider),
)
- }, [deploymentEdition, enableMarketplace, isCreditsExhausted, modelProviders, trialModels])
+ }, [deploymentEdition, marketplace, isCreditsExhausted, modelProviders, trialModels])
const showCreditsExhaustedAlert =
- enableMarketplace &&
+ marketplace !== null &&
isCreditsExhausted &&
modelProviders.some((provider) =>
providerSupportsCredits(provider, trialModels, deploymentEdition),
@@ -145,7 +143,7 @@ function Popup({
const handleInstallPlugin = useCallback(
async (key: ModelProviderQuotaGetPaid) => {
- if (!enableMarketplace || !canInstallPlugin || installingProvider) return
+ if (!marketplace || !canInstallPlugin || installingProvider) return
const pluginId = providerKeyToPluginId[key]
const [org, name] = pluginId.split('/')
if (!org || !name) return
@@ -170,7 +168,7 @@ function Popup({
}
},
[
- enableMarketplace,
+ marketplace,
canInstallPlugin,
installPackageFromMarketPlace,
installingProvider,
@@ -239,7 +237,7 @@ function Popup({
const shouldShowModelPredicateReveal = !!modelPredicate
const marketplaceProviders = useMemo(() => {
- if (!enableMarketplace) return []
+ if (!marketplace) return []
const installedPluginIds = new Set(
Object.values(modelProviderPlugins).map((plugin) => plugin.plugin_id),
@@ -247,7 +245,7 @@ function Popup({
return MODEL_PROVIDER_QUOTA_GET_PAID.filter(
(key) => !installedPluginIds.has(providerKeyToPluginId[key]),
)
- }, [enableMarketplace, modelProviderPlugins])
+ }, [marketplace, modelProviderPlugins])
const searchStatus =
!filteredModelList.length && installedModelList.length > 0
@@ -308,8 +306,9 @@ function Popup({
onClick={() => setShowIncompatibleModels((value) => !value)}
/>
)}
- {enableMarketplace && (
+ {marketplace && (
<MarketplaceSection
+ marketplace={marketplace}
marketplaceProviders={marketplaceProviders}
marketplaceCollapsed={marketplaceCollapsed}
installingProvider={installingProvider}
diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/provider-card-actions.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/provider-card-actions.tsx
index d85d11cbe03..01f6d28d4d9 100644
--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/provider-card-actions.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/provider-card-actions.tsx
@@ -22,7 +22,7 @@ import {
MenuTrigger,
} from '@langgenius/dify-ui/menu'
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
-import { skipToken, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useId, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useLocale } from '#i18n'
@@ -34,14 +34,11 @@ import { PluginCategoryEnum, PluginSource } from '@/app/components/plugins/types
import { checkGitHubPluginUpdate } from '@/app/components/plugins/update-plugin/check-github-update'
import MarketplaceUpdateDialog from '@/app/components/plugins/update-plugin/from-market-place'
import { useModalContext } from '@/context/modal-context'
-import { systemFeaturesQueryOptions } from '@/features/system-features/client'
-import useTheme from '@/hooks/use-theme'
+import { useMarketplace, useMarketplacePluginVersions } from '@/features/marketplace/client'
import useTimestamp from '@/hooks/use-timestamp'
import { consoleQuery } from '@/service/console'
-import { marketplaceQuery } from '@/service/marketplace'
import { normalizeInstalledPluginDetail, usePluginAutoUpgradeSettings } from '@/service/use-plugins'
import { isEarlierThanVersion } from '@/utils/semver'
-import { getMarketplaceUrl } from '@/utils/var'
type Props =
| Readonly<{
@@ -81,7 +78,6 @@ function ProviderCardActions(props: Props) {
const { canDeletePlugin, canUpdatePlugin } = usePluginSettingsAccess()
const { setShowUpdatePluginModal } = useModalContext()
const locale = useLocale()
- const { theme } = useTheme()
const { onUpdate } = props
const pluginID = props.detail ? props.detail.plugin_id : props.summary.plugin_id
const source = props.detail ? props.detail.source : pluginSourceMap[props.summary.source]
@@ -91,17 +87,14 @@ function ProviderCardActions(props: Props) {
props.detail?.latest_unique_identifier ?? props.summary?.latestUniqueIdentifier
const isFromMarketplace = source === PluginSource.marketplace
const isFromGitHub = source === PluginSource.github
- const canChangeVersion = canUpdatePlugin && isFromMarketplace
const hasNewVersion = isFromMarketplace && !!latestVersion && latestVersion !== version
const category = props.detail?.declaration.category ?? PluginCategoryEnum.model
const autoUpgradeSettings = usePluginAutoUpgradeSettings(category)
- const { data: enableMarketplace } = useQuery({
- ...systemFeaturesQueryOptions(),
- select: (value) => value.enable_marketplace,
- })
+ const marketplace = useMarketplace()
+ const canChangeVersion = canUpdatePlugin && isFromMarketplace && marketplace !== null
const policy = autoUpgradeSettings.data?.auto_upgrade
const autoUpgradeEnabled =
- enableMarketplace &&
+ marketplace !== null &&
policy &&
policy.strategy_setting !== 'disabled' &&
(policy.upgrade_mode === 'all' ||
@@ -123,18 +116,9 @@ function ProviderCardActions(props: Props) {
response.plugins[0] ? normalizeInstalledPluginDetail(response.plugins[0]) : undefined,
}),
)
- const versionsQuery = useQuery(
- marketplaceQuery.pluginVersions.queryOptions({
- input:
- organization && pluginName
- ? {
- params: { organization, pluginName },
- query: { page: 1, page_size: 100 },
- }
- : skipToken,
- enabled: versionMenuRequested && canChangeVersion,
- retry: false,
- }),
+ const versionsQuery = useMarketplacePluginVersions(
+ pluginID,
+ versionMenuRequested && canChangeVersion,
)
const detail = props.detail ?? detailQuery.data
const loadingVersions =
@@ -144,15 +128,6 @@ function ProviderCardActions(props: Props) {
(!props.detail && detailQuery.isPending) ||
autoUpgradeSettings.isPending)
const versionMenuOpen = versionMenuRequested && canChangeVersion && !loadingVersions
- const detailUrl =
- isFromMarketplace && organization && pluginName
- ? getMarketplaceUrl(
- `/plugins/${props.detail?.declaration.author ?? organization}/${props.detail?.declaration.name ?? pluginName}`,
- { language: locale, theme },
- )
- : isFromGitHub && detail?.meta?.repo
- ? `https://github.com/${detail.meta.repo}`
- : ''
const handlePluginChanged = async () => {
await Promise.all([
@@ -337,7 +312,15 @@ function ProviderCardActions(props: Props) {
onInfo={handleInfo}
onCheckVersion={handleUpdate}
onRemove={() => setShowDeleteConfirm(true)}
- detailUrl={detailUrl}
+ marketplacePlugin={
+ organization && pluginName
+ ? {
+ org: props.detail?.declaration.author ?? organization,
+ name: props.detail?.declaration.name ?? pluginName,
+ }
+ : undefined
+ }
+ repo={detail?.meta?.repo}
align="start"
destructiveRemove
showCheckVersion={canUpdatePlugin}
diff --git a/web/app/components/integrations/__tests__/page.spec.tsx b/web/app/components/integrations/__tests__/page.spec.tsx
index edcf8ca4529..b66cb29e63b 100644
--- a/web/app/components/integrations/__tests__/page.spec.tsx
+++ b/web/app/components/integrations/__tests__/page.spec.tsx
@@ -377,14 +377,16 @@ it.each([
)
})
-it('passes the category marketplace path to the settings host from the install menu', async () => {
+it('opens the category marketplace path from the install menu', async () => {
const user = userEvent.setup()
- const onSwitchToMarketplace = vi.fn()
- renderPage({ props: { section: 'trigger', onSwitchToMarketplace } })
+ renderPage({ props: { section: 'trigger' } })
await user.click(await screen.findByRole('button', { name: 'plugin.installAction' }))
await user.click(screen.getByRole('menuitem', { name: 'plugin.source.marketplace' }))
- expect(onSwitchToMarketplace).toHaveBeenCalledExactlyOnceWith('/plugins/trigger')
- expect(window.open).not.toHaveBeenCalled()
+ expect(window.open).toHaveBeenCalledExactlyOnceWith(
+ expect.stringContaining('/plugins/trigger?source='),
+ '_blank',
+ 'noopener,noreferrer',
+ )
})
it('saves category-specific automatic update settings from the toolbar', async () => {
diff --git a/web/app/components/integrations/index.tsx b/web/app/components/integrations/index.tsx
index c3ada47f424..18efdc41af2 100644
--- a/web/app/components/integrations/index.tsx
+++ b/web/app/components/integrations/index.tsx
@@ -35,10 +35,10 @@ import {
toolCategoryBySection,
} from '@/app/components/integrations/routes'
import { useDocLink } from '@/context/i18n'
+import { useMarketplace } from '@/features/marketplace/client'
import useDocumentTitle from '@/hooks/use-document-title'
import Link from '@/next/link'
import { useRouter } from '@/next/navigation'
-import { getMarketplaceUrl } from '@/utils/var'
import { STEP_BY_STEP_TOUR_TARGETS } from '../step-by-step-tour/target-registry'
import { getPluginCategoryBySection, useIntegrationNav } from './hooks/use-integration-nav'
import { useIntegrationPermissions } from './hooks/use-integration-permissions'
@@ -53,7 +53,6 @@ import {
type IntegrationsPageProps = {
onSectionChange?: (section: IntegrationSection) => void
- onSwitchToMarketplace?: (path: string) => void
section?: IntegrationSection
syncDocumentTitle?: boolean
}
@@ -144,7 +143,6 @@ function ToolsDisclosureIcon({ className }: { className?: string }) {
export default function IntegrationsPage({
onSectionChange,
- onSwitchToMarketplace,
section: routeSection,
syncDocumentTitle = false,
}: IntegrationsPageProps) {
@@ -216,6 +214,7 @@ export default function IntegrationsPage({
<UpdateSettingDialog category={pluginSettingCategory} />
</div>
) : undefined
+ const marketplace = useMarketplace()
const marketplaceUrlPath = buildMarketplaceUrlPathByIntegrationSection(section)
const headerDescription =
integrationHeader?.description ??
@@ -235,13 +234,10 @@ export default function IntegrationsPage({
headerDescription
)
const handleSwitchToMarketplace = () => {
- if (onSwitchToMarketplace) {
- onSwitchToMarketplace(marketplaceUrlPath)
- return
- }
+ if (!marketplace) return
window.open(
- getMarketplaceUrl(marketplaceUrlPath, undefined, { source: window.location.origin }),
+ marketplace.page(marketplaceUrlPath, undefined, window.location.origin),
'_blank',
'noopener,noreferrer',
)
diff --git a/web/app/components/integrations/modal.tsx b/web/app/components/integrations/modal.tsx
index 35bc3745857..599943ee89f 100644
--- a/web/app/components/integrations/modal.tsx
+++ b/web/app/components/integrations/modal.tsx
@@ -1,10 +1,8 @@
'use client'
import type { IntegrationSection } from './routes'
-import { useCallback } from 'react'
import { useTranslation } from 'react-i18next'
import MenuDialog from '@/app/components/header/account-setting/menu-dialog'
-import { getMarketplaceUrl } from '@/utils/var'
import IntegrationsPage from './index'
type IntegrationsSettingModalProps = {
@@ -19,13 +17,6 @@ export default function IntegrationsSettingModal({
onSectionChange,
}: IntegrationsSettingModalProps) {
const { t } = useTranslation(['navigation'])
- const handleSwitchToMarketplace = useCallback((path: string) => {
- window.open(
- getMarketplaceUrl(path, undefined, { source: window.location.origin }),
- '_blank',
- 'noopener,noreferrer',
- )
- }, [])
return (
<MenuDialog
@@ -34,11 +25,7 @@ export default function IntegrationsSettingModal({
>
<div className="mx-auto flex h-dvh w-[min(1440px,calc(100vw-48px))] shrink-0 py-6">
<div className="relative flex min-h-0 w-full shrink-0 overflow-hidden rounded-2xl border border-divider-subtle bg-components-panel-bg shadow-2xl">
- <IntegrationsPage
- section={section}
- onSectionChange={onSectionChange}
- onSwitchToMarketplace={handleSwitchToMarketplace}
- />
+ <IntegrationsPage section={section} onSectionChange={onSectionChange} />
</div>
</div>
</MenuDialog>
diff --git a/web/app/components/integrations/tool-provider-list.tsx b/web/app/components/integrations/tool-provider-list.tsx
index 10906bda1d0..d3ad4fd87f9 100644
--- a/web/app/components/integrations/tool-provider-list.tsx
+++ b/web/app/components/integrations/tool-provider-list.tsx
@@ -11,7 +11,7 @@ import {
ScrollAreaThumb,
ScrollAreaViewport,
} from '@langgenius/dify-ui/scroll-area'
-import { useQuery, useSuspenseQuery } from '@tanstack/react-query'
+import { useQuery } from '@tanstack/react-query'
import { useCallback, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { isSearchResultEmpty } from '@/app/components/base/search-input/search-state'
@@ -36,7 +36,7 @@ import {
selectToolCollections,
selectToolsWithProvider,
} from '@/app/components/tools/utils/query-select'
-import { systemFeaturesQueryOptions } from '@/features/system-features/client'
+import { useMarketplace } from '@/features/marketplace/client'
import { consoleQuery } from '@/service/console'
import { useCheckInstalled, useInvalidateInstalledPluginList } from '@/service/use-plugins'
import { useToolProviderCategory } from './hooks/use-tool-provider-category'
@@ -59,10 +59,7 @@ const ProviderList = ({ category, contentInset = 'default', layout }: ProviderLi
const { canDeletePlugin, canSetPluginPreferences, canUpdatePlugin } = usePluginSettingsAccess()
const canManageTools = useCanManageTools()
const canManageMCP = useCanManageMCP()
- const { data: enable_marketplace } = useSuspenseQuery({
- ...systemFeaturesQueryOptions(),
- select: (s) => s.enable_marketplace,
- })
+ const marketplace = useMarketplace()
const { activeTab, handleCategoryChange, isRouteCategory } = useToolProviderCategory(category)
const contentPaddingClassName = toolsContentInsetClassNames[contentInset]
const toolListFrameClassName = cn(contentPaddingClassName, toolsUnifiedContentFrameClassName)
@@ -237,8 +234,9 @@ const ProviderList = ({ category, contentInset = 'default', layout }: ProviderLi
{isCollectionSearchEmpty && activeTab === 'builtin' && (
<div className={cn('h-56 shrink-0', toolListFrameClassName)} />
)}
- {enable_marketplace && activeTab === 'builtin' && (
+ {marketplace && activeTab === 'builtin' && (
<BuiltinMarketplacePanel
+ marketplace={marketplace}
containerRef={containerRef}
contentInset={contentInset}
keywords={keywords}
diff --git a/web/app/components/main-nav/components/help-menu.tsx b/web/app/components/main-nav/components/help-menu.tsx
index e8d0948e239..82d1c45ee0e 100644
--- a/web/app/components/main-nav/components/help-menu.tsx
+++ b/web/app/components/main-nav/components/help-menu.tsx
@@ -29,7 +29,6 @@ import {
MenuItemContent,
} from '@/app/components/header/account-menu/menu-item-content'
import GithubStar from '@/app/components/header/github-star'
-import { useCreatorCenterUrl } from '@/app/components/plugins/marketplace/creator-center-url'
import { trackStepByStepTourEvent } from '@/app/components/step-by-step-tour/analytics'
import {
disableStepByStepTourForCurrentWorkspaceAtom,
@@ -39,7 +38,6 @@ import {
stepByStepTourSkipRecoveryVisibleAtom,
stepByStepTourStateUpdatingAtom,
} from '@/app/components/step-by-step-tour/state'
-import { MARKETPLACE_URL_PREFIX } from '@/config'
import { getLangGeniusVersionInfo } from '@/context/app-context-normalizers'
import { useDocLink } from '@/context/i18n'
import {
@@ -49,6 +47,7 @@ import {
} from '@/context/workspace-state'
import { env } from '@/env'
import { userProfileQueryOptions } from '@/features/account-profile/client'
+import { useMarketplace } from '@/features/marketplace/client'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import { consoleQuery } from '@/service/console'
import styles from './help-menu.module.css'
@@ -93,7 +92,7 @@ const MenuSwitchIndicator = ({ checked }: { checked: boolean }) => (
const HelpMenu = ({ triggerIcon, triggerClassName, triggerRef, triggerSize }: HelpMenuProps) => {
const { t } = useTranslation(['common', 'navigation'])
const docLink = useDocLink()
- const creatorCenterUrl = useCreatorCenterUrl(MARKETPLACE_URL_PREFIX)
+ const marketplace = useMarketplace()
const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
const { data: profileMeta } = useSuspenseQuery({
...userProfileQueryOptions(),
@@ -258,18 +257,20 @@ const HelpMenu = ({ triggerIcon, triggerClassName, triggerRef, triggerSize }: He
</MenuGroup>
<MenuSeparator className="my-0!" />
<MenuGroup className="py-1">
- <MenuLinkItem
- href={creatorCenterUrl}
- target="_blank"
- rel="noopener noreferrer"
- className="h-8 gap-1 px-3 py-1.5"
- >
- <MenuItemContent
- iconClassName="i-ri-user-star-line"
- label={t(($) => $['mainNav.help.creatorCenter'], { ns: 'navigation' })}
- trailing={<ExternalLinkIndicator />}
- />
- </MenuLinkItem>
+ {marketplace && (
+ <MenuLinkItem
+ href={marketplace.creatorCenter}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="h-8 gap-1 px-3 py-1.5"
+ >
+ <MenuItemContent
+ iconClassName="i-ri-user-star-line"
+ label={t(($) => $['mainNav.help.creatorCenter'], { ns: 'navigation' })}
+ trailing={<ExternalLinkIndicator />}
+ />
+ </MenuLinkItem>
+ )}
<MenuLinkItem
href="https://github.com/langgenius/dify"
target="_blank"
diff --git a/web/app/components/main-nav/index.tsx b/web/app/components/main-nav/index.tsx
index 860bb54ae7f..fd0f2dc0a0f 100644
--- a/web/app/components/main-nav/index.tsx
+++ b/web/app/components/main-nav/index.tsx
@@ -13,6 +13,7 @@ import StepByStepTourMount from '@/app/components/step-by-step-tour/mount'
import { isCurrentWorkspaceDatasetOperatorAtom } from '@/context/workspace-state'
import { userProfileQueryOptions } from '@/features/account-profile/client'
import { isAgentV2Enabled } from '@/features/agent-v2/feature-flag'
+import { useMarketplace } from '@/features/marketplace/client'
import { useCanViewSkills } from '@/features/skills/permissions'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import Link from '@/next/link'
@@ -32,6 +33,7 @@ export function MainNav({ className, initialPlatform }: MainNavProps) {
const pathname = usePathname()
const isCurrentWorkspaceDatasetOperator = useAtomValue(isCurrentWorkspaceDatasetOperatorAtom)
const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
+ const marketplaceEnabled = useMarketplace() !== null
const { data: currentEnv } = useSuspenseQuery({
...userProfileQueryOptions(),
select: (data) => data.meta.currentEnv,
@@ -53,7 +55,7 @@ export function MainNav({ className, initialPlatform }: MainNavProps) {
agentV2Enabled,
canViewSkills,
isCurrentWorkspaceDatasetOperator,
- marketplaceEnabled: systemFeatures.enable_marketplace,
+ marketplaceEnabled,
skillEnabled: enableSkill === true,
}),
).map((route) => ({
@@ -68,7 +70,7 @@ export function MainNav({ className, initialPlatform }: MainNavProps) {
canViewSkills,
enableSkill,
isCurrentWorkspaceDatasetOperator,
- systemFeatures.enable_marketplace,
+ marketplaceEnabled,
t,
],
)
diff --git a/web/app/components/plugins/__tests__/utils.spec.ts b/web/app/components/plugins/__tests__/utils.spec.ts
index 07198c4a751..6a220e95ade 100644
--- a/web/app/components/plugins/__tests__/utils.spec.ts
+++ b/web/app/components/plugins/__tests__/utils.spec.ts
@@ -1,6 +1,7 @@
import type { Plugin } from '../types'
import { describe, expect, it } from 'vite-plus/test'
-import { API_PREFIX, MARKETPLACE_API_PREFIX } from '@/config'
+import { API_PREFIX } from '@/config'
+import { MARKETPLACE_API_PREFIX } from '@/features/marketplace/api'
import { getPluginCardIconUrl } from '../utils'
const createPlugin = (
diff --git a/web/app/components/plugins/card/__tests__/index.spec.tsx b/web/app/components/plugins/card/__tests__/index.spec.tsx
index d3a81b75372..302509169cc 100644
--- a/web/app/components/plugins/card/__tests__/index.spec.tsx
+++ b/web/app/components/plugins/card/__tests__/index.spec.tsx
@@ -1,5 +1,5 @@
import { render, screen } from '@testing-library/react'
-import { MARKETPLACE_API_PREFIX } from '@/config'
+import { MARKETPLACE_API_PREFIX } from '@/features/marketplace/api'
import { createMarketplacePluginFixture } from '@/test/fixtures/plugin'
import Card from '../index'
diff --git a/web/app/components/plugins/install-plugin/hooks/use-install-from-marketplace-query.ts b/web/app/components/plugins/install-plugin/hooks/use-install-from-marketplace-query.ts
index 17d31b2cb2f..feecd2a879b 100644
--- a/web/app/components/plugins/install-plugin/hooks/use-install-from-marketplace-query.ts
+++ b/web/app/components/plugins/install-plugin/hooks/use-install-from-marketplace-query.ts
@@ -3,7 +3,7 @@
import type { Dependency, PluginDeclaration, PluginManifestInMarket } from '../../types'
import { useEffect, useState } from 'react'
import { parseMarketplacePluginId } from '@/app/components/plugins/plugin-routes'
-import { MARKETPLACE_API_PREFIX } from '@/config'
+import { getMarketplacePluginIconUrl } from '@/features/marketplace/api'
import { usePluginInstallation } from '@/hooks/use-query-params'
import {
fetchBundleInfoFromMarketPlace,
@@ -70,7 +70,7 @@ export const useInstallFromMarketplaceQuery = ({
manifest: {
...plugin,
version: version.version,
- icon: `${MARKETPLACE_API_PREFIX}/plugins/${plugin.org}/${plugin.name}/icon`,
+ icon: getMarketplacePluginIconUrl(`${plugin.org}/${plugin.name}`),
},
})
setIsShowInstallFromMarketplace(true)
diff --git a/web/app/components/plugins/install-plugin/install-bundle/item/loaded-item.tsx b/web/app/components/plugins/install-plugin/install-bundle/item/loaded-item.tsx
index a297bf724e6..b7667138be2 100644
--- a/web/app/components/plugins/install-plugin/install-bundle/item/loaded-item.tsx
+++ b/web/app/components/plugins/install-plugin/install-bundle/item/loaded-item.tsx
@@ -3,7 +3,7 @@ import type { FC } from 'react'
import type { Plugin, VersionProps } from '../../../types'
import { Checkbox } from '@langgenius/dify-ui/checkbox'
import * as React from 'react'
-import { MARKETPLACE_API_PREFIX } from '@/config'
+import { getMarketplacePluginIconUrl } from '@/features/marketplace/api'
import Card from '../../../card'
import useGetIcon from '../../base/use-get-icon'
import Version from '../../base/version'
@@ -44,7 +44,7 @@ const LoadedItem: FC<Props> = ({
payload={{
...payload,
icon: isFromMarketPlace
- ? `${MARKETPLACE_API_PREFIX}/plugins/${payload.org}/${payload.name}/icon`
+ ? getMarketplacePluginIconUrl(`${payload.org}/${payload.name}`)
: getIconUrl(payload.icon),
}}
titleLeft={payload.version ? <Version {...versionInfo} /> : null}
diff --git a/web/app/components/plugins/install-plugin/install-bundle/steps/installed.tsx b/web/app/components/plugins/install-plugin/install-bundle/steps/installed.tsx
index 135f4444e78..8269d0f69ad 100644
--- a/web/app/components/plugins/install-plugin/install-bundle/steps/installed.tsx
+++ b/web/app/components/plugins/install-plugin/install-bundle/steps/installed.tsx
@@ -6,7 +6,7 @@ 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 { MARKETPLACE_API_PREFIX } from '@/config'
+import { getMarketplacePluginIconUrl } from '@/features/marketplace/api'
import useGetIcon from '../../base/use-get-icon'
import Version from '../../base/version'
@@ -40,7 +40,7 @@ const Installed: FC<Props> = ({ list, installStatus, versionInfo, onCancel, isHi
payload={{
...plugin,
icon: installStatus[index]!.isFromMarketPlace
- ? `${MARKETPLACE_API_PREFIX}/plugins/${plugin.org}/${plugin.name}/icon`
+ ? getMarketplacePluginIconUrl(`${plugin.org}/${plugin.name}`)
: getIconUrl(plugin.icon),
}}
installed={installStatus[index]!.success}
diff --git a/web/app/components/plugins/marketplace/__tests__/creator-center-url.spec.ts b/web/app/components/plugins/marketplace/__tests__/creator-center-url.spec.ts
deleted file mode 100644
index 5801f854890..00000000000
--- a/web/app/components/plugins/marketplace/__tests__/creator-center-url.spec.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import { describe, expect, it } from 'vite-plus/test'
-import {
- getCreatorCenterUrl,
- PUBLIC_CREATOR_CENTER_URL,
- rewriteMarketplaceOriginToCreators,
-} from '../creator-center-url'
-
-describe('getCreatorCenterUrl', () => {
- it('maps the public Marketplace to the public Creator Center', () => {
- expect(getCreatorCenterUrl('https://marketplace.dify.ai')).toBe('https://creators.dify.ai/')
- })
-
- it('maps marketplace.dify.dev to creators.dify.dev', () => {
- expect(getCreatorCenterUrl('https://marketplace.dify.dev')).toBe('https://creators.dify.dev/')
- })
-
- it('keeps the staging suffix on the Creators host', () => {
- expect(getCreatorCenterUrl('https://marketplace-staging.dify.dev')).toBe(
- 'https://creators-staging.dify.dev/',
- )
- })
-
- it('falls back to the public Creator Center for localhost', () => {
- expect(getCreatorCenterUrl('http://localhost:3000')).toBe(PUBLIC_CREATOR_CENTER_URL)
- })
-
- it('falls back to the public Creator Center when the prefix is empty', () => {
- expect(getCreatorCenterUrl('')).toBe(PUBLIC_CREATOR_CENTER_URL)
- })
-
- it('prefers the current Marketplace page over a stale configured prefix', () => {
- expect(getCreatorCenterUrl('https://marketplace.dify.ai', 'https://marketplace.dify.dev')).toBe(
- 'https://creators.dify.dev/',
- )
- })
-})
-
-describe('rewriteMarketplaceOriginToCreators', () => {
- it('returns null for hosts that are not a Marketplace surface', () => {
- expect(rewriteMarketplaceOriginToCreators('https://cloud.dify.ai')).toBeNull()
- expect(rewriteMarketplaceOriginToCreators('http://localhost:3000')).toBeNull()
- expect(rewriteMarketplaceOriginToCreators('')).toBeNull()
- })
-})
diff --git a/web/app/components/plugins/marketplace/__tests__/hydration-server.spec.tsx b/web/app/components/plugins/marketplace/__tests__/hydration-server.spec.tsx
index 2588c3931f8..8bd2daddd95 100644
--- a/web/app/components/plugins/marketplace/__tests__/hydration-server.spec.tsx
+++ b/web/app/components/plugins/marketplace/__tests__/hydration-server.spec.tsx
@@ -7,12 +7,18 @@ vi.mock('@/config', () => ({
API_PREFIX: '/api',
APP_VERSION: '1.0.0',
IS_MARKETPLACE: false,
- MARKETPLACE_API_PREFIX: 'https://marketplace.dify.ai/api/v1',
-}))
-
-vi.mock('@/utils/var', () => ({
- getMarketplaceUrl: (path: string) => `https://marketplace.dify.ai${path}`,
}))
+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()
diff --git a/web/app/components/plugins/marketplace/__tests__/query.spec.tsx b/web/app/components/plugins/marketplace/__tests__/query.spec.tsx
index b4b0743f207..8e002a2de16 100644
--- a/web/app/components/plugins/marketplace/__tests__/query.spec.tsx
+++ b/web/app/components/plugins/marketplace/__tests__/query.spec.tsx
@@ -3,7 +3,7 @@ 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 '@/config'
+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'
diff --git a/web/app/components/plugins/marketplace/__tests__/state.spec.tsx b/web/app/components/plugins/marketplace/__tests__/state.spec.tsx
index 861e015c1f4..00c3ff73189 100644
--- a/web/app/components/plugins/marketplace/__tests__/state.spec.tsx
+++ b/web/app/components/plugins/marketplace/__tests__/state.spec.tsx
@@ -10,12 +10,18 @@ vi.mock('@/config', () => ({
API_PREFIX: '/api',
APP_VERSION: '1.0.0',
IS_MARKETPLACE: false,
- MARKETPLACE_API_PREFIX: 'https://marketplace.dify.ai/api/v1',
-}))
-
-vi.mock('@/utils/var', () => ({
- getMarketplaceUrl: (path: string) => `https://marketplace.dify.ai${path}`,
}))
+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()
diff --git a/web/app/components/plugins/marketplace/__tests__/utils.spec.ts b/web/app/components/plugins/marketplace/__tests__/utils.spec.ts
index 6878d2bea7d..10b9926df8e 100644
--- a/web/app/components/plugins/marketplace/__tests__/utils.spec.ts
+++ b/web/app/components/plugins/marketplace/__tests__/utils.spec.ts
@@ -3,14 +3,15 @@ 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('@/config', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@/config')>()),
- MARKETPLACE_API_PREFIX: 'https://marketplace.dify.ai/api/v1',
- MARKETPLACE_URL_PREFIX: 'https://marketplace.dify.ai',
-}))
vi.mock('@/env', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/env')>()
- return { ...actual, env: { ...actual.env, NEXT_PUBLIC_WEB_PREFIX: '' } }
+ return {
+ ...actual,
+ env: {
+ ...actual.env,
+ NEXT_PUBLIC_MARKETPLACE_API_PREFIX: 'https://marketplace.dify.ai/api/v1',
+ },
+ }
})
// Mock marketplace client
@@ -52,24 +53,15 @@ const createMockPlugin = (overrides?: Partial<Plugin>): Plugin => ({
...overrides,
})
-describe('plugin and bundle links', () => {
+describe('plugin and bundle icons', () => {
it.each([
- { type: 'plugin' as const, collection: 'plugins', detail: 'plugin' },
- { type: 'bundle' as const, collection: 'bundles', detail: 'bundles' },
- ])('builds $type links and formats card data', async ({ type, collection, detail }) => {
- const {
- getPluginIconInMarketplace,
- getFormattedPlugin,
- getPluginLinkInMarketplace,
- getPluginDetailLinkInMarketplace,
- } = await import('../utils')
+ { 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(getPluginLinkInMarketplace(plugin)).toBe(
- `https://marketplace.dify.ai/${collection}/test-org/test-plugin`,
- )
- expect(getPluginDetailLinkInMarketplace(plugin)).toBe(`/${detail}/test-org/test-plugin`)
expect(getFormattedPlugin(plugin)).toEqual({
...plugin,
icon,
@@ -78,72 +70,6 @@ describe('plugin and bundle links', () => {
})
})
-describe('getTemplateDetailLinkInMarketplace', () => {
- it('keeps the same local link after a title change and prefers the unique handle', async () => {
- const { getTemplateDetailLinkInMarketplace } = await import('../utils')
- const template = {
- id: '5d107b52-8d4d-447b-9bad-1c5c16b01721',
- template_name: 'Legal Research Agent',
- publisher_handle: 'Dify Display Name',
- publisher_unique_handle: 'dify-unique',
- }
-
- const link = getTemplateDetailLinkInMarketplace(template)
- expect(link).toBe('/template/dify-unique/5d107b52-8d4d-447b-9bad-1c5c16b01721')
- const renamedTemplate = { ...template, template_name: 'Renamed research agent' }
- expect(getTemplateDetailLinkInMarketplace(renamedTemplate)).toBe(link)
- })
-
- it('encodes both path segments and falls back to the publisher handle', async () => {
- const { getTemplateDetailLinkInMarketplace } = await import('../utils')
-
- expect(
- getTemplateDetailLinkInMarketplace({
- id: 'template/one',
- publisher_handle: 'Research / 团队',
- publisher_unique_handle: '',
- }),
- ).toBe('/template/Research%20%2F%20%E5%9B%A2%E9%98%9F/template%2Fone')
- })
-
- it('uses the template fallback when publisher handles are absent', async () => {
- const { getTemplateDetailLinkInMarketplace } = await import('../utils')
-
- expect(getTemplateDetailLinkInMarketplace({ id: 'template-2' })).toBe(
- '/template/template/template-2',
- )
- })
-})
-
-describe('getTemplateLinkInMarketplace', () => {
- it('preserves embedded context while dropping legacy identity parameters', async () => {
- const { getTemplateLinkInMarketplace } = await import('../utils')
-
- const link = new URL(
- getTemplateLinkInMarketplace(
- { id: 'template-1', publisher_handle: 'Display Name', publisher_unique_handle: 'dify' },
- {
- tid: 'legacy-short-id',
- templateId: 'legacy-id',
- creationType: 'templates',
- language: 'zh-Hans',
- theme: 'dark',
- source: 'https://cloud.dify.ai',
- view: 'modal',
- },
- ),
- )
-
- expect(link.origin + link.pathname).toBe('https://marketplace.dify.ai/template/dify/template-1')
- expect(Object.fromEntries(link.searchParams)).toEqual({
- language: 'zh-Hans',
- theme: 'dark',
- source: 'https://cloud.dify.ai',
- view: 'modal',
- })
- })
-})
-
describe('catalog filters', () => {
it.each([
[PLUGIN_TYPE_SEARCH_MAP.tool, 'category=tool', 'plugin'],
diff --git a/web/app/components/plugins/marketplace/creator-center-url.ts b/web/app/components/plugins/marketplace/creator-center-url.ts
index 33f2d3d5566..7e2093f78be 100644
--- a/web/app/components/plugins/marketplace/creator-center-url.ts
+++ b/web/app/components/plugins/marketplace/creator-center-url.ts
@@ -1,48 +1,16 @@
import { useSyncExternalStore } from 'react'
-
-export const PUBLIC_CREATOR_CENTER_URL = 'https://creators.dify.ai/'
+import { getCreatorCenterUrl } from '@/features/marketplace/links'
const subscribe = () => () => {}
-/**
- * marketplace.dify.ai → creators.dify.ai
- * marketplace.dify.dev → creators.dify.dev
- * marketplace-staging.dify.dev → creators-staging.dify.dev
- */
-export const rewriteMarketplaceOriginToCreators = (origin: string): string | null => {
- if (!origin) return null
-
- try {
- const marketplaceUrl = new URL(origin)
- const [service, ...domain] = marketplaceUrl.hostname.split('.')
- if (!service?.startsWith('marketplace') || domain.length === 0) return null
-
- marketplaceUrl.hostname = [service.replace(/^marketplace/, 'creators'), ...domain].join('.')
- marketplaceUrl.pathname = '/'
- marketplaceUrl.search = ''
- marketplaceUrl.hash = ''
- return marketplaceUrl.toString()
- } catch {
- return null
- }
-}
-
-export const getCreatorCenterUrl = (marketplaceUrlPrefix: string, pageOrigin?: string): string => {
- return (
- rewriteMarketplaceOriginToCreators(pageOrigin ?? '') ||
- rewriteMarketplaceOriginToCreators(marketplaceUrlPrefix) ||
- PUBLIC_CREATOR_CENTER_URL
- )
-}
-
/**
* 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 = (marketplaceUrlPrefix: string) => {
+export const useCreatorCenterUrl = () => {
return useSyncExternalStore(
subscribe,
- () => getCreatorCenterUrl(marketplaceUrlPrefix, window.location.origin),
- () => getCreatorCenterUrl(marketplaceUrlPrefix),
+ () => getCreatorCenterUrl(window.location.origin),
+ () => getCreatorCenterUrl(),
)
}
diff --git a/web/app/components/plugins/marketplace/creator-profile/__tests__/data.server.spec.ts b/web/app/components/plugins/marketplace/creator-profile/__tests__/data.server.spec.ts
index 28c4ee1771c..4c10d20343a 100644
--- a/web/app/components/plugins/marketplace/creator-profile/__tests__/data.server.spec.ts
+++ b/web/app/components/plugins/marketplace/creator-profile/__tests__/data.server.spec.ts
@@ -10,7 +10,16 @@ const mocks = vi.hoisted(() => ({
}))
vi.mock('server-only', () => ({}))
-vi.mock('@/config', () => ({ MARKETPLACE_API_PREFIX: 'https://marketplace.example/api/v1' }))
+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 = {
diff --git a/web/app/components/plugins/marketplace/creator-profile/__tests__/dify-profile.spec.tsx b/web/app/components/plugins/marketplace/creator-profile/__tests__/dify-profile.spec.tsx
index c964e5a5c7c..5f582d57fc8 100644
--- a/web/app/components/plugins/marketplace/creator-profile/__tests__/dify-profile.spec.tsx
+++ b/web/app/components/plugins/marketplace/creator-profile/__tests__/dify-profile.spec.tsx
@@ -146,16 +146,19 @@ vi.mock('../../detail-dialog/use-silent-install', () => ({
useSilentMarketplaceInstall: () => ({ install: vi.fn() }),
}))
// Exercise real dialog/frame message handling without loading external documents.
-vi.mock('../../utils', async (importOriginal) => {
- const actual = await importOriginal<typeof import('../../utils')>()
+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,
- getPluginLinkInMarketplace: (...args: Parameters<typeof actual.getPluginLinkInMarketplace>) =>
- `about:blank${new URL(actual.getPluginLinkInMarketplace(...args), 'https://marketplace.example.test').search}`,
- getTemplateLinkInMarketplace: (
- ...args: Parameters<typeof actual.getTemplateLinkInMarketplace>
- ) =>
- `about:blank${new URL(actual.getTemplateLinkInMarketplace(...args), 'https://marketplace.example.test').search}`,
+ 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) => {
diff --git a/web/app/components/plugins/marketplace/creator-profile/data.server.ts b/web/app/components/plugins/marketplace/creator-profile/data.server.ts
index 24ce1c93ae4..bf9e570280d 100644
--- a/web/app/components/plugins/marketplace/creator-profile/data.server.ts
+++ b/web/app/components/plugins/marketplace/creator-profile/data.server.ts
@@ -1,7 +1,7 @@
import type { MarketplaceCreator, MarketplaceOrganization } from '@dify/contracts/marketplace'
import type { CreatorSortField, CreatorSortOrder, LoadedCreatorProfile } from './model'
import { cache } from 'react'
-import { MARKETPLACE_API_PREFIX } from '@/config'
+import { getMarketplaceApiUrl } from '@/features/marketplace/api'
import { marketplaceClient } from '@/service/marketplace'
import { getPluginIconInMarketplace } from '../utils'
import {
@@ -81,10 +81,10 @@ const loadCreatorProfileCached = cache(
const resource = kind === 'organization' ? 'organizations' : 'creators'
const encodedHandle = encodeURIComponent(uniqueHandle)
const backgroundUrl = creator.background_image
- ? `${MARKETPLACE_API_PREFIX}/${resource}/${encodedHandle}/background-image`
+ ? getMarketplaceApiUrl(`${resource}/${encodedHandle}/background-image`)
: ''
const avatarUrl = creator.avatar
- ? `${MARKETPLACE_API_PREFIX}/${resource}/${encodedHandle}/avatar`
+ ? getMarketplaceApiUrl(`${resource}/${encodedHandle}/avatar`)
: ''
const viewModel = adaptCreatorProfile({
creator,
diff --git a/web/app/components/plugins/marketplace/creator-profile/publisher.ts b/web/app/components/plugins/marketplace/creator-profile/publisher.ts
index 2fab1de7266..537e014662e 100644
--- a/web/app/components/plugins/marketplace/creator-profile/publisher.ts
+++ b/web/app/components/plugins/marketplace/creator-profile/publisher.ts
@@ -1,7 +1,10 @@
import type { MarketplacePlugin, MarketplaceTemplate } from '@dify/contracts/marketplace'
import type { CreatorCreation, CreatorSortField, CreatorSortOrder } from './model'
import type { Plugin } from '@/app/components/plugins/types'
-import { MARKETPLACE_API_PREFIX } from '@/config'
+import {
+ getMarketplacePluginIconUrl,
+ getMarketplaceTemplateIconUrl,
+} from '@/features/marketplace/api'
import { marketplaceClient } from '@/service/marketplace'
import { getFormattedPlugin, getPluginIconInMarketplace } from '../utils'
import { adaptCreations, toPublisherSortQuery } from './model'
@@ -18,13 +21,11 @@ const publisherPageHasMore = (page: number, itemCount: number, total?: number) =
typeof total === 'number' ? page * CREATOR_PAGE_SIZE < total : itemCount === CREATOR_PAGE_SIZE
export const getTemplateIcon = (template: MarketplaceTemplate) =>
- template.icon_file_key
- ? `${MARKETPLACE_API_PREFIX}/templates/${encodeURIComponent(template.id)}/icon`
- : ''
+ template.icon_file_key ? getMarketplaceTemplateIconUrl(template.id) : ''
export const getDependencyIcon = (pluginId: string) => {
if (!pluginId.includes('/')) return ''
- return `${MARKETPLACE_API_PREFIX}/plugins/${pluginId.split('/').map(encodeURIComponent).join('/')}/icon`
+ return getMarketplacePluginIconUrl(pluginId)
}
export async function fetchPublisherPluginPage({
diff --git a/web/app/components/plugins/marketplace/detail-dialog/__tests__/index.spec.tsx b/web/app/components/plugins/marketplace/detail-dialog/__tests__/index.spec.tsx
index f92e4f37da5..ce599f5eaca 100644
--- a/web/app/components/plugins/marketplace/detail-dialog/__tests__/index.spec.tsx
+++ b/web/app/components/plugins/marketplace/detail-dialog/__tests__/index.spec.tsx
@@ -16,12 +16,17 @@ const mocks = vi.hoisted(() => ({
}))
// Preserve query construction while keeping the external iframe document local.
-vi.mock('../../utils', async (importOriginal) => {
- const actual = await importOriginal<typeof import('../../utils')>()
+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,
- getPluginLinkInMarketplace: (...args: Parameters<typeof actual.getPluginLinkInMarketplace>) =>
- `about:blank${new URL(actual.getPluginLinkInMarketplace(...args), 'https://marketplace.example.test').search}`,
+ marketplaceLinks: {
+ ...actual.marketplaceLinks,
+ plugin: (...args: Parameters<typeof actual.marketplaceLinks.plugin>) =>
+ toBlank(actual.marketplaceLinks.plugin(...args)),
+ },
}
})
vi.mock('@/service/console', async (importOriginal) => {
diff --git a/web/app/components/plugins/marketplace/detail-dialog/index.tsx b/web/app/components/plugins/marketplace/detail-dialog/index.tsx
index 087bd092466..57b9074e809 100644
--- a/web/app/components/plugins/marketplace/detail-dialog/index.tsx
+++ b/web/app/components/plugins/marketplace/detail-dialog/index.tsx
@@ -6,7 +6,7 @@ import { useTheme } from 'next-themes'
import { useCallback, useEffect, useRef } from 'react'
import { useLocale, useTranslation } from '#i18n'
import { useOptionalPluginInstallPermission } from '@/app/components/plugins/install-plugin/hooks/use-plugin-install-permission'
-import { getPluginLinkInMarketplace } from '../utils'
+import { marketplaceLinks } from '@/features/marketplace/links'
import MarketplaceDetailDialogFrame from './frame'
import { useSilentMarketplaceInstall } from './use-silent-install'
@@ -127,7 +127,7 @@ function MarketplaceDetailDialog({
const detailLabel = t(($) => $['detailPanel.operation.detail'], { ns: 'plugin' })
const installedForSrcRef = useRef(isInstalled)
if (!open) installedForSrcRef.current = isInstalled
- const detailURL = getPluginLinkInMarketplace(plugin, {
+ const detailURL = marketplaceLinks.plugin(plugin, {
canInstall: String(canInstallPlugin),
installed: String(installedForSrcRef.current),
language: locale,
diff --git a/web/app/components/plugins/marketplace/home/__tests__/embedded-marketplace-search.spec.tsx b/web/app/components/plugins/marketplace/home/__tests__/embedded-marketplace-search.spec.tsx
index 26f1cdbed39..8b61c413c14 100644
--- a/web/app/components/plugins/marketplace/home/__tests__/embedded-marketplace-search.spec.tsx
+++ b/web/app/components/plugins/marketplace/home/__tests__/embedded-marketplace-search.spec.tsx
@@ -81,16 +81,19 @@ vi.mock('../../detail-dialog/use-silent-install', () => ({
useSilentMarketplaceInstall: () => ({ install: vi.fn() }),
}))
// Exercise real dialog/frame message handling without loading external documents.
-vi.mock('../../utils', async (importOriginal) => {
- const actual = await importOriginal<typeof import('../../utils')>()
+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,
- getPluginLinkInMarketplace: (...args: Parameters<typeof actual.getPluginLinkInMarketplace>) =>
- `about:blank${new URL(actual.getPluginLinkInMarketplace(...args), 'https://marketplace.example.test').search}`,
- getTemplateLinkInMarketplace: (
- ...args: Parameters<typeof actual.getTemplateLinkInMarketplace>
- ) =>
- `about:blank${new URL(actual.getTemplateLinkInMarketplace(...args), 'https://marketplace.example.test').search}`,
+ 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)),
+ },
}
})
const plugin = {
diff --git a/web/app/components/plugins/marketplace/home/__tests__/home-guide.spec.tsx b/web/app/components/plugins/marketplace/home/__tests__/home-guide.spec.tsx
index a54e789e394..a89dda9df0a 100644
--- a/web/app/components/plugins/marketplace/home/__tests__/home-guide.spec.tsx
+++ b/web/app/components/plugins/marketplace/home/__tests__/home-guide.spec.tsx
@@ -27,11 +27,18 @@ vi.mock('@/context/i18n', () => ({
useDocLink: mocks.useDocLink,
}))
-vi.mock('@/config', () => ({
- get MARKETPLACE_URL_PREFIX() {
- return mocks.marketplaceUrlPrefix
- },
-}))
+vi.mock('@/env', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/env')>()
+ return {
+ ...actual,
+ env: {
+ ...actual.env,
+ get NEXT_PUBLIC_MARKETPLACE_URL_PREFIX() {
+ return mocks.marketplaceUrlPrefix
+ },
+ },
+ }
+})
const GUIDE_BUTTON_NAME = /marketplace\.home\.guide/
@@ -75,7 +82,7 @@ describe('HomeGuide', () => {
'href',
'https://docs.dify.ai/en/develop-plugin/publishing/marketplace-listing/release-overview',
)
- expect(options[3]).toHaveAttribute('href', 'https://creators.dify.ai')
+ expect(options[3]).toHaveAttribute('href', 'https://creators.dify.ai/')
expect(mocks.useDocLink).not.toHaveBeenCalled()
})
diff --git a/web/app/components/plugins/marketplace/home/__tests__/home-header.spec.tsx b/web/app/components/plugins/marketplace/home/__tests__/home-header.spec.tsx
index 8010c6f9eaf..cb626740da4 100644
--- a/web/app/components/plugins/marketplace/home/__tests__/home-header.spec.tsx
+++ b/web/app/components/plugins/marketplace/home/__tests__/home-header.spec.tsx
@@ -24,11 +24,18 @@ vi.mock('@/context/i18n', () => ({
useDocLink: () => (path?: string) => `https://docs.dify.ai/console${path || ''}`,
}))
-vi.mock('@/config', () => ({
- get MARKETPLACE_URL_PREFIX() {
- return mocks.marketplaceUrlPrefix
- },
-}))
+vi.mock('@/env', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/env')>()
+ return {
+ ...actual,
+ env: {
+ ...actual.env,
+ get NEXT_PUBLIC_MARKETPLACE_URL_PREFIX() {
+ return mocks.marketplaceUrlPrefix
+ },
+ },
+ }
+})
vi.mock('../home-sticky-state-provider', () => ({
HomeStickyCatalogTabs: ({ children }: { children: React.ReactNode }) => children,
diff --git a/web/app/components/plugins/marketplace/home/__tests__/home-trending.spec.tsx b/web/app/components/plugins/marketplace/home/__tests__/home-trending.spec.tsx
index c3e2a64743c..bfb500606e5 100644
--- a/web/app/components/plugins/marketplace/home/__tests__/home-trending.spec.tsx
+++ b/web/app/components/plugins/marketplace/home/__tests__/home-trending.spec.tsx
@@ -37,16 +37,19 @@ vi.mock('@/service/plugins', async (importOriginal) => ({
}))
// Keep real dialogs and message handling without loading external documents.
-vi.mock('../../utils', async (importOriginal) => {
- const actual = await importOriginal<typeof import('../../utils')>()
+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,
- getPluginLinkInMarketplace: (...args: Parameters<typeof actual.getPluginLinkInMarketplace>) =>
- `about:blank${new URL(actual.getPluginLinkInMarketplace(...args), 'https://marketplace.example.test').search}`,
- getTemplateLinkInMarketplace: (
- ...args: Parameters<typeof actual.getTemplateLinkInMarketplace>
- ) =>
- `about:blank${new URL(actual.getTemplateLinkInMarketplace(...args), 'https://marketplace.example.test').search}`,
+ 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)),
+ },
}
})
diff --git a/web/app/components/plugins/marketplace/home/__tests__/marketplace-search-autocomplete.spec.tsx b/web/app/components/plugins/marketplace/home/__tests__/marketplace-search-autocomplete.spec.tsx
index 820090cf506..20c284fca61 100644
--- a/web/app/components/plugins/marketplace/home/__tests__/marketplace-search-autocomplete.spec.tsx
+++ b/web/app/components/plugins/marketplace/home/__tests__/marketplace-search-autocomplete.spec.tsx
@@ -4,7 +4,7 @@ import { act, fireEvent, render, screen, waitFor, within } from '@testing-librar
import userEvent from '@testing-library/user-event'
import { useState } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
-import { MARKETPLACE_API_PREFIX } from '@/config'
+import { MARKETPLACE_API_PREFIX } from '@/features/marketplace/api'
import {
MarketplaceSearchAutocomplete,
MarketplaceSearchForm,
diff --git a/web/app/components/plugins/marketplace/home/home-creator-center.tsx b/web/app/components/plugins/marketplace/home/home-creator-center.tsx
index b61ef3ff9f7..7dc4ef00c3e 100644
--- a/web/app/components/plugins/marketplace/home/home-creator-center.tsx
+++ b/web/app/components/plugins/marketplace/home/home-creator-center.tsx
@@ -3,14 +3,13 @@
import { buttonVariants } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import { useTranslation } from '#i18n'
-import { MARKETPLACE_URL_PREFIX } from '@/config'
import Link from '@/next/link'
import { trackMarketplaceSiteEvent } from '@/utils/marketplace-site-track'
import { useCreatorCenterUrl } from '../creator-center-url'
export default function HomeCreatorCenter() {
const { t } = useTranslation(['plugin'])
- const creatorCenterUrl = useCreatorCenterUrl(MARKETPLACE_URL_PREFIX)
+ const creatorCenterUrl = useCreatorCenterUrl()
const label = t(($) => $['marketplace.home.creatorCenter'])
return (
diff --git a/web/app/components/plugins/marketplace/home/home-trending-slides.tsx b/web/app/components/plugins/marketplace/home/home-trending-slides.tsx
index f7bae91431e..bf793040a25 100644
--- a/web/app/components/plugins/marketplace/home/home-trending-slides.tsx
+++ b/web/app/components/plugins/marketplace/home/home-trending-slides.tsx
@@ -19,7 +19,12 @@ import Partner from '@/app/components/plugins/base/badges/partner'
import Verified from '@/app/components/plugins/base/badges/verified'
import useCheckInstalled from '@/app/components/plugins/install-plugin/hooks/use-check-installed'
import { PluginCategoryEnum } from '@/app/components/plugins/types'
-import { MARKETPLACE_API_PREFIX } from '@/config'
+import { resolveMarketplaceAssetUrl } from '@/features/marketplace/api'
+import {
+ getPluginDetailPath,
+ getTemplateDetailPath,
+ marketplaceLinks,
+} from '@/features/marketplace/links'
import Link from '@/next/link'
import { useRouter } from '@/next/navigation'
import { fetchPluginInfoFromMarketPlace } from '@/service/plugins'
@@ -31,11 +36,6 @@ import MarketplaceDetailDialog from '../detail-dialog'
import TemplateDetailDialog from '../templates/template-detail-dialog'
import { useOptionalTemplateDetailRoute } from '../templates/use-optional-template-detail-route'
import { useMarketplaceDetailNavigation } from '../use-detail-navigation'
-import {
- getPluginLinkInMarketplace,
- getTemplateDetailLinkInMarketplace,
- getTemplateLinkInMarketplace,
-} from '../utils'
import background from './assets/background.webp'
import {
EMBEDDED_MOBILE_BANNER_MEDIA,
@@ -47,19 +47,6 @@ import { buildMarketplaceBannerClickProperties } from './home-trending-track'
import styles from './home-trending.module.css'
import { sanitizeMarketplaceHref } from './marketplace-href'
-const getMarketplaceAssetURL = (path?: string) => {
- if (!path) return ''
- if (/^https?:\/\//.test(path) || path.startsWith('/_next/')) return path
-
- try {
- const apiURL = new URL(MARKETPLACE_API_PREFIX)
- if (path.startsWith('/api/')) return `${apiURL.origin}${path}`
- return `${MARKETPLACE_API_PREFIX.replace(/\/$/, '')}/${path.replace(/^\//, '')}`
- } catch {
- return path
- }
-}
-
const getPluginIdentity = (itemId: string) => {
const [org, name, ...rest] = itemId.split('/')
if (!org || !name || rest.length > 0) return null
@@ -148,12 +135,11 @@ const templateFromRecommendCard = (card: BannerRecommendCard): MarketplaceTempla
const getLocalCardHref = (card: BannerRecommendCard) => {
if (card.item_type === 'plugin') {
const identity = getPluginIdentity(card.item_id)
- if (identity)
- return `/plugin/${encodeURIComponent(identity.org)}/${encodeURIComponent(identity.name)}`
+ if (identity) return getPluginDetailPath(identity)
}
if (card.item_type === 'template')
- return getTemplateDetailLinkInMarketplace({
+ return getTemplateDetailPath({
id: card.item_id,
publisher_unique_handle: card.creator || 'template',
})
@@ -267,7 +253,7 @@ function trackRecommendCardClick(
function RecommendCardFace({ card }: { card: BannerRecommendCard }) {
const { t } = useTranslation(['plugin'])
- const iconURL = getMarketplaceAssetURL(card.icon_url)
+ const iconURL = resolveMarketplaceAssetUrl(card.icon_url)
const creator = getCardCreator(card)
const isPartner = card.badges?.includes('partner')
const isVerified = card.badges?.includes('verified')
@@ -367,7 +353,7 @@ function CloudRecommendPluginCard({
pluginIds: [plugin.plugin_id],
enabled: open,
})
- const href = getPluginLinkInMarketplace({
+ const href = marketplaceLinks.plugin({
org: plugin.org,
name: plugin.name,
type: 'plugin',
@@ -443,7 +429,7 @@ function CloudRecommendTemplateCard({
const [open, setOpen] = useState(false)
const router = useRouter()
const templateDetailRoute = useOptionalTemplateDetailRoute()
- const href = getTemplateLinkInMarketplace(template)
+ const href = marketplaceLinks.template(template)
return (
<>
@@ -607,7 +593,7 @@ function BlogBannerSlide({
const href = sanitizeMarketplaceHref(banner.content.link)
if (!href) return null
const opensInNewTab = /^https?:\/\//.test(href)
- const coverSrc = getMarketplaceAssetURL(banner.content.cover_image)
+ const coverSrc = resolveMarketplaceAssetUrl(banner.content.cover_image)
return (
<Link
@@ -722,9 +708,9 @@ function ImageBannerSlide({
const href = sanitizeMarketplaceHref(banner.content.link)
if (!href) return null
const resolved = resolveEventAdBannerImageSrcs({
- desktop: getMarketplaceAssetURL(banner.content.images.desktop),
- tablet: getMarketplaceAssetURL(banner.content.images.tablet) || undefined,
- mobile: getMarketplaceAssetURL(banner.content.images.mobile) || undefined,
+ desktop: resolveMarketplaceAssetUrl(banner.content.images.desktop),
+ tablet: resolveMarketplaceAssetUrl(banner.content.images.tablet) || undefined,
+ mobile: resolveMarketplaceAssetUrl(banner.content.images.mobile) || undefined,
})
return (
diff --git a/web/app/components/plugins/marketplace/home/marketplace-search-autocomplete.tsx b/web/app/components/plugins/marketplace/home/marketplace-search-autocomplete.tsx
index 71b3d8db5c1..30dc95787c0 100644
--- a/web/app/components/plugins/marketplace/home/marketplace-search-autocomplete.tsx
+++ b/web/app/components/plugins/marketplace/home/marketplace-search-autocomplete.tsx
@@ -26,15 +26,12 @@ import { keepPreviousData, useQuery } from '@tanstack/react-query'
import { useDebouncedValue } from 'foxact/use-debounced-value'
import { useState } from 'react'
import { useTranslation } from '#i18n'
-import { MARKETPLACE_API_PREFIX } from '@/config'
+import { getMarketplaceTemplateIconUrl } from '@/features/marketplace/api'
+import { getPluginDetailPath, getTemplateDetailPath } from '@/features/marketplace/links'
import { renderI18nObject } from '@/i18n/metadata'
import { marketplaceQuery } from '@/service/marketplace'
import { markMarketplaceSiteSearch } from '@/utils/marketplace-site-track'
-import {
- getPluginDetailLinkInMarketplace,
- getPluginIconInMarketplace,
- getTemplateDetailLinkInMarketplace,
-} from '../utils'
+import { getPluginIconInMarketplace } from '../utils'
type MarketplaceSearchScope = 'all' | 'plugins' | 'templates'
@@ -79,9 +76,7 @@ const getPluginText = (
const toTemplateSuggestion = (template: MarketplaceTemplate): MarketplaceSuggestion => ({
description: template.overview,
- iconUrl: template.icon_file_key
- ? `${MARKETPLACE_API_PREFIX}/templates/${template.id}/icon`
- : undefined,
+ iconUrl: template.icon_file_key ? getMarketplaceTemplateIconUrl(template.id) : undefined,
id: `template:${template.id}`,
kind: 'template',
label: template.template_name,
@@ -204,8 +199,8 @@ export function MarketplaceSearchAutocomplete({
window.location.assign(
selection.kind === 'plugin'
- ? getPluginDetailLinkInMarketplace(selection.plugin)
- : getTemplateDetailLinkInMarketplace(selection.template),
+ ? getPluginDetailPath(selection.plugin)
+ : getTemplateDetailPath(selection.template),
)
}
const debouncedSearch = useDebouncedValue(value.trim(), 300)
diff --git a/web/app/components/plugins/marketplace/list/__tests__/card-wrapper.spec.tsx b/web/app/components/plugins/marketplace/list/__tests__/card-wrapper.spec.tsx
index 036b14ba865..9d90981c07e 100644
--- a/web/app/components/plugins/marketplace/list/__tests__/card-wrapper.spec.tsx
+++ b/web/app/components/plugins/marketplace/list/__tests__/card-wrapper.spec.tsx
@@ -13,16 +13,16 @@ import { createMarketplacePluginFixture } from '@/test/fixtures/plugin'
import CardWrapper from '../card-wrapper'
// Keep the real dialog/iframe while preventing navigation to a remote document.
-vi.mock('../../utils', async (importOriginal) => {
- const actual = await importOriginal<typeof import('../../utils')>()
+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,
- getPluginLinkInMarketplace: (...args: Parameters<typeof actual.getPluginLinkInMarketplace>) => {
- const url = new URL(
- actual.getPluginLinkInMarketplace(...args),
- 'https://marketplace.example.test',
- )
- return `about:blank${url.search}`
+ marketplaceLinks: {
+ ...actual.marketplaceLinks,
+ plugin: (...args: Parameters<typeof actual.marketplaceLinks.plugin>) =>
+ toBlank(actual.marketplaceLinks.plugin(...args)),
},
}
})
diff --git a/web/app/components/plugins/marketplace/list/card-wrapper.tsx b/web/app/components/plugins/marketplace/list/card-wrapper.tsx
index 800530391bc..3bc0e989473 100644
--- a/web/app/components/plugins/marketplace/list/card-wrapper.tsx
+++ b/web/app/components/plugins/marketplace/list/card-wrapper.tsx
@@ -11,12 +11,12 @@ import { useTags } from '@/app/components/plugins/hooks'
import { useOptionalPluginInstallPermission } from '@/app/components/plugins/install-plugin/hooks/use-plugin-install-permission'
import InstallFromMarketplace from '@/app/components/plugins/install-plugin/install-from-marketplace'
import { useGetLanguage } from '@/context/i18n'
+import { getPluginDetailPath } from '@/features/marketplace/links'
import { renderI18nObject } from '@/i18n/metadata'
import Link from '@/next/link'
import { trackMarketplaceSiteCardClick } from '@/utils/marketplace-site-track'
import MarketplaceDetailDialog from '../detail-dialog'
import { useMarketplaceDetailNavigation } from '../use-detail-navigation'
-import { getPluginDetailLinkInMarketplace } from '../utils'
type CardWrapperProps = {
plugin: Plugin
@@ -73,7 +73,7 @@ const CardWrapperContent = ({
return (
<Link
- href={getPluginDetailLinkInMarketplace(plugin)}
+ href={getPluginDetailPath(plugin)}
className="block rounded-xl focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"
onClick={() => {
trackMarketplaceSiteCardClick({
diff --git a/web/app/components/plugins/marketplace/templates/__tests__/template-card.spec.tsx b/web/app/components/plugins/marketplace/templates/__tests__/template-card.spec.tsx
index 1ab99b23a67..7ccee4a4117 100644
--- a/web/app/components/plugins/marketplace/templates/__tests__/template-card.spec.tsx
+++ b/web/app/components/plugins/marketplace/templates/__tests__/template-card.spec.tsx
@@ -37,10 +37,16 @@ vi.mock('next-themes', () => ({
useTheme: () => ({ resolvedTheme: 'dark' }),
}))
-vi.mock('@/config', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@/config')>()),
- MARKETPLACE_URL_PREFIX: 'https://marketplace.example.com',
-}))
+vi.mock('@/env', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/env')>()
+ return {
+ ...actual,
+ env: {
+ ...actual.env,
+ NEXT_PUBLIC_MARKETPLACE_URL_PREFIX: 'https://marketplace.example.com',
+ },
+ }
+})
vi.mock('@/app/components/base/app-icon', () => ({
default: () => <div aria-hidden />,
diff --git a/web/app/components/plugins/marketplace/templates/template-card.tsx b/web/app/components/plugins/marketplace/templates/template-card.tsx
index 385f454448f..a60b5a9216b 100644
--- a/web/app/components/plugins/marketplace/templates/template-card.tsx
+++ b/web/app/components/plugins/marketplace/templates/template-card.tsx
@@ -6,10 +6,12 @@ import { useBoolean } from 'ahooks'
import { useCallback } from 'react'
import AppIcon from '@/app/components/base/app-icon'
import Partner from '@/app/components/plugins/base/badges/partner'
-import { MARKETPLACE_API_PREFIX } from '@/config'
+import {
+ getMarketplacePluginIconUrl,
+ getMarketplaceTemplateIconUrl,
+} from '@/features/marketplace/api'
import { useRouter } from '@/next/navigation'
import { formatNumberAbbreviated } from '@/utils/format'
-import { getIconFromMarketPlace } from '@/utils/get-icon'
import { useMarketplaceDetailNavigation } from '../use-detail-navigation'
import TemplateDetailDialog from './template-detail-dialog'
import { useOptionalTemplateDetailRoute } from './use-optional-template-detail-route'
@@ -35,9 +37,7 @@ export default function TemplateCard({ template, className, partnerText }: Templ
0,
(template.deps_plugins?.length ?? 0) - MAX_VISIBLE_PLUGIN_DEPENDENCIES,
)
- const imageUrl = template.icon_file_key
- ? `${MARKETPLACE_API_PREFIX}/templates/${template.id}/icon`
- : undefined
+ const imageUrl = template.icon_file_key ? getMarketplaceTemplateIconUrl(template.id) : undefined
const openDetail = () => {
if (templateDetailRoute) templateDetailRoute.open(template)
else showDetail()
@@ -112,7 +112,7 @@ export default function TemplateCard({ template, className, partnerText }: Templ
<img
key={pluginId}
className="size-6 rounded-md border-[0.5px] border-effects-icon-border object-cover"
- src={getIconFromMarketPlace(pluginId)}
+ src={getMarketplacePluginIconUrl(pluginId)}
alt=""
title={pluginId}
/>
diff --git a/web/app/components/plugins/marketplace/templates/template-detail-dialog.tsx b/web/app/components/plugins/marketplace/templates/template-detail-dialog.tsx
index c0d118f08bb..3f32b7321a9 100644
--- a/web/app/components/plugins/marketplace/templates/template-detail-dialog.tsx
+++ b/web/app/components/plugins/marketplace/templates/template-detail-dialog.tsx
@@ -4,8 +4,8 @@ import type { MarketplaceTemplate } from '@dify/contracts/marketplace'
import { useTheme } from 'next-themes'
import { useCallback } from 'react'
import { useLocale, useTranslation } from '#i18n'
+import { marketplaceLinks } from '@/features/marketplace/links'
import MarketplaceDetailDialogFrame from '../detail-dialog/frame'
-import { getTemplateLinkInMarketplace } from '../utils'
const MARKETPLACE_INSTALL_MESSAGE_TYPE = 'dify-marketplace:install-template'
@@ -28,7 +28,7 @@ export default function TemplateDetailDialog({
// value the marketplace page expects.
const { resolvedTheme } = useTheme()
const detailLabel = t(($) => $['detailPanel.operation.detail'], { ns: 'plugin' })
- const detailURL = getTemplateLinkInMarketplace(template, {
+ const detailURL = marketplaceLinks.template(template, {
language: locale,
source: globalThis.location?.origin,
theme: resolvedTheme,
diff --git a/web/app/components/plugins/marketplace/use-detail-navigation.ts b/web/app/components/plugins/marketplace/use-detail-navigation.ts
index 1385f78b75b..6c0fa930a06 100644
--- a/web/app/components/plugins/marketplace/use-detail-navigation.ts
+++ b/web/app/components/plugins/marketplace/use-detail-navigation.ts
@@ -5,8 +5,8 @@ import { useAtomValue } from 'jotai'
import { useTheme } from 'next-themes'
import { useSyncExternalStore } from 'react'
import { useLocale } from '#i18n'
+import { marketplaceLinks } from '@/features/marketplace/links'
import { deploymentEditionAtom } from '@/features/system-features/state'
-import { getPluginDetailLinkInMarketplace, getTemplateDetailLinkInMarketplace } from './utils'
const subscribe = () => () => {}
const getOrigin = () => window.location.origin
@@ -27,19 +27,15 @@ export function useMarketplaceDetailNavigation() {
const source = useSyncExternalStore(subscribe, getOrigin, getServerOrigin)
const opensExternally = edition === 'COMMUNITY' || edition === 'ENTERPRISE'
- const officialUrl = (path: string) => {
- const url = new URL(path, 'https://marketplace.dify.ai')
- if (source) url.searchParams.set('source', source)
- url.searchParams.set('language', language)
- if (resolvedTheme) url.searchParams.set('theme', resolvedTheme)
- return url.toString()
- }
+ const detailParams = { language, theme: resolvedTheme }
const pluginHref = (plugin: PluginDetail) =>
opensExternally && plugin.type !== 'bundle'
- ? officialUrl(getPluginDetailLinkInMarketplace(plugin))
+ ? marketplaceLinks.officialPluginDetail(plugin, detailParams, source)
: undefined
const templateHref = (template: TemplateDetail) =>
- opensExternally ? officialUrl(getTemplateDetailLinkInMarketplace(template)) : undefined
+ opensExternally
+ ? marketplaceLinks.officialTemplateDetail(template, detailParams, source)
+ : undefined
// Search selections are commands, so open synchronously within the gesture.
// Ordinary cards use the href directly to retain native link behavior.
diff --git a/web/app/components/plugins/marketplace/utils.ts b/web/app/components/plugins/marketplace/utils.ts
index 6a7ba9b6875..615579a90df 100644
--- a/web/app/components/plugins/marketplace/utils.ts
+++ b/web/app/components/plugins/marketplace/utils.ts
@@ -1,15 +1,13 @@
import type {
CollectionsAndPluginsSearchParams,
MarketplacePlugin,
- MarketplaceTemplate,
PluginsSearchParams,
} from '@dify/contracts/marketplace'
import type { ActivePluginType } from './constants'
import type { Plugin } from '@/app/components/plugins/types'
import { PluginCategoryEnum } from '@/app/components/plugins/types'
-import { MARKETPLACE_API_PREFIX } from '@/config'
+import { getMarketplacePluginIconUrl } from '@/features/marketplace/api'
import { marketplaceClient } from '@/service/marketplace'
-import { getMarketplaceUrl } from '@/utils/var'
import { PLUGIN_TYPE_SEARCH_MAP } from './constants'
type MarketplaceFetchOptions = {
@@ -64,11 +62,7 @@ type MarketplacePluginPayload = MarketplacePlugin | (Plugin & { labels?: Plugin[
export const getPluginIconInMarketplace = (
plugin: Pick<MarketplacePluginPayload, 'name' | 'org' | 'type'>,
-) => {
- if (plugin.type === 'bundle')
- return `${MARKETPLACE_API_PREFIX}/bundles/${plugin.org}/${plugin.name}/icon`
- return `${MARKETPLACE_API_PREFIX}/plugins/${plugin.org}/${plugin.name}/icon`
-}
+) => getMarketplacePluginIconUrl(`${plugin.org}/${plugin.name}`, plugin.type)
export const getFormattedPlugin = (payload: MarketplacePluginPayload): Plugin => {
const plugin = payload as Plugin
@@ -87,53 +81,6 @@ export const getFormattedPlugin = (payload: MarketplacePluginPayload): Plugin =>
}
}
-export const getPluginLinkInMarketplace = (
- plugin: Pick<MarketplacePluginPayload, 'name' | 'org' | 'type'>,
- params?: Record<string, string | undefined>,
-) => {
- if (plugin.type === 'bundle')
- return getMarketplaceUrl(`/bundles/${plugin.org}/${plugin.name}`, params)
- return getMarketplaceUrl(`/plugins/${plugin.org}/${plugin.name}`, params)
-}
-
-export const getPluginDetailLinkInMarketplace = (
- plugin: Pick<MarketplacePluginPayload, 'name' | 'org' | 'type'>,
-) => {
- const org = encodeURIComponent(plugin.org)
- const name = encodeURIComponent(plugin.name)
-
- if (plugin.type === 'bundle') return `/bundles/${org}/${name}`
- return `/plugin/${org}/${name}`
-}
-
-export const getTemplateDetailLinkInMarketplace = (
- template: Pick<MarketplaceTemplate, 'id' | 'publisher_handle' | 'publisher_unique_handle'>,
-) => {
- const publisher = template.publisher_unique_handle || template.publisher_handle || 'template'
-
- return `/template/${encodeURIComponent(publisher)}/${encodeURIComponent(template.id)}`
-}
-
-export const getTemplateLinkInMarketplace = (
- template: Pick<MarketplaceTemplate, 'id' | 'publisher_handle' | 'publisher_unique_handle'>,
- params?: Record<string, string | undefined>,
-) => {
- const {
- tid: _tid,
- templateId: _templateId,
- creationType: _creationType,
- ...detailParams
- } = params ?? {}
-
- return getMarketplaceUrl(getTemplateDetailLinkInMarketplace(template), detailParams)
-}
-
-export const getMarketplaceCategoryUrl = (
- category?: string,
- params?: Record<string, string | undefined>,
-) => {
- return getMarketplaceUrl(category ? `/plugins/${category}` : '/plugins', params)
-}
// One collections response lists every catalog carousel and each needs its own
// plugins request. Firing them all at once head-of-line blocks on the browser's
// per-origin connection cap, so the whole catalog waits on the slowest tail
diff --git a/web/app/components/plugins/plugin-detail-panel/__tests__/operation-menu.spec.tsx b/web/app/components/plugins/plugin-detail-panel/__tests__/operation-menu.spec.tsx
index 777f06cb923..5db5a00be67 100644
--- a/web/app/components/plugins/plugin-detail-panel/__tests__/operation-menu.spec.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/__tests__/operation-menu.spec.tsx
@@ -20,7 +20,8 @@ describe('OperationMenu', () => {
const mockOnViewReadme = vi.fn()
const defaultProps = {
source: PluginSource.github,
- detailUrl: 'https://github.com/test/repo',
+ marketplacePlugin: { org: 'test', name: 'repo' },
+ repo: 'test/repo',
onInfo: mockOnInfo,
onCheckVersion: mockOnCheckVersion,
onRemove: mockOnRemove,
@@ -39,7 +40,9 @@ describe('OperationMenu', () => {
expect(screen.queryByText('plugin.detailPanel.operation.info')).not.toBeInTheDocument()
expect(screen.queryByText('plugin.detailPanel.operation.checkUpdate')).not.toBeInTheDocument()
- expect(screen.getByText('plugin.detailPanel.operation.viewDetail')).toBeInTheDocument()
+ expect(
+ screen.getByText('plugin.detailPanel.operation.viewDetail').closest('a')?.href,
+ ).toContain('/plugins/test/repo')
expect(screen.getByText('plugin.detailPanel.operation.remove')).toBeInTheDocument()
})
diff --git a/web/app/components/plugins/plugin-detail-panel/detail-header/__tests__/index.spec.tsx b/web/app/components/plugins/plugin-detail-panel/detail-header/__tests__/index.spec.tsx
index 9806dda19b5..3c5030fe8f9 100644
--- a/web/app/components/plugins/plugin-detail-panel/detail-header/__tests__/index.spec.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/detail-header/__tests__/index.spec.tsx
@@ -254,10 +254,9 @@ it.each([
{ strategy: 'latest', mode: 'partial', listed: false, warning: false },
{ strategy: 'latest', mode: 'exclude', listed: true, warning: false },
{ strategy: 'latest', mode: 'exclude', listed: false, warning: true },
- { strategy: 'latest', mode: 'all', listed: false, warning: false, marketplace: false },
] as const)(
'warns before downgrading only when this plugin is eligible for automatic updates: %j',
- async ({ strategy, mode, listed, warning, ...options }) => {
+ async ({ strategy, mode, listed, warning }) => {
api.autoUpgrade.mockResolvedValue({
category: 'model',
auto_upgrade: {
@@ -268,10 +267,7 @@ it.each([
exclude_plugins: listed ? [detail.plugin_id] : ['other-plugin'],
},
})
- const { user } = setup(
- { detail: { ...detail, source: PluginSource.marketplace } },
- 'marketplace' in options ? options.marketplace : true,
- )
+ const { user } = setup({ detail: { ...detail, source: PluginSource.marketplace } })
await user.click(screen.getByRole('button', { name: '1.0.0' }))
await user.click(await screen.findByRole('menuitem', { name: /^0\.5\.0/ }))
const dialog = await screen.findByRole(warning ? 'alertdialog' : 'dialog', {
@@ -297,6 +293,12 @@ it.each([
},
)
+it('does not offer version switching when Marketplace is disabled', () => {
+ setup({ detail: { ...detail, source: PluginSource.marketplace } }, false)
+
+ expect(screen.getByRole('button', { name: '1.0.0' })).toBeDisabled()
+})
+
it('uses the newly selected target after cancelling a downgrade', async () => {
api.autoUpgrade.mockResolvedValue({
category: 'model',
diff --git a/web/app/components/plugins/plugin-detail-panel/detail-header/hooks/use-detail-header-state.ts b/web/app/components/plugins/plugin-detail-panel/detail-header/hooks/use-detail-header-state.ts
index f3e7f4d14ca..496b3ebc6d9 100644
--- a/web/app/components/plugins/plugin-detail-panel/detail-header/hooks/use-detail-header-state.ts
+++ b/web/app/components/plugins/plugin-detail-panel/detail-header/hooks/use-detail-header-state.ts
@@ -1,10 +1,9 @@
'use client'
import type { PluginDetail } from '../../../types'
-import { useSuspenseQuery } from '@tanstack/react-query'
import { useBoolean } from 'ahooks'
import { useMemo, useState } from 'react'
-import { systemFeaturesQueryOptions } from '@/features/system-features/client'
+import { useMarketplace } from '@/features/marketplace/client'
import { usePluginAutoUpgradeSettings } from '@/service/use-plugins'
import { AUTO_UPDATE_MODE } from '../../../reference-setting-modal/auto-update-setting/types'
import { PluginCategoryEnum, PluginSource } from '../../../types'
@@ -46,10 +45,7 @@ type UseDetailHeaderStateReturn = {
}
export const useDetailHeaderState = (detail: PluginDetail): UseDetailHeaderStateReturn => {
- const { data: enable_marketplace } = useSuspenseQuery({
- ...systemFeaturesQueryOptions(),
- select: (s) => s.enable_marketplace,
- })
+ const enable_marketplace = useMarketplace() !== null
const category = detail.declaration?.category ?? PluginCategoryEnum.tool
const autoUpgradeSettings = usePluginAutoUpgradeSettings(category)
diff --git a/web/app/components/plugins/plugin-detail-panel/detail-header/index.tsx b/web/app/components/plugins/plugin-detail-panel/detail-header/index.tsx
index 1df22a60cb1..1512b24fc28 100644
--- a/web/app/components/plugins/plugin-detail-panel/detail-header/index.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/detail-header/index.tsx
@@ -14,7 +14,7 @@ import {
MenuTrigger,
} from '@langgenius/dify-ui/menu'
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
-import { skipToken, useQuery } from '@tanstack/react-query'
+import { useQuery } from '@tanstack/react-query'
import { useCallback, useId, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import { useLocale } from '#i18n'
@@ -27,12 +27,11 @@ import { selectToolCollections } from '@/app/components/tools/utils/query-select
import { API_PREFIX } from '@/config'
import { useGetLanguage } from '@/context/i18n'
import { userProfileQueryOptions } from '@/features/account-profile/client'
+import { useMarketplace, useMarketplacePluginVersions } from '@/features/marketplace/client'
import useTheme from '@/hooks/use-theme'
import useTimestamp from '@/hooks/use-timestamp'
import { consoleQuery } from '@/service/console'
-import { marketplaceQuery } from '@/service/marketplace'
import { isEarlierThanVersion } from '@/utils/semver'
-import { getMarketplaceUrl } from '@/utils/var'
import Verified from '../../base/badges/verified'
import DeprecationNotice from '../../base/deprecation-notice'
import Icon from '../../card/base/card-icon'
@@ -44,7 +43,7 @@ import {
convertUTCDaySecondsToLocalSeconds,
timeOfDayToDayjs,
} from '../../reference-setting-modal/auto-update-setting/utils'
-import { PluginCategoryEnum, PluginSource } from '../../types'
+import { PluginCategoryEnum } from '../../types'
import { HeaderModals, PluginSourceBadge } from './components'
import { useDetailHeaderState, usePluginOperations } from './hooks'
@@ -70,24 +69,6 @@ const getIconSrc = (
: `${API_PREFIX}/workspaces/current/plugin/icon?tenant_id=${tenantId}&filename=${iconFileName}`
}
-const getDetailUrl = (
- source: PluginSource,
- meta: PluginDetail['meta'],
- author: string,
- name: string,
- locale: string,
- theme: string,
-): string => {
- if (source === PluginSource.github) {
- const repo = meta?.repo
- if (!repo) return ''
- return `https://github.com/${repo}`
- }
- if (source === PluginSource.marketplace)
- return getMarketplaceUrl(`/plugins/${author}/${name}`, { language: locale, theme })
- return ''
-}
-
const DetailHeader = ({
canDeletePlugin = true,
canUpdatePlugin = true,
@@ -108,6 +89,7 @@ const DetailHeader = ({
const { theme } = useTheme()
const locale = useGetLanguage()
const currentLocale = useLocale()
+ const marketplace = useMarketplace()
const detailCategory = detail.declaration?.category ?? PluginCategoryEnum.tool
const { referenceSetting } = useReferenceSetting(detailCategory)
@@ -144,16 +126,10 @@ const DetailHeader = ({
onUpdate,
})
- const [organization, pluginName] = plugin_id.split('/')
- const versionsQuery = useQuery(
- marketplaceQuery.pluginVersions.queryOptions({
- input:
- organization && pluginName
- ? { params: { organization, pluginName }, query: { page: 1, page_size: 100 } }
- : skipToken,
- enabled: versionPicker.isShow && canUpdatePlugin && isFromMarketplace && !isReadmeView,
- retry: false,
- }),
+ const canChangeVersion = canUpdatePlugin && isFromMarketplace && !!marketplace && !isReadmeView
+ const versionsQuery = useMarketplacePluginVersions(
+ plugin_id,
+ versionPicker.isShow && canChangeVersion,
)
const loadingVersions =
versionPicker.isShow && (versionsQuery.isPending || autoUpgradeSettings.isPending)
@@ -173,7 +149,6 @@ const DetailHeader = ({
}, [collectionList, providerKey])
const iconSrc = getIconSrc(icon, icon_dark, theme, tenant_id)
- const detailUrl = getDetailUrl(source, meta, author, name, currentLocale, theme)
const canViewReadme =
!!detail.plugin_unique_identifier && !BUILTIN_TOOLS_ARRAY.includes(detail.id)
const { auto_upgrade: autoUpgradeInfo } = referenceSetting || {}
@@ -238,14 +213,7 @@ const DetailHeader = ({
{/* Version Picker */}
<Menu
- open={
- !!version &&
- versionPicker.isShow &&
- canUpdatePlugin &&
- isFromMarketplace &&
- !isReadmeView &&
- !loadingVersions
- }
+ open={!!version && versionPicker.isShow && canChangeVersion && !loadingVersions}
onOpenChange={versionPicker.setIsShow}
>
{!!version && (
@@ -254,7 +222,7 @@ const DetailHeader = ({
<Button
variant="ghost"
size="small"
- disabled={!canUpdatePlugin || !isFromMarketplace || isReadmeView}
+ disabled={!canChangeVersion}
loading={loadingVersions}
className="relative mx-1 h-5 overflow-visible rounded-[5px] border border-divider-deep px-1.25 system-xs-medium text-text-tertiary"
>
@@ -262,12 +230,9 @@ const DetailHeader = ({
<span className="absolute -top-0.5 -right-0.5 size-1.5 rounded-xs border border-components-badge-status-light-error-border-inner bg-components-badge-status-light-error-bg shadow-sm" />
)}
<span>{isFromGitHub ? (meta?.version ?? version) : version}</span>
- {canUpdatePlugin &&
- isFromMarketplace &&
- !isReadmeView &&
- !loadingVersions && (
- <span aria-hidden className="i-ri-arrow-left-right-line size-3" />
- )}
+ {canChangeVersion && !loadingVersions && (
+ <span aria-hidden className="i-ri-arrow-left-right-line size-3" />
+ )}
</Button>
}
/>
@@ -386,7 +351,8 @@ const DetailHeader = ({
onCheckVersion={handleUpdate}
onRemove={modalStates.showDeleteConfirm}
onViewReadme={canViewReadme ? handleViewReadme : undefined}
- detailUrl={detailUrl}
+ marketplacePlugin={{ org: author, name }}
+ repo={meta?.repo}
showCheckVersion={canUpdatePlugin}
showRemove={canDeletePlugin}
/>
@@ -405,11 +371,13 @@ const DetailHeader = ({
<DeprecationNotice
status={status}
deprecatedReason={deprecated_reason}
- alternativePluginId={alternative_plugin_id}
- alternativePluginURL={getMarketplaceUrl(`/plugins/${alternative_plugin_id}`, {
- language: currentLocale,
- theme,
- })}
+ alternativePluginId={marketplace ? alternative_plugin_id : ''}
+ alternativePluginURL={
+ marketplace?.page(`/plugins/${alternative_plugin_id}`, {
+ language: currentLocale,
+ theme,
+ }) ?? ''
+ }
className="mt-3"
/>
)}
diff --git a/web/app/components/plugins/plugin-detail-panel/operation-menu.tsx b/web/app/components/plugins/plugin-detail-panel/operation-menu.tsx
index 860d063af77..e7a8dc334ed 100644
--- a/web/app/components/plugins/plugin-detail-panel/operation-menu.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/operation-menu.tsx
@@ -1,5 +1,6 @@
'use client'
import type { MenuContentProps } from '@langgenius/dify-ui/menu'
+import type { MarketplacePluginRef } from '@/features/marketplace/links'
import { cn } from '@langgenius/dify-ui/cn'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import {
@@ -10,19 +11,21 @@ import {
MenuSeparator,
MenuTrigger,
} from '@langgenius/dify-ui/menu'
-import { useSuspenseQuery } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
-import { systemFeaturesQueryOptions } from '@/features/system-features/client'
+import { useLocale } from '#i18n'
+import { useMarketplace } from '@/features/marketplace/client'
+import useTheme from '@/hooks/use-theme'
import { PluginSource } from '../types'
type OperationMenuProps = Readonly<
Pick<MenuContentProps, 'side' | 'align'> & {
source: PluginSource
+ marketplacePlugin?: MarketplacePluginRef
+ repo?: string
onInfo: () => void
onCheckVersion: () => void
onRemove: () => void
onViewReadme?: () => void
- detailUrl: string
popupClassName?: string
triggerSize?: 'm' | 'xs'
triggerAriaLabel?: string
@@ -34,7 +37,8 @@ type OperationMenuProps = Readonly<
export function OperationMenu({
source,
- detailUrl,
+ marketplacePlugin,
+ repo,
onInfo,
onCheckVersion,
onRemove,
@@ -49,24 +53,22 @@ export function OperationMenu({
showRemove = true,
}: OperationMenuProps) {
const { t } = useTranslation(['plugin'])
- const { data: enable_marketplace } = useSuspenseQuery({
- ...systemFeaturesQueryOptions(),
- select: (s) => s.enable_marketplace,
- })
+ const marketplace = useMarketplace()
+ const locale = useLocale()
+ const { theme } = useTheme()
const showInfo = source === PluginSource.github
const showCheckVersionAction = showCheckVersion && source === PluginSource.github
- const showMarketplaceDetail =
- (source === PluginSource.marketplace || source === PluginSource.github) && enable_marketplace
+ const detailUrl = !marketplace
+ ? undefined
+ : source === PluginSource.marketplace && marketplacePlugin
+ ? marketplace.plugin(marketplacePlugin, { language: locale, theme })
+ : source === PluginSource.github && repo
+ ? `https://github.com/${repo}`
+ : undefined
const showRemoveAction = showRemove
- const showSeparator = showRemoveAction && (showMarketplaceDetail || !!onViewReadme)
+ const showSeparator = showRemoveAction && (!!detailUrl || !!onViewReadme)
- if (
- !showInfo &&
- !showCheckVersionAction &&
- !showMarketplaceDetail &&
- !onViewReadme &&
- !showRemoveAction
- )
+ if (!showInfo && !showCheckVersionAction && !detailUrl && !onViewReadme && !showRemoveAction)
return null
return (
@@ -102,7 +104,7 @@ export function OperationMenu({
</span>
</MenuItem>
)}
- {showMarketplaceDetail && (
+ {detailUrl && (
<MenuLinkItem
className="px-2 py-1 system-md-regular text-text-secondary"
href={detailUrl}
diff --git a/web/app/components/plugins/plugin-detail-panel/tool-selector/hooks/use-tool-selector.ts b/web/app/components/plugins/plugin-detail-panel/tool-selector/hooks/use-tool-selector.ts
index dd8241f0336..b6c98ee0e69 100644
--- a/web/app/components/plugins/plugin-detail-panel/tool-selector/hooks/use-tool-selector.ts
+++ b/web/app/components/plugins/plugin-detail-panel/tool-selector/hooks/use-tool-selector.ts
@@ -14,9 +14,9 @@ import {
getStructureValue,
toolParametersToFormSchemas,
} from '@/app/components/tools/utils/to-form-schema'
+import { getMarketplacePluginIconUrl } from '@/features/marketplace/api'
import { consoleQuery } from '@/service/console'
import { useInvalidateInstalledPluginList } from '@/service/use-plugins'
-import { getIconFromMarketPlace } from '@/utils/get-icon'
import { matchesProviderReference } from '@/utils/provider-reference'
import { usePluginInstalledCheck } from './use-plugin-installed-check'
@@ -142,7 +142,7 @@ export function useToolSelector({ value, onSelect, onSelectMultiple }: UseToolSe
const manifestIcon = useMemo(() => {
if (!manifest || !pluginID) return ''
- return getIconFromMarketPlace(pluginID)
+ return getMarketplacePluginIconUrl(pluginID)
}, [manifest, pluginID])
const getToolValue = useCallback((tool: ToolDefaultValue): ToolValue => {
diff --git a/web/app/components/plugins/plugin-item/index.tsx b/web/app/components/plugins/plugin-item/index.tsx
index 4f83cac6262..dd845900191 100644
--- a/web/app/components/plugins/plugin-item/index.tsx
+++ b/web/app/components/plugins/plugin-item/index.tsx
@@ -17,11 +17,10 @@ import { useTranslation } from 'react-i18next'
import useRefreshPluginList from '@/app/components/plugins/install-plugin/hooks/use-refresh-plugin-list'
import { API_PREFIX } from '@/config'
import { userProfileQueryOptions } from '@/features/account-profile/client'
-import { systemFeaturesQueryOptions } from '@/features/system-features/client'
+import { useMarketplace } from '@/features/marketplace/client'
import { useRenderI18nObject } from '@/hooks/use-i18n'
import useTheme from '@/hooks/use-theme'
import { isEqualOrLaterThanVersion } from '@/utils/semver'
-import { getMarketplaceUrl } from '@/utils/var'
import Badge from '../../base/badge'
import Verified from '../base/badges/verified'
import Description from '../card/base/description'
@@ -107,10 +106,7 @@ const PluginItem: FC<Props> = ({
const title = getValueFromI18nObject(label)
const titleId = React.useId()
const descriptionText = getValueFromI18nObject(description)
- const { data: enable_marketplace } = useSuspenseQuery({
- ...systemFeaturesQueryOptions(),
- select: (s) => s.enable_marketplace,
- })
+ const marketplace = useMarketplace()
const iconFileName = theme === 'dark' && icon_dark ? icon_dark : icon
const iconSrc = iconFileName
? iconFileName.startsWith('http')
@@ -263,10 +259,10 @@ const PluginItem: FC<Props> = ({
</a>
</>
)}
- {source === PluginSource.marketplace && enable_marketplace && (
+ {source === PluginSource.marketplace && marketplace && (
<>
<a
- href={getMarketplaceUrl(`/plugins/${author}/${name}`, { theme })}
+ href={marketplace.plugin({ org: author, name }, { theme })}
target="_blank"
className="relative z-20 flex items-center gap-0.5"
>
@@ -298,7 +294,7 @@ const PluginItem: FC<Props> = ({
)}
</div>
{/* Deprecated */}
- {source === PluginSource.marketplace && enable_marketplace && isDeprecated && (
+ {source === PluginSource.marketplace && marketplace && isDeprecated && (
<div className="flex shrink-0 items-center gap-x-2 system-2xs-medium-uppercase">
<span className="text-text-tertiary">·</span>
<span className="text-text-warning">{t(($) => $.deprecated, { ns: 'plugin' })}</span>
@@ -306,7 +302,7 @@ const PluginItem: FC<Props> = ({
)}
</div>
{/* BG Effect for Deprecated Plugin */}
- {source === PluginSource.marketplace && enable_marketplace && isDeprecated && (
+ {source === PluginSource.marketplace && marketplace && isDeprecated && (
<div className="absolute -right-11.25 -bottom-17.75 z-0 size-40 bg-components-badge-status-light-warning-halo opacity-60 blur-[120px]" />
)}
</div>
diff --git a/web/app/components/plugins/plugin-page/__tests__/category-marketplace-panel.spec.tsx b/web/app/components/plugins/plugin-page/__tests__/category-marketplace-panel.spec.tsx
index 9bbc0cb430f..bbc3689bd5a 100644
--- a/web/app/components/plugins/plugin-page/__tests__/category-marketplace-panel.spec.tsx
+++ b/web/app/components/plugins/plugin-page/__tests__/category-marketplace-panel.spec.tsx
@@ -6,6 +6,7 @@ import { zGetWorkspacesCurrentPluginMarketplacePkgResponse } from '@dify/contrac
import { screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { ThemeProvider } from 'next-themes'
+import { marketplaceLinks } from '@/features/marketplace/links'
import { seedModelProviderQueries } from '@/test/console/model-provider'
import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/console/query-data'
import { createMarketplacePluginFixture, createPluginEntity } from '@/test/fixtures/plugin'
@@ -67,7 +68,12 @@ const setup = (
seedModelProviderQueries(queryClient)
const rendered = renderWithConsoleQuery(
<ThemeProvider defaultTheme="light" forcedTheme="light" enableSystem={false}>
- <CategoryMarketplacePanel category={Category.trigger} searchText="calendar" {...props} />
+ <CategoryMarketplacePanel
+ marketplace={marketplaceLinks}
+ category={Category.trigger}
+ searchText="calendar"
+ {...props}
+ />
</ThemeProvider>,
{
queryClient,
diff --git a/web/app/components/plugins/plugin-page/category-marketplace-panel.tsx b/web/app/components/plugins/plugin-page/category-marketplace-panel.tsx
index fc1396c7d04..23372341201 100644
--- a/web/app/components/plugins/plugin-page/category-marketplace-panel.tsx
+++ b/web/app/components/plugins/plugin-page/category-marketplace-panel.tsx
@@ -3,6 +3,7 @@
import type { PluginsSearchParams } from '@dify/contracts/marketplace'
import type { Plugin } from '../types'
import type { EmbeddedMarketplaceCategory } from './category-marketplace'
+import type { MarketplaceLinks } from '@/features/marketplace/links'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import { Separator } from '@langgenius/dify-ui/separator'
@@ -13,7 +14,6 @@ import { useTranslation } from 'react-i18next'
import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
import List from '@/app/components/plugins/marketplace/list'
import { useMarketplacePlugins } from '@/app/components/plugins/marketplace/query'
-import { getMarketplaceCategoryUrl } from '@/app/components/plugins/marketplace/utils'
import { usePluginSettingsAccess } from '@/app/components/plugins/plugin-page/use-reference-setting'
import ProviderCard from '@/app/components/plugins/provider-card'
import Link from '@/next/link'
@@ -23,10 +23,12 @@ import { getCategoryMarketplaceId } from './category-marketplace'
const MARKETPLACE_PAGE_SIZE = 30
const CategoryMarketplacePanel = ({
+ marketplace,
category,
searchText,
tags = [],
}: {
+ marketplace: MarketplaceLinks
category: EmbeddedMarketplaceCategory
searchText: string
tags?: string[]
@@ -72,14 +74,24 @@ const CategoryMarketplacePanel = ({
[data, installedPluginIds],
)
- const marketplaceLink = getMarketplaceCategoryUrl(category, { theme })
+ const marketplaceLink = marketplace.category(category, { theme })
const showInstalledPluginIdsError = hasInstalledPluginIdsError && !hasLoadedInstalledPluginIds
const showLoading = isLoadingInstalledPluginIds || !!(marketplaceSearchParams && isPending)
- const cardRender = useCallback((plugin: Plugin) => {
- if (plugin.type === 'bundle') return null
+ const cardRender = useCallback(
+ (plugin: Plugin) => {
+ if (plugin.type === 'bundle') return null
- return <ProviderCard key={plugin.plugin_id} className="h-36.5" payload={plugin} />
- }, [])
+ return (
+ <ProviderCard
+ key={plugin.plugin_id}
+ className="h-36.5"
+ marketplace={marketplace}
+ payload={plugin}
+ />
+ )
+ },
+ [marketplace],
+ )
return (
<section
diff --git a/web/app/components/plugins/plugin-page/context-provider.tsx b/web/app/components/plugins/plugin-page/context-provider.tsx
index 2985e8c68ea..f6b1e270fcb 100644
--- a/web/app/components/plugins/plugin-page/context-provider.tsx
+++ b/web/app/components/plugins/plugin-page/context-provider.tsx
@@ -3,10 +3,9 @@
import type { ReactNode } from 'react'
import type { PluginPageSelection, PluginPageTab } from './context'
import type { FilterState } from './filter-management'
-import { useSuspenseQuery } from '@tanstack/react-query'
import { parseAsStringEnum, useQueryState } from 'nuqs'
import { useMemo, useRef, useState } from 'react'
-import { systemFeaturesQueryOptions } from '@/features/system-features/client'
+import { useMarketplace } from '@/features/marketplace/client'
import { PLUGIN_PAGE_TABS_MAP, usePluginPageTabs } from '../hooks'
import { PLUGIN_TYPE_SEARCH_MAP } from '../marketplace/constants'
import { PluginPageContext } from './context'
@@ -40,10 +39,7 @@ export const PluginPageContextProvider = ({
)
const [selectedItem, setSelectedItem] = useState<PluginPageSelection | undefined>()
- const { data: enable_marketplace } = useSuspenseQuery({
- ...systemFeaturesQueryOptions(),
- select: (s) => s.enable_marketplace,
- })
+ const enable_marketplace = useMarketplace() !== null
const tabs = usePluginPageTabs()
const options = useMemo(() => {
return enable_marketplace
diff --git a/web/app/components/plugins/plugin-page/empty/index.tsx b/web/app/components/plugins/plugin-page/empty/index.tsx
index ce1ed95e414..37aa2cde4d1 100644
--- a/web/app/components/plugins/plugin-page/empty/index.tsx
+++ b/web/app/components/plugins/plugin-page/empty/index.tsx
@@ -11,6 +11,7 @@ import { useTranslation } from 'react-i18next'
import InstallFromGitHub from '@/app/components/plugins/install-plugin/install-from-github'
import InstallFromLocalPackage from '@/app/components/plugins/install-plugin/install-from-local-package'
import { SUPPORT_INSTALL_LOCAL_FILE_EXTENSIONS } from '@/config'
+import { useMarketplace } from '@/features/marketplace/client'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import { useInstalledPluginList } from '@/service/use-plugins'
import Line from '../../marketplace/empty/line'
@@ -43,10 +44,7 @@ const Empty = ({
const fileInputRef = useRef<HTMLInputElement>(null)
const [selectedAction, setSelectedAction] = useState<string | null>(null)
const [selectedFile, setSelectedFile] = useState<File | null>(null)
- const { data: enable_marketplace } = useSuspenseQuery({
- ...systemFeaturesQueryOptions(),
- select: (s) => s.enable_marketplace,
- })
+ const enable_marketplace = useMarketplace() !== null
const { data: plugin_installation_permission } = useSuspenseQuery({
...systemFeaturesQueryOptions(),
select: (s) => s.plugin_installation_permission,
diff --git a/web/app/components/plugins/plugin-page/install-plugin-menu.tsx b/web/app/components/plugins/plugin-page/install-plugin-menu.tsx
index d7cf5e54a0b..0f5b22dfac5 100644
--- a/web/app/components/plugins/plugin-page/install-plugin-menu.tsx
+++ b/web/app/components/plugins/plugin-page/install-plugin-menu.tsx
@@ -20,6 +20,7 @@ import { useTranslation } from 'react-i18next'
import InstallFromGitHub from '@/app/components/plugins/install-plugin/install-from-github'
import InstallFromLocalPackage from '@/app/components/plugins/install-plugin/install-from-local-package'
import { SUPPORT_INSTALL_LOCAL_FILE_EXTENSIONS } from '@/config'
+import { useMarketplace } from '@/features/marketplace/client'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import {
GithubInstallSourceIcon,
@@ -62,10 +63,7 @@ const InstallPluginMenu = ({
const [selectedAction, setSelectedAction] = useState<string | null>(null)
const [selectedFile, setSelectedFile] = useState<File | null>(null)
const buttonLabel = triggerLabel ?? t(($) => $.installPlugin, { ns: 'plugin' })
- const { data: enable_marketplace } = useSuspenseQuery({
- ...systemFeaturesQueryOptions(),
- select: (s) => s.enable_marketplace,
- })
+ const enable_marketplace = useMarketplace() !== null
const { data: plugin_installation_permission } = useSuspenseQuery({
...systemFeaturesQueryOptions(),
select: (s) => s.plugin_installation_permission,
diff --git a/web/app/components/plugins/plugin-page/nav-operations.tsx b/web/app/components/plugins/plugin-page/nav-operations.tsx
index f39594e4903..f00e73fcae4 100644
--- a/web/app/components/plugins/plugin-page/nav-operations.tsx
+++ b/web/app/components/plugins/plugin-page/nav-operations.tsx
@@ -13,8 +13,8 @@ import {
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
import { Fragment, useState } from 'react'
import { useTranslation } from 'react-i18next'
-import { MARKETPLACE_URL_PREFIX } from '@/config'
import { useDocLink } from '@/context/i18n'
+import { marketplaceLinks } from '@/features/marketplace/links'
type GuideMenuItemProps = {
href: string
@@ -65,7 +65,7 @@ function getOptions(docLink: (path: DocPathWithoutLang) => string): {
labelKey: 'pluginPublishGuide',
},
{
- href: MARKETPLACE_URL_PREFIX.replace('marketplace', 'creators'),
+ href: marketplaceLinks.creatorCenter,
icon: <span className="i-ri-book-open-line size-4 shrink-0 text-text-tertiary" />,
labelKey: 'templatePublishingGuide',
},
diff --git a/web/app/components/plugins/plugin-page/plugins-panel-results.tsx b/web/app/components/plugins/plugin-page/plugins-panel-results.tsx
index 2c0d990eb27..d7cf7ae4c16 100644
--- a/web/app/components/plugins/plugin-page/plugins-panel-results.tsx
+++ b/web/app/components/plugins/plugin-page/plugins-panel-results.tsx
@@ -3,6 +3,7 @@ import type { PluginDetail } from '../types'
import type { EmbeddedMarketplaceCategory } from './category-marketplace'
import type { PluginPageContentInset } from './content-inset'
import type { Collection } from '@/app/components/tools/types'
+import type { MarketplaceLinks } from '@/features/marketplace/links'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import {
@@ -36,6 +37,7 @@ type PluginsPanelResultsProps = {
filteredBuiltinTools: Collection[]
filteredList: Array<PluginDetail & { latest_version: string }>
hasToolMarketplacePanel: boolean
+ marketplace: MarketplaceLinks | null
hasVisibleBuiltinTools: boolean
hasVisiblePlugins: boolean
hasEmbeddedMarketplace: boolean
@@ -64,6 +66,7 @@ const PluginsPanelResults = ({
filteredBuiltinTools,
filteredList,
hasToolMarketplacePanel,
+ marketplace,
hasVisibleBuiltinTools,
hasVisiblePlugins,
hasEmbeddedMarketplace,
@@ -187,16 +190,18 @@ const PluginsPanelResults = ({
)}
</div>
)}
- {hasToolMarketplacePanel && (
+ {marketplace && hasToolMarketplacePanel && (
<BuiltinMarketplacePanel
+ marketplace={marketplace}
containerRef={containerRef}
contentInset={contentInset}
keywords={keywords}
tagFilterValue={tagFilterValue}
/>
)}
- {categoryMarketplace && (
+ {marketplace && categoryMarketplace && (
<CategoryMarketplacePanel
+ marketplace={marketplace}
category={categoryMarketplace}
searchText={keywords}
tags={categoryMarketplace === 'trigger' ? tagFilterValue : []}
diff --git a/web/app/components/plugins/plugin-page/plugins-panel.tsx b/web/app/components/plugins/plugin-page/plugins-panel.tsx
index e1f3e229dcc..449adcf4e96 100644
--- a/web/app/components/plugins/plugin-page/plugins-panel.tsx
+++ b/web/app/components/plugins/plugin-page/plugins-panel.tsx
@@ -4,7 +4,6 @@ import type { PluginDetail } from '../types'
import type { PluginPageContentInset } from './content-inset'
import type { FilterState } from './filter-management'
import { cn } from '@langgenius/dify-ui/cn'
-import { useSuspenseQuery } from '@tanstack/react-query'
import { useDebounceFn } from 'ahooks'
import { useMemo, useRef } from 'react'
import { useTranslation } from 'react-i18next'
@@ -13,7 +12,7 @@ import PluginDetailPanel from '@/app/components/plugins/plugin-detail-panel'
import { STEP_BY_STEP_TOUR_TARGETS } from '@/app/components/step-by-step-tour/target-registry'
import ProviderDetail from '@/app/components/tools/provider/detail'
import { useGetLanguage } from '@/context/i18n'
-import { systemFeaturesQueryOptions } from '@/features/system-features/client'
+import { useMarketplace } from '@/features/marketplace/client'
import { renderI18nObject } from '@/i18n/metadata'
import {
normalizePluginCategoryListLanguage,
@@ -106,10 +105,7 @@ const PluginsPanel = ({
: undefined,
[filters.searchQuery, filters.tags, isIntegrationCategoryPage, locale, supportsTagFilter],
)
- const { data: enableMarketplace } = useSuspenseQuery({
- ...systemFeaturesQueryOptions(),
- select: (s) => s.enable_marketplace,
- })
+ const marketplace = useMarketplace()
const {
data: pluginList,
isLoading: isPluginListLoading,
@@ -196,9 +192,8 @@ const PluginsPanel = ({
}, [currentBuiltinToolID, filteredBuiltinTools])
const handleDetailHide = () => setSelectedItem(undefined)
- const hasToolMarketplacePanel = enableMarketplace && isToolIntegrationPage
- const categoryMarketplace =
- enableMarketplace && hasEmbeddedMarketplace ? fixedCategory : undefined
+ const hasToolMarketplacePanel = marketplace !== null && isToolIntegrationPage
+ const categoryMarketplace = marketplace && hasEmbeddedMarketplace ? fixedCategory : undefined
const contentPaddingClassName = pluginPageContentInsetClassNames[contentInset]
const contentFrameClassName = cn(
pluginPageContentFrameClassNames[contentInset],
@@ -274,6 +269,7 @@ const PluginsPanel = ({
filteredBuiltinTools={filteredBuiltinTools}
filteredList={filteredList}
hasToolMarketplacePanel={hasToolMarketplacePanel}
+ marketplace={marketplace}
hasVisibleBuiltinTools={hasVisibleBuiltinTools}
hasVisiblePlugins={hasVisiblePlugins}
hasEmbeddedMarketplace={hasEmbeddedMarketplace}
diff --git a/web/app/components/plugins/plugin-page/use-reference-setting.ts b/web/app/components/plugins/plugin-page/use-reference-setting.ts
index 9c162c9e0b9..28507343dc5 100644
--- a/web/app/components/plugins/plugin-page/use-reference-setting.ts
+++ b/web/app/components/plugins/plugin-page/use-reference-setting.ts
@@ -14,6 +14,7 @@ import {
isCurrentWorkspaceOwnerAtom,
} from '@/context/workspace-state'
import { userProfileQueryOptions } from '@/features/account-profile/client'
+import { useMarketplace } from '@/features/marketplace/client'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import {
useInvalidateReferenceSettings,
@@ -148,7 +149,7 @@ const useReferenceSetting = (category: PluginCategoryEnum) => {
export const useCanInstallPluginFromMarketplace = () => {
const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
- const marketplaceAccess = systemFeatures.enable_marketplace
+ const marketplaceAccess = useMarketplace() !== null
const rbacEnabled = systemFeatures.rbac_enabled
const isCurrentWorkspaceManager = useAtomValue(isCurrentWorkspaceManagerAtom)
const isCurrentWorkspaceOwner = useAtomValue(isCurrentWorkspaceOwnerAtom)
diff --git a/web/app/components/plugins/provider-card.tsx b/web/app/components/plugins/provider-card.tsx
index 804f59e420d..99e9ef92eb2 100644
--- a/web/app/components/plugins/provider-card.tsx
+++ b/web/app/components/plugins/provider-card.tsx
@@ -1,6 +1,7 @@
'use client'
import type { FC } from 'react'
import type { Plugin } from './types'
+import type { MarketplaceLinks } from '@/features/marketplace/links'
import { Button, buttonVariants } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import { useBoolean } from 'ahooks'
@@ -12,7 +13,6 @@ import { useLocale } from '#i18n'
import usePluginInstallPermission from '@/app/components/plugins/install-plugin/hooks/use-plugin-install-permission'
import InstallFromMarketplace from '@/app/components/plugins/install-plugin/install-from-marketplace'
import { useMarketplaceDetailNavigation } from '@/app/components/plugins/marketplace/use-detail-navigation'
-import { getPluginLinkInMarketplace } from '@/app/components/plugins/marketplace/utils'
import { useRenderI18nObject } from '@/hooks/use-i18n'
import Badge from '../base/badge'
import Icon from './card/base/card-icon'
@@ -21,10 +21,11 @@ import DownloadCount from './card/base/download-count'
type Props = Readonly<{
className?: string
+ marketplace: MarketplaceLinks
payload: Plugin
}>
-const ProviderCardComponent: FC<Props> = ({ className, payload }) => {
+const ProviderCardComponent: FC<Props> = ({ className, marketplace, payload }) => {
const getValueFromI18nObject = useRenderI18nObject()
const { t } = useTranslation(['plugin'])
const { theme } = useTheme()
@@ -97,8 +98,7 @@ const ProviderCardComponent: FC<Props> = ({ className, payload }) => {
<a
aria-label={`${t(($) => $['detailPanel.operation.detail'], { ns: 'plugin' })} ${pluginLabel}`}
href={
- navigation.pluginHref(payload) ??
- getPluginLinkInMarketplace(payload, marketplaceLinkParams)
+ navigation.pluginHref(payload) ?? marketplace.plugin(payload, marketplaceLinkParams)
}
target="_blank"
rel="noopener noreferrer"
diff --git a/web/app/components/plugins/reference-setting-modal/auto-update-setting/__tests__/plugins-picker.spec.tsx b/web/app/components/plugins/reference-setting-modal/auto-update-setting/__tests__/plugins-picker.spec.tsx
index c1e9c37c324..50c1017fde5 100644
--- a/web/app/components/plugins/reference-setting-modal/auto-update-setting/__tests__/plugins-picker.spec.tsx
+++ b/web/app/components/plugins/reference-setting-modal/auto-update-setting/__tests__/plugins-picker.spec.tsx
@@ -3,7 +3,7 @@ import { screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useState } from 'react'
import { PluginCategoryEnum } from '@/app/components/plugins/types'
-import { MARKETPLACE_API_PREFIX } from '@/config'
+import { MARKETPLACE_API_PREFIX } from '@/features/marketplace/api'
import { renderWithConsoleQuery as render } from '@/test/console/query-data'
import { createInstalledPluginFixture } from '@/test/fixtures/plugin'
import PluginsPicker from '../plugins-picker'
diff --git a/web/app/components/plugins/reference-setting-modal/auto-update-setting/plugins-selected.tsx b/web/app/components/plugins/reference-setting-modal/auto-update-setting/plugins-selected.tsx
index a33206f2d5a..d89e100a623 100644
--- a/web/app/components/plugins/reference-setting-modal/auto-update-setting/plugins-selected.tsx
+++ b/web/app/components/plugins/reference-setting-modal/auto-update-setting/plugins-selected.tsx
@@ -3,7 +3,7 @@ import type { FC } from 'react'
import { cn } from '@langgenius/dify-ui/cn'
import * as React from 'react'
import Icon from '@/app/components/plugins/card/base/card-icon'
-import { MARKETPLACE_API_PREFIX } from '@/config'
+import { getMarketplacePluginIconUrl } from '@/features/marketplace/api'
const MAX_DISPLAY_COUNT = 14
type Props = Readonly<{
@@ -17,7 +17,7 @@ const PluginsSelected: FC<Props> = ({ className, plugins }) => {
return (
<div className={cn('flex min-w-0 items-center overflow-hidden', className)}>
{displayPlugins.map((plugin) => (
- <Icon key={plugin} size="tiny" src={`${MARKETPLACE_API_PREFIX}/plugins/${plugin}/icon`} />
+ <Icon key={plugin} size="tiny" src={getMarketplacePluginIconUrl(plugin)} />
))}
{hiddenPluginsCount > 0 && (
<div className="shrink-0 system-xs-medium text-text-tertiary">+{hiddenPluginsCount}</div>
diff --git a/web/app/components/plugins/reference-setting-modal/auto-update-setting/tool-item.tsx b/web/app/components/plugins/reference-setting-modal/auto-update-setting/tool-item.tsx
index b760595a4a1..9a6abad9372 100644
--- a/web/app/components/plugins/reference-setting-modal/auto-update-setting/tool-item.tsx
+++ b/web/app/components/plugins/reference-setting-modal/auto-update-setting/tool-item.tsx
@@ -4,8 +4,8 @@ import type { PluginDetail } from '@/app/components/plugins/types'
import { Checkbox } from '@langgenius/dify-ui/checkbox'
import * as React from 'react'
import Icon from '@/app/components/plugins/card/base/card-icon'
-import { MARKETPLACE_API_PREFIX } from '@/config'
import { useGetLanguage } from '@/context/i18n'
+import { getMarketplacePluginIconUrl } from '@/features/marketplace/api'
import { renderI18nObject } from '@/i18n/metadata'
type Props = Readonly<{
@@ -22,7 +22,7 @@ const ToolItem: FC<Props> = ({ payload, isChecked, onCheckChange }) => {
return (
<div className="flex w-full items-center gap-1 rounded-lg py-1 pr-2 pl-3 select-none hover:bg-state-base-hover">
<div className="flex min-w-0 grow items-center gap-2 pr-2">
- <Icon size="tiny" src={`${MARKETPLACE_API_PREFIX}/plugins/${plugin_id}/icon`} />
+ <Icon size="tiny" src={getMarketplacePluginIconUrl(plugin_id)} />
<div className="min-w-0 truncate system-sm-medium text-text-secondary">
{renderI18nObject(label, language)}
</div>
diff --git a/web/app/components/plugins/utils.ts b/web/app/components/plugins/utils.ts
index 8673d557a5a..4018989cf56 100644
--- a/web/app/components/plugins/utils.ts
+++ b/web/app/components/plugins/utils.ts
@@ -1,5 +1,6 @@
import type { Plugin } from './types'
-import { API_PREFIX, MARKETPLACE_API_PREFIX } from '@/config'
+import { API_PREFIX } from '@/config'
+import { getMarketplacePluginIconUrl } from '@/features/marketplace/api'
const hasUrlProtocol = (value: string) => /^[a-z][a-z\d+.-]*:/i.test(value)
@@ -14,10 +15,8 @@ export const getPluginCardIconUrl = (
if (hasUrlProtocol(icon) || icon.startsWith('/')) return icon
- if (plugin.from === 'marketplace') {
- const basePath = plugin.type === 'bundle' ? 'bundles' : 'plugins'
- return `${MARKETPLACE_API_PREFIX}/${basePath}/${plugin.org}/${plugin.name}/icon`
- }
+ if (plugin.from === 'marketplace')
+ return getMarketplacePluginIconUrl(`${plugin.org}/${plugin.name}`, plugin.type)
if (!tenantId) return icon
diff --git a/web/app/components/tools/marketplace/__tests__/builtin-marketplace-panel.spec.tsx b/web/app/components/tools/marketplace/__tests__/builtin-marketplace-panel.spec.tsx
index f4fb4309a35..71ac008b131 100644
--- a/web/app/components/tools/marketplace/__tests__/builtin-marketplace-panel.spec.tsx
+++ b/web/app/components/tools/marketplace/__tests__/builtin-marketplace-panel.spec.tsx
@@ -2,6 +2,7 @@ import type { MarketplaceCollection } from '@dify/contracts/marketplace'
import { act, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { createRef } from 'react'
+import { marketplaceLinks } from '@/features/marketplace/links'
import { renderWithConsoleQuery } from '@/test/console/query-data'
import { createMarketplacePluginFixture } from '@/test/fixtures/plugin'
import { createNuqsTestRenderer } from '@/test/nuqs-testing'
@@ -95,6 +96,7 @@ function renderPanel(keywords = '', tagFilterValue: string[] = []) {
render(
<div ref={containerRef}>
<BuiltinMarketplacePanel
+ marketplace={marketplaceLinks}
containerRef={containerRef}
contentInset="default"
keywords={keywords}
diff --git a/web/app/components/tools/marketplace/__tests__/hooks.spec.ts b/web/app/components/tools/marketplace/__tests__/hooks.spec.ts
index e6a493e9cf7..2345186bcdc 100644
--- a/web/app/components/tools/marketplace/__tests__/hooks.spec.ts
+++ b/web/app/components/tools/marketplace/__tests__/hooks.spec.ts
@@ -3,7 +3,7 @@ import { act, renderHook, waitFor } from '@testing-library/react'
import { createConsoleQueryWrapper } from '@/test/console/query-data'
import { createDeferred } from '@/test/deferred'
import { createMarketplacePluginFixture } from '@/test/fixtures/plugin'
-import { useMarketplace } from '../hooks'
+import { useToolMarketplace } from '../hooks'
const requests = vi.hoisted(() => ({
installed: vi.fn(),
@@ -51,7 +51,7 @@ const collection: MarketplaceCollection = {
const response = (plugins = [plugin], total = plugins.length) => ({ data: { plugins, total } })
function renderMarketplace(initial = { search: '', tags: [] as string[], enabled: true }) {
const { wrapper } = createConsoleQueryWrapper()
- return renderHook(({ search, tags, enabled }) => useMarketplace(search, tags, enabled), {
+ return renderHook(({ search, tags, enabled }) => useToolMarketplace(search, tags, enabled), {
wrapper,
initialProps: initial,
})
diff --git a/web/app/components/tools/marketplace/__tests__/index.spec.tsx b/web/app/components/tools/marketplace/__tests__/index.spec.tsx
index 2ccb1539ce8..8739e62d726 100644
--- a/web/app/components/tools/marketplace/__tests__/index.spec.tsx
+++ b/web/app/components/tools/marketplace/__tests__/index.spec.tsx
@@ -3,6 +3,7 @@ import type { ComponentProps } from 'react'
import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useState } from 'react'
+import { marketplaceLinks } from '@/features/marketplace/links'
import { renderWithConsoleQuery } from '@/test/console/query-data'
import { createMarketplacePluginFixture } from '@/test/fixtures/plugin'
import { createNuqsTestRenderer } from '@/test/nuqs-testing'
@@ -55,6 +56,7 @@ const context = (
function renderMarketplace(props: Partial<Props> = {}, canInstall = true) {
return render(
<Marketplace
+ marketplace={marketplaceLinks}
searchPluginText=""
filterPluginTags={[]}
isMarketplaceArrowVisible={false}
@@ -95,6 +97,7 @@ it('opens the caller panel and exposes a marketplace link with the current filte
<>
{open && <section aria-label="Marketplace panel">Expanded marketplace</section>}
<Marketplace
+ marketplace={marketplaceLinks}
searchPluginText="vector"
filterPluginTags={['tag-a', 'tag-b']}
isMarketplaceArrowVisible
diff --git a/web/app/components/tools/marketplace/builtin-marketplace-panel.tsx b/web/app/components/tools/marketplace/builtin-marketplace-panel.tsx
index f012618caea..070dd497fd2 100644
--- a/web/app/components/tools/marketplace/builtin-marketplace-panel.tsx
+++ b/web/app/components/tools/marketplace/builtin-marketplace-panel.tsx
@@ -1,9 +1,11 @@
import type { RefObject } from 'react'
import type { ToolsContentInset } from '../content-inset'
+import type { MarketplaceLinks } from '@/features/marketplace/links'
import Marketplace from '.'
import { useToolMarketplacePanel } from './use-tool-marketplace-panel'
type BuiltinMarketplacePanelProps = {
+ marketplace: MarketplaceLinks
containerRef: RefObject<HTMLDivElement | null>
contentInset: ToolsContentInset
keywords: string
@@ -11,6 +13,7 @@ type BuiltinMarketplacePanelProps = {
}
export function BuiltinMarketplacePanel({
+ marketplace,
containerRef,
contentInset,
keywords,
@@ -27,6 +30,7 @@ export function BuiltinMarketplacePanel({
<>
<div ref={toolListTailRef} />
<Marketplace
+ marketplace={marketplace}
searchPluginText={keywords}
filterPluginTags={tagFilterValue}
isMarketplaceArrowVisible={isMarketplaceArrowVisible}
diff --git a/web/app/components/tools/marketplace/hooks.ts b/web/app/components/tools/marketplace/hooks.ts
index f79ea04057f..581502c2657 100644
--- a/web/app/components/tools/marketplace/hooks.ts
+++ b/web/app/components/tools/marketplace/hooks.ts
@@ -9,7 +9,7 @@ import { getMarketplaceListCondition } from '@/app/components/plugins/marketplac
import { PluginCategoryEnum } from '@/app/components/plugins/types'
import { consoleQuery } from '@/service/console'
-export const useMarketplace = (
+export const useToolMarketplace = (
searchPluginText: string,
filterPluginTags: string[],
enabled = true,
diff --git a/web/app/components/tools/marketplace/index.tsx b/web/app/components/tools/marketplace/index.tsx
index 26f4075c84c..36e1d42fd88 100644
--- a/web/app/components/tools/marketplace/index.tsx
+++ b/web/app/components/tools/marketplace/index.tsx
@@ -1,6 +1,7 @@
import type { SearchParamsFromCollection } from '@dify/contracts/marketplace'
import type { ToolsContentInset } from '../content-inset'
-import type { useMarketplace } from './hooks'
+import type { useToolMarketplace } from './hooks'
+import type { MarketplaceLinks } from '@/features/marketplace/links'
import { cn } from '@langgenius/dify-ui/cn'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { useTheme } from 'next-themes'
@@ -10,18 +11,19 @@ import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
import List from '@/app/components/plugins/marketplace/list'
import { usePluginSettingsAccess } from '@/app/components/plugins/plugin-page/use-reference-setting'
import { useRouter } from '@/next/navigation'
-import { getMarketplaceUrl } from '@/utils/var'
import { toolsContentInsetClassNames, toolsUnifiedContentFrameClassName } from '../content-inset'
type MarketplaceProps = {
+ marketplace: MarketplaceLinks
searchPluginText: string
filterPluginTags: string[]
isMarketplaceArrowVisible: boolean
showMarketplacePanel: () => void
- marketplaceContext: ReturnType<typeof useMarketplace>
+ marketplaceContext: ReturnType<typeof useToolMarketplace>
contentInset?: ToolsContentInset
}
const Marketplace = ({
+ marketplace,
searchPluginText,
filterPluginTags,
isMarketplaceArrowVisible,
@@ -98,7 +100,7 @@ const Marketplace = ({
</span>
{t(($) => $['operation.in'], { ns: 'common' })}
<a
- href={getMarketplaceUrl('', {
+ href={marketplace.page('', {
language: locale,
q: searchPluginText,
tags: filterPluginTags.join(','),
diff --git a/web/app/components/tools/marketplace/use-tool-marketplace-panel.ts b/web/app/components/tools/marketplace/use-tool-marketplace-panel.ts
index 546f642b869..ab7e373ba17 100644
--- a/web/app/components/tools/marketplace/use-tool-marketplace-panel.ts
+++ b/web/app/components/tools/marketplace/use-tool-marketplace-panel.ts
@@ -1,6 +1,6 @@
import type { RefObject } from 'react'
import { useCallback, useEffect, useRef, useState } from 'react'
-import { useMarketplace } from './hooks'
+import { useToolMarketplace } from './hooks'
type UseToolMarketplacePanelParams = {
containerRef: RefObject<HTMLDivElement | null>
@@ -19,7 +19,7 @@ export function useToolMarketplacePanel({
)
const hasActiveSearchOrTagFilter = !!keywords || tagFilterValue.length > 0
const shouldLoadMarketplace = marketplaceActivated || hasActiveSearchOrTagFilter
- const marketplaceContext = useMarketplace(keywords, tagFilterValue, shouldLoadMarketplace)
+ const marketplaceContext = useToolMarketplace(keywords, tagFilterValue, shouldLoadMarketplace)
const { handleScroll } = marketplaceContext
const [isMarketplaceArrowVisible, setIsMarketplaceArrowVisible] = useState(true)
diff --git a/web/app/components/workflow/block-selector/__tests__/all-start-blocks.spec.tsx b/web/app/components/workflow/block-selector/__tests__/all-start-blocks.spec.tsx
index b8a40bbdd90..10511e1e4b7 100644
--- a/web/app/components/workflow/block-selector/__tests__/all-start-blocks.spec.tsx
+++ b/web/app/components/workflow/block-selector/__tests__/all-start-blocks.spec.tsx
@@ -41,17 +41,13 @@ vi.mock('@/service/use-plugins', () => ({
useFeaturedTriggersRecommendations: vi.fn(),
}))
-vi.mock('@/utils/var', async (importOriginal) => {
- const actual = await importOriginal<typeof import('@/utils/var')>()
+vi.mock('@/env', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/env')>()
return {
...actual,
- getMarketplaceUrl: (path = '', params?: Record<string, string | undefined>) => {
- const searchParams = new URLSearchParams()
- Object.entries(params || {}).forEach(([key, value]) => {
- if (value) searchParams.set(key, value)
- })
- const query = searchParams.toString()
- return `https://marketplace.test${path}${query ? `?${query}` : ''}`
+ env: {
+ ...actual.env,
+ NEXT_PUBLIC_MARKETPLACE_URL_PREFIX: 'https://marketplace.test',
},
}
})
diff --git a/web/app/components/workflow/block-selector/__tests__/featured-tools.spec.tsx b/web/app/components/workflow/block-selector/__tests__/featured-tools.spec.tsx
index c73f63e5fc7..1917ad56537 100644
--- a/web/app/components/workflow/block-selector/__tests__/featured-tools.spec.tsx
+++ b/web/app/components/workflow/block-selector/__tests__/featured-tools.spec.tsx
@@ -1,5 +1,6 @@
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
+import { marketplaceLinks } from '@/features/marketplace/links'
import FeaturedTools from '../featured-tools'
import { createPlugin, createToolProvider } from './factories'
@@ -24,10 +25,16 @@ vi.mock(
}),
)
-vi.mock('@/utils/var', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@/utils/var')>()),
- getMarketplaceUrl: (path = '') => `https://marketplace.test${path}`,
-}))
+vi.mock('@/env', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/env')>()
+ return {
+ ...actual,
+ env: {
+ ...actual.env,
+ NEXT_PUBLIC_MARKETPLACE_URL_PREFIX: 'https://marketplace.test',
+ },
+ }
+})
describe('FeaturedTools', () => {
beforeEach(() => {
@@ -55,7 +62,14 @@ describe('FeaturedTools', () => {
)
const providerMap = new Map(providers.map((provider) => [provider.plugin_id!, provider]))
- render(<FeaturedTools plugins={plugins} providerMap={providerMap} onSelect={vi.fn()} />)
+ render(
+ <FeaturedTools
+ marketplace={marketplaceLinks}
+ plugins={plugins}
+ providerMap={providerMap}
+ onSelect={vi.fn()}
+ />,
+ )
expect(screen.getByText('Provider 1')).toBeInTheDocument()
expect(screen.queryByText('Provider 6')).not.toBeInTheDocument()
@@ -89,6 +103,7 @@ describe('FeaturedTools', () => {
render(
<FeaturedTools
+ marketplace={marketplaceLinks}
plugins={[createPlugin()]}
providerMap={new Map([['plugin-1', createToolProvider()]])}
onSelect={vi.fn()}
@@ -113,6 +128,7 @@ describe('FeaturedTools', () => {
render(
<FeaturedTools
+ marketplace={marketplaceLinks}
plugins={[createPlugin({ name: 'plugin-one' })]}
providerMap={new Map()}
onSelect={vi.fn()}
@@ -136,7 +152,14 @@ describe('FeaturedTools', () => {
})
it('shows the marketplace empty state when no featured tools are available', () => {
- render(<FeaturedTools plugins={[]} providerMap={new Map()} onSelect={vi.fn()} />)
+ render(
+ <FeaturedTools
+ marketplace={marketplaceLinks}
+ plugins={[]}
+ providerMap={new Map()}
+ onSelect={vi.fn()}
+ />,
+ )
expect(screen.getByText('workflow.tabs.noFeaturedPlugins')).toBeInTheDocument()
})
diff --git a/web/app/components/workflow/block-selector/__tests__/featured-triggers.spec.tsx b/web/app/components/workflow/block-selector/__tests__/featured-triggers.spec.tsx
index 16042ed6625..ac0b3b8629a 100644
--- a/web/app/components/workflow/block-selector/__tests__/featured-triggers.spec.tsx
+++ b/web/app/components/workflow/block-selector/__tests__/featured-triggers.spec.tsx
@@ -4,6 +4,7 @@ import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { PluginCategoryEnum, SupportedCreationMethods } from '@/app/components/plugins/types'
import { CollectionType } from '@/app/components/tools/types'
+import { marketplaceLinks } from '@/features/marketplace/links'
import { BlockEnum } from '../../types'
import FeaturedTriggers from '../featured-triggers'
@@ -22,11 +23,14 @@ vi.mock(
}),
)
-vi.mock('@/utils/var', async (importOriginal) => {
- const actual = await importOriginal<typeof import('@/utils/var')>()
+vi.mock('@/env', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/env')>()
return {
...actual,
- getMarketplaceUrl: (path = '') => `https://marketplace.test${path}`,
+ env: {
+ ...actual.env,
+ NEXT_PUBLIC_MARKETPLACE_URL_PREFIX: 'https://marketplace.test',
+ },
}
})
@@ -106,7 +110,12 @@ describe('FeaturedTriggers', () => {
const user = userEvent.setup()
const { unmount } = render(
- <FeaturedTriggers plugins={[]} providerMap={new Map()} onSelect={vi.fn()} />,
+ <FeaturedTriggers
+ marketplace={marketplaceLinks}
+ plugins={[]}
+ providerMap={new Map()}
+ onSelect={vi.fn()}
+ />,
)
const trigger = screen.getByRole('button', { name: /workflow\.tabs\.featuredTools/ })
@@ -122,7 +131,14 @@ describe('FeaturedTriggers', () => {
).not.toBeInTheDocument()
expect(globalThis.localStorage.getItem('workflow_triggers_featured_collapsed')).toBe('true')
unmount()
- render(<FeaturedTriggers plugins={[]} providerMap={new Map()} onSelect={vi.fn()} />)
+ render(
+ <FeaturedTriggers
+ marketplace={marketplaceLinks}
+ plugins={[]}
+ providerMap={new Map()}
+ onSelect={vi.fn()}
+ />,
+ )
expect(screen.getByRole('button', { name: /workflow\.tabs\.featuredTools/ })).toHaveAttribute(
'aria-expanded',
'false',
@@ -148,7 +164,14 @@ describe('FeaturedTriggers', () => {
}),
)
- render(<FeaturedTriggers plugins={plugins} providerMap={providerMap} onSelect={vi.fn()} />)
+ render(
+ <FeaturedTriggers
+ marketplace={marketplaceLinks}
+ plugins={plugins}
+ providerMap={providerMap}
+ onSelect={vi.fn()}
+ />,
+ )
expect(screen.getByText('Provider 4')).toBeInTheDocument()
expect(screen.queryByText('Provider 5')).not.toBeInTheDocument()
@@ -177,7 +200,14 @@ describe('FeaturedTriggers', () => {
// Rendering should cover the empty state link and installed trigger selection.
describe('Rendering and Selection', () => {
it('should render the empty state link when there are no featured plugins', () => {
- render(<FeaturedTriggers plugins={[]} providerMap={new Map()} onSelect={vi.fn()} />)
+ render(
+ <FeaturedTriggers
+ marketplace={marketplaceLinks}
+ plugins={[]}
+ providerMap={new Map()}
+ onSelect={vi.fn()}
+ />,
+ )
expect(
screen.getByRole('link', { name: 'workflow.tabs.noFeaturedTriggers' }),
@@ -191,6 +221,7 @@ describe('FeaturedTriggers', () => {
render(
<FeaturedTriggers
+ marketplace={marketplaceLinks}
plugins={[
createPlugin({ plugin_id: 'plugin-1', latest_package_identifier: '[email protected]' }),
]}
@@ -221,7 +252,12 @@ describe('FeaturedTriggers', () => {
const user = userEvent.setup()
render(
- <FeaturedTriggers plugins={[createPlugin()]} providerMap={new Map()} onSelect={vi.fn()} />,
+ <FeaturedTriggers
+ marketplace={marketplaceLinks}
+ plugins={[createPlugin()]}
+ providerMap={new Map()}
+ onSelect={vi.fn()}
+ />,
)
const detailsLink = screen.getByRole('link', { name: 'Plugin One' })
diff --git a/web/app/components/workflow/block-selector/__tests__/tool-picker.spec.tsx b/web/app/components/workflow/block-selector/__tests__/tool-picker.spec.tsx
index 854a0f67f25..43586e305de 100644
--- a/web/app/components/workflow/block-selector/__tests__/tool-picker.spec.tsx
+++ b/web/app/components/workflow/block-selector/__tests__/tool-picker.spec.tsx
@@ -103,10 +103,16 @@ vi.mock('@/service/base', async (importOriginal) => ({
...(await importOriginal<typeof import('@/service/base')>()),
postMarketplace: api.recommend,
}))
-vi.mock('@/config', async (importOriginal) => ({
- ...(await importOriginal<typeof import('@/config')>()),
- MARKETPLACE_URL_PREFIX: 'https://marketplace.test',
-}))
+vi.mock('@/env', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/env')>()
+ return {
+ ...actual,
+ env: {
+ ...actual.env,
+ NEXT_PUBLIC_MARKETPLACE_URL_PREFIX: 'https://marketplace.test',
+ },
+ }
+})
const createTool = (
name: string,
diff --git a/web/app/components/workflow/block-selector/all-start-blocks.tsx b/web/app/components/workflow/block-selector/all-start-blocks.tsx
index 5072b3fda27..e3080e788f5 100644
--- a/web/app/components/workflow/block-selector/all-start-blocks.tsx
+++ b/web/app/components/workflow/block-selector/all-start-blocks.tsx
@@ -5,13 +5,11 @@ import type { ListRef } from './marketplace-plugin/list'
import type { TriggerDefaultValue, TriggerWithProvider } from './types'
import { cn } from '@langgenius/dify-ui/cn'
import { Separator } from '@langgenius/dify-ui/separator'
-import { useSuspenseQuery } from '@tanstack/react-query'
import { useDebounce } from 'ahooks'
import { useCallback, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useMarketplacePlugins } from '@/app/components/plugins/marketplace/query'
-import { getMarketplaceCategoryUrl } from '@/app/components/plugins/marketplace/utils'
-import { systemFeaturesQueryOptions } from '@/features/system-features/client'
+import { useMarketplace } from '@/features/marketplace/client'
import Link from '@/next/link'
import { useFeaturedTriggersRecommendations } from '@/service/use-plugins'
import { useAllTriggerPlugins, useInvalidateAllTriggerPlugins } from '@/service/use-triggers'
@@ -67,10 +65,7 @@ function AllStartBlocks({
const { t } = useTranslation(['plugin', 'workflow'])
const [hasStartBlocksContent, setHasStartBlocksContent] = useState(false)
const [hasPluginContent, setHasPluginContent] = useState(false)
- const { data: enable_marketplace } = useSuspenseQuery({
- ...systemFeaturesQueryOptions(),
- select: (s) => s.enable_marketplace,
- })
+ const marketplace = useMarketplace()
const pluginRef = useRef<ListRef>(null)
const wrapElemRef = useRef<HTMLDivElement>(null)
@@ -101,9 +96,9 @@ function AllStartBlocks({
)
const debouncedMarketplaceFilters = useDebounce(marketplaceFilters, { wait: 500 })
const isMarketplaceFilterSettled = debouncedMarketplaceFilters === marketplaceFilters
- const isMarketplaceSearchEnabled = enableTriggerPlugin && enable_marketplace && hasFilter
+ const isMarketplaceSearchEnabled = enableTriggerPlugin && marketplace !== null && hasFilter
const { plugins: featuredPlugins = [], isLoading: featuredLoading } =
- useFeaturedTriggersRecommendations(enableTriggerPlugin && enable_marketplace && !hasFilter)
+ useFeaturedTriggersRecommendations(enableTriggerPlugin && marketplace !== null && !hasFilter)
const marketplaceSearchParams = useMemo(
() =>
isMarketplaceSearchEnabled && isMarketplaceFilterSettled
@@ -125,8 +120,7 @@ function AllStartBlocks({
[marketplacePluginsData?.pages, providerMap],
)
- const shouldShowFeatured = enableTriggerPlugin && enable_marketplace && !hasFilter
- const shouldShowMarketplaceFooter = enable_marketplace
+ const shouldShowFeatured = enableTriggerPlugin && marketplace !== null && !hasFilter
const isPanelVariant = variant === 'panel'
const handleStartBlocksContentChange = useCallback((hasContent: boolean) => {
@@ -139,7 +133,7 @@ function AllStartBlocks({
const hasInstalledPluginContent = enableTriggerPlugin && hasPluginContent
const hasMarketplaceContent =
- enableTriggerPlugin && enable_marketplace && notInstalledPlugins.length > 0
+ enableTriggerPlugin && marketplace !== null && notInstalledPlugins.length > 0
const hasAnyContent =
hasStartBlocksContent ||
hasInstalledPluginContent ||
@@ -152,7 +146,7 @@ function AllStartBlocks({
isPanelVariant && hasStartBlocksContent && hasInstalledPluginContent
const shouldShowMarketplaceSectionDivider =
enableTriggerPlugin &&
- enable_marketplace &&
+ marketplace !== null &&
(hasStartBlocksContent || hasInstalledPluginContent) &&
(shouldShowFeatured || hasMarketplaceContent)
@@ -219,8 +213,9 @@ function AllStartBlocks({
{shouldShowMarketplaceSectionDivider && <SectionDivider />}
- {shouldShowFeatured && (
+ {marketplace && shouldShowFeatured && (
<FeaturedTriggers
+ marketplace={marketplace}
plugins={featuredPlugins}
providerMap={providerMap}
onSelect={onSelect}
@@ -230,8 +225,9 @@ function AllStartBlocks({
}}
/>
)}
- {enableTriggerPlugin && enable_marketplace && (
+ {enableTriggerPlugin && marketplace && (
<PluginList
+ marketplace={marketplace}
ref={pluginRef}
wrapElemRef={wrapElemRef as RefObject<HTMLElement>}
list={notInstalledPlugins}
@@ -265,7 +261,7 @@ function AllStartBlocks({
)}
</div>
- {shouldShowMarketplaceFooter && (
+ {marketplace && (
<footer
className={
isPanelVariant ? panelMarketplaceFooterClassName : popoverMarketplaceFooterClassName
@@ -279,7 +275,7 @@ function AllStartBlocks({
? 'gap-1 text-text-tertiary hover:text-text-secondary'
: 'text-text-accent-light-mode-only',
)}
- href={getMarketplaceCategoryUrl(PluginCategoryEnum.trigger)}
+ href={marketplace.category(PluginCategoryEnum.trigger)}
target="_blank"
rel="noopener noreferrer"
>
diff --git a/web/app/components/workflow/block-selector/data-sources.tsx b/web/app/components/workflow/block-selector/data-sources.tsx
index d80819a99e5..dd531de5f0a 100644
--- a/web/app/components/workflow/block-selector/data-sources.tsx
+++ b/web/app/components/workflow/block-selector/data-sources.tsx
@@ -6,7 +6,6 @@ import type { OnSelectBlock } from '../types'
import type { DataSourceDefaultValue } from './types'
import type { ListRef } from '@/app/components/workflow/block-selector/marketplace-plugin/list'
import { cn } from '@langgenius/dify-ui/cn'
-import { useSuspenseQuery } from '@tanstack/react-query'
import { useDebounce } from 'ahooks'
import dynamic from 'next/dynamic'
import { useCallback, useMemo, useRef } from 'react'
@@ -14,7 +13,7 @@ import { trackEvent } from '@/app/components/base/amplitude'
import { useMarketplacePlugins } from '@/app/components/plugins/marketplace/query'
import PluginList from '@/app/components/workflow/block-selector/marketplace-plugin/list'
import { useGetLanguage } from '@/context/i18n'
-import { systemFeaturesQueryOptions } from '@/features/system-features/client'
+import { useMarketplace } from '@/features/marketplace/client'
import { renderI18nObject } from '@/i18n/metadata'
import { PluginCategoryEnum } from '../../plugins/types'
import { BlockEnum } from '../types'
@@ -89,28 +88,20 @@ function DataSources({
[onSelect, language],
)
- const { data: enable_marketplace } = useSuspenseQuery({
- ...systemFeaturesQueryOptions(),
- select: (s) => s.enable_marketplace,
- })
+ const marketplace = useMarketplace()
const trimmedSearchText = searchText.trim()
const debouncedMarketplaceSearchText = useDebounce(trimmedSearchText, { wait: 500 })
const isMarketplaceSearchSettled = debouncedMarketplaceSearchText === trimmedSearchText
const marketplaceSearchParams = useMemo(
() =>
- enable_marketplace && trimmedSearchText && isMarketplaceSearchSettled
+ marketplace !== null && trimmedSearchText && isMarketplaceSearchSettled
? {
query: debouncedMarketplaceSearchText,
category: PluginCategoryEnum.datasource,
}
: undefined,
- [
- debouncedMarketplaceSearchText,
- enable_marketplace,
- isMarketplaceSearchSettled,
- trimmedSearchText,
- ],
+ [debouncedMarketplaceSearchText, marketplace, isMarketplaceSearchSettled, trimmedSearchText],
)
const { data: marketplacePluginsData } = useMarketplacePlugins(marketplaceSearchParams)
const notInstalledPlugins = useMemo(() => {
@@ -135,8 +126,9 @@ function DataSources({
onSelect={handleSelect}
hasSearchText={!!searchText}
/>
- {enable_marketplace && (
+ {marketplace && (
<PluginList
+ marketplace={marketplace}
ref={pluginRef}
wrapElemRef={wrapElemRef}
list={notInstalledPlugins}
diff --git a/web/app/components/workflow/block-selector/featured-tools.tsx b/web/app/components/workflow/block-selector/featured-tools.tsx
index 051a80ba2b3..47c8f70b8ad 100644
--- a/web/app/components/workflow/block-selector/featured-tools.tsx
+++ b/web/app/components/workflow/block-selector/featured-tools.tsx
@@ -5,6 +5,7 @@ import type { TFunction } from 'i18next'
import type { ToolWithProvider } from '../types'
import type { ToolDefaultValue, ToolValue } from './types'
import type { Plugin } from '@/app/components/plugins/types'
+import type { MarketplaceLinks } from '@/features/marketplace/links'
import type { PluginLanguage } from '@/i18n/metadata'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
@@ -20,13 +21,11 @@ import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
import { PluginInstallPermissionProvider } from '@/app/components/plugins/install-plugin/components/plugin-install-permission-provider'
import useWorkspacePluginInstallPermission from '@/app/components/plugins/install-plugin/hooks/use-workspace-plugin-install-permission'
import InstallFromMarketplace from '@/app/components/plugins/install-plugin/install-from-marketplace'
-import { getMarketplaceCategoryUrl } from '@/app/components/plugins/marketplace/utils'
import Action from '@/app/components/workflow/block-selector/marketplace-plugin/action'
import { useFeaturedToolsCollapsed } from '@/app/components/workflow/block-selector/storage'
import { useGetLanguage } from '@/context/i18n'
import Link from '@/next/link'
import { formatNumber } from '@/utils/format'
-import { getMarketplaceUrl } from '@/utils/var'
import { PluginCategoryEnum } from '../../plugins/types'
import BlockIcon from '../block-icon'
import { BlockEnum } from '../types'
@@ -38,6 +37,7 @@ const MAX_RECOMMENDED_COUNT = 15
const INITIAL_VISIBLE_COUNT = 5
type FeaturedToolsProps = {
+ marketplace: MarketplaceLinks
plugins: Plugin[]
providerMap: Map<string, ToolWithProvider>
onSelect: (type: BlockEnum, tool: ToolDefaultValue) => void
@@ -52,6 +52,7 @@ type FeaturedToolPreviewPayload = {
}
const FeaturedTools = ({
+ marketplace,
plugins,
providerMap,
onSelect,
@@ -147,7 +148,7 @@ const FeaturedTools = ({
<p className="py-2 system-xs-regular text-text-tertiary">
<Link
className="text-text-accent"
- href={getMarketplaceCategoryUrl(PluginCategoryEnum.tool)}
+ href={marketplace.category(PluginCategoryEnum.tool)}
target="_blank"
rel="noopener noreferrer"
>
@@ -175,6 +176,7 @@ const FeaturedTools = ({
<div className="mt-1 flex flex-col gap-1">
{visibleUninstalledPlugins.map((plugin) => (
<FeaturedToolUninstalledItem
+ marketplace={marketplace}
key={plugin.plugin_id}
plugin={plugin}
language={language}
@@ -236,6 +238,7 @@ const FeaturedTools = ({
}
type FeaturedToolUninstalledItemProps = {
+ marketplace: MarketplaceLinks
plugin: Plugin
language: PluginLanguage
previewCardHandle: PreviewCardHandle<FeaturedToolPreviewPayload>
@@ -244,6 +247,7 @@ type FeaturedToolUninstalledItemProps = {
}
function FeaturedToolUninstalledItem({
+ marketplace,
plugin,
language,
previewCardHandle,
@@ -277,7 +281,7 @@ function FeaturedToolUninstalledItem({
const detailsLink = (
<Link
className="flex h-full w-full min-w-0 items-center rounded-lg px-3 group-hover:bg-state-base-hover focus-visible:inset-ring-2 focus-visible:inset-ring-state-accent-solid focus-visible:outline-hidden"
- href={getMarketplaceUrl(`/plugins/${plugin.org}/${plugin.name}`)}
+ href={marketplace.plugin(plugin)}
target="_blank"
rel="noopener noreferrer"
>
@@ -333,6 +337,7 @@ function FeaturedToolUninstalledItem({
</Button>
)}
<Action
+ marketplace={marketplace}
open={actionOpen}
onOpenChange={setActionOpen}
author={plugin.org}
diff --git a/web/app/components/workflow/block-selector/featured-triggers.tsx b/web/app/components/workflow/block-selector/featured-triggers.tsx
index 47b8a6251b6..5999cfa66aa 100644
--- a/web/app/components/workflow/block-selector/featured-triggers.tsx
+++ b/web/app/components/workflow/block-selector/featured-triggers.tsx
@@ -5,6 +5,7 @@ import type { TFunction } from 'i18next'
import type { TriggerPluginActionPreviewPayload } from './trigger-plugin/action-item'
import type { TriggerDefaultValue, TriggerWithProvider } from './types'
import type { Plugin } from '@/app/components/plugins/types'
+import type { MarketplaceLinks } from '@/features/marketplace/links'
import type { PluginLanguage } from '@/i18n/metadata'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
@@ -20,13 +21,11 @@ import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
import { PluginInstallPermissionProvider } from '@/app/components/plugins/install-plugin/components/plugin-install-permission-provider'
import useWorkspacePluginInstallPermission from '@/app/components/plugins/install-plugin/hooks/use-workspace-plugin-install-permission'
import InstallFromMarketplace from '@/app/components/plugins/install-plugin/install-from-marketplace'
-import { getMarketplaceCategoryUrl } from '@/app/components/plugins/marketplace/utils'
import Action from '@/app/components/workflow/block-selector/marketplace-plugin/action'
import { useFeaturedTriggersCollapsed } from '@/app/components/workflow/block-selector/storage'
import { useGetLanguage } from '@/context/i18n'
import Link from '@/next/link'
import { formatNumber } from '@/utils/format'
-import { getMarketplaceUrl } from '@/utils/var'
import { PluginCategoryEnum } from '../../plugins/types'
import BlockIcon from '../block-icon'
import { BlockEnum } from '../types'
@@ -38,6 +37,7 @@ const MAX_RECOMMENDED_COUNT = 15
const INITIAL_VISIBLE_COUNT = 5
type FeaturedTriggersProps = {
+ marketplace: MarketplaceLinks
plugins: Plugin[]
providerMap: Map<string, TriggerWithProvider>
onSelect: (type: BlockEnum, trigger?: TriggerDefaultValue) => void
@@ -51,6 +51,7 @@ type FeaturedTriggerPreviewPayload = {
}
const FeaturedTriggers = ({
+ marketplace,
plugins,
providerMap,
onSelect,
@@ -151,7 +152,7 @@ const FeaturedTriggers = ({
<p className="px-4 py-2 system-xs-regular text-text-tertiary">
<Link
className="text-text-accent"
- href={getMarketplaceCategoryUrl(PluginCategoryEnum.trigger)}
+ href={marketplace.category(PluginCategoryEnum.trigger)}
target="_blank"
rel="noopener noreferrer"
>
@@ -175,6 +176,7 @@ const FeaturedTriggers = ({
{visibleUninstalledPlugins.map((plugin) => (
<div key={plugin.plugin_id} className="mb-1 last-of-type:mb-0">
<FeaturedTriggerUninstalledItem
+ marketplace={marketplace}
plugin={plugin}
language={language}
previewCardHandle={previewCardHandle}
@@ -237,6 +239,7 @@ const FeaturedTriggers = ({
}
type FeaturedTriggerUninstalledItemProps = {
+ marketplace: MarketplaceLinks
plugin: Plugin
language: PluginLanguage
previewCardHandle: PreviewCardHandle<FeaturedTriggerPreviewPayload>
@@ -245,6 +248,7 @@ type FeaturedTriggerUninstalledItemProps = {
}
function FeaturedTriggerUninstalledItem({
+ marketplace,
plugin,
language,
previewCardHandle,
@@ -278,7 +282,7 @@ function FeaturedTriggerUninstalledItem({
const detailsLink = (
<Link
className="flex h-full w-full min-w-0 items-center rounded-lg px-3 group-hover:bg-state-base-hover focus-visible:inset-ring-2 focus-visible:inset-ring-state-accent-solid focus-visible:outline-hidden"
- href={getMarketplaceUrl(`/plugins/${plugin.org}/${plugin.name}`)}
+ href={marketplace.plugin(plugin)}
target="_blank"
rel="noopener noreferrer"
>
@@ -339,6 +343,7 @@ function FeaturedTriggerUninstalledItem({
</Button>
)}
<Action
+ marketplace={marketplace}
open={actionOpen}
onOpenChange={setActionOpen}
author={plugin.org}
diff --git a/web/app/components/workflow/block-selector/marketplace-plugin/__tests__/action.spec.tsx b/web/app/components/workflow/block-selector/marketplace-plugin/__tests__/action.spec.tsx
index ca82515bbea..9dfd3fabe9f 100644
--- a/web/app/components/workflow/block-selector/marketplace-plugin/__tests__/action.spec.tsx
+++ b/web/app/components/workflow/block-selector/marketplace-plugin/__tests__/action.spec.tsx
@@ -3,6 +3,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import { marketplaceLinks } from '@/features/marketplace/links'
import OperationMenu from '../action'
const mockDownloadBlob = vi.fn()
@@ -29,9 +30,16 @@ vi.mock('@/utils/download', () => ({
downloadBlob: (...args: unknown[]) => mockDownloadBlob(...args),
}))
-vi.mock('@/utils/var', () => ({
- getMarketplaceUrl: (path: string) => `https://marketplace.example${path}`,
-}))
+vi.mock('@/env', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/env')>()
+ return {
+ ...actual,
+ env: {
+ ...actual.env,
+ NEXT_PUBLIC_MARKETPLACE_URL_PREFIX: 'https://marketplace.example',
+ },
+ }
+})
const createQueryClient = () =>
new QueryClient({
@@ -48,6 +56,7 @@ const renderComponent = (props?: Partial<ComponentProps<typeof OperationMenu>>)
return render(
<QueryClientProvider client={queryClient}>
<OperationMenu
+ marketplace={marketplaceLinks}
open={false}
onOpenChange={vi.fn()}
author="langgenius"
@@ -112,7 +121,7 @@ describe('MarketplaceOperationMenu', () => {
expect(screen.getByRole('menuitem', { name: 'common.operation.viewDetails' })).toHaveAttribute(
'href',
- 'https://marketplace.example/plugins/langgenius/test-plugin',
+ 'https://marketplace.example/plugins/langgenius/test-plugin?theme=light',
)
})
})
diff --git a/web/app/components/workflow/block-selector/marketplace-plugin/__tests__/item-list.spec.tsx b/web/app/components/workflow/block-selector/marketplace-plugin/__tests__/item-list.spec.tsx
index 4a053097636..d9fcd0fa08d 100644
--- a/web/app/components/workflow/block-selector/marketplace-plugin/__tests__/item-list.spec.tsx
+++ b/web/app/components/workflow/block-selector/marketplace-plugin/__tests__/item-list.spec.tsx
@@ -2,6 +2,7 @@ import { renderHook, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useTranslation } from 'react-i18next'
import { PluginCategoryEnum } from '@/app/components/plugins/types'
+import { marketplaceLinks } from '@/features/marketplace/links'
import { renderWithConsoleQuery as render } from '@/test/console/query-data'
import { createPlugin } from '../../__tests__/factories'
import useStickyScroll, { ScrollPosition } from '../../use-sticky-scroll'
@@ -72,6 +73,7 @@ describe('Marketplace plugin selector components', () => {
render(
<Item
+ marketplace={marketplaceLinks}
payload={createPlugin({
label: { en_US: 'Search Plugin', zh_Hans: '搜索插件', [language]: label },
brief: { en_US: 'Searches documents', zh_Hans: '搜索文档', [language]: brief },
@@ -90,6 +92,7 @@ describe('Marketplace plugin selector components', () => {
render(
<Item
+ marketplace={marketplaceLinks}
payload={createPlugin({
label: { en_US: 'Search Plugin', zh_Hans: '搜索插件' },
brief: { en_US: 'Searches documents', zh_Hans: '搜索文档' },
@@ -106,6 +109,7 @@ describe('Marketplace plugin selector components', () => {
render(
<Item
+ marketplace={marketplaceLinks}
payload={createPlugin({
org: 'LangGenius',
latest_package_identifier: '[email protected]',
@@ -147,6 +151,7 @@ describe('Marketplace plugin selector components', () => {
try {
render(
<List
+ marketplace={marketplaceLinks}
wrapElemRef={{ current: document.createElement('div') }}
list={[createPlugin()]}
searchText="filtered"
@@ -176,6 +181,7 @@ describe('Marketplace plugin selector components', () => {
render(
<List
+ marketplace={marketplaceLinks}
wrapElemRef={{ current: document.createElement('div') }}
list={[createPlugin()]}
searchText="filtered"
@@ -198,6 +204,7 @@ describe('Marketplace plugin selector components', () => {
const { rerender } = render(
<List
+ marketplace={marketplaceLinks}
wrapElemRef={wrapElemRef}
list={[]}
searchText=""
@@ -213,6 +220,7 @@ describe('Marketplace plugin selector components', () => {
rerender(
<List
+ marketplace={marketplaceLinks}
wrapElemRef={wrapElemRef}
list={[plugin]}
searchText="filtered"
@@ -237,6 +245,7 @@ describe('Marketplace plugin selector components', () => {
it('should hide the marketplace footer when requested and no filters are active', () => {
const { container } = render(
<List
+ marketplace={marketplaceLinks}
wrapElemRef={{ current: document.createElement('div') }}
list={[]}
searchText=""
diff --git a/web/app/components/workflow/block-selector/marketplace-plugin/action.tsx b/web/app/components/workflow/block-selector/marketplace-plugin/action.tsx
index 9416a3e4776..de2d1bfa61e 100644
--- a/web/app/components/workflow/block-selector/marketplace-plugin/action.tsx
+++ b/web/app/components/workflow/block-selector/marketplace-plugin/action.tsx
@@ -1,4 +1,5 @@
'use client'
+import type { MarketplaceLinks } from '@/features/marketplace/links'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { Menu, MenuContent, MenuItem, MenuLinkItem, MenuTrigger } from '@langgenius/dify-ui/menu'
import { useMutation } from '@tanstack/react-query'
@@ -7,9 +8,9 @@ import { memo } from 'react'
import { useTranslation } from 'react-i18next'
import { marketplaceQuery } from '@/service/marketplace'
import { downloadBlob } from '@/utils/download'
-import { getMarketplaceUrl } from '@/utils/var'
type Props = Readonly<{
+ marketplace: MarketplaceLinks
open: boolean
onOpenChange: (v: boolean) => void
author: string
@@ -17,7 +18,7 @@ type Props = Readonly<{
version: string
}>
-function OperationMenu({ open, onOpenChange, author, name, version }: Props) {
+function OperationMenu({ marketplace, open, onOpenChange, author, name, version }: Props) {
const { t } = useTranslation(['common'])
const { theme } = useTheme()
@@ -65,7 +66,7 @@ function OperationMenu({ open, onOpenChange, author, name, version }: Props) {
</MenuItem>
<MenuLinkItem
className="system-md-regular"
- href={getMarketplaceUrl(`/plugins/${author}/${name}`, { theme })}
+ href={marketplace.plugin({ org: author, name }, { theme })}
target="_blank"
rel="noopener noreferrer"
>
diff --git a/web/app/components/workflow/block-selector/marketplace-plugin/item.tsx b/web/app/components/workflow/block-selector/marketplace-plugin/item.tsx
index 79cab32dd45..f5d472bb77c 100644
--- a/web/app/components/workflow/block-selector/marketplace-plugin/item.tsx
+++ b/web/app/components/workflow/block-selector/marketplace-plugin/item.tsx
@@ -1,5 +1,6 @@
'use client'
import type { Plugin } from '@/app/components/plugins/types.ts'
+import type { MarketplaceLinks } from '@/features/marketplace/links'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import { useBoolean } from 'ahooks'
@@ -13,10 +14,11 @@ import { formatNumber } from '@/utils/format'
import Action from './action'
type Props = Readonly<{
+ marketplace: MarketplaceLinks
payload: Plugin
}>
-function Item({ payload }: Props) {
+function Item({ marketplace, payload }: Props) {
const { t } = useTranslation(['plugin'])
const [open, setOpen] = useState(false)
const language = useGetLanguage()
@@ -67,6 +69,7 @@ function Item({ payload }: Props) {
</Button>
)}
<Action
+ marketplace={marketplace}
open={open}
onOpenChange={setOpen}
author={payload.org}
diff --git a/web/app/components/workflow/block-selector/marketplace-plugin/list.tsx b/web/app/components/workflow/block-selector/marketplace-plugin/list.tsx
index 73137444d2c..3ae757c0244 100644
--- a/web/app/components/workflow/block-selector/marketplace-plugin/list.tsx
+++ b/web/app/components/workflow/block-selector/marketplace-plugin/list.tsx
@@ -1,15 +1,16 @@
'use client'
import type { RefObject } from 'react'
import type { Plugin, PluginCategoryEnum } from '@/app/components/plugins/types'
+import type { MarketplaceLinks } from '@/features/marketplace/links'
import { cn } from '@langgenius/dify-ui/cn'
import { useEffect, useImperativeHandle, useMemo, useRef } from 'react'
import { useTranslation } from 'react-i18next'
-import { getMarketplaceCategoryUrl } from '@/app/components/plugins/marketplace/utils'
import Link from '@/next/link'
import useStickyScroll, { ScrollPosition } from '../use-sticky-scroll'
import Item from './item'
export type ListProps = {
+ marketplace: MarketplaceLinks
wrapElemRef: React.RefObject<HTMLElement | null>
list: Plugin[]
searchText: string
@@ -24,6 +25,7 @@ export type ListProps = {
export type ListRef = { handleScroll: () => void }
function List({
+ marketplace,
wrapElemRef,
searchText,
tags,
@@ -37,7 +39,7 @@ function List({
const { t } = useTranslation(['plugin'])
const noFilter = !searchText && tags.length === 0
const hasRes = list.length > 0
- const urlWithSearchText = getMarketplaceCategoryUrl(category, {
+ const urlWithSearchText = marketplace.category(category, {
q: searchText,
tags: tags.join(','),
})
@@ -77,7 +79,7 @@ function List({
<footer className="sticky bottom-0 z-10 flex h-8 items-center border-t border-divider-subtle bg-components-panel-bg-blur px-4 py-1 system-sm-medium">
<Link
className="inline-flex items-center rounded-md text-text-accent-light-mode-only focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"
- href={getMarketplaceCategoryUrl(category)}
+ href={marketplace.category(category)}
target="_blank"
rel="noopener noreferrer"
>
@@ -131,7 +133,7 @@ function List({
)}
<div className={cn('p-1', !disableMaxWidth && maxWidthClassName)} ref={nextToStickyELemRef}>
{list.map((item) => (
- <Item key={item.plugin_id} payload={item} />
+ <Item key={item.plugin_id} marketplace={marketplace} payload={item} />
))}
</div>
</>
diff --git a/web/app/components/workflow/block-selector/rag-tool-recommendations/index.tsx b/web/app/components/workflow/block-selector/rag-tool-recommendations/index.tsx
index f1f309435d4..e850a290a93 100644
--- a/web/app/components/workflow/block-selector/rag-tool-recommendations/index.tsx
+++ b/web/app/components/workflow/block-selector/rag-tool-recommendations/index.tsx
@@ -10,9 +10,9 @@ import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
import { getFormattedPlugin } from '@/app/components/plugins/marketplace/utils'
import { selectRAGRecommendedPlugins } from '@/app/components/tools/utils/query-select'
import { useRAGRecommendationsCollapsed } from '@/app/components/workflow/block-selector/storage'
+import { useMarketplace } from '@/features/marketplace/client'
import Link from '@/next/link'
import { consoleQuery } from '@/service/console'
-import { getMarketplaceUrl } from '@/utils/var'
import List from './list'
type RAGToolRecommendationsProps = {
@@ -28,6 +28,7 @@ export function RAGToolRecommendations({
}: RAGToolRecommendationsProps) {
const { t } = useTranslation(['common', 'pipeline'])
const [isCollapsed, setIsCollapsed] = useRAGRecommendationsCollapsed()
+ const marketplace = useMarketplace()
const {
data: ragRecommendedPlugins,
@@ -78,7 +79,8 @@ export function RAGToolRecommendations({
<LoadingPlaceholder className="h-full" />
</div>
)}
- {!isFetchingRAGRecommendedPlugins &&
+ {marketplace &&
+ !isFetchingRAGRecommendedPlugins &&
recommendedPlugins.length === 0 &&
unInstalledPlugins.length === 0 && (
<p className="px-3 py-1 system-xs-regular text-text-tertiary">
@@ -91,7 +93,7 @@ export function RAGToolRecommendations({
className="text-text-accent"
target="_blank"
rel="noopener noreferrer"
- href={getMarketplaceUrl('', { tags: 'rag' })}
+ href={marketplace.page('', { tags: 'rag' })}
/>
),
}}
diff --git a/web/app/components/workflow/block-selector/tool-browser.tsx b/web/app/components/workflow/block-selector/tool-browser.tsx
index 227b797fbf1..dfacdc524e7 100644
--- a/web/app/components/workflow/block-selector/tool-browser.tsx
+++ b/web/app/components/workflow/block-selector/tool-browser.tsx
@@ -9,16 +9,14 @@ import type {
import type { OnSelectBlock } from '@/app/components/workflow/types'
import { cn } from '@langgenius/dify-ui/cn'
import { Separator } from '@langgenius/dify-ui/separator'
-import { useSuspenseQuery } from '@tanstack/react-query'
import { useDebounce } from 'ahooks'
import { useCallback, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { buildIntegrationPath } from '@/app/components/integrations/routes'
import { useMarketplacePlugins } from '@/app/components/plugins/marketplace/query'
-import { getMarketplaceCategoryUrl } from '@/app/components/plugins/marketplace/utils'
import PluginList from '@/app/components/workflow/block-selector/marketplace-plugin/list'
import { useGetLanguage } from '@/context/i18n'
-import { systemFeaturesQueryOptions } from '@/features/system-features/client'
+import { useMarketplace } from '@/features/marketplace/client'
import Link from '@/next/link'
import { PluginCategoryEnum } from '../../plugins/types'
import FeaturedTools from './featured-tools'
@@ -219,20 +217,17 @@ function ToolBrowser({
language,
])
- const { data: enable_marketplace } = useSuspenseQuery({
- ...systemFeaturesQueryOptions(),
- select: (s) => s.enable_marketplace,
- })
+ const marketplace = useMarketplace()
const marketplaceSearchParams = useMemo(
() =>
- enable_marketplace && hasFilter && isMarketplaceSearchSettled
+ marketplace && hasFilter && isMarketplaceSearchSettled
? {
query: debouncedMarketplaceFilters.query,
tags: debouncedMarketplaceFilters.tags,
category: PluginCategoryEnum.tool,
}
: undefined,
- [debouncedMarketplaceFilters, enable_marketplace, hasFilter, isMarketplaceSearchSettled],
+ [debouncedMarketplaceFilters, marketplace, hasFilter, isMarketplaceSearchSettled],
)
const { data: marketplacePluginsData, isFetching: isMarketplaceFetching } =
useMarketplacePlugins(marketplaceSearchParams)
@@ -251,20 +246,15 @@ function ToolBrowser({
const isShowRAGRecommendations = isInRAGPipeline && activeTab === ToolType.All && !hasFilter
const hasToolsListContent = tools.length > 0 || isShowRAGRecommendations
- const hasPluginContent = enable_marketplace && notInstalledPlugins.length > 0
+ const hasPluginContent = marketplace !== null && notInstalledPlugins.length > 0
const isMarketplaceSearchPending =
- enable_marketplace && hasFilter && (!isMarketplaceSearchSettled || isMarketplaceFetching)
+ marketplace !== null && hasFilter && (!isMarketplaceSearchSettled || isMarketplaceFetching)
const shouldShowEmptyState =
hasFilter && !isMarketplaceSearchPending && !hasToolsListContent && !hasPluginContent
const shouldShowCategoryEmptyState =
!hasFilter && activeTab !== ToolType.All && !hasToolsListContent
const shouldShowFeatured =
- showFeatured &&
- enable_marketplace &&
- !isInRAGPipeline &&
- activeTab === ToolType.All &&
- !hasFilter
- const shouldShowMarketplaceFooter = enable_marketplace && !hasFilter
+ showFeatured && !isInRAGPipeline && activeTab === ToolType.All && !hasFilter
const handleRAGSelect = useCallback<OnSelectBlock>(
(type, pluginDefaultValue) => {
@@ -317,9 +307,10 @@ function ToolBrowser({
onLoadMore={handleLoadMoreRAGTools}
/>
)}
- {shouldShowFeatured && (
+ {marketplace && shouldShowFeatured && (
<>
<FeaturedTools
+ marketplace={marketplace}
plugins={featuredPlugins}
providerMap={providerMap}
onSelect={onSelect}
@@ -352,8 +343,9 @@ function ToolBrowser({
</>
)}
{shouldShowCategoryEmptyState && <ToolCategoryEmptyState type={activeTab} />}
- {enable_marketplace && (
+ {marketplace && (
<PluginList
+ marketplace={marketplace}
ref={pluginRef}
wrapElemRef={wrapElemRef as RefObject<HTMLElement>}
list={notInstalledPlugins}
@@ -382,11 +374,11 @@ function ToolBrowser({
/>
)}
</div>
- {shouldShowMarketplaceFooter && (
+ {marketplace && !hasFilter && (
<footer className={marketplaceFooterClassName}>
<Link
className="inline-flex items-center rounded-md text-text-accent-light-mode-only focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"
- href={getMarketplaceCategoryUrl(PluginCategoryEnum.tool)}
+ href={marketplace.category(PluginCategoryEnum.tool)}
target="_blank"
rel="noopener noreferrer"
>
diff --git a/web/app/components/workflow/block-selector/tool-panel.tsx b/web/app/components/workflow/block-selector/tool-panel.tsx
index eccce8510d9..c642eb3c334 100644
--- a/web/app/components/workflow/block-selector/tool-panel.tsx
+++ b/web/app/components/workflow/block-selector/tool-panel.tsx
@@ -1,10 +1,10 @@
import type { RagPipelineDatasourceProviderResponse } from '@dify/contracts/api/console/rag/types.gen'
import type { OnSelectBlock, ToolWithProvider } from '../types'
-import { useQuery, useQueryClient, useSuspenseQuery } from '@tanstack/react-query'
+import { useQuery, useQueryClient } from '@tanstack/react-query'
import dynamic from 'next/dynamic'
import { useEffect, useMemo } from 'react'
import { selectToolsWithProvider } from '@/app/components/tools/utils/query-select'
-import { systemFeaturesQueryOptions } from '@/features/system-features/client'
+import { useMarketplace } from '@/features/marketplace/client'
import { consoleQuery } from '@/service/console'
import { useFeaturedToolsRecommendations } from '@/service/use-plugins'
import { basePath } from '@/utils/var'
@@ -97,10 +97,7 @@ export function ToolPanel({
consoleQuery.workspaces.current.tools.mcp.get.queryOptions({ select: selectToolsWithProvider }),
)
const queryClient = useQueryClient()
- const { data: enableMarketplace } = useSuspenseQuery({
- ...systemFeaturesQueryOptions(),
- select: (systemFeatures) => systemFeatures.enable_marketplace,
- })
+ const enableMarketplace = useMarketplace() !== null
const workflowStore = useWorkflowStore()
const inRAGPipeline = dataSources.length > 0
const { plugins: featuredPlugins = [], isLoading: isFeaturedLoading } =
diff --git a/web/app/components/workflow/block-selector/tool-picker.tsx b/web/app/components/workflow/block-selector/tool-picker.tsx
index 9ab686a438f..245ab53c410 100644
--- a/web/app/components/workflow/block-selector/tool-picker.tsx
+++ b/web/app/components/workflow/block-selector/tool-picker.tsx
@@ -7,7 +7,7 @@ import type { BlockEnum, OnSelectBlock } from '@/app/components/workflow/types'
import { cn } from '@langgenius/dify-ui/cn'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { Popover, PopoverContent, PopoverTitle, PopoverTrigger } from '@langgenius/dify-ui/popover'
-import { useQuery, useQueryClient, useSuspenseQuery } from '@tanstack/react-query'
+import { useQuery, useQueryClient } from '@tanstack/react-query'
import { useBoolean } from 'ahooks'
import dynamic from 'next/dynamic'
import { useMemo, useState } from 'react'
@@ -16,7 +16,7 @@ import { PluginSearchInput } from '@/app/components/plugins/plugin-search-input'
import EditCustomToolModal from '@/app/components/tools/edit-custom-collection-modal'
import { useCanManageTools } from '@/app/components/tools/hooks/use-tool-permissions'
import { selectToolsWithProvider } from '@/app/components/tools/utils/query-select'
-import { systemFeaturesQueryOptions } from '@/features/system-features/client'
+import { useMarketplace } from '@/features/marketplace/client'
import { consoleQuery } from '@/service/console'
import { createCustomCollection } from '@/service/tools'
import { useFeaturedToolsRecommendations } from '@/service/use-plugins'
@@ -61,10 +61,7 @@ export function ToolPickerContent({
const [tags, setTags] = useState<string[]>([])
const canManageTools = useCanManageTools()
- const { data: enable_marketplace } = useSuspenseQuery({
- ...systemFeaturesQueryOptions(),
- select: (s) => s.enable_marketplace,
- })
+ const enable_marketplace = useMarketplace() !== null
const { data: buildInTools } = useQuery(
consoleQuery.workspaces.current.tools.builtin.get.queryOptions({
select: selectToolsWithProvider,
diff --git a/web/app/components/workflow/nodes/_base/components/__tests__/switch-plugin-version.spec.tsx b/web/app/components/workflow/nodes/_base/components/__tests__/switch-plugin-version.spec.tsx
index ed04af0a6f6..0bf03a124bf 100644
--- a/web/app/components/workflow/nodes/_base/components/__tests__/switch-plugin-version.spec.tsx
+++ b/web/app/components/workflow/nodes/_base/components/__tests__/switch-plugin-version.spec.tsx
@@ -57,7 +57,7 @@ beforeEach(() => {
},
})
})
-function setup() {
+function setup({ enableMarketplace = true } = {}) {
const onChange = vi.fn()
renderWithConsoleQuery(
<SwitchPluginVersion
@@ -66,11 +66,20 @@ function setup() {
onChange={onChange}
/>,
{
+ systemFeatures: { enable_marketplace: enableMarketplace },
workspacePermissionKeys: ['plugin.install'],
},
)
return { user: userEvent.setup(), onChange }
}
+it('keeps the version badge but cannot switch versions when Marketplace is disabled', async () => {
+ setup({ enableMarketplace: false })
+
+ expect(await screen.findByRole('button', { name: /switchVersion 1\.0\.0/ })).toHaveAttribute(
+ 'aria-disabled',
+ 'true',
+ )
+})
it('submits the selected package once and reports the version only after success', async () => {
const result = createDeferred<Awaited<ReturnType<typeof api.upgrade>>>()
api.upgrade.mockReturnValueOnce(result.promise)
diff --git a/web/app/components/workflow/nodes/_base/components/agent-strategy-selector.tsx b/web/app/components/workflow/nodes/_base/components/agent-strategy-selector.tsx
index 73f3da24976..a7b7e43fc82 100644
--- a/web/app/components/workflow/nodes/_base/components/agent-strategy-selector.tsx
+++ b/web/app/components/workflow/nodes/_base/components/agent-strategy-selector.tsx
@@ -7,7 +7,7 @@ import type {
import { cn } from '@langgenius/dify-ui/cn'
import { Infotip, InfotipContent, InfotipTitle, InfotipTrigger } from '@langgenius/dify-ui/infotip'
import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'
-import { useQuery, useSuspenseQuery } from '@tanstack/react-query'
+import { useQuery } from '@tanstack/react-query'
import dynamic from 'next/dynamic'
import { memo, useEffect, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
@@ -17,7 +17,7 @@ import { useMarketplacePlugins } from '@/app/components/plugins/marketplace/hook
import { PluginCategoryEnum } from '@/app/components/plugins/types'
import PluginList from '@/app/components/workflow/block-selector/marketplace-plugin/list'
import { useGetLanguage } from '@/context/i18n'
-import { systemFeaturesQueryOptions } from '@/features/system-features/client'
+import { useMarketplace } from '@/features/marketplace/client'
import { renderI18nObject } from '@/i18n/metadata'
import Link from '@/next/link'
import { consoleQuery } from '@/service/console'
@@ -66,10 +66,7 @@ type AgentStrategySelectorProps = {
}
export const AgentStrategySelector = memo((props: AgentStrategySelectorProps) => {
- const { data: enable_marketplace } = useSuspenseQuery({
- ...systemFeaturesQueryOptions(),
- select: (s) => s.enable_marketplace,
- })
+ const marketplace = useMarketplace()
const { value, onChange } = props
const [open, setOpen] = useState(false)
@@ -124,14 +121,14 @@ export const AgentStrategySelector = memo((props: AgentStrategySelectorProps) =>
}, [marketplacePlugins, providers.data])
useEffect(() => {
- if (!enable_marketplace) return
+ if (!marketplace) return
if (query) {
fetchPlugins({
query,
category: PluginCategoryEnum.agent,
})
}
- }, [enable_marketplace, fetchPlugins, query])
+ }, [marketplace, fetchPlugins, query])
const pluginRef = useRef<ListRef>(null)
@@ -250,8 +247,9 @@ export const AgentStrategySelector = memo((props: AgentStrategySelectorProps) =>
}}
className="h-full max-h-full max-w-none overflow-y-auto"
/>
- {enable_marketplace && (
+ {marketplace && (
<PluginList
+ marketplace={marketplace}
ref={pluginRef}
wrapElemRef={wrapElemRef}
list={notInstalledPlugins}
diff --git a/web/app/components/workflow/nodes/_base/components/switch-plugin-version.tsx b/web/app/components/workflow/nodes/_base/components/switch-plugin-version.tsx
index a2841b8a5de..c2a15f9bb61 100644
--- a/web/app/components/workflow/nodes/_base/components/switch-plugin-version.tsx
+++ b/web/app/components/workflow/nodes/_base/components/switch-plugin-version.tsx
@@ -3,6 +3,7 @@
import type { PluginVersionsResponse } from '@dify/contracts/marketplace'
import type { FC, ReactNode } from 'react'
import type { PluginDetail } from '@/app/components/plugins/types'
+import type { MarketplaceLinks } from '@/features/marketplace/links'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import {
@@ -33,15 +34,14 @@ import Card from '@/app/components/plugins/card'
import useGetIcon from '@/app/components/plugins/install-plugin/base/use-get-icon'
import useWorkspacePluginInstallPermission from '@/app/components/plugins/install-plugin/hooks/use-workspace-plugin-install-permission'
import { pluginManifestToCardPluginProps } from '@/app/components/plugins/install-plugin/utils'
+import { useMarketplace, useMarketplacePluginVersions } from '@/features/marketplace/client'
import useTimestamp from '@/hooks/use-timestamp'
import Link from '@/next/link'
import { consoleQuery } from '@/service/console'
-import { marketplaceQuery } from '@/service/marketplace'
import {
normalizeInstalledPluginDetail,
useUpdatePackageFromMarketPlace,
} from '@/service/use-plugins'
-import { getMarketplaceUrl } from '@/utils/var'
type PluginVersionSelection = {
plugin: PluginDetail
@@ -64,6 +64,7 @@ export const SwitchPluginVersion: FC<SwitchPluginVersionProps> = (props) => {
const [installOpen, setInstallOpen] = useState(false)
const [selection, setSelection] = useState<PluginVersionSelection>()
const { canUpdatePlugin } = useWorkspacePluginInstallPermission()
+ const marketplace = useMarketplace()
const pluginDetails = useQuery(
consoleQuery.workspaces.current.plugin.list.installations.ids.post.queryOptions({
input: pluginId ? { body: { plugin_ids: [pluginId] } } : skipToken,
@@ -80,17 +81,8 @@ export const SwitchPluginVersion: FC<SwitchPluginVersionProps> = (props) => {
const { formatDate } = useTimestamp()
const dateFormat = t(($) => $.dateTimeFormat, { ns: 'appLog' }).split(' ')[0]!
- const [organization, pluginName] = pluginId?.split('/') ?? []
- const versionsQuery = useQuery(
- marketplaceQuery.pluginVersions.queryOptions({
- input:
- organization && pluginName
- ? { params: { organization, pluginName }, query: { page: 1, page_size: 100 } }
- : skipToken,
- enabled: requestedOpen && canUpdatePlugin,
- retry: false,
- }),
- )
+ const canSwitchVersion = canUpdatePlugin && marketplace !== null
+ const versionsQuery = useMarketplacePluginVersions(pluginId, requestedOpen && canSwitchVersion)
const loadingVersions = requestedOpen && versionsQuery.isPending
return (
@@ -102,6 +94,7 @@ export const SwitchPluginVersion: FC<SwitchPluginVersionProps> = (props) => {
<DialogContent className="w-140" finalFocus={triggerRef}>
{selection && (
<PluginVersionInstallConfirmation
+ marketplace={marketplace}
selection={selection}
onInstalled={(version) => {
void pluginDetails.refetch()
@@ -113,7 +106,7 @@ export const SwitchPluginVersion: FC<SwitchPluginVersionProps> = (props) => {
</DialogContent>
</Dialog>
<Menu
- open={requestedOpen && !!pluginDetail && canUpdatePlugin && !loadingVersions}
+ open={requestedOpen && !!pluginDetail && canSwitchVersion && !loadingVersions}
onOpenChange={setRequestedOpen}
>
{pluginDetail && canUpdatePlugin && (
@@ -126,6 +119,8 @@ export const SwitchPluginVersion: FC<SwitchPluginVersionProps> = (props) => {
<Button
variant="ghost"
size="small"
+ disabled={!canSwitchVersion}
+ focusableWhenDisabled
loading={loadingVersions}
className="relative mx-1 h-5 overflow-visible rounded-[5px] border border-divider-deep px-1.25 system-2xs-medium-uppercase text-text-tertiary"
>
@@ -134,7 +129,7 @@ export const SwitchPluginVersion: FC<SwitchPluginVersionProps> = (props) => {
{t(($) => $['detailPanel.switchVersion'], { ns: 'plugin' })}{' '}
</span>
<span>{pluginDetail.version}</span>
- {!loadingVersions && (
+ {canSwitchVersion && !loadingVersions && (
<span aria-hidden className="i-ri-arrow-left-right-line size-3" />
)}
</Button>
@@ -186,9 +181,11 @@ export const SwitchPluginVersion: FC<SwitchPluginVersionProps> = (props) => {
}
function PluginVersionInstallConfirmation({
+ marketplace,
selection,
onInstalled,
}: {
+ marketplace: MarketplaceLinks | null
selection: PluginVersionSelection
onInstalled: (version: PluginVersionSelection['target']['version']) => void
}) {
@@ -225,19 +222,22 @@ function PluginVersionInstallConfirmation({
</div>
</DialogBody>
<DialogFooter>
- <Link
- className="me-auto flex items-center justify-center gap-1"
- href={getMarketplaceUrl(
- `/plugins/${selection.plugin.declaration.author}/${selection.plugin.declaration.name}`,
- )}
- target="_blank"
- rel="noopener noreferrer"
- >
- <span className="system-xs-regular text-xs text-text-accent">
- {t(($) => $['nodes.agent.installPlugin.changelog'], { ns: 'workflowAgent' })}
- </span>
- <span className="i-ri-external-link-line size-3 text-text-accent" />
- </Link>
+ {marketplace && (
+ <Link
+ className="me-auto flex items-center justify-center gap-1"
+ href={marketplace.plugin({
+ org: selection.plugin.declaration.author,
+ name: selection.plugin.declaration.name,
+ })}
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ <span className="system-xs-regular text-xs text-text-accent">
+ {t(($) => $['nodes.agent.installPlugin.changelog'], { ns: 'workflowAgent' })}
+ </span>
+ <span className="i-ri-external-link-line size-3 text-text-accent" />
+ </Link>
+ )}
{!mutation.isPending && (
<DialogClose render={<Button />}>
{t(($) => $['nodes.agent.installPlugin.cancel'], { ns: 'workflowAgent' })}
diff --git a/web/app/components/workflow/nodes/agent/components/__tests__/tool-icon.spec.tsx b/web/app/components/workflow/nodes/agent/components/__tests__/tool-icon.spec.tsx
index 5e2a8f10fe7..a6ac6a0612d 100644
--- a/web/app/components/workflow/nodes/agent/components/__tests__/tool-icon.spec.tsx
+++ b/web/app/components/workflow/nodes/agent/components/__tests__/tool-icon.spec.tsx
@@ -1,6 +1,6 @@
import type { ToolProviderApiEntityResponse as ToolProvider } from '@dify/contracts/api/console/workspaces/types.gen'
import { fireEvent, screen } from '@testing-library/react'
-import { MARKETPLACE_API_PREFIX } from '@/config'
+import { MARKETPLACE_API_PREFIX } from '@/features/marketplace/api'
import { renderWithConsoleQuery as render } from '@/test/console/query-data'
import { createToolProviderFixture } from '@/test/console/tool-provider-fixture'
import { ToolIcon } from '../tool-icon'
diff --git a/web/app/components/workflow/nodes/agent/components/tool-icon.tsx b/web/app/components/workflow/nodes/agent/components/tool-icon.tsx
index aa5397b782b..b0871147032 100644
--- a/web/app/components/workflow/nodes/agent/components/tool-icon.tsx
+++ b/web/app/components/workflow/nodes/agent/components/tool-icon.tsx
@@ -7,8 +7,8 @@ import { memo, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import AppIcon from '@/app/components/base/app-icon'
import { selectToolsWithProvider } from '@/app/components/tools/utils/query-select'
+import { getMarketplacePluginIconUrl } from '@/features/marketplace/api'
import { consoleQuery } from '@/service/console'
-import { getIconFromMarketPlace } from '@/utils/get-icon'
import { matchesProviderReference } from '@/utils/provider-reference'
type Status = 'not-installed' | 'not-authorized' | undefined
@@ -58,7 +58,7 @@ export const ToolIcon = memo(({ providerName }: ToolIconProps) => {
const icon = useMemo(() => {
if (!isDataReady) return ''
if (currentProvider) return currentProvider.icon
- const iconFromMarketPlace = getIconFromMarketPlace(`${author}/${name}`)
+ const iconFromMarketPlace = getMarketplacePluginIconUrl(`${author}/${name}`)
return iconFromMarketPlace
}, [author, currentProvider, name, isDataReady])
const status: Status = useMemo(() => {
diff --git a/web/config/index.ts b/web/config/index.ts
index 01b7c1e9b56..dbe3717819a 100644
--- a/web/config/index.ts
+++ b/web/config/index.ts
@@ -11,25 +11,6 @@ const getStringConfig = (envVar: string | undefined, defaultValue: string) => {
return defaultValue
}
-const isLocalMarketplaceApiUrl = (url: string | undefined) =>
- /^https?:\/\/(?:localhost|127\.0\.0\.1|\[::1\])(?::|\/)/i.test(url ?? '')
-
-// Docker entrypoint sets NEXT_PUBLIC_MARKETPLACE_API_PREFIX=${MARKETPLACE_API_URL}/api/v1.
-// MARKETPLACE_API_URL itself is the site origin (no /api/v1). Standalone marketplace
-// images may set MARKETPLACE_API_URL at runtime for SSR; normalize the same way
-// entrypoint does so console SSR does not call the HTML origin and fail Templates.
-const marketplaceApiPrefixFromUrl = (url: string) => {
- const trimmed = url.replace(/\/$/, '')
- return trimmed.endsWith('/api/v1') ? trimmed : `${trimmed}/api/v1`
-}
-
-const runtimeMarketplaceApiUrl =
- typeof globalThis.window === 'undefined' &&
- process.env.MARKETPLACE_API_URL &&
- !isLocalMarketplaceApiUrl(process.env.MARKETPLACE_API_URL)
- ? marketplaceApiPrefixFromUrl(process.env.MARKETPLACE_API_URL)
- : undefined
-
export const API_PREFIX = getStringConfig(
env.NEXT_PUBLIC_API_PREFIX,
'http://localhost:5001/console/api',
@@ -38,12 +19,6 @@ export const PUBLIC_API_PREFIX = getStringConfig(
env.NEXT_PUBLIC_PUBLIC_API_PREFIX,
'http://localhost:5001/api',
)
-export const MARKETPLACE_API_PREFIX = getStringConfig(
- runtimeMarketplaceApiUrl || env.NEXT_PUBLIC_MARKETPLACE_API_PREFIX,
- 'http://localhost:5002/api',
-)
-export const MARKETPLACE_URL_PREFIX = getStringConfig(env.NEXT_PUBLIC_MARKETPLACE_URL_PREFIX, '')
-
export const AMPLITUDE_API_KEY = getStringConfig(env.NEXT_PUBLIC_AMPLITUDE_API_KEY, '')
export const COOKIEYES_SITE_KEY = getStringConfig(env.NEXT_PUBLIC_COOKIEYES_SITE_KEY, '')
export const TURNSTILE_SITE_KEY = getStringConfig(env.NEXT_PUBLIC_TURNSTILE_SITE_KEY, '')
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/model-config/field.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/model-config/field.tsx
index 559038876ee..8eced292aa7 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/model-config/field.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/model-config/field.tsx
@@ -8,8 +8,8 @@ import { useQuery } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'
import ModelParameterModal from '@/app/components/header/account-setting/model-provider-page/model-parameter-modal'
+import { getMarketplacePluginIconUrl } from '@/features/marketplace/api'
import { consoleQuery } from '@/service/console'
-import { getIconFromMarketPlace } from '@/utils/get-icon'
import { isAgentCompatibleModel, isAgentSuggestedModel } from '../../../model-compatibility'
import { useAgentOrchestrateReadOnly } from '../read-only-context'
@@ -53,7 +53,7 @@ export function AgentModelField({ currentModel, onSelect }: AgentModelFieldProps
aria-hidden="true"
className="size-5 shrink-0 rounded-md"
height={20}
- src={getIconFromMarketPlace(currentModel.plugin_id)}
+ src={getMarketplacePluginIconUrl(currentModel.plugin_id)}
width={20}
/>
)}
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/slash.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/slash.tsx
index 63961bad691..90237eae860 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/slash.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/slash.tsx
@@ -18,7 +18,6 @@ import { FileTreeIcon } from '@langgenius/dify-ui/file-tree'
import { useQuery } from '@tanstack/react-query'
import { useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
-import { getMarketplaceCategoryUrl } from '@/app/components/plugins/marketplace/utils'
import { PluginCategoryEnum } from '@/app/components/plugins/types'
import { parseToolProviderType } from '@/app/components/tools/provider-type'
import { CollectionType } from '@/app/components/tools/types'
@@ -28,6 +27,7 @@ import { ToolType } from '@/app/components/workflow/block-selector/types'
import { BlockEnum } from '@/app/components/workflow/types'
import { useGetLanguage } from '@/context/i18n'
import { ENABLE_AGENT_CLI_TOOLS } from '@/features/agent-v2/agent-detail/configure/feature-flags'
+import { useMarketplace } from '@/features/marketplace/client'
import { consoleQuery } from '@/service/console'
import { getProviderReference, matchesProviderReference } from '@/utils/provider-reference'
import { useAgentPromptToolIconResolver } from './hooks'
@@ -695,21 +695,26 @@ function AgentPromptProviderIcon({
function AgentPromptToolFooter({ onAddCliTool }: { onAddCliTool?: () => void }) {
const { t } = useTranslation(['agentV2', 'plugin'])
+ const marketplace = useMarketplace()
+
+ if (!marketplace && !onAddCliTool) return null
return (
<div className="border-t border-divider-subtle p-1">
- <a
- href={getMarketplaceCategoryUrl(PluginCategoryEnum.tool)}
- target="_blank"
- rel="noreferrer"
- {...agentPromptSlashMenuItemProps}
- className="flex h-7 w-full items-center gap-1.5 rounded-md px-2 text-left hover:bg-state-base-hover focus-visible:bg-state-base-hover focus-visible:outline-hidden data-agent-prompt-menu-active:bg-state-base-hover"
- >
- <span aria-hidden className="i-ri-store-2-line size-4 shrink-0 text-text-secondary" />
- <span className="system-sm-regular text-text-secondary">
- {t(($) => $.findMoreInMarketplace, { ns: 'plugin' })}
- </span>
- </a>
+ {marketplace && (
+ <a
+ href={marketplace.category(PluginCategoryEnum.tool)}
+ target="_blank"
+ rel="noreferrer"
+ {...agentPromptSlashMenuItemProps}
+ className="flex h-7 w-full items-center gap-1.5 rounded-md px-2 text-left hover:bg-state-base-hover focus-visible:bg-state-base-hover focus-visible:outline-hidden data-agent-prompt-menu-active:bg-state-base-hover"
+ >
+ <span aria-hidden className="i-ri-store-2-line size-4 shrink-0 text-text-secondary" />
+ <span className="system-sm-regular text-text-secondary">
+ {t(($) => $.findMoreInMarketplace, { ns: 'plugin' })}
+ </span>
+ </a>
+ )}
{onAddCliTool && (
<button
type="button"
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/provider-tool/item.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/provider-tool/item.tsx
index 44156bd6da4..e2e5c428be1 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/provider-tool/item.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/provider-tool/item.tsx
@@ -19,10 +19,10 @@ import { CollectionType } from '@/app/components/tools/types'
import BlockIcon from '@/app/components/workflow/block-icon'
import { InstallPluginButton } from '@/app/components/workflow/nodes/_base/components/install-plugin-button'
import { BlockEnum } from '@/app/components/workflow/types'
+import { getMarketplacePluginIconUrl } from '@/features/marketplace/api'
import useTheme from '@/hooks/use-theme'
import { usePluginManifestInfo } from '@/service/use-plugins'
import { Theme } from '@/types/app'
-import { getIconFromMarketPlace } from '@/utils/get-icon'
import { useAgentOrchestrateReadOnly } from '../../read-only-context'
function ProviderIcon({
@@ -295,7 +295,7 @@ export const AgentProviderToolItem = memo(
const configuredIcon = theme === Theme.dark && tool.iconDark ? tool.iconDark : tool.icon
const icon =
configuredIcon ??
- (pluginManifest && tool.pluginId ? getIconFromMarketPlace(tool.pluginId) : undefined)
+ (pluginManifest && tool.pluginId ? getMarketplacePluginIconUrl(tool.pluginId) : undefined)
const installInfo = tool.pluginUniqueIdentifier ?? pluginManifest?.latest_package_identifier
const installIdentifiers = [tool.pluginId, tool.id].filter((identifier): identifier is string =>
Boolean(identifier),
diff --git a/web/features/agent-v2/agent-detail/configure/tool-provider-catalog.ts b/web/features/agent-v2/agent-detail/configure/tool-provider-catalog.ts
index 68261d7ae79..50ec896ab2f 100644
--- a/web/features/agent-v2/agent-detail/configure/tool-provider-catalog.ts
+++ b/web/features/agent-v2/agent-detail/configure/tool-provider-catalog.ts
@@ -8,9 +8,9 @@ import { useMemo } from 'react'
import { CollectionType } from '@/app/components/tools/types'
import { selectToolsWithProvider } from '@/app/components/tools/utils/query-select'
import { useGetLanguage } from '@/context/i18n'
+import { getMarketplacePluginIconUrl } from '@/features/marketplace/api'
import { consoleQuery } from '@/service/console'
import { useFetchPluginsInMarketPlaceByInfo } from '@/service/use-plugins'
-import { getIconFromMarketPlace } from '@/utils/get-icon'
import { getProviderReference } from '@/utils/provider-reference'
type AgentToolPresentationProvider = Pick<
@@ -116,7 +116,7 @@ export function getAgentProviderToolIcon(tool: AgentProviderTool, provider?: Too
if (provider?.icon) return provider.icon
const pluginId = getAgentProviderPluginId(tool)
- return pluginId ? getIconFromMarketPlace(pluginId) : undefined
+ return pluginId ? getMarketplacePluginIconUrl(pluginId) : undefined
}
function getMarketplacePluginInfo(pluginId: string) {
diff --git a/web/features/home/home-content/__tests__/home-content.spec.tsx b/web/features/home/home-content/__tests__/home-content.spec.tsx
index fdde4dbd665..b708d58ddc3 100644
--- a/web/features/home/home-content/__tests__/home-content.spec.tsx
+++ b/web/features/home/home-content/__tests__/home-content.spec.tsx
@@ -224,6 +224,7 @@ type RenderOptions = {
hasEditPermission?: boolean
enableExploreBanner?: boolean
enableLearnApp?: boolean
+ enableMarketplace?: boolean
extra?: ReactNode
deploymentEdition?: DeploymentEdition
searchParams?: Record<string, string>
@@ -250,6 +251,7 @@ const renderHomeContent = ({
deployment_edition: options.deploymentEdition ?? 'COMMUNITY',
enable_explore_banner: options.enableExploreBanner ?? false,
enable_learn_app: options.enableLearnApp ?? true,
+ enable_marketplace: options.enableMarketplace ?? false,
},
})
queryClient.setQueryData(
@@ -541,6 +543,20 @@ describe('HomeContent', () => {
).not.toBeInTheDocument()
})
+ it('links more templates to Marketplace only when Marketplace is enabled', () => {
+ const { unmount } = renderHomeContent({ enableMarketplace: true })
+
+ expect(screen.getByRole('link', { name: 'explore.apps.viewMore' })).toHaveAttribute(
+ 'href',
+ expect.stringContaining('/templates'),
+ )
+
+ unmount()
+ renderHomeContent({ enableMarketplace: false })
+
+ expect(screen.queryByRole('link', { name: 'explore.apps.viewMore' })).not.toBeInTheDocument()
+ })
+
it('should hide learn dify templates when learn app is disabled', () => {
mockExploreData = {
categories: ['Writing'],
diff --git a/web/features/home/home-content/templates-header.tsx b/web/features/home/home-content/templates-header.tsx
index a4f71c9bf42..dd5aaeff915 100644
--- a/web/features/home/home-content/templates-header.tsx
+++ b/web/features/home/home-content/templates-header.tsx
@@ -1,10 +1,9 @@
'use client'
-import { useSuspenseQuery } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { SearchInput } from '@/app/components/base/search-input'
import Category from '@/app/components/explore/category'
-import { systemFeaturesQueryOptions } from '@/features/system-features/client'
+import { useMarketplace } from '@/features/marketplace/client'
export function HomeTemplatesHeader({
allCategoriesEn,
@@ -22,10 +21,7 @@ export function HomeTemplatesHeader({
onKeywordsChange: (keywords: string) => void
}) {
const { t } = useTranslation(['explore', 'app'])
- const { data: enableMarketplace } = useSuspenseQuery({
- ...systemFeaturesQueryOptions(),
- select: ({ enable_marketplace }) => enable_marketplace,
- })
+ const marketplace = useMarketplace()
return (
<div className="sticky top-0 z-10 bg-background-body">
@@ -36,9 +32,9 @@ export function HomeTemplatesHeader({
>
{t(($) => $['apps.title'], { ns: 'explore' })}
</h2>
- {enableMarketplace && (
+ {marketplace && (
<a
- href="https://marketplace.dify.ai/templates"
+ href={marketplace.page('/templates')}
target="_blank"
rel="noopener noreferrer"
className="-my-1 -me-1 flex min-h-6 shrink-0 touch-manipulation items-center gap-1 rounded-md p-1 system-xs-medium text-text-tertiary outline-hidden transition-colors hover:text-text-secondary focus-visible:ring-2 focus-visible:ring-state-accent-solid motion-reduce:transition-none"
diff --git a/web/features/marketplace/__tests__/api.spec.ts b/web/features/marketplace/__tests__/api.spec.ts
new file mode 100644
index 00000000000..f0a46caed39
--- /dev/null
+++ b/web/features/marketplace/__tests__/api.spec.ts
@@ -0,0 +1,51 @@
+import { describe, expect, it, vi } from 'vite-plus/test'
+import {
+ getMarketplaceApiUrl,
+ getMarketplacePluginIconUrl,
+ getMarketplaceTemplateIconUrl,
+ resolveMarketplaceAssetUrl,
+} from '../api'
+
+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/',
+ },
+ }
+})
+
+describe('marketplace asset urls', () => {
+ it('joins API paths without duplicate slashes', () => {
+ expect(getMarketplaceApiUrl('/creators/dify/avatar')).toBe(
+ 'https://marketplace.dify.ai/api/v1/creators/dify/avatar',
+ )
+ })
+
+ it('builds plugin and bundle icons with encoded segments', () => {
+ expect(getMarketplacePluginIconUrl('langgenius/openai')).toBe(
+ 'https://marketplace.dify.ai/api/v1/plugins/langgenius/openai/icon',
+ )
+ expect(getMarketplacePluginIconUrl('org/my bundle', 'bundle')).toBe(
+ 'https://marketplace.dify.ai/api/v1/bundles/org/my%20bundle/icon',
+ )
+ })
+
+ it('builds template icons', () => {
+ expect(getMarketplaceTemplateIconUrl('template/1')).toBe(
+ 'https://marketplace.dify.ai/api/v1/templates/template%2F1/icon',
+ )
+ })
+
+ it.each([
+ [undefined, ''],
+ ['https://cdn.example.com/a.png', 'https://cdn.example.com/a.png'],
+ ['/_next/static/a.png', '/_next/static/a.png'],
+ ['/api/banners/a.png', 'https://marketplace.dify.ai/api/banners/a.png'],
+ ['banners/a.png', 'https://marketplace.dify.ai/api/v1/banners/a.png'],
+ ])('resolves asset path %s', (path, expected) => {
+ expect(resolveMarketplaceAssetUrl(path)).toBe(expected)
+ })
+})
diff --git a/web/features/marketplace/__tests__/client.spec.tsx b/web/features/marketplace/__tests__/client.spec.tsx
new file mode 100644
index 00000000000..cea7eca791d
--- /dev/null
+++ b/web/features/marketplace/__tests__/client.spec.tsx
@@ -0,0 +1,31 @@
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { renderHook } from '@testing-library/react'
+import { describe, expect, it } from 'vite-plus/test'
+import { systemFeaturesQueryOptions } from '@/features/system-features/client'
+import { createSystemFeaturesFixture } from '@/test/console/system-features'
+import { useMarketplace } from '../client'
+import { marketplaceLinks } from '../links'
+
+const renderUseMarketplace = (enableMarketplace: boolean) => {
+ const queryClient = new QueryClient()
+ queryClient.setQueryData(
+ systemFeaturesQueryOptions().queryKey,
+ createSystemFeaturesFixture({ enable_marketplace: enableMarketplace }),
+ )
+
+ return renderHook(() => useMarketplace(), {
+ wrapper: ({ children }) => (
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ ),
+ })
+}
+
+describe('useMarketplace', () => {
+ it('returns the Marketplace links when the deployment enables Marketplace', () => {
+ expect(renderUseMarketplace(true).result.current).toBe(marketplaceLinks)
+ })
+
+ it('returns null when the deployment disables Marketplace', () => {
+ expect(renderUseMarketplace(false).result.current).toBeNull()
+ })
+})
diff --git a/web/features/marketplace/__tests__/links.spec.ts b/web/features/marketplace/__tests__/links.spec.ts
new file mode 100644
index 00000000000..9bf5d869700
--- /dev/null
+++ b/web/features/marketplace/__tests__/links.spec.ts
@@ -0,0 +1,181 @@
+import { describe, expect, it, vi } from 'vite-plus/test'
+import {
+ getCreatorCenterUrl,
+ getPluginDetailPath,
+ getTemplateDetailPath,
+ marketplaceLinks,
+ PUBLIC_CREATOR_CENTER_URL,
+ rewriteMarketplaceOriginToCreators,
+} from '../links'
+
+vi.mock('@/env', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/env')>()
+ return {
+ ...actual,
+ env: {
+ ...actual.env,
+ NEXT_PUBLIC_MARKETPLACE_URL_PREFIX: 'https://marketplace.dify.ai',
+ NEXT_PUBLIC_WEB_PREFIX: '',
+ },
+ }
+})
+
+describe('marketplaceLinks.page', () => {
+ it('adds defined params and skips undefined ones', () => {
+ const url = new URL(marketplaceLinks.page('/plugins', { category: 'ai', version: undefined }))
+
+ expect(url.origin + url.pathname).toBe('https://marketplace.dify.ai/plugins')
+ expect(Object.fromEntries(url.searchParams)).toEqual({ category: 'ai' })
+ })
+
+ it('reduces the source to its origin without double encoding', () => {
+ const url = marketplaceLinks.page('/plugins', { category: 'ai' }, 'https://example.com/app')
+
+ expect(url).toContain('source=https%3A%2F%2Fexample.com')
+ expect(url).not.toContain('source=https%253A%252F%252Fexample.com')
+ })
+
+ it('lets params replace the source without duplicating it', () => {
+ const url = new URL(
+ marketplaceLinks.page(
+ '/plugins',
+ { source: 'http://localhost:3001', language: 'en-US' },
+ 'http://localhost:3000',
+ ),
+ )
+
+ expect(url.searchParams.getAll('source')).toEqual(['http://localhost:3001'])
+ expect(url.searchParams.get('language')).toBe('en-US')
+ })
+
+ it('does not append an empty query string', () => {
+ expect(marketplaceLinks.page('/plugins')).toBe('https://marketplace.dify.ai/plugins')
+ })
+})
+
+describe('plugin links', () => {
+ it.each([
+ { type: 'plugin' as const, collection: 'plugins', detail: 'plugin' },
+ { type: 'bundle' as const, collection: 'bundles', detail: 'bundles' },
+ ])('builds $type links', ({ type, collection, detail }) => {
+ const plugin = { type, org: 'test-org', name: 'test-plugin' }
+
+ expect(marketplaceLinks.plugin(plugin)).toBe(
+ `https://marketplace.dify.ai/${collection}/test-org/test-plugin`,
+ )
+ expect(getPluginDetailPath(plugin)).toBe(`/${detail}/test-org/test-plugin`)
+ })
+
+ it('builds category links', () => {
+ expect(marketplaceLinks.category()).toBe('https://marketplace.dify.ai/plugins')
+ expect(marketplaceLinks.category('tool', { theme: 'dark' })).toBe(
+ 'https://marketplace.dify.ai/plugins/tool?theme=dark',
+ )
+ })
+})
+
+describe('getTemplateDetailPath', () => {
+ it('keeps the same link after a title change and prefers the unique handle', () => {
+ const template = {
+ id: '5d107b52-8d4d-447b-9bad-1c5c16b01721',
+ publisher_handle: 'Dify Display Name',
+ publisher_unique_handle: 'dify-unique',
+ }
+
+ expect(getTemplateDetailPath(template)).toBe(
+ '/template/dify-unique/5d107b52-8d4d-447b-9bad-1c5c16b01721',
+ )
+ })
+
+ it('encodes both path segments and falls back to the publisher handle', () => {
+ expect(
+ getTemplateDetailPath({
+ id: 'template/one',
+ publisher_handle: 'Research / 团队',
+ publisher_unique_handle: '',
+ }),
+ ).toBe('/template/Research%20%2F%20%E5%9B%A2%E9%98%9F/template%2Fone')
+ })
+
+ it('uses the template fallback when publisher handles are absent', () => {
+ expect(getTemplateDetailPath({ id: 'template-2' })).toBe('/template/template/template-2')
+ })
+})
+
+describe('marketplaceLinks.template', () => {
+ it('preserves embedded context while dropping legacy identity parameters', () => {
+ const link = new URL(
+ marketplaceLinks.template(
+ { id: 'template-1', publisher_handle: 'Display Name', publisher_unique_handle: 'dify' },
+ {
+ tid: 'legacy-short-id',
+ templateId: 'legacy-id',
+ creationType: 'templates',
+ language: 'zh-Hans',
+ theme: 'dark',
+ source: 'https://cloud.dify.ai',
+ view: 'modal',
+ },
+ ),
+ )
+
+ expect(link.origin + link.pathname).toBe('https://marketplace.dify.ai/template/dify/template-1')
+ expect(Object.fromEntries(link.searchParams)).toEqual({
+ language: 'zh-Hans',
+ theme: 'dark',
+ source: 'https://cloud.dify.ai',
+ view: 'modal',
+ })
+ })
+})
+
+describe('creator center', () => {
+ it.each([
+ ['https://marketplace.dify.ai', 'https://creators.dify.ai/'],
+ ['https://marketplace.dify.dev', 'https://creators.dify.dev/'],
+ ['https://marketplace-staging.dify.dev', 'https://creators-staging.dify.dev/'],
+ ])('maps %s to %s', (origin, creators) => {
+ expect(rewriteMarketplaceOriginToCreators(origin)).toBe(creators)
+ })
+
+ it('returns null for hosts that are not a Marketplace surface', () => {
+ expect(rewriteMarketplaceOriginToCreators('https://cloud.dify.ai')).toBeNull()
+ expect(rewriteMarketplaceOriginToCreators('http://localhost:3000')).toBeNull()
+ expect(rewriteMarketplaceOriginToCreators('')).toBeNull()
+ })
+
+ it('prefers the current Marketplace page over the configured prefix', () => {
+ expect(getCreatorCenterUrl('https://marketplace.dify.dev')).toBe('https://creators.dify.dev/')
+ expect(getCreatorCenterUrl('http://localhost:3000')).toBe('https://creators.dify.ai/')
+ expect(marketplaceLinks.creatorCenter).toBe('https://creators.dify.ai/')
+ })
+
+ it('exposes the public Creator Center fallback', () => {
+ expect(PUBLIC_CREATOR_CENTER_URL).toBe('https://creators.dify.ai/')
+ })
+})
+
+describe('official detail links', () => {
+ it('opens plugin and template details on the official Marketplace', () => {
+ const params = { language: 'en-US', theme: 'dark' }
+
+ expect(
+ marketplaceLinks.officialPluginDetail(
+ { org: 'org', name: 'plugin' },
+ params,
+ 'https://dify.example.com/app',
+ ),
+ ).toBe(
+ 'https://marketplace.dify.ai/plugin/org/plugin?source=https%3A%2F%2Fdify.example.com&language=en-US&theme=dark',
+ )
+ expect(
+ marketplaceLinks.officialTemplateDetail(
+ { id: 'template-1' },
+ params,
+ 'https://dify.example.com',
+ ),
+ ).toBe(
+ 'https://marketplace.dify.ai/template/template/template-1?source=https%3A%2F%2Fdify.example.com&language=en-US&theme=dark',
+ )
+ })
+})
diff --git a/web/features/marketplace/api.ts b/web/features/marketplace/api.ts
new file mode 100644
index 00000000000..77425f87e4a
--- /dev/null
+++ b/web/features/marketplace/api.ts
@@ -0,0 +1,48 @@
+import type { MarketplacePlugin } from '@dify/contracts/marketplace'
+import { env } from '@/env'
+
+const isLocalMarketplaceApiUrl = (url: string | undefined) =>
+ /^https?:\/\/(?:localhost|127\.0\.0\.1|\[::1\])(?::|\/)/i.test(url ?? '')
+
+// Docker entrypoint sets NEXT_PUBLIC_MARKETPLACE_API_PREFIX=${MARKETPLACE_API_URL}/api/v1.
+// MARKETPLACE_API_URL itself is the site origin (no /api/v1). Standalone marketplace
+// images may set MARKETPLACE_API_URL at runtime for SSR; normalize the same way
+// entrypoint does so console SSR does not call the HTML origin and fail Templates.
+const marketplaceApiPrefixFromUrl = (url: string) => {
+ const trimmed = url.replace(/\/$/, '')
+ return trimmed.endsWith('/api/v1') ? trimmed : `${trimmed}/api/v1`
+}
+
+const runtimeMarketplaceApiUrl =
+ typeof globalThis.window === 'undefined' &&
+ process.env.MARKETPLACE_API_URL &&
+ !isLocalMarketplaceApiUrl(process.env.MARKETPLACE_API_URL)
+ ? marketplaceApiPrefixFromUrl(process.env.MARKETPLACE_API_URL)
+ : undefined
+
+export const MARKETPLACE_API_PREFIX =
+ runtimeMarketplaceApiUrl || env.NEXT_PUBLIC_MARKETPLACE_API_PREFIX || 'http://localhost:5002/api'
+
+const apiPrefix = MARKETPLACE_API_PREFIX.replace(/\/$/, '')
+
+const encodePath = (path: string) => path.split('/').map(encodeURIComponent).join('/')
+
+export const getMarketplaceApiUrl = (path: string) => `${apiPrefix}/${path.replace(/^\//, '')}`
+
+export const getMarketplacePluginIconUrl = (pluginId: string, type?: MarketplacePlugin['type']) =>
+ getMarketplaceApiUrl(`${type === 'bundle' ? 'bundles' : 'plugins'}/${encodePath(pluginId)}/icon`)
+
+export const getMarketplaceTemplateIconUrl = (templateId: string) =>
+ getMarketplaceApiUrl(`templates/${encodeURIComponent(templateId)}/icon`)
+
+export const resolveMarketplaceAssetUrl = (path?: string) => {
+ if (!path) return ''
+ if (/^https?:\/\//.test(path) || path.startsWith('/_next/')) return path
+ if (!path.startsWith('/api/')) return getMarketplaceApiUrl(path)
+
+ try {
+ return `${new URL(apiPrefix).origin}${path}`
+ } catch {
+ return path
+ }
+}
diff --git a/web/features/marketplace/client.ts b/web/features/marketplace/client.ts
new file mode 100644
index 00000000000..2fdb89b5011
--- /dev/null
+++ b/web/features/marketplace/client.ts
@@ -0,0 +1,52 @@
+'use client'
+
+import type { Plugin } from '@/app/components/plugins/types'
+import { keepPreviousData, skipToken, useQuery, useSuspenseQuery } from '@tanstack/react-query'
+import { getFormattedPlugin } from '@/app/components/plugins/marketplace/utils'
+import { systemFeaturesQueryOptions } from '@/features/system-features/client'
+import { marketplaceQuery } from '@/service/marketplace'
+import { marketplaceLinks } from './links'
+
+export const useMarketplace = () => {
+ const { data: enabled } = useSuspenseQuery({
+ ...systemFeaturesQueryOptions(),
+ select: (systemFeatures) => systemFeatures.enable_marketplace,
+ })
+
+ return enabled ? marketplaceLinks : null
+}
+
+export const useMarketplacePluginVersions = (pluginId: string | undefined, enabled: boolean) => {
+ const marketplace = useMarketplace()
+ const [organization, pluginName] = pluginId?.split('/') ?? []
+
+ return useQuery(
+ marketplaceQuery.pluginVersions.queryOptions({
+ input:
+ marketplace && organization && pluginName
+ ? { params: { organization, pluginName }, query: { page: 1, page_size: 100 } }
+ : skipToken,
+ enabled,
+ retry: false,
+ }),
+ )
+}
+
+export const useMarketplacePluginSearch = <TData>(
+ query: string,
+ { enabled, select }: { enabled: boolean; select: (plugins: Plugin[]) => TData },
+) => {
+ const marketplace = useMarketplace()
+
+ return useQuery(
+ marketplaceQuery.searchAdvanced.queryOptions({
+ input: marketplace
+ ? { params: { kind: 'plugins' }, body: { page: 1, page_size: 10, query } }
+ : skipToken,
+ enabled,
+ retry: false,
+ placeholderData: keepPreviousData,
+ select: (response) => select((response.data?.plugins ?? []).map(getFormattedPlugin)),
+ }),
+ )
+}
diff --git a/web/features/marketplace/links.ts b/web/features/marketplace/links.ts
new file mode 100644
index 00000000000..c5ca35db9af
--- /dev/null
+++ b/web/features/marketplace/links.ts
@@ -0,0 +1,128 @@
+import type { MarketplacePlugin, MarketplaceTemplate } from '@dify/contracts/marketplace'
+import { env } from '@/env'
+
+type MarketplaceUrlParams = Record<string, string | undefined>
+
+export type MarketplacePluginRef = Pick<MarketplacePlugin, 'org' | 'name'> & {
+ type?: MarketplacePlugin['type']
+}
+
+type MarketplaceTemplateRef = Pick<
+ MarketplaceTemplate,
+ 'id' | 'publisher_handle' | 'publisher_unique_handle'
+>
+
+export const PUBLIC_CREATOR_CENTER_URL = 'https://creators.dify.ai/'
+
+const getUrlOrigin = (url?: string) => {
+ if (!url) return undefined
+
+ try {
+ return new URL(url).origin
+ } catch {
+ return undefined
+ }
+}
+
+const defaultSource = getUrlOrigin(env.NEXT_PUBLIC_WEB_PREFIX)
+
+const OFFICIAL_MARKETPLACE_URL = 'https://marketplace.dify.ai'
+
+const buildUrl = (origin: string, path: string, params?: MarketplaceUrlParams, source?: string) => {
+ const searchParams = new URLSearchParams()
+ const sourceOrigin = getUrlOrigin(source) ?? defaultSource
+ if (sourceOrigin) searchParams.set('source', sourceOrigin)
+
+ Object.entries(params ?? {}).forEach(([key, value]) => {
+ if (value !== undefined) searchParams.set(key, value)
+ })
+
+ const queryString = searchParams.toString()
+ return queryString ? `${origin}${path}?${queryString}` : `${origin}${path}`
+}
+
+const page = (path: string, params?: MarketplaceUrlParams, source?: string) =>
+ buildUrl(env.NEXT_PUBLIC_MARKETPLACE_URL_PREFIX ?? '', path, params, source)
+
+export const getPluginDetailPath = (plugin: MarketplacePluginRef) => {
+ const org = encodeURIComponent(plugin.org)
+ const name = encodeURIComponent(plugin.name)
+
+ if (plugin.type === 'bundle') return `/bundles/${org}/${name}`
+ return `/plugin/${org}/${name}`
+}
+
+export const getTemplateDetailPath = (template: MarketplaceTemplateRef) => {
+ const publisher = template.publisher_unique_handle || template.publisher_handle || 'template'
+
+ return `/template/${encodeURIComponent(publisher)}/${encodeURIComponent(template.id)}`
+}
+
+/**
+ * marketplace.dify.ai → creators.dify.ai
+ * marketplace.dify.dev → creators.dify.dev
+ * marketplace-staging.dify.dev → creators-staging.dify.dev
+ */
+export const rewriteMarketplaceOriginToCreators = (origin: string): string | null => {
+ if (!origin) return null
+
+ try {
+ const marketplaceUrl = new URL(origin)
+ const [service, ...domain] = marketplaceUrl.hostname.split('.')
+ if (!service?.startsWith('marketplace') || domain.length === 0) return null
+
+ marketplaceUrl.hostname = [service.replace(/^marketplace/, 'creators'), ...domain].join('.')
+ marketplaceUrl.pathname = '/'
+ marketplaceUrl.search = ''
+ marketplaceUrl.hash = ''
+ return marketplaceUrl.toString()
+ } catch {
+ return null
+ }
+}
+
+export const getCreatorCenterUrl = (pageOrigin?: string): string => {
+ return (
+ rewriteMarketplaceOriginToCreators(pageOrigin ?? '') ||
+ rewriteMarketplaceOriginToCreators(env.NEXT_PUBLIC_MARKETPLACE_URL_PREFIX ?? '') ||
+ PUBLIC_CREATOR_CENTER_URL
+ )
+}
+
+/**
+ * Links to Marketplace pages. Console surfaces get them from `useMarketplace()`,
+ * which returns `null` when the deployment disables Marketplace.
+ */
+export const marketplaceLinks = {
+ page,
+ plugin: (plugin: MarketplacePluginRef, params?: MarketplaceUrlParams) =>
+ page(
+ `/${plugin.type === 'bundle' ? 'bundles' : 'plugins'}/${plugin.org}/${plugin.name}`,
+ params,
+ ),
+ category: (category?: string, params?: MarketplaceUrlParams) =>
+ page(category ? `/plugins/${category}` : '/plugins', params),
+ template: (template: MarketplaceTemplateRef, params?: MarketplaceUrlParams) => {
+ const {
+ tid: _tid,
+ templateId: _templateId,
+ creationType: _creationType,
+ ...detailParams
+ } = params ?? {}
+
+ return page(getTemplateDetailPath(template), detailParams)
+ },
+ officialPluginDetail: (
+ plugin: MarketplacePluginRef,
+ params: MarketplaceUrlParams,
+ source: string,
+ ) => buildUrl(OFFICIAL_MARKETPLACE_URL, getPluginDetailPath(plugin), params, source),
+ officialTemplateDetail: (
+ template: MarketplaceTemplateRef,
+ params: MarketplaceUrlParams,
+ source: string,
+ ) => buildUrl(OFFICIAL_MARKETPLACE_URL, getTemplateDetailPath(template), params, source),
+ creatorCenter: getCreatorCenterUrl(),
+}
+
+export type MarketplaceLinks = typeof marketplaceLinks
diff --git a/web/service/fetch.ts b/web/service/fetch.ts
index 3db0b2565f6..8654a6f14ef 100644
--- a/web/service/fetch.ts
+++ b/web/service/fetch.ts
@@ -9,11 +9,11 @@ import {
CSRF_COOKIE_NAME,
CSRF_HEADER_NAME,
IS_MARKETPLACE,
- MARKETPLACE_API_PREFIX,
PASSPORT_HEADER_NAME,
PUBLIC_API_PREFIX,
WEB_APP_SHARE_CODE_HEADER_NAME,
} from '@/config'
+import { MARKETPLACE_API_PREFIX } from '@/features/marketplace/api'
import { shouldSuppressAppDeletionErrorToast } from './app-deletion'
import { httpErrorFromResponse, isHttpErrorStatus } from './http-error'
import { clearRequestErrorToasts, notifyRequestError } from './request-error-toast'
diff --git a/web/service/marketplace-templates.ts b/web/service/marketplace-templates.ts
index c997f620a42..659f53e8bd5 100644
--- a/web/service/marketplace-templates.ts
+++ b/web/service/marketplace-templates.ts
@@ -1,5 +1,5 @@
import { useQuery } from '@tanstack/react-query'
-import { MARKETPLACE_API_PREFIX } from '@/config'
+import { getMarketplaceApiUrl } from '@/features/marketplace/api'
import { marketplaceQuery } from '@/service/marketplace'
export const useMarketplaceTemplateDetail = (templateId: string | null) => {
@@ -12,8 +12,7 @@ export const useMarketplaceTemplateDetail = (templateId: string | null) => {
}
export const fetchMarketplaceTemplateDSL = async (templateId: string): Promise<string> => {
- const url = `${MARKETPLACE_API_PREFIX}/templates/${templateId}/dsl`
- const response = await fetch(url)
+ const response = await fetch(getMarketplaceApiUrl(`templates/${templateId}/dsl`))
if (!response.ok) throw new Error(`Failed to fetch DSL: ${response.statusText}`)
return response.text()
}
diff --git a/web/service/marketplace.ts b/web/service/marketplace.ts
index 824824a513c..02a77e0dc4f 100644
--- a/web/service/marketplace.ts
+++ b/web/service/marketplace.ts
@@ -4,7 +4,8 @@ import { marketplaceRouterContract } from '@dify/contracts/marketplace'
import { createORPCClient, onError } from '@orpc/client'
import { OpenAPILink } from '@orpc/openapi-client/fetch'
import { createTanstackQueryUtils } from '@orpc/tanstack-query'
-import { APP_VERSION, IS_MARKETPLACE, MARKETPLACE_API_PREFIX } from '@/config'
+import { APP_VERSION, IS_MARKETPLACE } from '@/config'
+import { MARKETPLACE_API_PREFIX } from '@/features/marketplace/api'
import { reportClientError } from './client-error'
// 15s deadline so a stalled Marketplace fetch can error/retry.
diff --git a/web/utils/get-icon.ts b/web/utils/get-icon.ts
deleted file mode 100644
index f2ed116a14b..00000000000
--- a/web/utils/get-icon.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-import { MARKETPLACE_API_PREFIX } from '@/config'
-
-export const getIconFromMarketPlace = (plugin_id: string) => {
- return `${MARKETPLACE_API_PREFIX}/plugins/${plugin_id}/icon`
-}
diff --git a/web/utils/var.spec.ts b/web/utils/var.spec.ts
index d8b256de9a9..41268ec1b8f 100644
--- a/web/utils/var.spec.ts
+++ b/web/utils/var.spec.ts
@@ -1,10 +1,9 @@
-import { describe, expect, it, vi } from 'vite-plus/test'
+import { describe, expect, it } from 'vite-plus/test'
import { InputVarType } from '@/app/components/workflow/types'
import { getMaxVarNameLength, MAX_VAR_KEY_LENGTH } from '@/config'
import {
checkKey,
checkKeys,
- getMarketplaceUrl,
getNewVar,
getNewVarInWorkflow,
getVars,
@@ -192,58 +191,6 @@ describe('Variable Utilities', () => {
})
})
- describe('getMarketplaceUrl', () => {
- it('should add additional parameters', () => {
- const url = getMarketplaceUrl('/plugins', { category: 'ai', version: '1.0' })
- expect(url).toContain('category=ai')
- expect(url).toContain('version=1.0')
- })
-
- it('should skip undefined parameters', () => {
- const url = getMarketplaceUrl('/plugins', { category: 'ai', version: undefined })
- expect(url).toContain('category=ai')
- expect(url).not.toContain('version=')
- })
-
- it('should include provided source without double encoding', () => {
- const url = getMarketplaceUrl(
- '/plugins',
- { category: 'ai' },
- { source: 'https://example.com/app' },
- )
- expect(url).toContain('source=https%3A%2F%2Fexample.com')
- expect(url).not.toContain('source=https%253A%252F%252Fexample.com')
- })
-
- it('should let params replace the default source without duplicating it', () => {
- const url = getMarketplaceUrl(
- '/plugins',
- { source: 'http://localhost:3001', language: 'en-US' },
- { source: 'http://localhost:3000' },
- )
- const searchParams = new URL(url, 'https://marketplace.dify.ai').searchParams
-
- expect(searchParams.getAll('source')).toEqual(['http://localhost:3001'])
- expect(searchParams.get('language')).toBe('en-US')
- })
-
- it('should not access window during server render', () => {
- vi.stubGlobal('window', undefined)
-
- try {
- const url = getMarketplaceUrl('/plugins', { category: 'ai' })
- expect(url).toContain('category=ai')
- expect(url).not.toContain('source=')
- } finally {
- vi.unstubAllGlobals()
- }
- })
-
- it('should not append empty query string when no params are available', () => {
- expect(getMarketplaceUrl('/plugins')).toBe('/plugins')
- })
- })
-
describe('replaceSpaceWithUnderscoreInVarNameInput', () => {
it('should replace spaces with underscores', () => {
const input = document.createElement('input')
diff --git a/web/utils/var.ts b/web/utils/var.ts
index 167ae9cef69..f893476ad6e 100644
--- a/web/utils/var.ts
+++ b/web/utils/var.ts
@@ -9,7 +9,6 @@ import {
import { InputVarType } from '@/app/components/workflow/types'
import {
getMaxVarNameLength,
- MARKETPLACE_URL_PREFIX,
MAX_VAR_KEY_LENGTH,
VAR_ITEM_TEMPLATE,
VAR_ITEM_TEMPLATE_IN_WORKFLOW,
@@ -146,44 +145,6 @@ export const getVars = (value: string) => {
// example: /dify
export const basePath = env.NEXT_PUBLIC_BASE_PATH
-type MarketplaceUrlOptions = {
- source?: string
-}
-
-const getUrlOrigin = (url?: string) => {
- if (!url) return undefined
-
- try {
- return new URL(url).origin
- } catch {
- return undefined
- }
-}
-
-const marketplaceSource = getUrlOrigin(env.NEXT_PUBLIC_WEB_PREFIX)
-
-export function getMarketplaceUrl(
- path: string,
- params?: Record<string, string | undefined>,
- options?: MarketplaceUrlOptions,
-) {
- const searchParams = new URLSearchParams()
- const source = getUrlOrigin(options?.source) ?? marketplaceSource
- if (source) searchParams.set('source', source)
-
- if (params) {
- Object.keys(params).forEach((key) => {
- const value = params[key]
- if (value !== undefined && value !== null) searchParams.set(key, value)
- })
- }
-
- const queryString = searchParams.toString()
- return queryString
- ? `${MARKETPLACE_URL_PREFIX}${path}?${queryString}`
- : `${MARKETPLACE_URL_PREFIX}${path}`
-}
-
export const replaceSpaceWithUnderscoreInVarNameInput = (input: HTMLInputElement) => {
const start = input.selectionStart
const end = input.selectionEnd