feat(dify): 把本地控制台的中文与去外链改动入库

这些界面改动和专家服务草稿停在工作区,没有随上一笔主分支提交进入仓库。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
wuzilongandCursor committed 2026-11-23 09:44:09 +08:00
1 parent 9c7c80e194
commit c2cb845a32
211 files changed
+3030 -2794

No files matched your search

@@ -11,7 +11,6 @@ import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { TIME_PERIOD_MAPPING as LONG_TIME_PERIOD_MAPPING } from '@/app/components/app/log/filter'
import { AppCharts } from '@/app/components/app/overview/app-chart'
import { useDocLink } from '@/context/i18n'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import LongTimeRangePicker from './long-time-range-picker'
import TimeRangePicker from './time-range-picker'
@@ -61,8 +60,7 @@ function ChartViewContent({
const { t } = useTranslation(['appLog', 'common'])
const isCloudEdition = deploymentEdition === 'CLOUD'
const isNonCloudEdition = deploymentEdition === 'COMMUNITY' || deploymentEdition === 'ENTERPRISE'
const docLink = useDocLink()
const [period, setPeriod] = useState<PeriodParams>(() =>
const [period, setPeriod] = useState<PeriodParams>(() =>
isCloudEdition
? {
name: t(($) => $['filter.period.today'], { ns: 'appLog' }),
@@ -93,15 +91,6 @@ function ChartViewContent({
<p className="min-w-0 truncate">
{t(($) => $['monitoring.description'], { ns: 'appLog' })}
</p>
<a
href={docLink('/use-dify/monitor/analysis')}
target="_blank"
rel="noopener noreferrer"
className="inline-flex shrink-0 items-center text-text-accent hover:underline"
>
<span>{t(($) => $['operation.learnMore'], { ns: 'common' })}</span>
<span className="i-ri-external-link-line size-3" aria-hidden="true" />
</a>
</div>
</div>
<div className="mt-1 flex h-10 items-center justify-between pr-10 pl-6">
@@ -7,7 +7,6 @@ import { skipToken, useQuery, useSuspenseQuery } from '@tanstack/react-query'
import { useAtomValue } from 'jotai'
import { useTranslation } from 'react-i18next'
import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
import { useDocLink } from '@/context/i18n'
import { currentWorkspaceAtom, currentWorkspaceLoadingAtom } from '@/context/workspace-state'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import Link from '@/next/link'
@@ -39,8 +38,7 @@ export function BuiltInAccessPoints({
highlightedAccessPoint,
}: BuiltInAccessPointsProps) {
const { t } = useTranslation(['common', 'deployments'])
const docLink = useDocLink()
const { data: appInfo } = useSuspenseQuery(
const { data: appInfo } = useSuspenseQuery(
consoleQuery.apps.byAppId.get.queryOptions({ input: { params: { app_id: appId } } }),
)
const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
@@ -185,15 +183,7 @@ export function BuiltInAccessPoints({
<span>
{t(($) => $['studio.accessPoint.triggerExclusiveNotice'], {
ns: 'deployments',
})}{' '}
<Link
href={docLink('/use-dify/nodes/start')}
target="_blank"
rel="noopener noreferrer"
className="text-text-accent hover:underline"
>
{t(($) => $['operation.learnMore'], { ns: 'common' })}
</Link>
})}
</span>
</div>
)}
@@ -15,7 +15,6 @@ import BlockIcon from '@/app/components/workflow/block-icon'
import { useTriggerStatusStore } from '@/app/components/workflow/store/trigger-status'
import { BlockEnum } from '@/app/components/workflow/types'
import { toast } from '@/app/notifications'
import { useDocLink } from '@/context/i18n'
import Link from '@/next/link'
import { consoleQuery } from '@/service/console'
import { useAllTriggerPlugins } from '@/service/use-triggers'
@@ -155,8 +154,7 @@ export function TriggerAccessPointCard({
highlighted,
}: TriggerAccessPointCardProps) {
const { t } = useTranslation(['appOverview', 'deployments', 'navigation'])
const docLink = useDocLink()
const { data: response, isLoading } = useQuery(
const { data: response, isLoading } = useQuery(
consoleQuery.apps.byAppId.triggers.get.queryOptions({
input: { params: { app_id: appInfo.id } },
enabled: !!appInfo.id,
@@ -210,16 +208,13 @@ export function TriggerAccessPointCard({
{t(($) => $['overview.triggerInfo.triggerStatusDescription'], {
ns: 'appOverview',
})}{' '}
<Link
href={docLink('/use-dify/nodes/trigger/overview')}
target="_blank"
rel="noopener noreferrer"
<span
className="text-text-accent underline"
>
{t(($) => $['overview.triggerInfo.learnAboutTriggers'], {
ns: 'appOverview',
})}
</Link>
</span>
</span>
</AccessPointEmptyContent>
)}
@@ -3,12 +3,13 @@
import type { AppDetailWithSite } from '@dify/contracts/api/console/apps/types.gen'
import type { ReactNode } from 'react'
import type { AccessPointStatus } from '@/app/components/base/access-point/status'
import { Button, buttonVariants } from '@langgenius/dify-ui/button'
import { buttonVariants } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import { useTranslation } from 'react-i18next'
import { AccessPointCard } from '@/app/components/base/access-point/card'
import { AccessPointUrl } from '@/app/components/base/access-point/url'
import { useDocLink } from '@/context/i18n'
import { isOfficialDifyUrl } from '@/utils/official-link'
import Link from '@/next/link'
import { useAccessPointStatusLabel } from './use-access-point-status-label'
import { getAppApiReferencePath } from './utils'
@@ -59,7 +60,7 @@ export function ServiceApiCardView({
actions={
<>
{apiKeyAction}
{available && apiReferenceUrl ? (
{available && apiReferenceUrl && !isOfficialDifyUrl(apiReferenceUrl) ? (
<Link
href={apiReferenceUrl}
target="_blank"
@@ -70,13 +71,7 @@ export function ServiceApiCardView({
{t(($) => $['overview.apiInfo.doc'], { ns: 'appOverview' })}
<span aria-hidden className="i-ri-arrow-right-up-line size-3.5" />
</Link>
) : (
<Button variant="secondary" disabled className="flex items-center gap-1">
<span aria-hidden className="i-ri-book-open-line size-4" />
{t(($) => $['overview.apiInfo.doc'], { ns: 'appOverview' })}
<span aria-hidden className="i-ri-arrow-right-up-line size-3.5" />
</Button>
)}
) : null}
</>
}
>
@@ -31,7 +31,6 @@ import CodeEditor from '@/app/components/workflow/nodes/_base/components/editor/
import FileUploadSetting from '@/app/components/workflow/nodes/_base/components/file-upload-setting'
import { CodeLanguage } from '@/app/components/workflow/nodes/code/types'
import { InputVarType, SupportUploadFileTypes } from '@/app/components/workflow/types'
import { useDocLink } from '@/context/i18n'
import { TransferMethod } from '@/types/app'
import ConfigSelect from '../config-select'
import ConfigString from '../config-string'
@@ -42,6 +41,10 @@ import { CHECKBOX_DEFAULT_FALSE_VALUE, CHECKBOX_DEFAULT_TRUE_VALUE, TEXT_MAX_LEN
const EMPTY_SELECT_VALUE = '__empty__' as const
function HiddenOfficialPhrase() {
return null
}
type ConfigModalFormFieldsProps = {
checkboxDefaultSelectValue: string
isStringInput: boolean
@@ -92,7 +95,6 @@ const ConfigModalFormFields: FC<ConfigModalFormFieldsProps> = ({
? Number(tempPayload.default)
: Number.NaN
const isFileInput = fileInputTypes.includes(type)
const docLink = useDocLink()
const fieldId = React.useId()
const errorId = `${fieldId}-error`
const getError = (field: ConfigModalValidationError['field']) =>
@@ -416,14 +418,7 @@ const ConfigModalFormFields: FC<ConfigModalFormFieldsProps> = ({
i18nKey={($) => $['variableConfig.hiddenDescription']}
ns="appDebug"
components={{
docLink: (
<a
href={docLink('/use-dify/nodes/user-input#hide-and-pre-fill-input-fields')}
target="_blank"
rel="noopener noreferrer"
className="text-text-accent hover:underline"
/>
),
docLink: <HiddenOfficialPhrase />,
}}
/>
</InfotipContent>
@@ -131,14 +131,6 @@ const InternalRetrievalSection: FC<InternalRetrievalSectionProps> = ({
{t(($) => $['form.retrievalSetting.title'], { ns: 'datasetSettings' })}
</div>
<div className="text-xs leading-4.5 font-normal text-text-tertiary">
<a
target="_blank"
rel="noopener noreferrer"
href={docLink('/use-dify/knowledge/create-knowledge/setting-indexing-methods')}
className="text-text-accent"
>
{t(($) => $['form.retrievalSetting.learnMore'], { ns: 'datasetSettings' })}
</a>
{t(($) => $['form.retrievalSetting.description'], { ns: 'datasetSettings' })}
</div>
</div>
@@ -32,7 +32,6 @@ import {
IconPickerTrigger,
} from '@/app/components/base/icon-picker'
import { ApiBasedExtensionSelector } from '@/app/components/header/account-setting/api-based-extension-page/selector'
import { useDocLink } from '@/context/i18n'
import { codeBasedExtensionsQueryOptions } from '@/features/code-based-extension/query'
import {
buildProviders,
@@ -54,8 +53,7 @@ const ExternalDataToolModal: FC<ExternalDataToolModalProps> = ({
onValidateBeforeSave,
}) => {
const { t } = useTranslation(['appDebug', 'common', 'app'])
const docLink = useDocLink()
const locale = useLocale()
const locale = useLocale()
const [localeData, setLocaleData] = useState(data.type ? data : { ...data, type: 'api' })
const { data: codeBasedExtensionList } = useQuery(
codeBasedExtensionsQueryOptions('external_data_tool'),
@@ -218,18 +216,6 @@ const ExternalDataToolModal: FC<ExternalDataToolModalProps> = ({
<div className="py-2">
<div className="flex h-9 items-center justify-between text-sm font-medium text-text-primary">
{t(($) => $['apiBasedExtension.selector.title'], { ns: 'common' })}
<a
href={docLink('/use-dify/workspace/api-extension/api-extension')}
target="_blank"
rel="noopener noreferrer"
className="group flex items-center text-xs font-normal text-text-tertiary hover:text-text-accent"
>
<span
aria-hidden
className="mr-1 i-custom-vender-line-education-book-open-01 size-3 text-text-tertiary group-hover:text-text-accent"
/>
{t(($) => $['apiBasedExtension.link'], { ns: 'common' })}
</a>
</div>
<ApiBasedExtensionSelector
value={localeData.config?.api_based_extension_id || ''}
@@ -3,11 +3,8 @@
import { useSuspenseQuery } from '@tanstack/react-query'
import { useAtomValue } from 'jotai'
import { useTranslation } from 'react-i18next'
import { useLocale } from '#i18n'
import { getEnterpriseDocUrl } from '@/context/i18n'
import { workspacePermissionKeysAtom } from '@/context/permission-state'
import { userProfileQueryOptions } from '@/features/account-profile/client'
import { getDocLanguage } from '@/i18n/language'
import { useParams } from '@/next/navigation'
import { consoleQuery } from '@/service/console'
import { getAppACLCapabilities } from '@/utils/permission'
@@ -26,9 +23,6 @@ function AppDeployContent({
}) {
const { t } = useTranslation(['deployments'])
const { t: tCommon } = useTranslation(['common'])
const locale = useLocale()
const docLanguage = getDocLanguage(locale)
const deployOverviewDocUrl = getEnterpriseDocUrl('/use/deploy/overview', docLanguage)
useRefreshAppEnvironmentsAfterDeploymentPolling(appId)
const undeployWorkflow = useUndeployWorkflow(appId)
@@ -42,14 +36,6 @@ function AppDeployContent({
</div>
<p className="flex flex-wrap items-center gap-x-1 system-xs-regular text-text-tertiary">
<span>{t(($) => $['studio.description'])}</span>
<a
href={deployOverviewDocUrl}
target="_blank"
rel="noreferrer"
className="inline-flex items-center text-text-accent hover:underline focus-visible:ring-1 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"
>
{tCommon(($) => $['operation.learnMore'])}
</a>
</p>
</header>
@@ -5,6 +5,7 @@ import { cn } from '@langgenius/dify-ui/cn'
import { useEffect, useMemo, useState } from 'react'
import { trackEvent } from '@/app/components/base/amplitude'
import { MarkdownWithDirective } from '@/app/components/base/markdown-with-directive'
import { isOfficialDifyUrl } from '@/utils/official-link'
type InSiteMessageAction = 'link' | 'close'
type InSiteMessageButtonType = 'primary' | 'default' | 'outline'
@@ -123,7 +124,7 @@ function InSiteMessage({
)
const linkData = item.action === 'link' ? normalizeLinkData(item.data) : null
if (linkData) {
if (linkData && !isOfficialDifyUrl(linkData.href)) {
const target = linkData.target ?? '_blank'
return (
<a
@@ -1,4 +1,5 @@
import type { ReactNode } from 'react'
import { isOfficialDifyUrl } from '@/utils/official-link'
type PageTitleProps = {
title: ReactNode
@@ -8,7 +9,11 @@ type PageTitleProps = {
}
const PageTitle = ({ title, description, learnMoreHref, learnMoreLabel }: PageTitleProps) => {
const showLearnMore = !!learnMoreHref && learnMoreLabel !== undefined && learnMoreLabel !== null
const showLearnMore =
!!learnMoreHref &&
!isOfficialDifyUrl(learnMoreHref) &&
learnMoreLabel !== undefined &&
learnMoreLabel !== null
return (
<div className="flex shrink-0 flex-col gap-0.5">
@@ -16,6 +16,7 @@ import {
} from '@langgenius/dify-ui/dialog'
import { useTranslation } from 'react-i18next'
import { useDocLink } from '@/context/i18n'
import { isOfficialDifyUrl } from '@/utils/official-link'
type CustomizeDialogProps = {
disabled?: boolean
@@ -164,6 +165,7 @@ export function CustomizeDialog({
<p className="my-2 system-sm-medium text-text-secondary">
{t(($) => $[`${prefixCustomize}.way2.name`], { ns: 'appOverview' })}
</p>
{apiDocLink && !isOfficialDifyUrl(apiDocLink) ? (
<a
href={apiDocLink}
target="_blank"
@@ -178,6 +180,7 @@ export function CustomizeDialog({
className="i-heroicons-arrow-top-right-on-square size-4 shrink-0 text-text-secondary"
/>
</a>
) : null}
</div>
</DialogBody>
</DialogContent>
@@ -58,9 +58,12 @@ import {
} from '@/app/components/billing/pricing/query-params'
import { deploymentEditionAtom } from '@/features/system-features/state'
import { languages } from '@/i18n/language'
import Link from '@/next/link'
import { consoleQuery } from '@/service/console'
function HiddenOfficialLink() {
return null
}
type SettingsDialogProps = {
isChat: boolean
canDeploy?: boolean
@@ -566,14 +569,7 @@ function SettingsForm({
i18nKey={($) => $[`${prefixSettings}.more.privacyPolicyTip`]}
ns="appOverview"
components={{
privacyPolicyLink: (
<Link
href="#"
target="_blank"
rel="noopener noreferrer"
className="text-text-accent underline"
/>
),
privacyPolicyLink: <HiddenOfficialLink />,
}}
/>
</FieldDescription>
@@ -28,7 +28,6 @@ import {
settingsQueryParser,
} from '@/app/components/header/account-setting/query-params'
import { toast } from '@/app/notifications'
import { useDocLink } from '@/context/i18n'
import { codeBasedExtensionsQueryOptions } from '@/features/code-based-extension/query'
import { LanguagesSupported } from '@/i18n/language'
import FormGeneration from './form-generation'
@@ -69,8 +68,7 @@ type ModerationSettingModalProps = {
const ModerationSettingModal: FC<ModerationSettingModalProps> = ({ data, onCancel, onSave }) => {
const { t } = useTranslation(['appDebug', 'common', 'navigation'])
const docLink = useDocLink()
const locale = useLocale()
const locale = useLocale()
const { data: modelProviders, isPending: isLoading } = useQuery(
modelProviderDetailsQueryOptions(),
)
@@ -429,19 +427,10 @@ const ModerationSettingModal: FC<ModerationSettingModalProps> = ({ data, onCance
)}
{localeData.type === 'api' && (
<div className="flex flex-col gap-1">
<div className="flex h-6 items-center justify-between">
<div className="flex h-6 items-center justify-between">
<div className="system-sm-medium text-text-secondary">
{t(($) => $['apiBasedExtension.selector.title'], { ns: 'common' })}
</div>
<a
href={docLink('/use-dify/workspace/api-extension/api-extension')}
target="_blank"
rel="noopener noreferrer"
className="group flex items-center system-xs-regular text-text-tertiary hover:text-primary-600"
>
<span className="mr-1 i-custom-vender-line-education-book-open-01 size-3 text-text-tertiary group-hover:text-primary-600" />
{t(($) => $['apiBasedExtension.link'], { ns: 'common' })}
</a>
</div>
<ApiBasedExtensionSelector
value={localeData.config?.api_based_extension_id || ''}
@@ -1,4 +1,5 @@
import type { AnyFieldApi } from '@tanstack/react-form'
import { isOfficialDifyUrl } from '@/utils/official-link'
import type { FieldState, FormSchema, TypeWithI18N } from '@/app/components/base/form/types'
import { cn } from '@langgenius/dify-ui/cn'
import { Field, FieldItem, FieldLabel } from '@langgenius/dify-ui/field'
@@ -541,7 +542,7 @@ const BaseField = ({
{translatedDescription}
</div>
)}
{url && (
{url && !isOfficialDifyUrl(url) && (
<a
className="mt-4 flex items-center system-xs-regular text-text-accent"
href={url}
@@ -5,6 +5,7 @@
*/
import * as React from 'react'
import { useChatContext } from '@/app/components/base/chat/chat/context'
import { isOfficialDifyUrl } from '@/utils/official-link'
import { isValidUrl } from './utils'
const filePreviewPathPattern = /\/files\/[^/?#]+\/file-preview(?:[?#]|$)/
@@ -57,6 +58,8 @@ const Link = ({ node, children, ...props }: any) => {
)
}
if (href && isOfficialDifyUrl(href)) return null
if (!href || !isValidUrl(href)) return <span>{children}</span>
return (
@@ -34,6 +34,11 @@ const AppsFull: FC<{ loc: string; className?: string }> = ({ loc, className }) =
const percent = total > 0 ? (usage / total) * 100 : 0
const tone: MeterTone = percent >= 80 ? 'error' : percent >= 50 ? 'warning' : 'neutral'
const buildAppsLabel = t(($) => $['usagePage.buildApps'], { ns: 'billing' })
const supportHref = mailToSupport(
accountProfile.email,
billing.plan,
accountProfile.currentVersion ?? '',
)
return (
<div
className={cn(
@@ -65,15 +70,11 @@ const AppsFull: FC<{ loc: string; className?: string }> = ({ loc, className }) =
{(billing.plan === 'sandbox' || billing.plan === 'professional') && (
<UpgradeBtn isShort loc={loc} />
)}
{billing.plan !== 'sandbox' && billing.plan !== 'professional' && (
{billing.plan !== 'sandbox' && billing.plan !== 'professional' && supportHref && (
<a
target="_blank"
rel="noopener noreferrer"
href={mailToSupport(
accountProfile.email,
billing.plan,
accountProfile.currentVersion ?? '',
)}
href={supportHref}
className={buttonVariants({ variant: 'secondary-accent' })}
>
{t(($) => $['apps.contactUs'], { ns: 'billing' })}
@@ -56,13 +56,10 @@ describe('MultimodalRetrievalGuidance', () => {
screen.getByText('datasetSettings.form.multimodalRetrievalGuidance.pipelineDescription'),
).toBeInTheDocument()
expect(
screen.getByRole('link', {
screen.queryByRole('link', {
name: 'datasetSettings.form.multimodalRetrievalGuidance.helpLink',
}),
).toHaveAttribute(
'href',
'https://dify.ai/blog/multimodal-retrieval-is-now-available-in-the-knowledge-base',
)
).not.toBeInTheDocument()
expect(
screen.getByText('datasetSettings.form.multimodalRetrievalGuidance.helpDescription'),
).toBeInTheDocument()
@@ -103,9 +100,7 @@ describe('MultimodalRetrievalGuidance', () => {
expect(localStorage.getItem(MULTIMODAL_RETRIEVAL_GUIDANCE_DISMISSED_STORAGE_KEY)).toBe('true')
expect(
screen.getByRole('link', {
name: 'datasetSettings.form.multimodalRetrievalGuidance.helpLink',
}),
screen.getByText('datasetSettings.form.multimodalRetrievalGuidance.helpDescription'),
).toBeInTheDocument()
expect(
screen.queryByText('datasetSettings.form.multimodalRetrievalGuidance.createTitle'),
@@ -19,9 +19,6 @@ type MultimodalRetrievalGuidanceProps = {
className?: string
}
const MULTIMODAL_RETRIEVAL_DOC_URL =
'https://dify.ai/blog/multimodal-retrieval-is-now-available-in-the-knowledge-base'
const isVisionEmbeddingModel = (
embeddingModel?: DefaultModel,
embeddingModelList?: ProviderWithModelsResponse[],
@@ -74,17 +71,6 @@ export const MultimodalRetrievalGuidanceLearnMore = ({ className }: { className?
return (
<div className={cn('flex items-center body-xs-regular text-text-tertiary', className)}>
<a
target="_blank"
rel="noopener noreferrer"
href={MULTIMODAL_RETRIEVAL_DOC_URL}
className="text-text-accent"
>
{t(($) => $['form.multimodalRetrievalGuidance.helpLink'], {
ns: 'datasetSettings',
})}
</a>
&nbsp;
{t(($) => $['form.multimodalRetrievalGuidance.helpDescription'], {
ns: 'datasetSettings',
})}
@@ -1,20 +1,9 @@
import type { PipelineTemplateListResponse } from '@dify/contracts/api/console/rag/types.gen'
import { act, screen, waitFor } from '@testing-library/react'
import { ChunkingMode } from '@/models/datasets'
import { screen } from '@testing-library/react'
import { renderWithConsoleQuery as render } from '@/test/console/query-data'
import { createDeferred } from '@/test/deferred'
import BuiltInPipelineList from '../built-in-pipeline-list'
const { getTemplates } = vi.hoisted(() => ({ getTemplates: vi.fn() }))
let locale = 'en-US'
vi.mock('#i18n', async (importOriginal) => ({
...(await importOriginal<typeof import('#i18n')>()),
useLocale: () => locale,
}))
vi.mock('@/next/navigation', () => ({ useRouter: () => ({ push: vi.fn() }) }))
vi.mock('@/app/components/workflow/plugin-dependency/hooks', () => ({
usePluginDependencies: () => ({ handleCheckPluginDependencies: vi.fn() }),
}))
vi.mock('@/service/console', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/service/console')>()
const { withConsoleResponses } = await import('@/test/console/service-responses')
@@ -26,50 +15,12 @@ vi.mock('@/service/console', async (importOriginal) => {
}
})
beforeEach(() => {
locale = 'en-US'
getTemplates.mockResolvedValue({ pipeline_templates: [] })
})
it('shows built-in templates after loading without custom-template management actions', async () => {
const pending = createDeferred<PipelineTemplateListResponse>()
getTemplates.mockReturnValue(pending.promise)
it('offers a blank pipeline and does not list built-in templates', () => {
render(<BuiltInPipelineList />, { systemFeatures: { enable_marketplace: true } })
expect(screen.queryByText('Legal documents')).not.toBeInTheDocument()
await act(async () =>
pending.resolve({
pipeline_templates: [
{
id: 'template-1',
name: 'Legal documents',
description: 'Process legal documents',
chunk_structure: ChunkingMode.text,
position: 1,
icon: { icon_type: 'emoji', icon: '📚', icon_background: '#FFF4ED' },
},
],
}),
)
expect(await screen.findByText('Legal documents')).toBeInTheDocument()
expect(
screen.getByRole('button', { name: 'datasetPipeline.operations.choose' }),
screen.getByText('datasetPipeline.creation.createFromScratch.title'),
).toBeInTheDocument()
expect(screen.queryByRole('button', { name: 'common.operation.more' })).not.toBeInTheDocument()
})
it.each([
['zh-Hans', 'zh-Hans'],
['ja-JP', 'ja-JP'],
['fr-FR', 'en-US'],
])('requests %s templates using %s', async (requested, language) => {
locale = requested
render(<BuiltInPipelineList />, { systemFeatures: { enable_marketplace: true } })
await waitFor(() =>
expect(getTemplates).toHaveBeenCalledWith({ query: { type: 'built-in', language } }),
)
})
it('does not request marketplace templates when the marketplace is disabled', () => {
render(<BuiltInPipelineList />, { systemFeatures: { enable_marketplace: false } })
expect(screen.queryByText('Legal documents')).not.toBeInTheDocument()
expect(getTemplates).not.toHaveBeenCalled()
})
@@ -1,41 +1,9 @@
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 { useMarketplace } from '@/features/marketplace/client'
import { LanguagesSupported } from '@/i18n/language'
import { consoleQuery } from '@/service/console'
import CreateCard from './create-card'
import TemplateCard from './template-card'
const BuiltInPipelineList = () => {
const locale = useLocale()
const language = useMemo(() => {
if (['zh-Hans', 'ja-JP'].includes(locale)) return locale
return LanguagesSupported[0]
}, [locale])
const enableMarketplace = useMarketplace() !== null
const { data: pipelineList, isLoading } = useQuery(
consoleQuery.rag.pipeline.templates.get.queryOptions({
input: { query: { type: 'built-in', language } },
enabled: enableMarketplace,
select: selectPipelineTemplateList,
}),
)
const list = pipelineList?.pipeline_templates || []
return (
<div className="grid grid-cols-[repeat(auto-fill,minmax(296px,1fr))] gap-3 py-2">
<CreateCard />
{!isLoading &&
list.map((pipeline, index) => (
<TemplateCard
key={index}
type="built-in"
pipeline={pipeline}
showMoreOperations={false}
/>
))}
</div>
)
}
@@ -1,11 +1,9 @@
import BuiltInPipelineList from './built-in-pipeline-list'
import CustomizedList from './customized-list'
const List = () => {
return (
<div className="grow gap-y-1 overflow-y-auto px-16 pt-1 pb-15">
<BuiltInPipelineList />
<CustomizedList />
</div>
)
}
@@ -12,6 +12,7 @@ import { useTranslation } from 'react-i18next'
import VectorSpaceAdmissionAlert from '@/app/components/datasets/common/vector-space-admission-alert'
import { deploymentEditionAtom } from '@/features/system-features/state'
import { useDatasetApiAccessUrl } from '@/hooks/use-api-access-url'
import { isOfficialDifyUrl } from '@/utils/official-link'
import Link from '@/next/link'
import { consoleQuery } from '@/service/console'
import IndexingProgressItem from './indexing-progress-item'
@@ -62,15 +63,17 @@ const ActionButtons: FC<{
return (
<div className="mt-6 flex flex-wrap items-center gap-2 py-2">
<Link
href={apiReferenceUrl}
target="_blank"
rel="noopener noreferrer"
className={cn(buttonVariants(), 'w-fit')}
>
<RiTerminalBoxLine className="size-4" />
<span>Access the API</span>
</Link>
{apiReferenceUrl && !isOfficialDifyUrl(apiReferenceUrl) ? (
<Link
href={apiReferenceUrl}
target="_blank"
rel="noopener noreferrer"
className={cn(buttonVariants(), 'w-fit')}
>
<RiTerminalBoxLine className="size-4" />
<span>Access the API</span>
</Link>
) : null}
<Link
href={documentsHref}
className={cn(buttonVariants({ variant: 'primary' }), 'w-fit')}
@@ -29,14 +29,11 @@ describe('StepThree', () => {
expect(screen.queryByText('datasetCreation.stepThree.creationTitle')).not.toBeInTheDocument()
})
it('links to the document-processing documentation', () => {
it('does not link the document-processing note to the official documentation site', () => {
render(<StepThree />)
expect(
screen.getByRole('link', { name: 'datasetPipeline.addDocuments.stepThree.learnMore' }),
).toHaveAttribute(
'href',
'https://docs.dify.ai/use-dify/knowledge/integrate-knowledge-within-application',
)
screen.queryByRole('link', { name: 'datasetPipeline.addDocuments.stepThree.learnMore' }),
).not.toBeInTheDocument()
})
})
@@ -6,7 +6,6 @@ import { RiBookOpenLine } from '@remixicon/react'
import * as React from 'react'
import { useTranslation } from 'react-i18next'
import AppIcon from '@/app/components/base/app-icon'
import { useDocLink } from '@/context/i18n'
import EmbeddingProcess from '../embedding-process'
type StepThreeProps = {
@@ -25,9 +24,7 @@ const StepThree = ({
retrievalMethod,
}: StepThreeProps) => {
const { t } = useTranslation(['datasetCreation', 'datasetPipeline'])
const docLink = useDocLink()
// The creation response carries no icon; new knowledge bases start with the default one.
// The creation response carries no icon; new knowledge bases start with the default one.
const iconInfo = {
icon: '📙',
icon_type: 'emoji',
@@ -91,14 +88,6 @@ const StepThree = ({
<div className="text-text-tertiary">
{t(($) => $['stepThree.sideTipContent'], { ns: 'datasetCreation' })}
</div>
<a
href={docLink('/use-dify/knowledge/integrate-knowledge-within-application')}
target="_blank"
rel="noreferrer noopener"
className="system-sm-regular text-text-accent"
>
{t(($) => $['addDocuments.stepThree.learnMore'], { ns: 'datasetPipeline' })}
</a>
</div>
</div>
</div>
@@ -26,7 +26,6 @@ import {
} from '@/app/components/datasets/common/multimodal-retrieval-guidance'
import RetrievalMethodConfig from '@/app/components/datasets/common/retrieval-method-config'
import { ModelSelector } from '@/app/components/header/account-setting/model-provider-page/model-selector'
import { useDocLink } from '@/context/i18n'
import { ChunkingMode } from '@/models/datasets'
import Link from '@/next/link'
import { indexMethodIcon } from '../../icons'
@@ -74,9 +73,7 @@ export const IndexingModeSection: FC<IndexingModeSectionProps> = ({
onQAConfirmDialogConfirm,
}) => {
const { t } = useTranslation(['datasetCreation', 'datasetSettings'])
const docLink = useDocLink()
const getIndexingTechnique = () => indexType
const getIndexingTechnique = () => indexType
const economicalDisabledReason = (() => {
if (docForm === ChunkingMode.qa)
return t(($) => $['stepTwo.notAvailableForQA'], { ns: 'datasetCreation' })
@@ -234,14 +231,6 @@ export const IndexingModeSection: FC<IndexingModeSectionProps> = ({
{t(($) => $['form.retrievalSetting.title'], { ns: 'datasetSettings' })}
</h2>
<div className="body-xs-regular text-text-tertiary">
<a
target="_blank"
rel="noopener noreferrer"
href={docLink('/use-dify/knowledge/create-knowledge/setting-indexing-methods')}
className="text-text-accent"
>
{t(($) => $['form.retrievalSetting.learnMore'], { ns: 'datasetSettings' })}
</a>
{t(($) => $['form.retrievalSetting.longDescription'], { ns: 'datasetSettings' })}
</div>
</div>
@@ -3,6 +3,7 @@ import { cn } from '@langgenius/dify-ui/cn'
import { Separator } from '@langgenius/dify-ui/separator'
import { RiBookOpenLine, RiEqualizer2Line } from '@remixicon/react'
import * as React from 'react'
import { isOfficialDifyUrl } from '@/utils/official-link'
type HeaderProps = {
isInPipeline?: boolean
@@ -43,17 +44,19 @@ const Header = ({
{!isInPipeline && <span className="system-xs-medium">{buttonText}</span>}
</Button>
</div>
<a
className="flex items-center gap-x-1 overflow-hidden system-xs-medium text-text-accent"
href={docLink}
target="_blank"
rel="noopener noreferrer"
>
<RiBookOpenLine className="size-3.5 shrink-0" />
<span className="grow truncate" title={docTitle}>
{docTitle}
</span>
</a>
{docLink && !isOfficialDifyUrl(docLink) && (
<a
className="flex items-center gap-x-1 overflow-hidden system-xs-medium text-text-accent"
href={docLink}
target="_blank"
rel="noopener noreferrer"
>
<RiBookOpenLine className="size-3.5 shrink-0" />
<span className="grow truncate" title={docTitle}>
{docTitle}
</span>
</a>
)}
</div>
)
}
@@ -4,7 +4,6 @@ import { Button } from '@langgenius/dify-ui/button'
import * as React from 'react'
import { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useDocLink } from '@/context/i18n'
import Input from './text-input'
const I18N_PREFIX = 'stepOne.website'
@@ -16,7 +15,6 @@ type Props = Readonly<{
const UrlInput: FC<Props> = ({ isRunning, onRun }) => {
const { t } = useTranslation(['datasetCreation'])
const docLink = useDocLink()
const [url, setUrl] = useState('')
const handleUrlChange = useCallback((url: string | number) => {
setUrl(url as string)
@@ -28,7 +26,7 @@ const UrlInput: FC<Props> = ({ isRunning, onRun }) => {
return (
<div className="flex items-center justify-between gap-x-2">
<Input value={url} onChange={handleUrlChange} placeholder={docLink()} />
<Input value={url} onChange={handleUrlChange} placeholder="https://example.com" />
<Button variant="primary" onClick={handleOnRun} loading={isRunning}>
{t(($) => $[`${I18N_PREFIX}.run`], { ns: 'datasetCreation' })}
</Button>
@@ -30,7 +30,7 @@ vi.mock('@/utils', () => ({
// Mock i18n context
vi.mock('@/context/i18n', () => ({
useDocLink: () => (path?: string) =>
path ? `https://docs.dify.ai/en${path}` : 'https://docs.dify.ai/en/',
path ? `https://docs.dify.ai/en${path}` : 'https://example.com',
}))
// Note: limit and max_depth are typed as `number | string` in CrawlOptions
@@ -138,7 +138,7 @@ describe('WaterCrawl', () => {
const props = createDefaultProps()
render(<WaterCrawl {...props} />)
const urlInput = screen.getByPlaceholderText('https://docs.dify.ai/en/')
const urlInput = screen.getByPlaceholderText('https://example.com')
await user.type(urlInput, 'https://example.com')
const runButton = screen.getByRole('button', { name: /run/i })
@@ -173,7 +173,7 @@ describe('WaterCrawl', () => {
// Options should be visible initially
expect(screen.getByText('datasetCreation.stepOne.website.crawlSubPage'))!.toBeInTheDocument()
const input = screen.getByPlaceholderText('https://docs.dify.ai/en/')
const input = screen.getByPlaceholderText('https://example.com')
await user.type(input, 'https://example.com')
await user.click(screen.getByRole('button', { name: /run/i }))
@@ -273,7 +273,7 @@ describe('WaterCrawl', () => {
const props = createDefaultProps({ crawlOptions })
render(<WaterCrawl {...props} />)
const input = screen.getByPlaceholderText('https://docs.dify.ai/en/')
const input = screen.getByPlaceholderText('https://example.com')
await user.type(input, 'https://api-test.com')
await user.click(screen.getByRole('button', { name: /run/i }))
@@ -302,7 +302,7 @@ describe('WaterCrawl', () => {
const props = createDefaultProps({ crawlOptions })
render(<WaterCrawl {...props} />)
const input = screen.getByPlaceholderText('https://docs.dify.ai/en/')
const input = screen.getByPlaceholderText('https://example.com')
await user.type(input, 'https://test.com')
await user.click(screen.getByRole('button', { name: /run/i }))
@@ -327,7 +327,7 @@ describe('WaterCrawl', () => {
const props = createDefaultProps()
render(<WaterCrawl {...props} />)
const input = screen.getByPlaceholderText('https://docs.dify.ai/en/')
const input = screen.getByPlaceholderText('https://example.com')
await user.type(input, 'https://fail-test.com')
await user.click(screen.getByRole('button', { name: /run/i }))
@@ -353,7 +353,7 @@ describe('WaterCrawl', () => {
const props = createDefaultProps()
render(<WaterCrawl {...props} />)
const input = screen.getByPlaceholderText('https://docs.dify.ai/en/')
const input = screen.getByPlaceholderText('https://example.com')
await user.type(input, 'https://error-test.com')
await user.click(screen.getByRole('button', { name: /run/i }))
@@ -386,7 +386,7 @@ describe('WaterCrawl', () => {
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime })
render(<WaterCrawl {...props} />)
await user.type(
screen.getByPlaceholderText('https://docs.dify.ai/en/'),
screen.getByPlaceholderText('https://example.com'),
'https://example.com',
)
await user.click(screen.getByRole('button', { name: /run/i }))
@@ -411,7 +411,7 @@ describe('WaterCrawl', () => {
const props = createDefaultProps()
render(<WaterCrawl {...props} />)
const input = screen.getByPlaceholderText('https://docs.dify.ai/en/')
const input = screen.getByPlaceholderText('https://example.com')
await user.type(input, 'https://no-status-test.com')
await user.click(screen.getByRole('button', { name: /run/i }))
@@ -443,7 +443,7 @@ describe('WaterCrawl', () => {
const props = createDefaultProps()
render(<WaterCrawl {...props} />)
const input = screen.getByPlaceholderText('https://docs.dify.ai/en/')
const input = screen.getByPlaceholderText('https://example.com')
await user.type(input, 'invalid-url')
await user.click(screen.getByRole('button', { name: /run/i }))
@@ -457,7 +457,7 @@ describe('WaterCrawl', () => {
const props = createDefaultProps()
render(<WaterCrawl {...props} />)
const input = screen.getByPlaceholderText('https://docs.dify.ai/en/')
const input = screen.getByPlaceholderText('https://example.com')
await user.type(input, 'example.com')
await user.click(screen.getByRole('button', { name: /run/i }))
@@ -482,7 +482,7 @@ describe('WaterCrawl', () => {
const props = createDefaultProps()
render(<WaterCrawl {...props} />)
const input = screen.getByPlaceholderText('https://docs.dify.ai/en/')
const input = screen.getByPlaceholderText('https://example.com')
await user.type(input, 'http://example.com')
await user.click(screen.getByRole('button', { name: /run/i }))
@@ -498,7 +498,7 @@ describe('WaterCrawl', () => {
})
render(<WaterCrawl {...props} />)
const input = screen.getByPlaceholderText('https://docs.dify.ai/en/')
const input = screen.getByPlaceholderText('https://example.com')
await user.type(input, 'https://example.com')
await user.click(screen.getByRole('button', { name: /run/i }))
@@ -517,7 +517,7 @@ describe('WaterCrawl', () => {
const props = createDefaultProps()
render(<WaterCrawl {...props} />)
const input = screen.getByPlaceholderText('https://docs.dify.ai/en/')
const input = screen.getByPlaceholderText('https://example.com')
await user.type(input, 'https://exception-test.com')
await user.click(screen.getByRole('button', { name: /run/i }))
@@ -544,7 +544,7 @@ describe('WaterCrawl', () => {
const props = createDefaultProps()
render(<WaterCrawl {...props} />)
const input = screen.getByPlaceholderText('https://docs.dify.ai/en/')
const input = screen.getByPlaceholderText('https://example.com')
await user.type(input, 'https://empty-error-test.com')
await user.click(screen.getByRole('button', { name: /run/i }))
@@ -572,7 +572,7 @@ describe('WaterCrawl', () => {
const props = createDefaultProps({ onCheckedCrawlResultChange })
render(<WaterCrawl {...props} />)
const input = screen.getByPlaceholderText('https://docs.dify.ai/en/')
const input = screen.getByPlaceholderText('https://example.com')
await user.type(input, 'https://empty-data-test.com')
await user.click(screen.getByRole('button', { name: /run/i }))
@@ -605,7 +605,7 @@ describe('WaterCrawl', () => {
const props = createDefaultProps({ onCheckedCrawlResultChange })
render(<WaterCrawl {...props} />)
const input = screen.getByPlaceholderText('https://docs.dify.ai/en/')
const input = screen.getByPlaceholderText('https://example.com')
await user.type(input, 'https://null-data-test.com')
await user.click(screen.getByRole('button', { name: /run/i }))
@@ -631,7 +631,7 @@ describe('WaterCrawl', () => {
const props = createDefaultProps({ onCheckedCrawlResultChange })
render(<WaterCrawl {...props} />)
const input = screen.getByPlaceholderText('https://docs.dify.ai/en/')
const input = screen.getByPlaceholderText('https://example.com')
await user.type(input, 'https://undefined-data-test.com')
await user.click(screen.getByRole('button', { name: /run/i }))
@@ -658,7 +658,7 @@ describe('WaterCrawl', () => {
})
render(<WaterCrawl {...props} />)
const input = screen.getByPlaceholderText('https://docs.dify.ai/en/')
const input = screen.getByPlaceholderText('https://example.com')
await user.type(input, 'https://zero-current-test.com')
await user.click(screen.getByRole('button', { name: /run/i }))
@@ -686,7 +686,7 @@ describe('WaterCrawl', () => {
})
render(<WaterCrawl {...props} />)
const input = screen.getByPlaceholderText('https://docs.dify.ai/en/')
const input = screen.getByPlaceholderText('https://example.com')
await user.type(input, 'https://zero-total-test.com')
await user.click(screen.getByRole('button', { name: /run/i }))
@@ -721,7 +721,7 @@ describe('WaterCrawl', () => {
})
render(<WaterCrawl {...props} />)
const input = screen.getByPlaceholderText('https://docs.dify.ai/en/')
const input = screen.getByPlaceholderText('https://example.com')
await user.type(input, 'https://both-zero-test.com')
await user.click(screen.getByRole('button', { name: /run/i }))
@@ -750,7 +750,7 @@ describe('WaterCrawl', () => {
const props = createDefaultProps()
render(<WaterCrawl {...props} />)
const input = screen.getByPlaceholderText('https://docs.dify.ai/en/')
const input = screen.getByPlaceholderText('https://example.com')
await user.type(input, 'https://time.com')
await user.click(screen.getByRole('button', { name: /run/i }))
@@ -801,7 +801,7 @@ describe('WaterCrawl', () => {
})
render(<WaterCrawl {...props} />)
const input = screen.getByPlaceholderText('https://docs.dify.ai/en/')
const input = screen.getByPlaceholderText('https://example.com')
await user.type(input, 'https://full-workflow.com')
await user.click(screen.getByRole('button', { name: /run/i }))
@@ -863,7 +863,7 @@ describe('WaterCrawl', () => {
render(<WaterCrawl {...props} />)
// Step 1: Enter URL
const input = screen.getByPlaceholderText('https://docs.dify.ai/en/')
const input = screen.getByPlaceholderText('https://example.com')
await user.type(input, 'https://preview.com')
// Step 2: Run crawl
@@ -15,7 +15,6 @@ import AutoDisabledDocument from '@/app/components/datasets/common/document-stat
import IndexFailed from '@/app/components/datasets/common/document-status-with-action/index-failed'
import StatusWithAction from '@/app/components/datasets/common/document-status-with-action/status-with-action'
import DatasetMetadataDrawer from '@/app/components/datasets/metadata/metadata-dataset/dataset-metadata-drawer'
import { useDocLink } from '@/context/i18n'
import { DataSourceType } from '@/models/datasets'
import { useIndexStatus } from '../status-item/hooks'
@@ -87,8 +86,7 @@ const DocumentsHeader: FC<DocumentsHeaderProps> = ({
const { t } = useTranslation(['dataset', 'datasetDocuments'])
const statusFilterId = useId()
const statusFilterLabelId = useId()
const docLink = useDocLink()
const DOC_INDEX_STATUS_MAP = useIndexStatus()
const DOC_INDEX_STATUS_MAP = useIndexStatus()
const isDataSourceNotion = dataSourceType === DataSourceType.NOTION
const isDataSourceWeb = dataSourceType === DataSourceType.WEB
@@ -139,15 +137,6 @@ const DocumentsHeader: FC<DocumentsHeaderProps> = ({
</h1>
<div className="flex items-center space-x-0.5 text-sm font-normal text-text-tertiary">
<span>{t(($) => $['list.desc'], { ns: 'datasetDocuments' })}</span>
<a
className="flex items-center text-text-accent"
target="_blank"
rel="noopener noreferrer"
href={docLink('/use-dify/knowledge/integrate-knowledge-within-application')}
>
<span>{t(($) => $['list.learnMore'], { ns: 'datasetDocuments' })}</span>
<span className="i-ri-external-link-line size-3" />
</a>
</div>
</div>
@@ -4,6 +4,7 @@ import { Separator } from '@langgenius/dify-ui/separator'
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
import * as React from 'react'
import { useTranslation } from 'react-i18next'
import { isOfficialDifyUrl } from '@/utils/official-link'
import CredentialSelector from './credential-selector'
type HeaderProps = {
@@ -39,15 +40,17 @@ const Header = ({ docTitle, docLink, onClickConfiguration, pluginName, ...rest }
<TooltipContent>{configurationTip}</TooltipContent>
</Tooltip>
</div>
<a
className="flex shrink-0 items-center gap-x-1 system-xs-medium text-text-accent"
href={docLink}
target="_blank"
rel="noopener noreferrer"
>
<span aria-hidden className="i-ri-book-open-line size-3.5 shrink-0" />
<span title={docTitle}>{docTitle}</span>
</a>
{docLink && !isOfficialDifyUrl(docLink) && (
<a
className="flex shrink-0 items-center gap-x-1 system-xs-medium text-text-accent"
href={docLink}
target="_blank"
rel="noopener noreferrer"
>
<span aria-hidden className="i-ri-book-open-line size-3.5 shrink-0" />
<span title={docTitle}>{docTitle}</span>
</a>
)}
</div>
)
}
@@ -143,15 +143,12 @@ describe('EmbeddingProcess', () => {
})
describe('Rendering', () => {
it('should render API reference link with correct URL', () => {
it('does not link the API reference to the official documentation site', () => {
const props = createDefaultProps()
render(<EmbeddingProcess {...props} />)
const apiLink = screen.getByRole('link', { name: /access the api/i })
expect(apiLink).toHaveAttribute('href', 'https://docs.dify.ai/api-reference/datasets')
expect(apiLink).toHaveAttribute('target', '_blank')
expect(apiLink).toHaveAttribute('rel', 'noopener noreferrer')
expect(screen.queryByRole('link', { name: /access the api/i })).not.toBeInTheDocument()
})
})
@@ -27,6 +27,7 @@ import DocumentFileIcon from '@/app/components/datasets/common/document-file-ico
import VectorSpaceAdmissionAlert from '@/app/components/datasets/common/vector-space-admission-alert'
import { deploymentEditionAtom } from '@/features/system-features/state'
import { useDatasetApiAccessUrl } from '@/hooks/use-api-access-url'
import { isOfficialDifyUrl } from '@/utils/official-link'
import { DatasourceType } from '@/models/pipeline'
import Link from '@/next/link'
import { consoleQuery } from '@/service/console'
@@ -277,15 +278,17 @@ const EmbeddingProcess = ({
/>
</div>
<div className="mt-6 flex items-center gap-x-2 py-2">
<Link
href={apiReferenceUrl}
target="_blank"
rel="noopener noreferrer"
className={cn(buttonVariants(), 'w-fit')}
>
<RiTerminalBoxLine className="size-4" />
<span>Access the API</span>
</Link>
{apiReferenceUrl && !isOfficialDifyUrl(apiReferenceUrl) ? (
<Link
href={apiReferenceUrl}
target="_blank"
rel="noopener noreferrer"
className={cn(buttonVariants(), 'w-fit')}
>
<RiTerminalBoxLine className="size-4" />
<span>Access the API</span>
</Link>
) : null}
<Link
href={documentsHref}
className={cn(buttonVariants({ variant: 'primary' }), 'w-fit')}
@@ -4,7 +4,6 @@ import { RiBookOpenLine } from '@remixicon/react'
import * as React from 'react'
import { useTranslation } from 'react-i18next'
import { useDatasetDetailContextWithSelector } from '@/context/dataset-detail'
import { useDocLink } from '@/context/i18n'
import EmbeddingProcess from './embedding-process'
type ProcessingProps = {
@@ -14,8 +13,7 @@ type ProcessingProps = {
const Processing = ({ batchId, documents }: ProcessingProps) => {
const { t } = useTranslation(['datasetCreation', 'datasetPipeline'])
const docLink = useDocLink()
const datasetId = useDatasetDetailContextWithSelector((s) => s.dataset?.id)
const datasetId = useDatasetDetailContextWithSelector((s) => s.dataset?.id)
const indexingType = useDatasetDetailContextWithSelector(
(s) => s.dataset?.indexing_technique ?? undefined,
)
@@ -48,14 +46,6 @@ const Processing = ({ batchId, documents }: ProcessingProps) => {
<div className="system-sm-regular text-text-tertiary">
{t(($) => $['stepThree.sideTipContent'], { ns: 'datasetCreation' })}
</div>
<a
href={docLink('/use-dify/knowledge/knowledge-pipeline/authorize-data-source')}
target="_blank"
rel="noreferrer noopener"
className="system-sm-regular text-text-accent"
>
{t(($) => $['addDocuments.stepThree.learnMore'], { ns: 'datasetPipeline' })}
</a>
</div>
</div>
</div>
@@ -4,10 +4,8 @@ import { cn } from '@langgenius/dify-ui/cn'
import { Field, FieldError } from '@langgenius/dify-ui/field'
import { Form } from '@langgenius/dify-ui/form'
import { Input } from '@langgenius/dify-ui/input'
import { RiBookOpenLine } from '@remixicon/react'
import * as React from 'react'
import { useTranslation } from 'react-i18next'
import { useDocLink } from '@/context/i18n'
type ExternalAPIFormProps = {
id: string
@@ -36,7 +34,6 @@ const ExternalAPIForm: FC<ExternalAPIFormProps> = React.memo(
errors,
}) => {
const { t, i18n } = useTranslation(['common', 'dataset'])
const docLink = useDocLink()
const handleFormChange = (key: string, val: string) => {
if (key === 'name') {
@@ -69,17 +66,6 @@ const ExternalAPIForm: FC<ExternalAPIFormProps> = React.memo(
{label[i18n.language] || label.en_US}
{required && <span className="ml-1 text-red-500">*</span>}
</label>
{variable === 'endpoint' && (
<a
href={docLink('/use-dify/knowledge/external-knowledge-api') || '/'}
target="_blank"
rel="noopener noreferrer"
className="flex items-center body-xs-regular text-text-accent"
>
<RiBookOpenLine className="mr-1 size-3 text-text-accent" />
{t(($) => $.externalAPIPanelDocumentation, { ns: 'dataset' })}
</a>
)}
</div>
<Input
type={type === 'secret' ? 'password' : 'text'}
@@ -1,12 +1,11 @@
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { RiAddLine, RiBookOpenLine, RiCloseLine } from '@remixicon/react'
import { RiAddLine, RiCloseLine } from '@remixicon/react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import * as React from 'react'
import { useTranslation } from 'react-i18next'
import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
import { useDocLink } from '@/context/i18n'
import { useModalContext } from '@/context/modal-context'
import { consoleQuery } from '@/service/console'
import ExternalKnowledgeAPICard from '../external-knowledge-api-card'
@@ -21,8 +20,7 @@ const ExternalAPIPanel: React.FC<ExternalAPIPanelProps> = ({
onClose,
}) => {
const { t } = useTranslation(['common', 'dataset'])
const docLink = useDocLink()
const { setShowExternalKnowledgeAPIModal } = useModalContext()
const { setShowExternalKnowledgeAPIModal } = useModalContext()
const queryClient = useQueryClient()
const externalKnowledgeApiQueryOptions =
consoleQuery.datasets.externalKnowledgeApi.get.queryOptions({ input: {} })
@@ -59,16 +57,6 @@ const ExternalAPIPanel: React.FC<ExternalAPIPanelProps> = ({
<div className="self-stretch body-xs-regular text-text-tertiary">
{t(($) => $.externalAPIPanelDescription, { ns: 'dataset' })}
</div>
<a
className="flex cursor-pointer items-center justify-center gap-1 self-stretch"
href={docLink('/use-dify/knowledge/external-knowledge-api')}
target="_blank"
>
<RiBookOpenLine className="size-3 text-text-accent" />
<div className="grow body-xs-regular text-text-accent">
{t(($) => $.externalAPIPanelDocumentation, { ns: 'dataset' })}
</div>
</a>
</div>
<div className="flex items-center">
<IconButton
@@ -1,10 +1,8 @@
import { RiBookOpenLine } from '@remixicon/react'
import { useTranslation } from 'react-i18next'
import { useDocLink } from '@/context/i18n'
const InfoPanel = () => {
const { t } = useTranslation(['dataset'])
const docLink = useDocLink()
return (
<div className="flex w-90 flex-col items-start pt-27 pr-8 pb-2">
@@ -18,24 +16,8 @@ const InfoPanel = () => {
</span>
<span className="system-sm-regular text-text-tertiary">
{t(($) => $['connectDatasetIntro.content.front'], { ns: 'dataset' })}
<a
className="ml-1 system-sm-regular text-text-accent"
href={docLink('/use-dify/knowledge/external-knowledge-api')}
target="_blank"
rel="noopener noreferrer"
>
{t(($) => $['connectDatasetIntro.content.link'], { ns: 'dataset' })}
</a>
{t(($) => $['connectDatasetIntro.content.end'], { ns: 'dataset' })}
</span>
<a
className="self-stretch system-sm-regular text-text-accent"
href={docLink('/use-dify/knowledge/connect-external-knowledge-base')}
target="_blank"
rel="noopener noreferrer"
>
{t(($) => $['connectDatasetIntro.learnMore'], { ns: 'dataset' })}
</a>
</p>
</div>
</div>
@@ -6,7 +6,6 @@ import { IconButton } from '@langgenius/dify-ui/icon-button'
import { Separator } from '@langgenius/dify-ui/separator'
import { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useDocLink } from '@/context/i18n'
import Link from '@/next/link'
import { useRouter } from '@/next/navigation'
import ExternalApiSelection from './ExternalApiSelection'
@@ -24,7 +23,6 @@ const ExternalKnowledgeBaseCreate: React.FC<ExternalKnowledgeBaseCreateProps> =
loading,
}) => {
const { t } = useTranslation(['common', 'dataset'])
const docLink = useDocLink()
const router = useRouter()
const [formData, setFormData] = useState<CreateKnowledgeBaseReq>({
name: '',
@@ -69,14 +67,6 @@ const ExternalKnowledgeBaseCreate: React.FC<ExternalKnowledgeBaseCreateProps> =
{t(($) => $['connectHelper.helper2'], { ns: 'dataset' })}
</span>
<span>{t(($) => $['connectHelper.helper3'], { ns: 'dataset' })}</span>
<a
className="self-stretch system-sm-regular text-text-accent"
href={docLink('/use-dify/knowledge/connect-external-knowledge-base')}
target="_blank"
rel="noopener noreferrer"
>
{t(($) => $['connectHelper.helper4'], { ns: 'dataset' })}
</a>
<span>{t(($) => $['connectHelper.helper5'], { ns: 'dataset' })} </span>
</p>
<IconButton
@@ -72,8 +72,8 @@ describe('Dataset API access', () => {
await user.keyboard('{Enter}')
expect(await screen.findByText('dataset.serviceApi.enabled')).toBeInTheDocument()
expect(
screen.getByRole('link', { name: 'appOverview.overview.apiInfo.doc' }),
).toHaveAttribute('href', 'https://docs.dify.ai/api-reference/datasets')
screen.queryByRole('link', { name: 'appOverview.overview.apiInfo.doc' }),
).not.toBeInTheDocument()
},
)
@@ -10,6 +10,7 @@ import { useDatasetDetailContextWithSelector } from '@/context/dataset-detail'
import { workspacePermissionKeysAtom } from '@/context/permission-state'
import { userProfileQueryOptions } from '@/features/account-profile/client'
import { useDatasetApiAccessUrl } from '@/hooks/use-api-access-url'
import { isOfficialDifyUrl } from '@/utils/official-link'
import Link from '@/next/link'
import { consoleQuery } from '@/service/console'
import { getDatasetACLCapabilities } from '@/utils/permission'
@@ -85,20 +86,22 @@ const Card = ({ apiEnabled }: CardProps) => {
</div>
</div>
<div className="h-px bg-divider-subtle"></div>
<div className="p-1">
<Link
href={apiReferenceUrl}
target="_blank"
rel="noopener noreferrer"
className="flex h-8 items-center space-x-1.75 rounded-lg px-2 text-text-tertiary hover:bg-state-base-hover"
>
<span className="i-ri-book-open-line size-3.5 shrink-0" />
<div className="grow truncate system-sm-regular">
{t(($) => $['overview.apiInfo.doc'], { ns: 'appOverview' })}
</div>
<span className="i-ri-arrow-right-up-line size-3.5 shrink-0" />
</Link>
</div>
{apiReferenceUrl && !isOfficialDifyUrl(apiReferenceUrl) ? (
<div className="p-1">
<Link
href={apiReferenceUrl}
target="_blank"
rel="noopener noreferrer"
className="flex h-8 items-center space-x-1.75 rounded-lg px-2 text-text-tertiary hover:bg-state-base-hover"
>
<span className="i-ri-book-open-line size-3.5 shrink-0" />
<div className="grow truncate system-sm-regular">
{t(($) => $['overview.apiInfo.doc'], { ns: 'appOverview' })}
</div>
<span className="i-ri-arrow-right-up-line size-3.5 shrink-0" />
</Link>
</div>
) : null}
</div>
)
}
@@ -52,8 +52,8 @@ describe('ServiceApi', () => {
expect(screen.getByText('https://api.example.com')).toBeInTheDocument()
expect(
screen.getByRole('link', { name: 'dataset.serviceApi.card.apiReference' }),
).toHaveAttribute('href', 'https://docs.dify.ai/api-reference/datasets')
screen.queryByRole('link', { name: 'dataset.serviceApi.card.apiReference' }),
).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'dataset.serviceApi.card.apiKey' }))
const dialog = await screen.findByRole('dialog', { name: 'appApi.apiKeyModal.apiSecretKey' })
@@ -6,6 +6,7 @@ import { StatusDot } from '@langgenius/dify-ui/status-dot'
import { useTranslation } from 'react-i18next'
import { CopyFeedback } from '@/app/components/base/copy-feedback'
import { useDatasetApiAccessUrl } from '@/hooks/use-api-access-url'
import { isOfficialDifyUrl } from '@/utils/official-link'
import Link from '@/next/link'
type CardProps = {
@@ -74,17 +75,19 @@ export function ServiceApiCard({ apiBaseUrl, apiReferenceUrl, canManageApiKey }:
{t(($) => $['serviceApi.card.apiKey'], { ns: 'dataset' })}
</span>
</PopoverClose>
<Link
href={referenceUrl}
target="_blank"
rel="noopener noreferrer"
className={cn(buttonVariants({ variant: 'ghost', size: 'small' }), 'text-text-tertiary')}
>
<span aria-hidden className="i-ri-book-open-line size-3.5 shrink-0" />
<span className="system-xs-medium">
{t(($) => $['serviceApi.card.apiReference'], { ns: 'dataset' })}
</span>
</Link>
{referenceUrl && !isOfficialDifyUrl(referenceUrl) ? (
<Link
href={referenceUrl}
target="_blank"
rel="noopener noreferrer"
className={cn(buttonVariants({ variant: 'ghost', size: 'small' }), 'text-text-tertiary')}
>
<span aria-hidden className="i-ri-book-open-line size-3.5 shrink-0" />
<span className="system-xs-medium">
{t(($) => $['serviceApi.card.apiReference'], { ns: 'dataset' })}
</span>
</Link>
) : null}
</div>
</div>
)
@@ -14,7 +14,6 @@ import EconomicalRetrievalMethodConfig from '@/app/components/datasets/common/ec
import RetrievalMethodConfig from '@/app/components/datasets/common/retrieval-method-config'
import { toast } from '@/app/notifications'
import { useDatasetDetailContextWithSelector } from '@/context/dataset-detail'
import { useDocLink } from '@/context/i18n'
import { consoleQuery } from '@/service/console'
import { ModelTypeEnum } from '../../header/account-setting/model-provider-page/declarations'
import { checkShowMultiModalTip } from '../settings/utils'
@@ -29,8 +28,7 @@ type Props = Readonly<{
const ModifyRetrievalModal: FC<Props> = ({ indexMethod, value, isShow, onHide, onSave }) => {
const ref = useRef(null)
const { t } = useTranslation(['appDebug', 'common', 'datasetSettings'])
const docLink = useDocLink()
const [retrievalConfig, setRetrievalConfig] = useState(value)
const [retrievalConfig, setRetrievalConfig] = useState(value)
const embeddingModel = useDatasetDetailContextWithSelector(
(state) => state.dataset?.embedding_model,
)
@@ -109,14 +107,6 @@ const ModifyRetrievalModal: FC<Props> = ({ indexMethod, value, isShow, onHide, o
{t(($) => $['form.retrievalSetting.title'], { ns: 'datasetSettings' })}
</DrawerTitle>
<div className="text-xs leading-4.5 font-normal text-text-tertiary">
<a
target="_blank"
rel="noopener noreferrer"
href={docLink('/use-dify/knowledge/create-knowledge/setting-indexing-methods')}
className="text-text-accent"
>
{t(($) => $['form.retrievalSetting.learnMore'], { ns: 'datasetSettings' })}
</a>
{t(($) => $['form.retrievalSetting.description'], { ns: 'datasetSettings' })}
</div>
</div>
@@ -1,13 +1,10 @@
import { RiApps2AddLine, RiBookOpenLine } from '@remixicon/react'
import { RiApps2AddLine } from '@remixicon/react'
import * as React from 'react'
import { useTranslation } from 'react-i18next'
import { useDocLink } from '@/context/i18n'
const NoLinkedAppsPanel = () => {
const { t } = useTranslation(['common'])
const docLink = useDocLink()
return (
return (
<div className="w-60 rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur p-4">
<div className="inline-flex rounded-lg border-[0.5px] border-components-panel-border-subtle bg-background-default-subtle p-2">
<RiApps2AddLine className="size-4 text-text-tertiary" />
@@ -15,15 +12,6 @@ const NoLinkedAppsPanel = () => {
<div className="my-2 text-xs text-text-tertiary">
{t(($) => $['datasetMenus.emptyTip'], { ns: 'common' })}
</div>
<a
className="mt-2 inline-flex cursor-pointer items-center text-xs text-text-accent"
href={docLink('/use-dify/knowledge/integrate-knowledge-within-application')}
target="_blank"
rel="noopener noreferrer"
>
<RiBookOpenLine className="mr-1 size-4 text-text-accent" />
{t(($) => $['datasetMenus.viewDoc'], { ns: 'common' })}
</a>
</div>
)
}
@@ -16,7 +16,6 @@ import {
} from '@/app/components/datasets/common/multimodal-retrieval-guidance'
import RetrievalMethodConfig from '@/app/components/datasets/common/retrieval-method-config'
import { ModelSelector } from '@/app/components/header/account-setting/model-provider-page/model-selector'
import { useDocLink } from '@/context/i18n'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import { ChunkingMode } from '@/models/datasets'
import { IndexingType } from '../../../create/step-two'
@@ -73,8 +72,7 @@ const IndexingSection = ({
select: ({ deployment_edition }) => deployment_edition,
})
const isNonCloudEdition = deploymentEdition === 'COMMUNITY' || deploymentEdition === 'ENTERPRISE'
const docLink = useDocLink()
const chunkingMode = toChunkingMode(currentDataset?.doc_form)
const chunkingMode = toChunkingMode(currentDataset?.doc_form)
const isShowIndexMethod =
currentDataset &&
@@ -104,14 +102,6 @@ const IndexingSection = ({
{t(($) => $['form.chunkStructure.title'], { ns: 'datasetSettings' })}
</div>
<div className="body-xs-regular text-text-tertiary">
<a
target="_blank"
rel="noopener noreferrer"
href={docLink('/use-dify/knowledge/create-knowledge/chunking-and-cleaning-text')}
className="text-text-accent"
>
{t(($) => $['form.chunkStructure.learnMore'], { ns: 'datasetSettings' })}
</a>
{t(($) => $['form.chunkStructure.description'], { ns: 'datasetSettings' })}
</div>
</div>
@@ -205,14 +195,6 @@ const IndexingSection = ({
{t(($) => $['form.retrievalSetting.title'], { ns: 'datasetSettings' })}
</div>
<div className="body-xs-regular text-text-tertiary">
<a
target="_blank"
rel="noopener noreferrer"
href={docLink('/use-dify/knowledge/create-knowledge/setting-indexing-methods')}
className="text-text-accent"
>
{t(($) => $['form.retrievalSetting.learnMore'], { ns: 'datasetSettings' })}
</a>
{t(($) => $['form.retrievalSetting.description'], { ns: 'datasetSettings' })}
</div>
</div>
@@ -3,7 +3,6 @@ import { createInstance } from 'i18next'
import { renderToString } from 'react-dom/server'
import { accountCommand } from '../account'
import { slashCommandRegistry } from '../catalog'
import { discordCommand } from '../discord'
import { docsCommand } from '../docs'
import { goCommand } from '../go'
import { languageCommand } from '../language'
@@ -41,7 +40,7 @@ describe('command journeys', () => {
})
it('uses the current destination for direct and search-result activation', async () => {
for (const command of [accountCommand, modelsCommand, docsCommand, discordCommand]) {
for (const command of [accountCommand, modelsCommand, docsCommand]) {
const context = createCommandContext({
getDocsHomeUrl: () => 'https://enterprise.example/help/zh',
})
@@ -58,9 +57,7 @@ describe('command journeys', () => {
? '/account'
: command === modelsCommand
? SYSTEM_MODELS_PATH
: command === docsCommand
? 'https://enterprise.example/help/zh'
: 'https://discord.gg/5AEfbxcd9k'
: 'https://enterprise.example/help/zh'
expect(callback).toHaveBeenCalledTimes(2)
expect(callback).toHaveBeenLastCalledWith(destination)
}
@@ -1,7 +1,6 @@
import { ENABLE_FEATURE_PREVIEW } from '@/config'
import { accountCommand } from './account'
import { createCommand } from './create'
import { discordCommand } from './discord'
import { docsCommand } from './docs'
import { goCommand } from './go'
import { languageCommand } from './language'
@@ -14,7 +13,6 @@ export const slashCommandRegistry = new SlashCommandRegistry([
themeCommand,
languageCommand,
docsCommand,
discordCommand,
modelsCommand,
accountCommand,
goCommand,
@@ -1,32 +1,13 @@
import type { SlashCommand } from './types'
const DISCORD_URL = 'https://discord.gg/5AEfbxcd9k'
export const discordCommand: SlashCommand = {
name: 'discord',
description: 'Open Discord community',
description: 'Discord community',
mode: 'direct',
execute: (_args, context) => context.openExternal(DISCORD_URL),
execute: () => {},
search(args: string, context) {
return [
{
id: 'discord',
title: 'Discord',
description:
context.t(($) => $['gotoAnything.actions.discordDesc'], {
ns: 'app',
lng: context.locale,
}) || 'Open Discord community',
type: 'command' as const,
icon: (
<div className="flex h-6 w-6 items-center justify-center rounded-md border-[0.5px] border-divider-regular bg-components-panel-bg">
<span aria-hidden className="i-ri-discord-line size-4 text-text-tertiary" />
</div>
),
data: { command: 'discord', args: { url: DISCORD_URL } },
},
]
search() {
return []
},
}
@@ -1,4 +1,5 @@
import type { SlashCommand } from './types'
import { isOfficialDifyUrl } from '@/utils/official-link'
/**
* Documentation command - Opens help documentation
@@ -8,9 +9,16 @@ export const docsCommand: SlashCommand = {
description: 'Open documentation',
mode: 'direct',
execute: (_args, context) => context.openExternal(context.getDocsHomeUrl()),
execute: (_args, context) => {
const url = context.getDocsHomeUrl()
if (!url || isOfficialDifyUrl(url)) return
context.openExternal(url)
},
search(args: string, context) {
const url = context.getDocsHomeUrl()
if (!url || isOfficialDifyUrl(url)) return []
return [
{
id: 'doc',
@@ -15,9 +15,6 @@ import { Input } from '@langgenius/dify-ui/input'
import { Textarea } from '@langgenius/dify-ui/textarea'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useLocale } from '#i18n'
import { getEnterpriseDocUrl } from '@/context/i18n'
import { getDocLanguage } from '@/i18n/language'
import PermissionPicker from './permission-picker'
export type PermissionSetModalMode = 'create' | 'edit' | 'view'
@@ -47,8 +44,6 @@ const PermissionSetModalBody = ({
onSubmit,
}: PermissionSetModalBodyProps) => {
const { t } = useTranslation(['common', 'permission'])
const locale = useLocale()
const docLanguage = getDocLanguage(locale)
const [name, setName] = useState(initialValues?.name ?? '')
const [description, setDescription] = useState(initialValues?.description ?? '')
const [permissionKeys, setPermissionKeys] = useState<string[]>(
@@ -158,15 +153,6 @@ const PermissionSetModalBody = ({
{t(($) => $['api.actionFailed'], { ns: 'common' })}
</p>
)}
<a
href={getEnterpriseDocUrl('/use/workspace/permission-reference', docLanguage)}
target="_blank"
rel="noreferrer"
className="me-auto inline-flex items-center gap-1 system-xs-medium text-text-accent hover:underline"
>
<span>{t(($) => $['permissionSet.learnMore'], { ns: 'permission' })}</span>
<span aria-hidden className="i-ri-external-link-line h-3.5 w-3.5" />
</a>
<Button type="button" variant="secondary" onClick={onClose}>
{readonly
? t(($) => $['operation.close'], { ns: 'common' })
@@ -1,12 +1,9 @@
import { useTranslation } from 'react-i18next'
import { STEP_BY_STEP_TOUR_TARGETS } from '@/app/components/step-by-step-tour/target-registry'
import { useDocLink } from '@/context/i18n'
export function Empty() {
const { t } = useTranslation(['common'])
const docLink = useDocLink()
return (
return (
<div
className="mb-2 flex flex-col items-start gap-3 rounded-xl bg-background-section p-6"
data-step-by-step-tour-target={STEP_BY_STEP_TOUR_TARGETS.integrationCustomEndpointEmpty}
@@ -21,15 +18,6 @@ export function Empty() {
<div className="system-xs-regular text-text-primary">
{t(($) => $['apiBasedExtension.title'], { ns: 'common' })}
</div>
<a
className="flex items-center gap-1 system-xs-regular text-text-accent"
href={docLink('/use-dify/workspace/api-extension/api-extension')}
target="_blank"
rel="noopener noreferrer"
>
{t(($) => $['apiBasedExtension.link'], { ns: 'common' })}
<span aria-hidden className="i-ri-external-link-line size-3" />
</a>
</div>
</div>
)
@@ -12,12 +12,11 @@ import {
DialogHeaderCloseButton,
DialogTitle,
} from '@langgenius/dify-ui/dialog'
import { Field, FieldDescription, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
import { Field, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
import { Form } from '@langgenius/dify-ui/form'
import { Input } from '@langgenius/dify-ui/input'
import { useMutation } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { useDocLink } from '@/context/i18n'
import { consoleQuery } from '@/service/console'
type ApiBasedExtensionModalProps = {
@@ -37,8 +36,7 @@ type ApiBasedExtensionModalProps = {
export function ApiBasedExtensionModal(props: ApiBasedExtensionModalProps) {
const { open, mode, onOpenChange, onSaved } = props
const { t } = useTranslation(['common'])
const docLink = useDocLink()
const createApiBasedExtensionMutation = useMutation(
const createApiBasedExtensionMutation = useMutation(
consoleQuery.apiBasedExtension.post.mutationOptions(),
)
const updateApiBasedExtensionMutation = useMutation(
@@ -127,20 +125,6 @@ export function ApiBasedExtensionModal(props: ApiBasedExtensionModalProps) {
ns: 'common',
})}
/>
<FieldDescription>
<a
href={docLink('/use-dify/workspace/api-extension/api-extension')}
target="_blank"
rel="noopener noreferrer"
className="inline-flex w-fit items-center text-text-accent focus-visible:ring-1 focus-visible:ring-components-input-border-active focus-visible:outline-hidden"
>
<span
className="me-1 i-custom-vender-line-education-book-open-01 size-3"
aria-hidden="true"
/>
{t(($) => $['apiBasedExtension.link'], { ns: 'common' })}
</a>
</FieldDescription>
<FieldError match="valueMissing">
{t(($) => $['errorMsg.fieldRequired'], { ns: 'common', field: apiEndpointLabel })}
</FieldError>
@@ -149,9 +149,6 @@ function setup(
)
return { queryClient, user: userEvent.setup() }
}
const marketplaceToggle = () =>
screen.getByRole('button', { name: 'modelProvider.modelProvider.installDataSource' })
it.each([false, true])(
'shows the empty-state guidance with marketplace enabled=%s',
async (enableMarketplace) => {
@@ -162,18 +159,11 @@ it.each([false, true])(
)
expect(await screen.findByText('common.dataSourcePage.installFirst')).toBeInTheDocument()
expect(screen.getByRole('searchbox')).toBeInTheDocument()
if (enableMarketplace) {
expect(await screen.findByText('Recommended Source')).toBeInTheDocument()
const link = screen.getByRole('link', { name: 'plugin.marketplace.difyMarketplace' })
const url = new URL(link.getAttribute('href')!, window.location.href)
expect(url.pathname).toBe('/plugins/datasource')
expect(url.searchParams.get('theme')).toBe('light')
} else {
expect(
screen.queryByRole('button', { name: 'modelProvider.modelProvider.installDataSource' }),
).not.toBeInTheDocument()
expect(api.search).not.toHaveBeenCalled()
}
expect(
screen.queryByRole('button', { name: 'modelProvider.modelProvider.installDataSource' }),
).not.toBeInTheDocument()
expect(screen.queryByText('Recommended Source')).not.toBeInTheDocument()
expect(api.search).not.toHaveBeenCalled()
await user.click(screen.getByRole('button', { name: /plugin.autoUpdate.autoUpdate/ }))
expect(
await screen.findByRole('dialog', { name: 'plugin.autoUpdate.autoUpdateSettings' }),
@@ -212,105 +202,24 @@ it('filters installed sources, announces result counts, and restores them when s
expect(screen.queryByRole('status')).not.toBeInTheDocument()
})
it('combines recommendations without installed plugins or duplicates and sends datasource searches to the marketplace', async () => {
api.search.mockResolvedValue({
data: {
plugins: [
recommendation,
createMarketplacePluginFixture({
type: 'bundle',
plugin_id: 'bundle',
name: 'bundle',
label: { 'en-US': 'Plugin Bundle' },
}),
],
total: 2,
},
})
api.collection.mockResolvedValue({
data: {
plugins: [
createMarketplacePluginFixture({
plugin_id: 'plugin-1',
label: { 'en-US': 'Already Installed' },
}),
recommendation,
],
},
})
it('does not list uninstalled marketplace data sources', async () => {
const { user } = setup({ systemFeatures: { enable_marketplace: true } })
expect(await screen.findByText('Recommended Source')).toBeInTheDocument()
expect(screen.getAllByText('Recommended Source')).toHaveLength(1)
expect(screen.queryByText('Already Installed')).not.toBeInTheDocument()
expect(screen.queryByText('Plugin Bundle')).not.toBeInTheDocument()
await waitFor(() =>
expect(api.search).toHaveBeenCalledWith(
'/plugins/search/advanced',
expect.objectContaining({
body: expect.objectContaining({
query: '',
category: 'datasource',
exclude: ['plugin-1', 'plugin-2'],
page_size: 1000,
}),
}),
),
)
await user.type(screen.getByRole('searchbox'), 'partner')
await waitFor(() =>
expect(api.search).toHaveBeenLastCalledWith(
'/plugins/search/advanced',
expect.objectContaining({
body: expect.objectContaining({
query: 'partner',
category: 'datasource',
exclude: ['plugin-1', 'plugin-2'],
}),
}),
),
)
expect(await screen.findByRole('heading', { name: 'Dify Source' })).toBeInTheDocument()
expect(
screen
.getAllByRole('status')
.some(
(status) =>
status.textContent ===
'modelProvider.modelProvider.installDataSource: plugin.marketplace.pluginsResult:{"num":1}',
),
).toBe(true)
await user.click(marketplaceToggle())
expect(marketplaceToggle()).toHaveAttribute('aria-expanded', 'false')
screen.queryByRole('button', { name: 'modelProvider.modelProvider.installDataSource' }),
).not.toBeInTheDocument()
expect(screen.queryByText('Recommended Source')).not.toBeInTheDocument()
await user.click(marketplaceToggle())
expect(screen.getByText('Recommended Source')).toBeInTheDocument()
expect(api.search).not.toHaveBeenCalled()
await user.type(screen.getByRole('searchbox'), 'partner')
expect(api.search).not.toHaveBeenCalled()
})
it.each(['collection', 'search'] as const)(
'keeps recommendations loading until the %s request completes and hides loading when collapsed',
async (boundary) => {
const response = createDeferred<{
data: { plugins: (typeof recommendation)[]; total: number }
}>()
if (boundary === 'collection') api.collection.mockReturnValueOnce(response.promise)
else api.search.mockReturnValueOnce(response.promise)
const { user } = setup({ systemFeatures: { enable_marketplace: true } })
await screen.findByRole('heading', { name: 'Dify Source' })
expect(screen.getByRole('progressbar')).toBeInTheDocument()
await user.click(marketplaceToggle())
expect(screen.queryByRole('progressbar')).not.toBeInTheDocument()
await act(async () => response.resolve({ data: { plugins: [recommendation], total: 1 } }))
await user.click(marketplaceToggle())
expect(await screen.findByText('Recommended Source')).toBeInTheDocument()
},
)
it('opens the embedded marketplace through the supplied action', async () => {
const onOpenMarketplace = vi.fn()
const { user } = setup({ systemFeatures: { enable_marketplace: true } }, { onOpenMarketplace })
await user.click(
await screen.findByRole('button', { name: 'plugin.marketplace.difyMarketplace' }),
)
expect(onOpenMarketplace).toHaveBeenCalledOnce()
it('does not offer an official marketplace shortcut from data sources', async () => {
setup({ systemFeatures: { enable_marketplace: true } }, { onOpenMarketplace: vi.fn() })
await screen.findByRole('heading', { name: 'Dify Source' })
expect(
screen.queryByRole('button', { name: 'plugin.marketplace.difyMarketplace' }),
).not.toBeInTheDocument()
expect(
screen.queryByRole('link', { name: 'plugin.marketplace.difyMarketplace' }),
).not.toBeInTheDocument()
@@ -8,13 +8,11 @@ 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 { useMarketplace } from '@/features/marketplace/client'
import { useRenderI18nObject } from '@/hooks/use-i18n'
import { consoleQuery } from '@/service/console'
import { useInstalledPluginList, useInvalidateInstalledPluginList } from '@/service/use-plugins'
import { UpdateSettingDialog } from '../update-setting-dialog'
import Card from './card'
import InstallFromMarketplace from './install-from-marketplace'
type DataSourcePageProps = {
layout?: (parts: { body: ReactNode; toolbar: ReactNode }) => ReactNode
@@ -52,13 +50,12 @@ function DataSourceListSkeleton() {
)
}
const DataSourcePage = ({ layout, onOpenMarketplace, stickyToolbar }: DataSourcePageProps) => {
const DataSourcePage = ({ layout, stickyToolbar }: DataSourcePageProps) => {
const { t } = useTranslation(['common', 'plugin'])
const queryClient = useQueryClient()
const renderI18nObject = useRenderI18nObject()
const [searchText, setSearchText] = useState('')
const { canSetPluginPreferences } = usePluginSettingsAccess()
const marketplace = useMarketplace()
const { data, isLoading: isDataSourceListLoading } = useQuery(
consoleQuery.auth.plugin.datasource.list.get.queryOptions(),
)
@@ -176,14 +173,6 @@ const DataSourcePage = ({ layout, onOpenMarketplace, stickyToolbar }: DataSource
})}
</div>
)}
{!isDataSourceListLoading && marketplace && (
<InstallFromMarketplace
marketplace={marketplace}
providers={dataSources}
searchText={searchText}
onOpenMarketplace={onOpenMarketplace}
/>
)}
</>
)
@@ -3,15 +3,12 @@ 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'
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 { 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'
import Link from '@/next/link'
import { useMarketplaceAllPlugins } from './hooks'
type InstallFromMarketplaceProps = {
@@ -22,12 +19,10 @@ type InstallFromMarketplaceProps = {
}
const InstallFromMarketplace = ({
marketplace,
onOpenMarketplace,
providers,
searchText,
}: InstallFromMarketplaceProps) => {
const { t } = useTranslation(['plugin', 'modelProvider'])
const { theme } = useTheme()
const { canInstallPlugin } = usePluginSettingsAccess()
const [collapse, setCollapse] = useState(false)
const { plugins: allPlugins, isLoading: isAllPluginsLoading } = useMarketplaceAllPlugins(
@@ -67,37 +62,6 @@ const InstallFromMarketplace = ({
/>
{t(($) => $['modelProvider.installDataSource'], { ns: 'modelProvider' })}
</button>
<div className="mb-2 flex flex-wrap items-center pt-2">
<span className="pe-1 system-sm-regular text-text-tertiary">
{t(($) => $['modelProvider.discoverMore'], { ns: 'modelProvider' })}
</span>
{onOpenMarketplace ? (
<button
type="button"
className="inline-flex items-center border-0 bg-transparent p-0 system-sm-medium text-text-accent"
onClick={onOpenMarketplace}
>
{t(($) => $['marketplace.difyMarketplace'], { ns: 'plugin' })}
<span
className="i-ri-arrow-right-up-line size-4 rtl:-scale-x-100"
aria-hidden="true"
/>
</button>
) : (
<Link
target="_blank"
rel="noopener noreferrer"
href={marketplace.category(PluginCategoryEnum.datasource, { theme })}
className="inline-flex items-center system-sm-medium text-text-accent"
>
{t(($) => $['marketplace.difyMarketplace'], { ns: 'plugin' })}
<span
className="i-ri-arrow-right-up-line size-4 rtl:-scale-x-100"
aria-hidden="true"
/>
</Link>
)}
</div>
</div>
{!!searchText.trim() && !isAllPluginsLoading && !collapse && (
<div role="status" className="sr-only">
@@ -13,6 +13,7 @@ import { useQuery, useSuspenseQuery } from '@tanstack/react-query'
import { useAtomValue } from 'jotai'
import { lazy, Suspense, useRef } from 'react'
import { useTranslation } from 'react-i18next'
import { isOfficialDifyUrl } from '@/utils/official-link'
import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
import BillingPage from '@/app/components/billing/billing-page'
import CustomPage from '@/app/components/custom/custom-page'
@@ -306,7 +307,7 @@ export default function AccountSetting({
{activeItem?.description && (
<p className="mt-1 system-sm-regular wrap-break-word whitespace-normal text-text-tertiary">
{activeItem.description}
{activeItem?.docLink && (
{activeItem?.docLink?.href && !isOfficialDifyUrl(activeItem.docLink.href) && (
<a
href={activeItem.docLink.href}
target="_blank"
@@ -393,7 +393,7 @@ describe('ModelProviderPage', () => {
})
expect(autoUpdateButton).toBeInTheDocument()
expect(systemModelSelector).toBeInTheDocument()
expect(screen.getByTestId('install-from-marketplace')).toBeInTheDocument()
expect(screen.queryByTestId('install-from-marketplace')).not.toBeInTheDocument()
})
it('should skip system model settings without plugin preference access', () => {
@@ -12,7 +12,6 @@ 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 { useMarketplace } from '@/features/marketplace/client'
import { consoleQuery } from '@/service/console'
import { UpdateSettingDialog } from '../update-setting-dialog'
import { ModelTypeEnum } from './declarations'
@@ -102,7 +101,6 @@ const ModelProviderPage = ({
}
return map
}, [latestVersionData, modelProviderPlugins])
const marketplace = useMarketplace()
const isDefaultModelLoading =
isTextGenerationDefaultModelLoading ||
isEmbeddingsDefaultModelLoading ||
@@ -261,10 +259,7 @@ const ModelProviderPage = ({
showEmptyProvider={showEmptyProvider}
showConfiguredProviders={showConfiguredProviders}
showNotConfiguredProviders={showNotConfiguredProviders}
marketplace={marketplace}
searchText={searchText}
pluginSummaryMap={pluginSummaryMap}
onOpenMarketplace={onOpenMarketplace}
/>
)
@@ -3,15 +3,12 @@ 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'
import { useTheme } from 'next-themes'
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 { 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'
import Link from '@/next/link'
import { consoleQuery } from '@/service/console'
import { useMarketplaceAllPlugins } from './hooks'
@@ -23,12 +20,10 @@ type InstallFromMarketplaceProps = {
}
const InstallFromMarketplace = ({
marketplace,
onOpenMarketplace,
searchText,
stepByStepTourTarget,
}: InstallFromMarketplaceProps) => {
const { t } = useTranslation(['plugin', 'modelProvider'])
const { theme } = useTheme()
const { canInstallPlugin } = usePluginSettingsAccess()
const [collapse, setCollapse] = useState(false)
const [hasEnteredViewport, setHasEnteredViewport] = useState(
@@ -114,37 +109,6 @@ const InstallFromMarketplace = ({
/>
{t(($) => $['modelProvider.installProvider'], { ns: 'modelProvider' })}
</button>
<div className="flex items-center gap-1">
<span className="system-sm-regular text-text-tertiary">
{t(($) => $['modelProvider.discoverMore'], { ns: 'modelProvider' })}
</span>
{onOpenMarketplace ? (
<button
type="button"
className="inline-flex items-center border-0 bg-transparent p-0 system-sm-medium text-text-accent"
onClick={onOpenMarketplace}
>
{t(($) => $['marketplace.difyMarketplace'], { ns: 'plugin' })}
<span
className="i-ri-arrow-right-up-line size-4 [&:dir(rtl)]:-scale-x-100"
aria-hidden="true"
/>
</button>
) : (
<Link
target="_blank"
rel="noopener noreferrer"
href={marketplace.category(PluginCategoryEnum.model, { theme })}
className="inline-flex items-center system-sm-medium text-text-accent"
>
{t(($) => $['marketplace.difyMarketplace'], { ns: 'plugin' })}
<span
className="i-ri-arrow-right-up-line size-4 [&:dir(rtl)]:-scale-x-100"
aria-hidden="true"
/>
</Link>
)}
</div>
</div>
{!collapse && shouldLoadMarketplace && !hasLoadedInstalledPluginIds && (
<LoadingPlaceholder />
@@ -1,4 +1,5 @@
import type { FC } from 'react'
import { isOfficialDifyUrl } from '@/utils/official-link'
import type {
Credential,
CustomConfigurationModelFixedFields,
@@ -383,7 +384,9 @@ const ModelModal: FC<ModelModalProps> = ({
)}
</DialogBody>
<DialogFooter>
{provider.help && (provider.help.title || provider.help.url) && (
{provider.help &&
(provider.help.title || provider.help.url) &&
!isOfficialDifyUrl(provider.help?.url[language] || provider.help?.url.en_US) && (
<a
href={provider.help?.url[language] || provider.help?.url.en_US}
target="_blank"
@@ -1,13 +1,11 @@
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 { useTranslation } from 'react-i18next'
import { SkeletonContainer, SkeletonRectangle, SkeletonRow } from '@/app/components/base/skeleton'
import { STEP_BY_STEP_TOUR_TARGETS } from '@/app/components/step-by-step-tour/target-registry'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import InstallFromMarketplace from './install-from-marketplace'
import ProviderAddedCard from './provider-added-card'
import QuotaPanel from './provider-added-card/quota-panel'
@@ -19,10 +17,7 @@ type ModelProviderPageBodyProps = {
showEmptyProvider: boolean
showConfiguredProviders: boolean
showNotConfiguredProviders: boolean
marketplace: MarketplaceLinks | null
searchText: string
pluginSummaryMap: Map<string, ModelProviderPluginSummary>
onOpenMarketplace?: () => void
}
function ModelProviderCardSkeleton() {
@@ -58,14 +53,8 @@ function ModelProviderListSkeleton() {
)
}
function EmptyProviderState({
enableMarketplace,
stepByStepTourTarget,
}: {
enableMarketplace: boolean
stepByStepTourTarget?: string
}) {
const { t } = useTranslation(['plugin', 'modelProvider', 'navigation'])
function EmptyProviderState({ stepByStepTourTarget }: { stepByStepTourTarget?: string }) {
const { t } = useTranslation(['modelProvider'])
return (
<div
@@ -79,25 +68,7 @@ function EmptyProviderState({
{t(($) => $['modelProvider.emptyProviderTitle'], { ns: 'modelProvider' })}
</div>
<p className="mt-1 system-xs-regular text-text-tertiary">
{enableMarketplace ? (
<Trans
i18nKey={($) => $['modelProvider.emptyProviderTipWithMarketplace']}
ns="modelProvider"
components={{
marketplace: (
<a
href="#model-provider-marketplace"
aria-label={t(($) => $['marketplace.difyMarketplace'], { ns: 'plugin' })}
className="system-xs-medium text-text-accent hover:underline"
>
{t(($) => $['mainNav.marketplace'], { ns: 'navigation' })}
</a>
),
}}
/>
) : (
t(($) => $['modelProvider.emptyProviderTip'], { ns: 'modelProvider' })
)}
{t(($) => $['modelProvider.emptyProviderTip'], { ns: 'modelProvider' })}
</p>
</div>
)
@@ -162,10 +133,7 @@ const ModelProviderPageBody: FC<ModelProviderPageBodyProps> = ({
showEmptyProvider,
showConfiguredProviders,
showNotConfiguredProviders,
marketplace,
searchText,
pluginSummaryMap,
onOpenMarketplace,
}) => {
const { t } = useTranslation(['modelProvider'])
const { data: deploymentEdition } = useSuspenseQuery({
@@ -189,7 +157,6 @@ const ModelProviderPageBody: FC<ModelProviderPageBodyProps> = ({
)}
{showEmptyProvider && (
<EmptyProviderState
enableMarketplace={marketplace !== null}
stepByStepTourTarget={
!showConfiguredProviders && !showNotConfiguredProviders
? STEP_BY_STEP_TOUR_TARGETS.integrationModelProviderProduction
@@ -221,16 +188,6 @@ const ModelProviderPageBody: FC<ModelProviderPageBodyProps> = ({
/>
</div>
)}
{!isLoadingModelProviders && marketplace && (
<div>
<InstallFromMarketplace
marketplace={marketplace}
searchText={searchText}
onOpenMarketplace={onOpenMarketplace}
stepByStepTourTarget={STEP_BY_STEP_TOUR_TARGETS.integrationModelProviderInstall}
/>
</div>
)}
</div>
)
}
@@ -522,10 +522,9 @@ describe('workspace credits and marketplace availability', () => {
it('keeps marketplace discovery available without installation permission', async () => {
await setup({ modelList: [] }, { marketplace: true, installPermission: false })
expect(screen.queryByRole('button', { name: /selector.install/ })).not.toBeInTheDocument()
expect(screen.getByRole('link', { name: /discoverMoreInMarketplace/ })).toHaveAttribute(
'href',
expect.stringMatching(/\/plugins\/model$/),
)
expect(
screen.queryByRole('link', { name: /discoverMoreInMarketplace/ }),
).not.toBeInTheDocument()
})
})
@@ -5,7 +5,6 @@ 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 { PluginCategoryEnum } from '@/app/components/plugins/types'
import { modelNameMap, providerLogoMap } from '../utils'
type MarketplaceSectionProps = {
@@ -21,15 +20,12 @@ type MarketplaceSectionProps = {
}
function MarketplaceSection({
marketplace,
marketplaceProviders,
marketplaceCollapsed,
installingProvider,
canInstallPlugin,
theme,
onMarketplaceCollapsedChange,
onInstallPlugin,
onOpenMarketplace,
}: MarketplaceSectionProps) {
const { t } = useTranslation(['plugin', 'modelProvider'])
const headingId = useId()
@@ -116,43 +112,6 @@ function MarketplaceSection({
)
})}
</ul>
<div className="px-1 pb-1">
{onOpenMarketplace ? (
<Button
variant="ghost"
size="small"
className="h-auto w-full justify-start gap-0.5 px-3 py-1.5 text-start"
onClick={onOpenMarketplace}
>
<span className="flex-1 system-xs-regular text-text-accent">
{t(($) => $['modelProvider.selector.discoverMoreInMarketplace'], {
ns: 'modelProvider',
})}
</span>
<span
className="i-ri-arrow-right-up-line size-3! text-text-accent rtl:-scale-x-100"
aria-hidden="true"
/>
</Button>
) : (
<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={marketplace.category(PluginCategoryEnum.model, { theme })}
target="_blank"
rel="noopener noreferrer"
>
<span className="flex-1 system-xs-regular text-text-accent">
{t(($) => $['modelProvider.selector.discoverMoreInMarketplace'], {
ns: 'modelProvider',
})}
</span>
<span
className="i-ri-arrow-right-up-line size-3! text-text-accent rtl:-scale-x-100"
aria-hidden="true"
/>
</a>
)}
</div>
</CollapsiblePanel>
</Collapsible>
</>
@@ -306,7 +306,7 @@ function Popup({
onClick={() => setShowIncompatibleModels((value) => !value)}
/>
)}
{marketplace && (
{marketplace && canInstallPlugin && (
<MarketplaceSection
marketplace={marketplace}
marketplaceProviders={marketplaceProviders}
@@ -15,9 +15,6 @@ import { Input } from '@langgenius/dify-ui/input'
import { Textarea } from '@langgenius/dify-ui/textarea'
import { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useLocale } from '#i18n'
import { getEnterpriseDocUrl } from '@/context/i18n'
import { getDocLanguage } from '@/i18n/language'
import PermissionField from './permission-field'
export type RoleModalMode = 'create' | 'view' | 'edit'
@@ -38,8 +35,6 @@ type RoleModalProps = {
const RoleModal = ({ mode, open, role, onClose, onSubmit }: RoleModalProps) => {
const { t } = useTranslation(['common', 'permission'])
const locale = useLocale()
const docLanguage = getDocLanguage(locale)
const [name, setName] = useState(role?.name ?? '')
const [desc, setDesc] = useState(role?.description ?? '')
const [permissionKeys, setPermissionKeys] = useState<string[]>(role?.permission_keys ?? [])
@@ -116,15 +111,6 @@ const RoleModal = ({ mode, open, role, onClose, onSubmit }: RoleModalProps) => {
/>
</DialogBody>
<DialogFooter>
<a
href={getEnterpriseDocUrl('/use/workspace/permission-reference', docLanguage)}
target="_blank"
rel="noreferrer"
className="me-auto inline-flex items-center gap-1 system-xs-medium text-text-accent hover:underline"
>
<span>{t(($) => $['permissionSet.learnMore'], { ns: 'permission' })}</span>
<span aria-hidden className="i-ri-external-link-line h-3.5 w-3.5" />
</a>
<Button variant="secondary" onClick={onClose}>
{readonly
? t(($) => $['operation.close'], { ns: 'common' })
@@ -10,9 +10,14 @@ describe('generateMailToLink', () => {
describe('mailToSupport', () => {
it('encodes support context without allowing it to introduce extra query parameters', () => {
const result = mailToSupport('user+support@test.com', 'Pro & Team', '1.0.0')
const result = mailToSupport(
'user+support@test.com',
'Pro & Team',
'1.0.0',
'ops@example.com',
)
expect(result.startsWith('mailto:support@dify.ai?')).toBe(true)
expect(result.startsWith('mailto:ops@example.com?')).toBe(true)
const query = result.split('?')[1]
expect(query).toBeDefined()
@@ -26,4 +31,8 @@ describe('mailToSupport', () => {
expect(body).toContain('Version: 1.0.0')
expect([...params.keys()]).toEqual(['subject', 'body'])
})
it('does not fall back to an official support address', () => {
expect(mailToSupport('user@example.com', 'Pro', '1.0.0')).toBe('')
})
})
@@ -24,5 +24,6 @@ export const mailToSupport = (
Platform:
Problem Description:
`
return generateMailToLink(supportEmailAddress || 'support@dify.ai', subject, body)
if (!supportEmailAddress) return ''
return generateMailToLink(supportEmailAddress, subject, body)
}
@@ -277,16 +277,16 @@ it('closes compact navigation after changing the settings section', async () =>
})
it('preserves the host title in settings and updates it for route navigation', () => {
document.title = 'Workspace settings - Dify'
document.title = 'Workspace settings - 甘肃省房地产价格评估行业协会'
const view = renderPage()
expect(document.title).toBe('Workspace settings - Dify')
expect(document.title).toBe('Workspace settings - 甘肃省房地产价格评估行业协会')
view.rerender(<IntegrationsPage section="provider" syncDocumentTitle />)
expect(document.title).toBe(
'navigation.settings.provider · navigation.mainNav.integrations - Dify',
'navigation.settings.provider · navigation.mainNav.integrations - 甘肃省房地产价格评估行业协会',
)
view.rerender(<IntegrationsPage section="data-source" syncDocumentTitle />)
expect(document.title).toBe(
'navigation.settings.dataSource · navigation.mainNav.integrations - Dify',
'navigation.settings.dataSource · navigation.mainNav.integrations - 甘肃省房地产价格评估行业协会',
)
})
@@ -362,31 +362,24 @@ it.each([
expect(screen.getByRole('link', { name: heading })).toHaveAttribute('aria-current', 'page')
})
it.each([
['provider', '/plugins/model'],
['data-source', '/plugins/datasource'],
] as const)('opens the %s marketplace from its actual section action', async (section, path) => {
const user = userEvent.setup()
renderPage({ props: { section } })
const action = 'plugin.marketplace.difyMarketplace'
await user.click(await screen.findByRole('button', { name: action }))
expect(window.open).toHaveBeenCalledWith(
expect.stringContaining(`${path}?source=`),
'_blank',
'noopener,noreferrer',
)
})
it.each(['provider', 'data-source'] as const)(
'does not open the official %s marketplace',
async (section) => {
renderPage({ props: { section } })
expect(
screen.queryByRole('button', { name: 'plugin.marketplace.difyMarketplace' }),
).not.toBeInTheDocument()
expect(window.open).not.toHaveBeenCalled()
},
)
it('opens the category marketplace path from the install menu', async () => {
it('opens the in-app marketplace from the install menu', async () => {
const user = userEvent.setup()
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(window.open).toHaveBeenCalledExactlyOnceWith(
expect.stringContaining('/plugins/trigger?source='),
'_blank',
'noopener,noreferrer',
)
expect(api.push).toHaveBeenCalledExactlyOnceWith('/marketplace')
expect(window.open).not.toHaveBeenCalled()
})
it('saves category-specific automatic update settings from the toolbar', async () => {
@@ -579,17 +579,11 @@ it.each([
},
)
it('loads the tool marketplace when the user expands it', async () => {
const user = userEvent.setup()
it('does not show the marketplace catalog on builtin tools', async () => {
renderProviderList({ marketplace: true })
await user.click(screen.getByRole('button', { name: 'plugin.marketplace.moreFrom' }))
await waitFor(() =>
expect(api.collections).toHaveBeenCalledWith(
{ query: expect.objectContaining({ category: 'tool', exclude: [] }) },
expect.anything(),
),
)
expect(screen.getByText('plugin.marketplace.moreFrom')).toBeInTheDocument()
await act(async () => {})
expect(screen.queryByText('plugin.marketplace.moreFrom')).not.toBeInTheDocument()
expect(api.collections).not.toHaveBeenCalled()
})
it('loads an installed plugin detail and closes it without losing the catalog', async () => {
@@ -29,13 +29,9 @@ import {
import { Suspense, useId, useRef, useState, useSyncExternalStore } from 'react'
import { useTranslation } from 'react-i18next'
import { UpdateSettingDialog } from '@/app/components/header/account-setting/update-setting-dialog'
import {
buildIntegrationPath,
buildMarketplaceUrlPathByIntegrationSection,
toolCategoryBySection,
} from '@/app/components/integrations/routes'
import { buildIntegrationPath, toolCategoryBySection } from '@/app/components/integrations/routes'
import { useDocLink } from '@/context/i18n'
import { useMarketplace } from '@/features/marketplace/client'
import { isOfficialDifyUrl } from '@/utils/official-link'
import useDocumentTitle from '@/hooks/use-document-title'
import Link from '@/next/link'
import { useRouter } from '@/next/navigation'
@@ -100,15 +96,17 @@ const DescriptionWithLearnMore = ({ children, href, label }: DescriptionWithLear
<span className="min-w-0 break-words whitespace-normal sm:truncate" title={title}>
{children}
</span>
<Link
className="inline-flex shrink-0 items-center text-text-accent"
href={href}
target="_blank"
rel="noopener noreferrer"
>
{label}
<span aria-hidden className="i-ri-external-link-line size-3 [&:dir(rtl)]:-scale-x-100" />
</Link>
{href && !isOfficialDifyUrl(href) ? (
<Link
className="inline-flex shrink-0 items-center text-text-accent"
href={href}
target="_blank"
rel="noopener noreferrer"
>
{label}
<span aria-hidden className="i-ri-external-link-line size-3 [&:dir(rtl)]:-scale-x-100" />
</Link>
) : null}
</span>
)
}
@@ -214,8 +212,6 @@ export default function IntegrationsPage({
<UpdateSettingDialog category={pluginSettingCategory} />
</div>
) : undefined
const marketplace = useMarketplace()
const marketplaceUrlPath = buildMarketplaceUrlPathByIntegrationSection(section)
const headerDescription =
integrationHeader?.description ??
(section === 'provider'
@@ -234,13 +230,7 @@ export default function IntegrationsPage({
headerDescription
)
const handleSwitchToMarketplace = () => {
if (!marketplace) return
window.open(
marketplace.page(marketplaceUrlPath, undefined, window.location.origin),
'_blank',
'noopener,noreferrer',
)
router.push('/marketplace')
}
const handleSelectSection = (nextSection: IntegrationSection) => {
if (onSectionChange) {
@@ -9,6 +9,7 @@ import Icon from '@/app/components/plugins/card/base/card-icon'
import CornerMark from '@/app/components/plugins/card/base/corner-mark'
import { useGetLanguage } from '@/context/i18n'
import { renderI18nObject } from '@/i18n/metadata'
import { visibleAuthorName } from '@/utils/visible-author'
const getCollectionPluginIdentity = (collection: Collection) => {
const [org, ...nameParts] = collection.plugin_id?.split('/').filter(Boolean) ?? []
@@ -43,6 +44,10 @@ function IntegrationsToolProviderCard({
const { t } = useTranslation(['dataset', 'tools'])
const title = renderI18nObject(collection.label, language)
const description = renderI18nObject(collection.description, language)
const authorName = visibleAuthorName(collection.author)
const authorLabel = authorName
? `${t(($) => $.author, { ns: 'tools' })} ${authorName}`
: undefined
const { org, name } = getCollectionPluginIdentity(collection)
const toolsCount = collection.tools?.length ?? 0
const builtInLabel = t(($) => $['metadata.datasetMetadata.builtIn'], { ns: 'dataset' })
@@ -69,13 +74,9 @@ function IntegrationsToolProviderCard({
</div>
<div
className="h-4 truncate system-xs-regular text-text-tertiary"
title={
collection.author
? `${t(($) => $.author, { ns: 'tools' })} ${collection.author}`
: undefined
}
title={authorLabel}
>
{collection.author && `${t(($) => $.author, { ns: 'tools' })} ${collection.author}`}
{authorLabel}
</div>
</div>
</div>
@@ -129,10 +130,10 @@ function IntegrationsToolProviderCard({
</div>
<div className="flex h-6.5 w-full items-center gap-2 px-3 pt-1.5 pb-1">
<div className="flex h-4 min-w-0 flex-1 items-center gap-0.5 system-xs-regular">
{!!org && (
{!!visibleAuthorName(org) && (
<>
<div className="min-w-0 shrink truncate text-text-tertiary" title={org}>
{org}
<div className="min-w-0 shrink truncate text-text-tertiary" title={visibleAuthorName(org)}>
{visibleAuthorName(org)}
</div>
<div className="shrink-0 text-text-quaternary">/</div>
</>
@@ -28,7 +28,6 @@ import {
useCanManageMCP,
useCanManageTools,
} from '@/app/components/tools/hooks/use-tool-permissions'
import { BuiltinMarketplacePanel } from '@/app/components/tools/marketplace/builtin-marketplace-panel'
import MCPList from '@/app/components/tools/mcp'
import ProviderDetail from '@/app/components/tools/provider/detail'
import { ToolProviderGrid } from '@/app/components/tools/tool-provider-grid'
@@ -36,7 +35,6 @@ import {
selectToolCollections,
selectToolsWithProvider,
} from '@/app/components/tools/utils/query-select'
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,7 +57,6 @@ const ProviderList = ({ category, contentInset = 'default', layout }: ProviderLi
const { canDeletePlugin, canSetPluginPreferences, canUpdatePlugin } = usePluginSettingsAccess()
const canManageTools = useCanManageTools()
const canManageMCP = useCanManageMCP()
const marketplace = useMarketplace()
const { activeTab, handleCategoryChange, isRouteCategory } = useToolProviderCategory(category)
const contentPaddingClassName = toolsContentInsetClassNames[contentInset]
const toolListFrameClassName = cn(contentPaddingClassName, toolsUnifiedContentFrameClassName)
@@ -234,15 +231,6 @@ const ProviderList = ({ category, contentInset = 'default', layout }: ProviderLi
{isCollectionSearchEmpty && activeTab === 'builtin' && (
<div className={cn('h-56 shrink-0', toolListFrameClassName)} />
)}
{marketplace && activeTab === 'builtin' && (
<BuiltinMarketplacePanel
marketplace={marketplace}
containerRef={containerRef}
contentInset={contentInset}
keywords={keywords}
tagFilterValue={tagFilterValue}
/>
)}
{activeTab === 'mcp' && (
<MCPList
providers={activeTabCollectionList}
@@ -446,8 +446,9 @@ describe('MainNav', () => {
expect(knowledgeLink).toHaveAttribute('href', '/datasets')
const integrationsLink = screen.getByRole('link', { name: /navigation.mainNav.integrations/ })
expect(integrationsLink).toHaveAttribute('href', '/integrations/model-provider')
const marketplaceLink = screen.getByRole('link', { name: /navigation.mainNav.marketplace/ })
expect(marketplaceLink).toHaveAttribute('href', '/marketplace')
expect(
screen.queryByRole('link', { name: /navigation.mainNav.marketplace/ }),
).not.toBeInTheDocument()
expect(
within(screen.getByRole('navigation', { name: 'common.navigation.primary' }))
.getAllByRole('link')
@@ -460,7 +461,6 @@ describe('MainNav', () => {
'/contacts',
'/skills',
'/integrations/model-provider',
'/marketplace',
])
})
@@ -481,7 +481,6 @@ describe('MainNav', () => {
'/datasets',
'/skills',
'/integrations/model-provider',
'/marketplace',
])
})
@@ -602,10 +601,9 @@ describe('MainNav', () => {
'href',
'/integrations/model-provider',
)
expect(screen.getByRole('link', { name: /navigation.mainNav.marketplace/ })).toHaveAttribute(
'href',
'/marketplace',
)
expect(
screen.queryByRole('link', { name: /navigation.mainNav.marketplace/ }),
).not.toBeInTheDocument()
expect(
screen.queryByRole('button', { name: 'explore.sidebar.webApps' }),
).not.toBeInTheDocument()
@@ -634,7 +632,9 @@ describe('MainNav', () => {
expect(
screen.getByRole('link', { name: /navigation.mainNav.integrations/ }),
).toBeInTheDocument()
expect(screen.getByRole('link', { name: /navigation.mainNav.marketplace/ })).toBeInTheDocument()
expect(
screen.queryByRole('link', { name: /navigation.mainNav.marketplace/ }),
).not.toBeInTheDocument()
})
it('marks the matching primary route active', () => {
@@ -698,14 +698,15 @@ describe('MainNav', () => {
)
it.each(['/marketplace', '/plugins', '/templates', '/templates/marketing'])(
'marks marketplace active on route %s',
'keeps the marketplace menu hidden on route %s',
(pathname) => {
mockPathname = pathname
renderMainNav()
const marketplaceLink = screen.getByRole('link', { name: /navigation.mainNav.marketplace/ })
expect(marketplaceLink).toHaveAttribute('aria-current', 'page')
expect(
screen.queryByRole('link', { name: /navigation.mainNav.marketplace/ }),
).not.toBeInTheDocument()
},
)
@@ -859,7 +860,7 @@ describe('MainNav', () => {
await user.click(screen.getByRole('button', { name: 'navigation.mainNav.help.openMenu' }))
await screen.findByText('navigation.mainNav.help.docs')
await screen.findByRole('menuitem', { name: /common\.userProfile\.about/ })
expect(
screen.queryByRole('menuitemcheckbox', { name: 'navigation.mainNav.help.stepByStepTour' }),
).not.toBeInTheDocument()
@@ -871,27 +872,23 @@ describe('MainNav', () => {
await user.click(screen.getByRole('button', { name: 'navigation.mainNav.help.openMenu' }))
await screen.findByText('navigation.mainNav.help.docs')
await screen.findByRole('menuitem', { name: /common\.userProfile\.about/ })
expect(
screen.queryByRole('menuitemcheckbox', { name: 'navigation.mainNav.help.learnDify' }),
).not.toBeInTheDocument()
})
it('opens Creator Center from the help menu above GitHub', async () => {
it('does not link the help menu to Creator Center or the official docs', async () => {
const user = userEvent.setup()
renderMainNav()
await user.click(screen.getByRole('button', { name: 'navigation.mainNav.help.openMenu' }))
const creatorCenter = await screen.findByRole('menuitem', {
name: 'navigation.mainNav.help.creatorCenter',
})
const github = screen.getByRole('menuitem', { name: /common\.userProfile\.github/ })
expect(creatorCenter).toHaveAttribute('href', 'https://creators.dify.ai/')
expect(creatorCenter).toHaveAttribute('target', '_blank')
expect(creatorCenter).toHaveAttribute('rel', 'noopener noreferrer')
expect(creatorCenter.compareDocumentPosition(github)).toBe(Node.DOCUMENT_POSITION_FOLLOWING)
await screen.findByRole('menuitem', { name: /common\.userProfile\.about/ })
expect(
screen.queryByRole('menuitem', { name: 'navigation.mainNav.help.creatorCenter' }),
).not.toBeInTheDocument()
expect(screen.queryByText('navigation.mainNav.help.docs')).not.toBeInTheDocument()
})
it('opens About from its real Help menu owner and restores focus when closed', async () => {
@@ -914,19 +911,8 @@ describe('MainNav', () => {
).toBeInTheDocument()
expect(screen.queryByRole('menu')).not.toBeInTheDocument()
expect(screen.getByRole('button', { name: 'common.operation.close' })).toHaveFocus()
expect(screen.getByRole('link', { name: 'Privacy Policy' })).toHaveAttribute(
'href',
'https://dify.ai/privacy',
)
expect(screen.getByRole('link', { name: 'common.about.changeLog' })).toHaveAttribute(
'href',
'https://github.com/langgenius/dify/releases',
)
expect(screen.getByRole('link', { name: 'common.about.updateNow' })).toHaveAttribute(
'href',
'https://github.com/langgenius/dify/releases/tag/1.1.0',
)
expect(screen.queryByRole('button', { name: 'common.about.changeLog' })).not.toBeInTheDocument()
expect(screen.queryByRole('link', { name: 'Privacy Policy' })).not.toBeInTheDocument()
expect(screen.queryByRole('link', { name: 'common.about.changeLog' })).not.toBeInTheDocument()
await user.keyboard('{Escape}')
@@ -945,10 +931,8 @@ describe('MainNav', () => {
await user.click(screen.getByRole('button', { name: 'navigation.mainNav.help.openMenu' }))
await user.click(await screen.findByRole('menuitem', { name: /common\.userProfile\.about/ }))
expect(await screen.findByRole('link', { name: 'Open Source License' })).toHaveAttribute(
'href',
'https://github.com/langgenius/dify/blob/main/LICENSE',
)
expect(await screen.findByRole('dialog', { name: 'common.userProfile.about' })).toBeInTheDocument()
expect(screen.queryByRole('link', { name: 'Open Source License' })).not.toBeInTheDocument()
expect(screen.queryByRole('link', { name: 'Privacy Policy' })).not.toBeInTheDocument()
})
@@ -110,19 +110,14 @@ describe('SupportMenu', () => {
)
}
it('renders contact us before Discord when Zendesk is configured', async () => {
it('renders contact us when Zendesk is configured', async () => {
const user = userEvent.setup()
renderSupportMenu()
expect(screen.getByText('common.userProfile.contactUs')).toBeInTheDocument()
expect(screen.getByText('common.userProfile.discord')).toBeInTheDocument()
expect(screen.queryByText('common.userProfile.discord')).not.toBeInTheDocument()
expect(screen.queryByText('common.userProfile.forum')).not.toBeInTheDocument()
expect(screen.queryByText('common.userProfile.community')).not.toBeInTheDocument()
expect(
screen
.getByText('common.userProfile.contactUs')
.compareDocumentPosition(screen.getByText('common.userProfile.discord')),
).toBe(Node.DOCUMENT_POSITION_FOLLOWING)
await user.click(screen.getByRole('menuitem', { name: 'common.userProfile.contactUs' }))
@@ -202,7 +197,7 @@ describe('SupportMenu', () => {
expect(screen.queryByText('common.userProfile.contactUs')).not.toBeInTheDocument()
expect(screen.queryByText('common.userProfile.emailSupport')).not.toBeInTheDocument()
expect(screen.getByText('common.userProfile.discord')).toBeInTheDocument()
expect(screen.queryByText('common.userProfile.discord')).not.toBeInTheDocument()
})
it('renders email support when Zendesk is not configured for a dedicated support channel', () => {
@@ -225,7 +220,7 @@ describe('SupportMenu', () => {
expect(screen.queryByText('common.userProfile.emailSupport')).not.toBeInTheDocument()
expect(mailToSupport).not.toHaveBeenCalled()
expect(screen.getByText('common.userProfile.discord')).toBeInTheDocument()
expect(screen.queryByText('common.userProfile.discord')).not.toBeInTheDocument()
})
it('keeps configured self-hosted email support independent of Cloud plan data', () => {
@@ -239,11 +234,11 @@ describe('SupportMenu', () => {
expect(mailToSupport).not.toHaveBeenCalled()
})
it('has the Discord link and no Forum entry', () => {
it('does not link to Discord, Forum, or Community', () => {
renderSupportMenu()
const discordLink = screen.getByText('common.userProfile.discord').closest('a')
expect(discordLink).toHaveAttribute('href', 'https://discord.gg/5AEfbxcd9k')
expect(screen.queryByText('common.userProfile.discord')).not.toBeInTheDocument()
expect(screen.queryByRole('link', { name: 'common.userProfile.discord' })).not.toBeInTheDocument()
expect(screen.queryByText('common.userProfile.forum')).not.toBeInTheDocument()
expect(screen.queryByText('common.userProfile.community')).not.toBeInTheDocument()
})
@@ -10,7 +10,6 @@ import {
MenuContent,
MenuGroup,
MenuItem,
MenuLinkItem,
MenuSeparator,
MenuTrigger,
} from '@langgenius/dify-ui/menu'
@@ -24,11 +23,7 @@ import {
useSetLearnDifyHidden,
} from '@/app/components/explore/learn-dify/storage'
import Compliance from '@/app/components/header/account-menu/compliance'
import {
ExternalLinkIndicator,
MenuItemContent,
} from '@/app/components/header/account-menu/menu-item-content'
import GithubStar from '@/app/components/header/github-star'
import { MenuItemContent } from '@/app/components/header/account-menu/menu-item-content'
import { trackStepByStepTourEvent } from '@/app/components/step-by-step-tour/analytics'
import {
disableStepByStepTourForCurrentWorkspaceAtom,
@@ -39,7 +34,6 @@ import {
stepByStepTourStateUpdatingAtom,
} from '@/app/components/step-by-step-tour/state'
import { getLangGeniusVersionInfo } from '@/context/app-context-normalizers'
import { useDocLink } from '@/context/i18n'
import {
currentWorkspaceIdAtom,
currentWorkspaceLoadingAtom,
@@ -47,12 +41,11 @@ 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'
import AccountAboutDialog from './help-menu/account-about-dialog'
import SupportMenu from './support-menu'
import SupportMenu, { useHasSupportMenuItems } from './support-menu'
type HelpMenuProps = {
triggerIcon?: ReactElement
@@ -91,8 +84,6 @@ const MenuSwitchIndicator = ({ checked }: { checked: boolean }) => (
const HelpMenu = ({ triggerIcon, triggerClassName, triggerRef, triggerSize }: HelpMenuProps) => {
const { t } = useTranslation(['common', 'navigation'])
const docLink = useDocLink()
const marketplace = useMarketplace()
const { data: systemFeatures } = useSuspenseQuery(systemFeaturesQueryOptions())
const { data: profileMeta } = useSuspenseQuery({
...userProfileQueryOptions(),
@@ -119,10 +110,15 @@ const HelpMenu = ({ triggerIcon, triggerClassName, triggerRef, triggerSize }: He
const enableStepByStepTour = useSetAtom(enableStepByStepTourForCurrentWorkspaceAtom)
const disableStepByStepTour = useSetAtom(disableStepByStepTourForCurrentWorkspaceAtom)
const setStepByStepTourChecklistMinimized = useSetAtom(stepByStepTourChecklistMinimizedAtom)
const hasSupportMenuItems = useHasSupportMenuItems()
const [aboutOpen, setAboutOpen] = useState(false)
const usesDefaultTrigger = !triggerIcon
const shouldShowLearnDifySwitch = systemFeatures.enable_learn_app
const shouldShowStepByStepTourSwitch = systemFeatures.enable_step_by_step_tour
const shouldShowDocsGroup =
shouldShowLearnDifySwitch ||
(systemFeatures.deployment_edition === 'CLOUD' && shouldShowStepByStepTourSwitch) ||
(systemFeatures.deployment_edition === 'CLOUD' && isCurrentWorkspaceOwner)
const canToggleStepByStepTour =
Boolean(currentWorkspaceId) && !isLoadingCurrentWorkspace && !stepByStepTourStateUpdating
@@ -187,20 +183,9 @@ const HelpMenu = ({ triggerIcon, triggerClassName, triggerRef, triggerSize }: He
className="w-60 overflow-hidden bg-components-panel-bg-blur! p-0! backdrop-blur-[5px]"
>
<>
<MenuGroup className="py-1">
<MenuLinkItem
href={docLink('/use-dify/getting-started/introduction')}
target="_blank"
rel="noopener noreferrer"
className="h-8 gap-1 px-3 py-1"
>
<MenuItemContent
iconClassName="i-ri-book-open-line"
label={t(($) => $['mainNav.help.docs'], { ns: 'navigation' })}
trailing={<ExternalLinkIndicator />}
/>
</MenuLinkItem>
{shouldShowLearnDifySwitch && (
{shouldShowDocsGroup && (
<MenuGroup className="py-1">
{shouldShowLearnDifySwitch && (
<MenuCheckboxItem
checked={!learnDifyHidden}
closeOnClick={false}
@@ -238,27 +223,16 @@ const HelpMenu = ({ triggerIcon, triggerClassName, triggerRef, triggerSize }: He
{systemFeatures.deployment_edition === 'CLOUD' && isCurrentWorkspaceOwner && (
<Compliance />
)}
</MenuGroup>
<MenuSeparator className="my-0!" />
</MenuGroup>
)}
{shouldShowDocsGroup && hasSupportMenuItems && <MenuSeparator className="my-0!" />}
{hasSupportMenuItems && (
<MenuGroup className="py-1">
<SupportMenu />
</MenuGroup>
)}
{(shouldShowDocsGroup || hasSupportMenuItems) && <MenuSeparator className="my-0!" />}
<MenuGroup className="py-1">
<SupportMenu />
</MenuGroup>
<MenuSeparator className="my-0!" />
<MenuGroup className="py-1">
{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>
)}
{env.NEXT_PUBLIC_SITE_ABOUT !== 'hide' && (
<MenuItem className="h-8 gap-1 px-3 py-1.5" onClick={() => setAboutOpen(true)}>
<MenuItemContent
@@ -109,18 +109,37 @@ export default function SupportMenu() {
/>
</MenuLinkItem>
)}
<MenuLinkItem
className="h-8 gap-1 px-3 py-1"
href="https://discord.gg/5AEfbxcd9k"
rel="noopener noreferrer"
target="_blank"
>
<MenuItemContent
iconClassName="i-ri-discord-line"
label={t(($) => $['userProfile.discord'], { ns: 'common' })}
trailing={<ExternalLinkIndicator />}
/>
</MenuLinkItem>
</>
)
}
export function useHasSupportMenuItems() {
const { data: deploymentEdition } = useSuspenseQuery({
...systemFeaturesQueryOptions(),
select: ({ deployment_edition }) => deployment_edition,
})
const { data: plan } = useQuery(
consoleQuery.features.get.queryOptions({
enabled: deploymentEdition === 'CLOUD',
select: (data) => data.billing.subscription.plan,
}),
)
const hasDedicatedChannel =
(deploymentEdition === 'CLOUD' && (plan === 'professional' || plan === 'team')) ||
Boolean(SUPPORT_EMAIL_ADDRESS.trim())
const shouldShowUpgradeContact =
deploymentEdition === 'CLOUD' && plan === 'sandbox' && !hasDedicatedChannel
const hasZendeskWidget = deploymentEdition === 'CLOUD' && Boolean(ZENDESK_WIDGET_KEY.trim())
const hasEmailSupport =
!shouldShowUpgradeContact &&
hasDedicatedChannel &&
!hasZendeskWidget &&
Boolean(SUPPORT_EMAIL_ADDRESS.trim()) &&
(deploymentEdition !== 'CLOUD' || plan !== undefined)
return (
shouldShowUpgradeContact ||
(!shouldShowUpgradeContact && hasDedicatedChannel && hasZendeskWidget) ||
hasEmailSupport
)
}
@@ -32,6 +32,8 @@ export type DetailSidebarVisibilityOptions = Pick<
const VISIBLE_TO_ALL: MainNavRouteVisibility = () => true
const CAN_VIEW_CONTACTS: MainNavRouteVisibility = (options) => options.canViewContacts
/** Soft-hidden for this deployment. The Marketplace page and install flows stay available. */
const HIDE_MARKETPLACE_NAV: MainNavRouteVisibility = () => false
const SKILL_ENABLED_FOR_WORKSPACE: MainNavRouteVisibility = (options) =>
options.skillEnabled && options.canViewSkills && !options.isCurrentWorkspaceDatasetOperator
@@ -120,7 +122,7 @@ export const MAIN_NAV_ROUTES = [
isPathUnderRoute(path, '/templates'),
icon: 'i-custom-vender-main-nav-marketplace-v2',
activeIcon: 'i-custom-vender-main-nav-marketplace-v2-active',
visibility: VISIBLE_TO_ALL,
visibility: HIDE_MARKETPLACE_NAV,
feature: 'marketplace',
},
] as const satisfies readonly MainNavRouteConfig[]
@@ -5,7 +5,6 @@ import * as React from 'react'
import { useMemo } from 'react'
import { Trans } from 'react-i18next'
import { useTranslation } from '#i18n'
import Link from '@/next/link'
type DeprecationNoticeProps = {
status: 'deleted' | 'active'
@@ -32,7 +31,6 @@ const DeprecationNotice: FC<DeprecationNoticeProps> = ({
status,
deprecatedReason,
alternativePluginId,
alternativePluginURL,
className,
}) => {
const { t } = useTranslation(['plugin'])
@@ -58,14 +56,7 @@ const DeprecationNotice: FC<DeprecationNoticeProps> = ({
i18nKey={($) => $[`${i18nPrefix}.fullMessage`]}
ns="plugin"
components={{
CustomLink: (
<Link
href={alternativePluginURL}
target="_blank"
rel="noopener noreferrer"
className="underline"
/>
),
CustomLink: <span />,
}}
values={{
deprecatedReason: deprecatedReasonKey
@@ -1,4 +1,5 @@
import { cn } from '@langgenius/dify-ui/cn'
import { visibleAuthorName } from '@/utils/visible-author'
type Props = Readonly<{
className?: string
@@ -8,15 +9,16 @@ type Props = Readonly<{
}>
const OrgInfo = ({ className, orgName, packageName, packageNameClassName }: Props) => {
const label = visibleAuthorName(orgName)
return (
<div className={cn('flex h-4 min-w-0 items-center gap-0.5', className)}>
{orgName && (
{label && (
<>
<span
className="min-w-0 shrink truncate system-xs-regular text-text-tertiary"
title={orgName}
title={label}
>
{orgName}
{label}
</span>
<span className="shrink-0 system-xs-regular text-text-quaternary">/</span>
</>
@@ -10,6 +10,7 @@ import useTheme from '@/hooks/use-theme'
import { renderI18nObject } from '@/i18n/metadata'
import { Theme } from '@/types/app'
import { formatNumber } from '@/utils/format'
import { visibleAuthorName } from '@/utils/visible-author'
import Partner from '../base/badges/partner'
import Verified from '../base/badges/verified'
import Icon from '../card/base/card-icon'
@@ -92,6 +93,7 @@ const Card = ({
const { t } = useTranslation(['plugin'])
const { categoriesMap } = useCategories(true)
const { category, type, name, org, label, brief, icon, icon_dark, verified, from } = payload
const publicOrg = visibleAuthorName(org)
const badges = payload.badges ?? []
const { theme } = useTheme()
const activeIcon = theme === Theme.dark && icon_dark ? icon_dark : icon
@@ -146,15 +148,15 @@ const Card = ({
{titleLeft}
</div>
<div className="flex h-4 min-w-0 items-center gap-2 system-xs-regular text-text-tertiary">
{org && (
{publicOrg && (
<div className="flex min-w-0 items-center gap-1">
<span className="shrink-0 lowercase">
{t(($) => $['marketplace.by'], { ns: 'plugin' })}
</span>
<span className="truncate">{org}</span>
<span className="truncate">{publicOrg}</span>
</div>
)}
{org && payload.install_count !== undefined && (
{publicOrg && payload.install_count !== undefined && (
<span className="shrink-0 text-text-quaternary">·</span>
)}
{payload.install_count !== undefined && (
@@ -247,17 +247,13 @@ describe('DifyCreatorProfile', () => {
expect(new URL(src).searchParams.get('installed')).toBe('false')
})
it.each(['COMMUNITY', 'ENTERPRISE'] as const)(
'links %s creator inventory to official details',
'keeps %s creator inventory inside the app',
(edition) => {
deploymentState.deploymentEdition = edition
renderWithNuqs(<DifyCreatorProfile loadedProfile={loadedProfile} locale="en-US" />)
for (const name of ['Deep Research', 'Research Template']) {
const link = screen.getByRole('link', { name })
const url = new URL(link.getAttribute('href')!)
expect(url.origin).toBe('https://marketplace.dify.ai')
expect(url.searchParams.get('source')).toBe(window.location.origin)
expect(link).toHaveAttribute('target', '_blank')
expect(link).toHaveAttribute('rel', 'noopener noreferrer')
expect(screen.queryByRole('link', { name })).not.toBeInTheDocument()
expect(screen.getByRole('button', { name })).toBeInTheDocument()
}
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
},
@@ -268,7 +264,7 @@ describe('DifyCreatorProfile', () => {
})
it.each(['COMMUNITY', 'ENTERPRISE'] as const)(
'opens %s creator search results externally',
'opens %s creator search results in the app',
async (edition) => {
deploymentState.deploymentEdition = edition
const open = vi.spyOn(window, 'open').mockReturnValue(null)
@@ -278,14 +274,8 @@ describe('DifyCreatorProfile', () => {
)
await user.type(searchInput(), 'search')
await user.click(await screen.findByRole('option', { name: /Search result/ }))
expect(open).toHaveBeenCalledTimes(1)
expect(new URL(String(open.mock.calls[0]![0])).pathname).toBe('/plugin/dify/search_result')
await user.clear(searchInput())
await user.type(searchInput(), 'template')
await user.click(await screen.findByRole('option', { name: /Research Template/ }))
expect(open).toHaveBeenCalledTimes(2)
expect(new URL(String(open.mock.calls[1]![0])).pathname).toBe('/template/dify/template-one')
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
expect(open).not.toHaveBeenCalled()
expect(await screen.findByRole('dialog')).toBeInTheDocument()
expect(onUrlUpdate).not.toHaveBeenCalled()
},
)
@@ -5,6 +5,8 @@ import { cn } from '@langgenius/dify-ui/cn'
import { useTranslation } from '#i18n'
import Partner from '@/app/components/plugins/base/badges/partner'
import Verified from '@/app/components/plugins/base/badges/verified'
import { isOfficialDifyUrl } from '@/utils/official-link'
import { visibleAuthorName } from '@/utils/visible-author'
import PublisherAvatar from './publisher-avatar'
type CreatorSidebarProps = {
@@ -29,6 +31,7 @@ function SocialIcon({ platform }: { platform: CreatorSocialPlatform }) {
export default function CreatorSidebar({ profile }: CreatorSidebarProps) {
const { t } = useTranslation(['plugin'])
const isOrganization = profile.kind === 'organization'
const displayName = visibleAuthorName(profile.displayName)
const isPartner = profile.badges.includes('partner')
const isVerified = profile.badges.includes('verified')
@@ -36,7 +39,7 @@ export default function CreatorSidebar({ profile }: CreatorSidebarProps) {
<div className="relative flex min-w-0 flex-col gap-4 pt-11 md:w-[234px] md:pt-12">
<PublisherAvatar
avatarUrl={profile.avatarUrl}
name={profile.displayName}
name={displayName}
isOrganization={isOrganization}
size={100}
className={cn(
@@ -47,7 +50,9 @@ export default function CreatorSidebar({ profile }: CreatorSidebarProps) {
<div className="flex flex-col gap-1">
<div className="flex flex-wrap items-center gap-1">
<h1 className="title-2xl-semi-bold text-text-primary">{profile.displayName}</h1>
{displayName ? (
<h1 className="title-2xl-semi-bold text-text-primary">{displayName}</h1>
) : null}
{isOrganization && (
<span className="rounded-[5px] border border-divider-deep bg-components-badge-bg-dimm px-1.5 py-0.5 system-2xs-medium text-text-tertiary uppercase">
{t(($) => $['marketplace.creatorProfile.organization'], { ns: 'plugin' })}
@@ -75,7 +80,7 @@ export default function CreatorSidebar({ profile }: CreatorSidebarProps) {
</p>
)}
{profile.email && (
{profile.email && !isOfficialDifyUrl(`mailto:${profile.email}`) && (
<a
href={`mailto:${profile.email}`}
className="flex min-w-0 items-center gap-1.5 py-1 system-sm-regular text-text-secondary outline-hidden hover:text-text-accent focus-visible:rounded-sm focus-visible:ring-2 focus-visible:ring-state-accent-solid"
@@ -94,7 +99,7 @@ export default function CreatorSidebar({ profile }: CreatorSidebarProps) {
<div className="h-px min-w-0 flex-1 bg-gradient-to-r from-divider-regular to-transparent" />
</div>
<div className="flex flex-col gap-2">
{profile.socialLinks.map((link) => (
{profile.socialLinks.filter((link) => !isOfficialDifyUrl(link.href)).map((link) => (
<a
key={link.href}
href={link.href}
@@ -5,7 +5,6 @@ import { useState } from 'react'
import { useTranslation } from '#i18n'
import Link from '@/next/link'
import HomeCatalogTabs from '../home/home-catalog-tabs'
import HomeGuide from '../home/home-guide'
import { MarketplaceSearchAutocomplete } from '../home/marketplace-search-autocomplete'
import { MarketplaceLogo } from '../marketplace-logo'
@@ -51,12 +50,7 @@ export default function CreatorProfileHeader({
/>
</div>
<div className="flex min-w-0 flex-1 items-center justify-end gap-2.5">
<div className="hidden md:block">
<HomeGuide isMarketplacePlatform={false} />
</div>
{actions}
</div>
<div className="flex min-w-0 flex-1 items-center justify-end gap-2.5">{actions}</div>
</header>
)
}
@@ -1,12 +1,10 @@
'use client'
import type { MotionValue } from 'motion/react'
import { Separator } from '@langgenius/dify-ui/separator'
import { motion, useMotionValue, useSpring, useTransform } from 'motion/react'
import { useEffect, useLayoutEffect, useRef } from 'react'
import { useLocale, useTranslation } from '#i18n'
import { DifyLogo } from '@/app/components/base/logo/dify-logo'
import { SubmitRequestMenu } from '@/app/components/plugins/plugin-page/nav-operations'
import { MARKETPLACE_CONTAINER_ID } from '../constants'
import PluginTypeSwitch from '../plugin-type-switch'
import { MarketplaceSearchInput } from '../search-input'
@@ -239,10 +237,6 @@ const Description = ({
</div>
</div>
<MarketplaceSearchInput className="w-64 shrink-0" />
<div className="flex h-full shrink-0 items-center justify-end gap-4 pr-3.5 pl-4">
<Separator decorative orientation="vertical" className="mx-0 h-4" />
<SubmitRequestMenu dividerAfterFirst />
</div>
</div>
</div>
)
@@ -0,0 +1,55 @@
import { render, screen } from '@testing-library/react'
import { afterEach, describe, expect, it, vi } from 'vite-plus/test'
import { createMarketplacePluginFixture } from '@/test/fixtures/plugin'
import MarketplaceLocalDetail from '../local-detail'
const plugin = createMarketplacePluginFixture()
describe('MarketplaceLocalDetail', () => {
afterEach(() => {
vi.unstubAllGlobals()
})
it('shows the plugin tools from the marketplace detail payload', async () => {
vi.stubGlobal(
'fetch',
vi.fn(async () => ({
ok: true,
json: async () => ({
data: {
plugin: {
introduction: '# Perplexity overview',
latest_version: '1.0.10',
tool: {
tools: [
{
identity: {
name: 'perplexity',
label: { en_US: 'Perplexity Search' },
description: { en_US: 'Search the web' },
},
},
],
},
},
},
}),
})),
)
render(
<MarketplaceLocalDetail
open
isInstalled={false}
plugin={plugin}
title="Plugin A · detail"
onOpenChange={vi.fn()}
/>,
)
expect(screen.getByRole('dialog', { name: /Plugin A/ })).toBeInTheDocument()
expect(await screen.findByText('Perplexity Search')).toBeInTheDocument()
expect(screen.getByText('Search the web')).toBeInTheDocument()
expect(await screen.findByText('Perplexity overview')).toBeInTheDocument()
})
})
@@ -7,7 +7,9 @@ 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 { marketplaceLinks } from '@/features/marketplace/links'
import { isOfficialDifyUrl } from '@/utils/official-link'
import MarketplaceDetailDialogFrame from './frame'
import MarketplaceLocalDetail from './local-detail'
import { useSilentMarketplaceInstall } from './use-silent-install'
const MARKETPLACE_INSTALL_MESSAGE_TYPE = 'dify-marketplace:install-plugin'
@@ -137,6 +139,18 @@ function MarketplaceDetailDialog({
})
const title = `${pluginLabel} · ${detailLabel}`
if (isOfficialDifyUrl(detailURL)) {
return (
<MarketplaceLocalDetail
open={open}
plugin={plugin}
title={title}
isInstalled={isInstalled}
onOpenChange={onOpenChange}
/>
)
}
if (!open) {
return (
<MarketplaceDetailDialogFrame
@@ -0,0 +1,188 @@
'use client'
import type { Plugin } from '@/app/components/plugins/types'
import { Button } from '@langgenius/dify-ui/button'
import { Dialog, DialogClose, DialogContent, DialogTitle } from '@langgenius/dify-ui/dialog'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { useEffect, useState } from 'react'
import { useTranslation } from '#i18n'
import { Markdown } from '@/app/components/base/markdown'
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 { getPluginIconInMarketplace } from '@/app/components/plugins/marketplace/utils'
import { useGetLanguage } from '@/context/i18n'
import { getMarketplaceApiUrl } from '@/features/marketplace/api'
import { renderI18nObject } from '@/i18n/metadata'
type ToolIdentity = {
name?: string
label?: Record<string, string>
description?: Record<string, string>
}
type PluginDetailPayload = {
introduction?: string
latest_version?: string
install_count?: number
tool?: {
tools?: Array<{ identity?: ToolIdentity }>
}
}
type MarketplaceLocalDetailProps = {
open: boolean
plugin: Plugin
title: string
isInstalled: boolean
onOpenChange: (open: boolean) => void
}
const readPluginDetail = (payload: unknown): PluginDetailPayload | null => {
if (!payload || typeof payload !== 'object') return null
const data = 'data' in payload ? payload.data : payload
if (!data || typeof data !== 'object') return null
const plugin = 'plugin' in data ? data.plugin : data
if (!plugin || typeof plugin !== 'object') return null
return plugin as PluginDetailPayload
}
export default function MarketplaceLocalDetail({
open,
plugin,
title,
isInstalled,
onOpenChange,
}: MarketplaceLocalDetailProps) {
const { t } = useTranslation(['common', 'plugin', 'tools'])
const locale = useGetLanguage()
const { canInstallPlugin } = useOptionalPluginInstallPermission()
const [detail, setDetail] = useState<PluginDetailPayload | null>(null)
const [failed, setFailed] = useState(false)
const [showInstall, setShowInstall] = useState(false)
const label = renderI18nObject(plugin.label, locale) || plugin.name
const brief = renderI18nObject(plugin.brief, locale)
const introduction = detail?.introduction?.trim() || ''
const tools = (detail?.tool?.tools ?? [])
.map((tool) => {
const identity = tool.identity
const name = renderI18nObject(identity?.label, locale) || identity?.name || ''
const description = renderI18nObject(identity?.description, locale)
return name ? { name, description } : null
})
.filter((tool): tool is { name: string; description: string } => tool !== null)
useEffect(() => {
if (!open) return
const controller = new AbortController()
const url = getMarketplaceApiUrl(
`plugins/${encodeURIComponent(plugin.org)}/${encodeURIComponent(plugin.name)}`,
)
setDetail(null)
setFailed(false)
void fetch(url, { signal: controller.signal })
.then(async (response) => {
if (!response.ok) throw new Error('plugin detail unavailable')
return readPluginDetail(await response.json())
})
.then((next) => {
if (!next) throw new Error('plugin detail unavailable')
setDetail(next)
})
.catch((error: unknown) => {
if (error instanceof DOMException && error.name === 'AbortError') return
setFailed(true)
})
return () => controller.abort()
}, [open, plugin.name, plugin.org])
return (
<>
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="flex max-h-[min(800px,calc(100dvh-48px))] w-[min(760px,calc(100vw-48px))] flex-col overflow-hidden">
<div className="flex items-start gap-3 px-6 pt-5 pe-14">
<img
src={getPluginIconInMarketplace(plugin)}
alt=""
className="size-12 shrink-0 rounded-xl border border-divider-subtle bg-background-default-subtle object-cover"
/>
<div className="min-w-0">
<DialogTitle className="system-md-semibold text-text-primary">{label}</DialogTitle>
<p className="mt-1 system-xs-regular text-text-tertiary">
{plugin.org} / {plugin.name}
{detail?.latest_version ? ` · ${detail.latest_version}` : ''}
</p>
</div>
</div>
<DialogClose
render={
<IconButton
aria-label={t(($) => $['operation.close'], { ns: 'common' })}
size="lg"
className="absolute top-5 right-5"
onClick={() => onOpenChange(false)}
>
<span aria-hidden className="i-ri-close-line size-4" />
</IconButton>
}
/>
<div className="min-h-0 flex-1 overflow-y-auto px-6 py-5">
{brief && <p className="mb-4 system-sm-regular text-text-secondary">{brief}</p>}
{tools.length > 0 && (
<section className="mb-5">
<h3 className="mb-2 system-xs-medium text-text-tertiary">
{t(($) => $['mcp.toolsNum'], { ns: 'tools', count: tools.length })}
</h3>
<ul className="flex flex-col gap-2">
{tools.map((tool) => (
<li
key={tool.name}
className="rounded-xl border border-divider-subtle bg-background-section-burn px-3 py-2"
>
<p className="system-sm-medium text-text-primary">{tool.name}</p>
{tool.description && (
<p className="mt-0.5 system-xs-regular text-text-tertiary">
{tool.description}
</p>
)}
</li>
))}
</ul>
</section>
)}
{introduction ? (
<Markdown content={introduction} />
) : (
failed && (
<p className="system-sm-regular text-text-tertiary">
{t(($) => $['readmeInfo.failedToFetch'], { ns: 'plugin' })}
</p>
)
)}
</div>
{canInstallPlugin && !isInstalled && (
<div className="flex justify-end border-t border-divider-subtle px-6 py-4">
<Button onClick={() => setShowInstall(true)}>
{t(($) => $['detailPanel.operation.install'], { ns: 'plugin' })}
</Button>
</div>
)}
<span className="sr-only">{title}</span>
</DialogContent>
</Dialog>
{showInstall && (
<InstallFromMarketplace
manifest={plugin}
uniqueIdentifier={plugin.latest_package_identifier}
onClose={() => setShowInstall(false)}
onSuccess={() => {
setShowInstall(false)
onOpenChange(false)
}}
/>
)}
</>
)
}
@@ -208,19 +208,9 @@ describe('EmbeddedMarketplaceSearch', () => {
const option = await screen.findByRole('option')
if (interaction === 'mouse') await user.click(option)
else await user.keyboard('{ArrowDown}{Enter}')
expect(open).toHaveBeenCalledTimes(1)
const [href, target, features] = open.mock.calls[0]!
const url = new URL(String(href))
expect(url.origin).toBe('https://marketplace.dify.ai')
expect(url.pathname).toBe(
kind === 'plugin' ? '/plugin/langgenius/google-search' : '/template/dify/template-1',
)
expect(url.searchParams.get('source')).toBe(window.location.origin)
expect(target).toBe('_blank')
expect(features).toBe('noopener,noreferrer')
expect(input).toHaveValue('search')
expect(open).not.toHaveBeenCalled()
expect(onUrlUpdate).not.toHaveBeenCalled()
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
expect(await screen.findByRole('dialog')).toBeInTheDocument()
},
)
})
@@ -47,37 +47,13 @@ describe('HomeHeader', () => {
mocks.marketplaceUrlPrefix = 'https://marketplace.dify.ai'
})
it('keeps Creator Center and docs in the in-app header', () => {
it('does not link the header to Creator Center or the official guide', () => {
render(<HomeHeader isMarketplacePlatform={false} />)
expect(screen.getByRole('link', { name: 'marketplace.home.creatorCenter' })).toBeInTheDocument()
expect(screen.getByRole('button', { name: /marketplace\.home\.guide/ })).toBeInTheDocument()
})
it('links Creator Center alongside the docs dropdown', () => {
render(<HomeHeader isMarketplacePlatform />)
const creatorCenterLink = screen.getByRole('link', { name: 'marketplace.home.creatorCenter' })
expect(screen.getByRole('button', { name: /marketplace\.home\.guide/ })).toBeInTheDocument()
expect(creatorCenterLink).toHaveAttribute('href', 'https://creators.dify.ai/')
expect(creatorCenterLink).toHaveAttribute('target', '_blank')
expect(creatorCenterLink).toHaveAttribute('rel', 'noopener noreferrer')
// Creator Center must be a single interactive element, not a link-wrapped button.
expect(creatorCenterLink.querySelector('button')).toBeNull()
expect(screen.queryByRole('link', { name: 'marketplace.home.guide' })).not.toBeInTheDocument()
})
it('links Creator Center to the staging Creators site in staging', () => {
mocks.marketplaceUrlPrefix = 'https://marketplace-staging.dify.dev'
render(<HomeHeader isMarketplacePlatform />)
expect(screen.getByRole('link', { name: 'marketplace.home.creatorCenter' })).toHaveAttribute(
'href',
'https://creators-staging.dify.dev/',
)
expect(
screen.queryByRole('link', { name: 'marketplace.home.creatorCenter' }),
).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: /marketplace\.home\.guide/ })).not.toBeInTheDocument()
})
it('selects neither catalog tab on non-catalog pages', () => {
@@ -220,21 +220,14 @@ describe('HomeTrending', () => {
expect(screen.getByRole('heading', { name: 'Dify v1.9 new launch' })).toBeInTheDocument()
const blogSlide = screen.getByRole('group', { name: 'Dify Updates' })
const blogLink = within(blogSlide).getByRole('link', {
name: /^plugin\.marketplace\.home\.trendingReadMoreAbout/,
})
expect(blogLink).toHaveAttribute('href', 'https://dify.ai/blog')
expect(within(blogSlide).getAllByRole('link')).toHaveLength(1)
expect(within(blogSlide).queryByRole('link')).not.toBeInTheDocument()
expect(
within(blogLink).getByRole('heading', { name: 'Dify v1.9 new launch' }),
within(blogSlide).getByRole('heading', { name: 'Dify v1.9 new launch' }),
).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Duck Duck Go' }))
expect(screen.getByRole('link', { name: 'DuckDuckGo plugin' })).toHaveAttribute(
'href',
'https://marketplace.dify.ai/plugin/langgenius/duckduckgo',
)
expect(screen.queryByRole('link', { name: 'DuckDuckGo plugin' })).not.toBeInTheDocument()
})
it('renders the delivered blog cover instead of bundled art', () => {
@@ -255,10 +248,8 @@ describe('HomeTrending', () => {
render(<HomeTrending banners={[blogBanner]} isMarketplacePlatform page="plugins" />)
const blogLink = screen.getByRole('link', {
name: /^plugin\.marketplace\.home\.trendingReadMoreAbout/,
})
expect(blogLink.querySelector('img')?.getAttribute('src')).toContain(
const blogSlide = screen.getByRole('group', { name: 'Research' })
expect(blogSlide.querySelector('img')?.getAttribute('src')).toContain(
'/api/v1/banners/images/banners/trust-cover.png',
)
})
@@ -266,10 +257,8 @@ describe('HomeTrending', () => {
it('omits blog cover art when the payload has no cover_image', () => {
render(<HomeTrending banners={[banners[1]!]} isMarketplacePlatform page="plugins" />)
const blogLink = screen.getByRole('link', {
name: /^plugin\.marketplace\.home\.trendingReadMoreAbout/,
})
expect(blogLink.querySelector('img')).toBeNull()
const blogSlide = screen.getByRole('group', { name: 'Dify Updates' })
expect(blogSlide.querySelector('img')).toBeNull()
})
it('keeps only the selected slide in the accessibility tree', async () => {
@@ -999,34 +988,22 @@ describe('HomeTrending', () => {
)
})
it('tracks whole-slide blog and event links as frame clicks', async () => {
it('does not link official blog and event banners', async () => {
const user = userEvent.setup()
render(<HomeTrending banners={banners} isMarketplacePlatform page="plugins" />)
await user.click(screen.getByRole('button', { name: 'Dify Updates' }))
await user.click(
screen.getByRole('link', { name: /^plugin\.marketplace\.home\.trendingReadMoreAbout/ }),
)
expect(mockTrackEvent).toHaveBeenCalledWith('marketplace_banner_click', {
banner_id: 'blog',
sort: 1,
page: 'plugins',
language: 'en',
style_type: 'blog',
})
expect(
screen.queryByRole('link', { name: /^plugin\.marketplace\.home\.trendingReadMoreAbout/ }),
).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Duck Duck Go' }))
await user.click(screen.getByRole('link', { name: 'DuckDuckGo plugin' }))
expect(mockTrackEvent).toHaveBeenCalledWith('marketplace_banner_click', {
banner_id: 'event',
sort: 2,
page: 'plugins',
language: 'en',
style_type: 'event',
})
expect(screen.queryByRole('link', { name: 'DuckDuckGo plugin' })).not.toBeInTheDocument()
expect(mockTrackEvent).not.toHaveBeenCalledWith(
'marketplace_banner_click',
expect.objectContaining({ style_type: 'blog' }),
)
})
it('does not render banner slides whose CMS link is not http(s) or relative', () => {
@@ -1083,7 +1060,7 @@ describe('HomeTrending', () => {
}
})
it.each(['COMMUNITY', 'ENTERPRISE'] as const)(
'links %s recommendations directly to the official site',
'keeps %s recommendations inside the app',
(edition) => {
const mixedBanner: PluginBanner = {
id: 'mixed',
@@ -1116,20 +1093,10 @@ describe('HomeTrending', () => {
<HomeTrending banners={[mixedBanner]} isMarketplacePlatform={false} page="plugins" />,
{ systemFeatures: { deployment_edition: edition } },
)
const links = [
screen.getByRole('link', { name: 'Dropbox' }),
screen.getByRole('link', { name: 'Support Bot' }),
]
expect(new URL(links[0]!.getAttribute('href')!).pathname).toBe('/plugin/langgenius/dropbox')
expect(new URL(links[1]!.getAttribute('href')!).pathname).toBe('/template/aisa-team/tpl-1')
for (const link of links)
expect(new URL(link.getAttribute('href')!).origin).toBe('https://marketplace.dify.ai')
for (const link of links) {
expect(link).toHaveAttribute('target', '_blank')
expect(new URL(link.getAttribute('href')!).searchParams.get('source')).toBe(
window.location.origin,
)
}
expect(screen.getByRole('button', { name: 'Dropbox' })).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Support Bot' })).toBeInTheDocument()
expect(screen.queryByRole('link', { name: 'Dropbox' })).not.toBeInTheDocument()
expect(screen.queryByRole('link', { name: 'Support Bot' })).not.toBeInTheDocument()
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
},
)
@@ -5,12 +5,14 @@ import { cn } from '@langgenius/dify-ui/cn'
import { useTranslation } from '#i18n'
import Link from '@/next/link'
import { trackMarketplaceSiteEvent } from '@/utils/marketplace-site-track'
import { isOfficialDifyUrl } from '@/utils/official-link'
import { useCreatorCenterUrl } from '../creator-center-url'
export default function HomeCreatorCenter() {
const { t } = useTranslation(['plugin'])
const creatorCenterUrl = useCreatorCenterUrl()
const label = t(($) => $['marketplace.home.creatorCenter'])
if (!creatorCenterUrl || isOfficialDifyUrl(creatorCenterUrl)) return null
return (
<Link
@@ -1,13 +1,8 @@
import type { HomeCatalogTab, HomeCatalogTabLabels } from './home-catalog-tabs'
import { cn } from '@langgenius/dify-ui/cn'
import Link from '@/next/link'
import { MarketplaceLogo } from '../marketplace-logo'
import HomeCatalogTabs from './home-catalog-tabs'
import { HOME_HEADER_HEIGHT_PX } from './home-constants'
// HomeCreatorCenter stays in its own client module: it derives styles via
// buttonVariants(), which cannot be invoked inside this server component.
import HomeCreatorCenter from './home-creator-center'
import HomeGuide from './home-guide'
import { HomeStickyCatalogTabs } from './home-sticky-state-provider'
import styles from './home-sticky.module.css'
@@ -53,15 +48,6 @@ const HomeHeader = ({
</div>
<div className="flex h-full min-w-0 flex-1 items-center justify-end gap-2.5">
<div
className={cn(
'flex min-w-0 items-center gap-2.5',
isMarketplacePlatform && styles.standaloneHeaderActions,
)}
>
<HomeCreatorCenter />
<HomeGuide isMarketplacePlatform={isMarketplacePlatform} />
</div>
{actions}
</div>
</header>
@@ -12,7 +12,7 @@ import type {
import type { MarketplaceBannerPage } from './banners'
import type { Plugin } from '@/app/components/plugins/types'
import { cn } from '@langgenius/dify-ui/cn'
import { useState } from 'react'
import { useState, type ReactNode } from 'react'
import { useTranslation } from '#i18n'
import { trackEvent } from '@/app/components/base/amplitude'
import Partner from '@/app/components/plugins/base/badges/partner'
@@ -29,6 +29,8 @@ import Link from '@/next/link'
import { useRouter } from '@/next/navigation'
import { fetchPluginInfoFromMarketPlace } from '@/service/plugins'
import { resolveEmoji } from '@/utils/emoji'
import { isOfficialDifyUrl } from '@/utils/official-link'
import { visibleAuthorName } from '@/utils/visible-author'
import {
rememberMarketplaceSiteReferrer,
trackMarketplaceSiteEvent,
@@ -151,7 +153,7 @@ const getLocalCardHref = (card: BannerRecommendCard) => {
const getCardHref = (card: BannerRecommendCard, isMarketplacePlatform: boolean) => {
if (isMarketplacePlatform) return getLocalCardHref(card)
const deliveryHref = card.link ? sanitizeMarketplaceHref(card.link) : null
if (deliveryHref) return deliveryHref
if (deliveryHref && !isOfficialDifyUrl(deliveryHref)) return deliveryHref
return getLocalCardHref(card)
}
@@ -255,7 +257,7 @@ function trackRecommendCardClick(
function RecommendCardFace({ card }: { card: BannerRecommendCard }) {
const { t } = useTranslation(['plugin'])
const iconURL = resolveMarketplaceAssetUrl(card.icon_url)
const creator = getCardCreator(card)
const creator = visibleAuthorName(getCardCreator(card))
const isPartner = card.badges?.includes('partner')
const isVerified = card.badges?.includes('verified')
@@ -581,6 +583,36 @@ function TrendingRecommendationSlide({
)
}
function SlideFrame({
href,
className,
label,
onClick,
children,
}: {
href: string | null
className: string
label: string
onClick: () => void
children: ReactNode
}) {
if (!href) return <div className={className}>{children}</div>
const opensInNewTab = /^https?:\/\//.test(href)
return (
<Link
href={href}
target={opensInNewTab ? '_blank' : undefined}
rel={opensInNewTab ? 'noopener noreferrer' : undefined}
aria-label={label}
className={className}
onClick={onClick}
>
{children}
</Link>
)
}
function BlogBannerSlide({
banner,
isMarketplacePlatform,
@@ -591,21 +623,18 @@ function BlogBannerSlide({
page: MarketplaceBannerPage
}) {
const { t } = useTranslation(['plugin'])
const href = sanitizeMarketplaceHref(banner.content.link)
if (!href) return null
const opensInNewTab = /^https?:\/\//.test(href)
const sanitized = sanitizeMarketplaceHref(banner.content.link)
if (!sanitized || isOfficialDifyUrl(sanitized)) return null
const coverSrc = resolveMarketplaceAssetUrl(banner.content.cover_image)
return (
<Link
href={href}
target={opensInNewTab ? '_blank' : undefined}
rel={opensInNewTab ? 'noopener noreferrer' : undefined}
<SlideFrame
href={sanitized}
onClick={() => {
trackEvent('marketplace_banner_click', getBannerFrameProps(banner, page))
trackMarketplaceBannerClick(banner)
}}
aria-label={t(($) => $['marketplace.home.trendingReadMoreAbout'], {
label={t(($) => $['marketplace.home.trendingReadMoreAbout'], {
title: banner.content.blog_title,
})}
className={cn(
@@ -693,7 +722,7 @@ function BlogBannerSlide({
)}
/>
) : null}
</Link>
</SlideFrame>
)
}
@@ -706,8 +735,8 @@ function ImageBannerSlide({
isMarketplacePlatform: boolean
page: MarketplaceBannerPage
}) {
const href = sanitizeMarketplaceHref(banner.content.link)
if (!href) return null
const sanitized = sanitizeMarketplaceHref(banner.content.link)
if (!sanitized || isOfficialDifyUrl(sanitized)) return null
const resolved = resolveEventAdBannerImageSrcs({
desktop: resolveMarketplaceAssetUrl(banner.content.images.desktop),
tablet: resolveMarketplaceAssetUrl(banner.content.images.tablet) || undefined,
@@ -715,15 +744,13 @@ function ImageBannerSlide({
})
return (
<Link
href={href}
target="_blank"
rel="noopener noreferrer"
<SlideFrame
href={sanitized}
onClick={() => {
trackEvent('marketplace_banner_click', getBannerFrameProps(banner, page))
trackMarketplaceBannerClick(banner)
}}
aria-label={banner.content.alt_text || banner.title}
label={banner.content.alt_text || banner.title}
className={cn(
'block h-[200px] w-full overflow-hidden rounded-2xl outline-hidden focus-visible:ring-2 focus-visible:ring-state-accent-solid',
isMarketplacePlatform && styles.imageSlide,
@@ -751,7 +778,7 @@ function ImageBannerSlide({
className="size-full object-cover object-left"
/>
</picture>
</Link>
</SlideFrame>
)
}
@@ -31,6 +31,7 @@ import { getPluginDetailPath, getTemplateDetailPath } from '@/features/marketpla
import { renderI18nObject } from '@/i18n/metadata'
import { marketplaceQuery } from '@/service/marketplace'
import { markMarketplaceSiteSearch } from '@/utils/marketplace-site-track'
import { visibleAuthorName } from '@/utils/visible-author'
import { getPluginIconInMarketplace } from '../utils'
type MarketplaceSearchScope = 'all' | 'plugins' | 'templates'
@@ -80,7 +81,7 @@ const toTemplateSuggestion = (template: MarketplaceTemplate): MarketplaceSuggest
id: `template:${template.id}`,
kind: 'template',
label: template.template_name,
meta: template.publisher_handle || template.publisher_unique_handle || '',
meta: visibleAuthorName(template.publisher_handle || template.publisher_unique_handle),
selection: { kind: 'template', template },
})
@@ -90,7 +91,7 @@ const toPluginSuggestion = (plugin: MarketplacePlugin, locale: string): Marketpl
id: `plugin:${plugin.org}/${plugin.name}`,
kind: 'plugin',
label: getPluginText(plugin.label, locale) || plugin.name,
meta: plugin.org,
meta: visibleAuthorName(plugin.org),
selection: { kind: 'plugin', plugin },
})
@@ -154,24 +154,13 @@ describe('CardWrapper', () => {
})
it.each(['COMMUNITY', 'ENTERPRISE'] as const)(
'links %s plugin details to the official site while preserving direct installation',
'opens %s plugin details in the app while preserving direct installation',
async (edition) => {
const user = userEvent.setup()
renderCardWrapper({ showInstallButton: true }, edition)
const card = screen.getByRole('link', { name: 'Plugin A' })
const url = new URL(card.getAttribute('href')!)
expect(url.origin).toBe('https://marketplace.dify.ai')
expect(url.pathname).toBe('/plugin/dify/plugin-a')
expect(url.searchParams.get('source')).toBe(window.location.origin)
expect(url.searchParams.get('theme')).toBe('dark')
expect(card).toHaveAttribute('target', '_blank')
expect(card).toHaveAttribute('rel', 'noopener noreferrer')
expect(
screen.getByRole('link', { name: 'plugin.detailPanel.operation.detail' }),
).toHaveAttribute('href', url.toString())
expect(screen.queryByTitle(detailTitle)).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'plugin.detailPanel.operation.install' }))
expect(await screen.findByRole('dialog', { name: installTitle })).toBeInTheDocument()
expect(screen.queryByRole('link', { name: 'Plugin A' })).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Plugin A' }))
expect(await screen.findByRole('dialog', { name: detailTitle })).toBeInTheDocument()
},
)
@@ -168,14 +168,9 @@ describe('ListWithCollection', () => {
/>,
)
const partnerLink = screen.getByRole('link', { name: 'plugin.marketplace.becomePartner' })
expect(partnerLink).toHaveAttribute(
'href',
'https://share-na2.hsforms.com/1NiS4r9lsSqGcuNBB77DeEQ40s9fk',
)
expect(partnerLink).toHaveAttribute('target', '_blank')
expect(partnerLink).toHaveAttribute('rel', 'noopener noreferrer')
expect(
screen.queryByRole('link', { name: 'plugin.marketplace.becomePartner' }),
).not.toBeInTheDocument()
expect(
screen.getAllByText(/^(?:Plugin (?:One|Two)|Partner Plugin|Featured Plugin)$/),
).toHaveLength(2)
@@ -12,6 +12,7 @@ import { useOptionalPluginInstallPermission } from '@/app/components/plugins/ins
import InstallFromMarketplace from '@/app/components/plugins/install-plugin/install-from-marketplace'
import { useGetLanguage } from '@/context/i18n'
import { getPluginDetailPath } from '@/features/marketplace/links'
import { isOfficialDifyUrl } from '@/utils/official-link'
import { renderI18nObject } from '@/i18n/metadata'
import Link from '@/next/link'
import { trackMarketplaceSiteCardClick } from '@/utils/marketplace-site-track'
@@ -31,8 +32,8 @@ const CardWrapperContent = ({
isInstalled = false,
linkToMarketplaceDetail = false,
section = 'list',
externalDetailHref,
}: CardWrapperProps & { externalDetailHref?: string }) => {
detailHref: externalDetailHref,
}: CardWrapperProps & { detailHref?: string }) => {
const { t } = useTranslation(['plugin'])
const locale = useGetLanguage()
const [
@@ -46,6 +47,8 @@ const CardWrapperContent = ({
const { canInstallPlugin } = useOptionalPluginInstallPermission()
const { getTagLabel } = useTags()
const pluginLabel = renderI18nObject(plugin.label, locale) || plugin.name
const detailHref =
externalDetailHref && !isOfficialDifyUrl(externalDetailHref) ? externalDetailHref : undefined
// Memoize tag labels to prevent recreating array on every render
const tagLabels = useMemo(
@@ -96,9 +99,9 @@ const CardWrapperContent = ({
className="group relative cursor-pointer rounded-xl"
data-marketplace-card={plugin.plugin_id}
>
{externalDetailHref ? (
{detailHref ? (
<a
href={externalDetailHref}
href={detailHref}
target="_blank"
rel="noopener noreferrer"
aria-label={pluginLabel}
@@ -128,9 +131,9 @@ const CardWrapperContent = ({
? t(($) => $['task.installed'], { ns: 'plugin' })
: t(($) => $['detailPanel.operation.install'], { ns: 'plugin' })}
</Button>
{externalDetailHref ? (
{detailHref ? (
<a
href={externalDetailHref}
href={detailHref}
target="_blank"
rel="noopener noreferrer"
className={buttonVariants({
@@ -152,7 +155,7 @@ const CardWrapperContent = ({
)}
</div>
)}
{!externalDetailHref && (
{!detailHref && (
<MarketplaceDetailDialog
isInstalled={isInstalled}
open={isShowMarketplaceDetail}
@@ -174,7 +177,7 @@ const CardWrapperContent = ({
function DifyCardWrapper(props: CardWrapperProps) {
const navigation = useMarketplaceDetailNavigation()
return <CardWrapperContent {...props} externalDetailHref={navigation.pluginHref(props.plugin)} />
return <CardWrapperContent {...props} detailHref={navigation.pluginHref(props.plugin)} />
}
function CardWrapperComponent(props: CardWrapperProps) {
@@ -6,13 +6,12 @@ import { cn } from '@langgenius/dify-ui/cn'
import { useEffect, useId, useMemo, useRef, useState } from 'react'
import { useLocale, useTranslation } from '#i18n'
import { getPluginLanguage } from '@/i18n/metadata'
import { trackMarketplaceSiteEvent } from '@/utils/marketplace-site-track'
import { useMarketplaceMoreClick } from '../atoms'
import { MARKETPLACE_CONTAINER_ID } from '../constants'
import { buildCarouselPages } from '../utils'
import CardWrapper from './card-wrapper'
import Carousel from './carousel'
import { BECOME_PARTNER_URL, GRID_CLASS, PARTNER_COLLECTION_NAMES } from './collection-constants'
import { GRID_CLASS, PARTNER_COLLECTION_NAMES } from './collection-constants'
import styles from './partner-header.module.css'
import { useCarouselItemsPerPage } from './use-carousel-items-per-page'
@@ -211,36 +210,6 @@ const CollectionSection = ({
) : (
collection.description[getPluginLanguage(locale)]
)}
{isPartnersCollection && (
<>
<span className={cn(styles.partnerSeparator, 'text-divider-regular')}>|</span>
<a
href={BECOME_PARTNER_URL}
target="_blank"
rel="noopener noreferrer"
className={cn(
styles.partnerAction,
'flex items-center gap-x-0.5 text-text-accent hover:underline',
)}
onClick={() => {
trackMarketplaceSiteEvent('marketplace_creator_partner_click', {
click_target: 'Become a Partner',
})
}}
>
<span className={styles.partnerActionLabel}>
{t(($) => $['marketplace.becomePartner'], { ns: 'plugin' })}
</span>
<span
aria-hidden
className={cn(
styles.partnerActionIcon,
'i-ri-external-link-line size-3 [&:dir(rtl)]:-scale-x-100',
)}
/>
</a>
</>
)}
</div>
</div>
{collection.searchable && !hasMultiplePages && (
@@ -132,7 +132,7 @@ describe('TemplateCard', () => {
}),
)
expect(mockPush).toHaveBeenCalledWith('/apps?template-id=template%2Fone')
expect(screen.getByText('dify')).toBeInTheDocument()
expect(screen.queryByText('dify')).not.toBeInTheDocument()
expect(screen.getByText('1.2k')).toBeInTheDocument()
expect(screen.getByText('Verified by a Dify partner')).toBeInTheDocument()
})
@@ -156,32 +156,20 @@ describe('TemplateCard', () => {
expect(screen.getByRole('dialog')).toBeInTheDocument()
})
it.each(['COMMUNITY', 'ENTERPRISE'] as const)(
'opens %s template links outside Dify without changing the catalog route',
(edition) => {
'opens %s template details in the app',
async (edition) => {
const user = userEvent.setup()
deploymentState.deploymentEdition = edition
;(window as unknown as Window).happyDOM.setURL(
'https://ai.njueai.com:8443/templates?q=research',
)
const before = window.location.href
render(
<TemplateDetailRouteProvider>
<TemplateCard partnerText="Partner" template={template} />
</TemplateDetailRouteProvider>,
)
const link = screen.getByRole('link', { name: template.template_name })
const url = new URL(link.getAttribute('href')!)
expect(url.origin).toBe('https://marketplace.dify.ai')
expect(url.pathname).toBe('/template/dify/template%2Fone')
expect(Object.fromEntries(url.searchParams)).toEqual({
source: window.location.origin,
language: 'en-US',
theme: 'dark',
})
expect(link).toHaveAttribute('target', '_blank')
expect(link).toHaveAttribute('rel', 'noopener noreferrer')
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
expect(document.querySelector('iframe')).toBeNull()
expect(window.location.href).toBe(before)
expect(
screen.queryByRole('link', { name: template.template_name }),
).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: template.template_name }))
expect(screen.getByRole('dialog')).toBeInTheDocument()
},
)
})
@@ -113,7 +113,7 @@ describe('TemplateDetailRouteProvider', () => {
expect(window.location.pathname).toBe('/templates/marketing')
})
it.each(['COMMUNITY', 'ENTERPRISE'] as const)(
'replaces a legacy %s template detail URL with its official detail',
'keeps a legacy %s template detail inside the app',
(edition) => {
deploymentState.deploymentEdition = edition
window.history.replaceState(window.history.state, '', `/templates/dify/${id}`)
@@ -123,13 +123,8 @@ describe('TemplateDetailRouteProvider', () => {
<span>catalog</span>
</TemplateDetailRouteProvider>,
)
expect(replace).toHaveBeenCalledOnce()
const url = new URL(replace.mock.calls[0]![0])
expect(url.origin).toBe('https://marketplace.dify.ai')
expect(url.pathname).toBe(`/template/dify/${id}`)
expect(url.searchParams.get('source')).toBe(window.location.origin)
expect(url.searchParams.has('view')).toBe(false)
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
expect(replace).not.toHaveBeenCalled()
expect(screen.getByRole('dialog')).toBeInTheDocument()
replace.mockRestore()
},
)
@@ -12,6 +12,8 @@ import {
} from '@/features/marketplace/api'
import { useRouter } from '@/next/navigation'
import { formatNumberAbbreviated } from '@/utils/format'
import { isOfficialDifyUrl } from '@/utils/official-link'
import { visibleAuthorName } from '@/utils/visible-author'
import { useMarketplaceDetailNavigation } from '../use-detail-navigation'
import TemplateDetailDialog from './template-detail-dialog'
import { useOptionalTemplateDetailRoute } from './use-optional-template-detail-route'
@@ -30,8 +32,9 @@ export default function TemplateCard({ template, className, partnerText }: Templ
const externalHref = navigation.templateHref(template)
const templateDetailRoute = useOptionalTemplateDetailRoute()
const [isDetailOpen, { setTrue: showDetail, setFalse: hideDetail }] = useBoolean(false)
const publisher =
template.publisher_handle || template.publisher_unique_handle || template.creator_email || ''
const publisher = visibleAuthorName(
template.publisher_handle || template.publisher_unique_handle || template.creator_email,
)
const visiblePlugins = template.deps_plugins?.slice(0, MAX_VISIBLE_PLUGIN_DEPENDENCIES) ?? []
const remainingPluginCount = Math.max(
0,
@@ -60,7 +63,7 @@ export default function TemplateCard({ template, className, partnerText }: Templ
className,
)}
>
{externalHref ? (
{externalHref && !isOfficialDifyUrl(externalHref) ? (
<a
href={externalHref}
target="_blank"
Loaded 100 of 211 files, more files were not shown because too many files have changed in this diff. Show more