Skip to content

armgit / dify

Public Imported from GitHub
0

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

feat(marketplace): use stable template UUID links in the Dify embed (#42172)

Coding On Starbad3a868160e
diff --git a/web/app/(commonLayout)/templates/[[...category]]/__tests__/page.spec.tsx b/web/app/(commonLayout)/templates/[[...category]]/__tests__/page.spec.tsx
index edb97129952..2f1c403ebb0 100644
--- a/web/app/(commonLayout)/templates/[[...category]]/__tests__/page.spec.tsx
+++ b/web/app/(commonLayout)/templates/[[...category]]/__tests__/page.spec.tsx
@@ -1,4 +1,4 @@
-import type { FunctionComponent, ReactElement } from 'react'
+import type { FunctionComponent, ReactElement, ReactNode } from 'react'
import { readFileSync } from 'node:fs'
import { dirname, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
@@ -21,6 +21,20 @@ const resolveTemplatesPage = async (props: TemplatesPageProps) => {
return createElement(tree.type, tree.props, content)
}
+vi.mock('@/app/components/plugins/marketplace/templates/template-detail-route', () => ({
+ TemplateDetailRouteProvider: ({
+ children,
+ initialSelection,
+ }: {
+ children: ReactNode
+ initialSelection?: { id: string }
+ }) => (
+ <div data-testid="template-route" data-template-id={initialSelection?.id ?? ''}>
+ {children}
+ </div>
+ ),
+}))
+
vi.mock('@/app/components/plugins/marketplace/templates', () => ({
EmbeddedTemplatesMarketplace: ({
category,
@@ -79,10 +93,9 @@ describe('embedded templates route', () => {
render(page)
expect(screen.getByText('Templates catalog: all:agent')).toBeInTheDocument()
- expect(screen.getByText('Templates catalog: all:agent').parentElement).toHaveAttribute(
- 'id',
- 'marketplace-container',
- )
+ expect(
+ screen.getByText('Templates catalog: all:agent').closest('#marketplace-container'),
+ ).toBeInTheDocument()
})
it('passes a supported path category to the templates catalog', async () => {
@@ -138,6 +151,19 @@ describe('embedded templates route', () => {
expect(catalog).not.toHaveAttribute('data-view')
})
+ it('opens /templates/{publisher}/{uuid} as the all catalog with a selected template', async () => {
+ const templateId = 'c558a1fb-bb8c-4a5e-9404-d681c6659cf2'
+ const page = await resolveTemplatesPage({
+ params: Promise.resolve({ category: ['langgenius', templateId] }),
+ searchParams: Promise.resolve({}),
+ })
+
+ render(page)
+
+ expect(screen.getByText('Templates catalog: all:')).toBeInTheDocument()
+ expect(screen.getByTestId('template-route')).toHaveAttribute('data-template-id', templateId)
+ })
+
it('opens template recommendations in the existing Dify import flow', async () => {
await expect(
resolveTemplatesPage({
diff --git a/web/app/(commonLayout)/templates/[[...category]]/page.tsx b/web/app/(commonLayout)/templates/[[...category]]/page.tsx
index 4d31ad4a2e0..3a4f554086c 100644
--- a/web/app/(commonLayout)/templates/[[...category]]/page.tsx
+++ b/web/app/(commonLayout)/templates/[[...category]]/page.tsx
@@ -1,6 +1,7 @@
import { MARKETPLACE_CONTAINER_ID } from '@/app/components/plugins/marketplace/constants'
import { EmbeddedTemplatesMarketplace } from '@/app/components/plugins/marketplace/templates'
-import { isTemplateCategory } from '@/app/components/plugins/marketplace/templates/categories'
+import { TemplateDetailRouteProvider } from '@/app/components/plugins/marketplace/templates/template-detail-route'
+import { parseTemplatesRoute } from '@/app/components/plugins/marketplace/templates/template-links'
import { getLocaleOnServer } from '@/i18n-config/server'
import { redirect } from '@/next/navigation'
@@ -60,19 +61,20 @@ async function TemplatesPageContent({ params, searchParams }: TemplatesPageProps
redirect(`/apps?template-id=${encodeURIComponent(resolvedSearchParams.tid)}`)
}
- const requestedCategory = resolvedParams.category?.[0]
- const category = isTemplateCategory(requestedCategory) ? requestedCategory : 'all'
+ const { category, selection } = parseTemplatesRoute(resolvedParams.category)
return (
- <EmbeddedTemplatesMarketplace
- category={category}
- languages={resolvedSearchParams.languages}
- locale={locale}
- page={parsePage(resolvedSearchParams.page)}
- query={resolvedSearchParams.q ?? ''}
- sortBy={parseSortBy(resolvedSearchParams.sort_by)}
- sortOrder={parseSortOrder(resolvedSearchParams.sort_order)}
- view={parseView(resolvedSearchParams.view)}
- />
+ <TemplateDetailRouteProvider initialSelection={selection}>
+ <EmbeddedTemplatesMarketplace
+ category={category}
+ languages={resolvedSearchParams.languages}
+ locale={locale}
+ page={parsePage(resolvedSearchParams.page)}
+ query={resolvedSearchParams.q ?? ''}
+ sortBy={parseSortBy(resolvedSearchParams.sort_by)}
+ sortOrder={parseSortOrder(resolvedSearchParams.sort_order)}
+ view={parseView(resolvedSearchParams.view)}
+ />
+ </TemplateDetailRouteProvider>
)
}
diff --git a/web/app/components/plugins/marketplace/__tests__/utils.spec.ts b/web/app/components/plugins/marketplace/__tests__/utils.spec.ts
index 2cb649046cc..c6d4372fa38 100644
--- a/web/app/components/plugins/marketplace/__tests__/utils.spec.ts
+++ b/web/app/components/plugins/marketplace/__tests__/utils.spec.ts
@@ -13,7 +13,13 @@ vi.mock('@/config', () => ({
// Mock var utils
vi.mock('@/utils/var', () => ({
- getMarketplaceUrl: (path: string) => `https://marketplace.dify.ai${path}`,
+ getMarketplaceUrl: (path: string, params?: Record<string, string | undefined>) => {
+ const url = new URL(path, 'https://marketplace.dify.ai')
+ for (const [key, value] of Object.entries(params ?? {})) {
+ if (value !== undefined) url.searchParams.set(key, value)
+ }
+ return url.toString()
+ },
}))
// Mock marketplace client
@@ -139,30 +145,68 @@ describe('getPluginDetailLinkInMarketplace', () => {
})
describe('getTemplateDetailLinkInMarketplace', () => {
- it('should return the local template detail link', async () => {
+ it('keeps the same local link after a title change and prefers the unique handle', async () => {
const { getTemplateDetailLinkInMarketplace } = await import('../utils')
+ const template = {
+ id: '5d107b52-8d4d-447b-9bad-1c5c16b01721',
+ template_name: 'Legal Research Agent',
+ publisher_handle: 'Dify Display Name',
+ publisher_unique_handle: 'dify-unique',
+ }
- expect(
- getTemplateDetailLinkInMarketplace({
- id: 'template-1',
- template_name: 'Legal Research Agent',
- publisher_handle: 'dify',
- publisher_unique_handle: 'dify-unique',
- }),
- ).toBe('/template/dify/Legal%20Research%20Agent?templateId=template-1')
+ const link = getTemplateDetailLinkInMarketplace(template)
+ expect(link).toBe('/template/dify-unique/5d107b52-8d4d-447b-9bad-1c5c16b01721')
+ const renamedTemplate = { ...template, template_name: 'Renamed research agent' }
+ expect(getTemplateDetailLinkInMarketplace(renamedTemplate)).toBe(link)
})
- it('should fall back to the unique publisher handle', async () => {
+ it('encodes both path segments and falls back to the publisher handle', async () => {
const { getTemplateDetailLinkInMarketplace } = await import('../utils')
expect(
getTemplateDetailLinkInMarketplace({
- id: 'template-2',
- template_name: 'Inbox',
- publisher_handle: '',
- publisher_unique_handle: 'langgenius',
+ id: 'template/one',
+ publisher_handle: 'Research / 团队',
+ publisher_unique_handle: '',
}),
- ).toBe('/template/langgenius/Inbox?templateId=template-2')
+ ).toBe('/template/Research%20%2F%20%E5%9B%A2%E9%98%9F/template%2Fone')
+ })
+
+ it('uses the template fallback when publisher handles are absent', async () => {
+ const { getTemplateDetailLinkInMarketplace } = await import('../utils')
+
+ expect(getTemplateDetailLinkInMarketplace({ id: 'template-2' })).toBe(
+ '/template/template/template-2',
+ )
+ })
+})
+
+describe('getTemplateLinkInMarketplace', () => {
+ it('preserves embedded context while dropping legacy identity parameters', async () => {
+ const { getTemplateLinkInMarketplace } = await import('../utils')
+
+ const link = new URL(
+ getTemplateLinkInMarketplace(
+ { id: 'template-1', publisher_handle: 'Display Name', publisher_unique_handle: 'dify' },
+ {
+ tid: 'legacy-short-id',
+ templateId: 'legacy-id',
+ creationType: 'templates',
+ language: 'zh-Hans',
+ theme: 'dark',
+ source: 'https://cloud.dify.ai',
+ view: 'modal',
+ },
+ ),
+ )
+
+ expect(link.origin + link.pathname).toBe('https://marketplace.dify.ai/template/dify/template-1')
+ expect(Object.fromEntries(link.searchParams)).toEqual({
+ language: 'zh-Hans',
+ theme: 'dark',
+ source: 'https://cloud.dify.ai',
+ view: 'modal',
+ })
})
})
diff --git a/web/app/components/plugins/marketplace/creator-profile/__tests__/model.spec.ts b/web/app/components/plugins/marketplace/creator-profile/__tests__/model.spec.ts
index e5331f267d1..50d048adaee 100644
--- a/web/app/components/plugins/marketplace/creator-profile/__tests__/model.spec.ts
+++ b/web/app/components/plugins/marketplace/creator-profile/__tests__/model.spec.ts
@@ -5,6 +5,7 @@ import type {
} from '@dify/contracts/marketplace'
import { describe, expect, it } from 'vite-plus/test'
import {
+ adaptCreations,
adaptCreatorProfile,
getStandaloneCreationHref,
normalizeCreatorSocialLink,
@@ -41,6 +42,7 @@ const template = {
icon_background: '#fff',
icon_file_key: '',
publisher_unique_handle: 'dify',
+ publisher_handle: 'Dify Display Name',
usage_count: 10,
categories: [],
deps_plugins: ['dify/search'],
@@ -100,8 +102,35 @@ describe('creator profile model', () => {
'/bundles/dify/research?language=zh-Hans',
)
expect(getStandaloneCreationHref(viewModel.creations[1]!, 'zh-Hans')).toBe(
- '/template/dify/Research%20template?templateId=template%2Fone&creationType=templates&language=zh-Hans',
+ '/template/dify/template%2Fone?language=zh-Hans',
)
+ expect(getStandaloneCreationHref(viewModel.creations[1]!)).toBe('/template/dify/template%2Fone')
+ })
+
+ it('uses stable template links for publisher handle fallbacks without exposing creator email', () => {
+ const creations = adaptCreations({
+ locale: 'en-US',
+ plugins: [],
+ templates: [
+ { ...template, publisher_unique_handle: '', publisher_handle: '研究 / Team' },
+ {
+ ...template,
+ publisher_unique_handle: '',
+ publisher_handle: '',
+ creator_email: '[email protected]',
+ },
+ { ...template, template_name: 'Renamed research template' },
+ ],
+ resolvePluginIcon: () => '',
+ resolveTemplateIcon: () => '',
+ resolveDependencyIcon: () => '',
+ })
+
+ expect(creations.map((creation) => getStandaloneCreationHref(creation))).toEqual([
+ '/template/%E7%A0%94%E7%A9%B6%20%2F%20Team/template%2Fone',
+ '/template/template/template%2Fone',
+ '/template/dify/template%2Fone',
+ ])
})
it('normalizes Unix-second, Unix-millisecond, and ISO timestamps', () => {
diff --git a/web/app/components/plugins/marketplace/creator-profile/model.ts b/web/app/components/plugins/marketplace/creator-profile/model.ts
index 9814dcec192..ed0d729d537 100644
--- a/web/app/components/plugins/marketplace/creator-profile/model.ts
+++ b/web/app/components/plugins/marketplace/creator-profile/model.ts
@@ -261,11 +261,7 @@ export const adaptCreations = ({
const dependencyIds = (template.deps_plugins ?? []).filter(
(id): id is string => typeof id === 'string' && id.length > 0,
)
- const publisher =
- template.publisher_handle ||
- template.publisher_unique_handle ||
- template.creator_email ||
- 'template'
+ const publisher = template.publisher_unique_handle || template.publisher_handle || 'template'
return {
id: `template:${template.id}`,
@@ -352,10 +348,6 @@ export const getStandaloneCreationHref = (creation: CreatorCreation, locale?: st
return language ? `${path}?${language}` : path
}
- const params = new URLSearchParams({
- templateId: creation.target.id,
- creationType: 'templates',
- })
- if (locale) params.set('language', locale)
- return `/template/${encodeURIComponent(creation.target.publisher)}/${encodeURIComponent(creation.target.templateName)}?${params.toString()}`
+ const path = `/template/${encodeURIComponent(creation.target.publisher)}/${encodeURIComponent(creation.target.id)}`
+ return language ? `${path}?${language}` : path
}
diff --git a/web/app/components/plugins/marketplace/detail-dialog/__tests__/index.spec.tsx b/web/app/components/plugins/marketplace/detail-dialog/__tests__/index.spec.tsx
index a5e528050b3..6b5ea811e7b 100644
--- a/web/app/components/plugins/marketplace/detail-dialog/__tests__/index.spec.tsx
+++ b/web/app/components/plugins/marketplace/detail-dialog/__tests__/index.spec.tsx
@@ -83,6 +83,19 @@ describe('MarketplaceDetailDialog', () => {
expect(onOpenChange).toHaveBeenCalledWith(false)
})
+ it('delegates clipboard-write permission to the marketplace detail iframe', () => {
+ render(
+ <ThemeProvider forcedTheme="dark">
+ <MarketplaceDetailDialog open isInstalled plugin={plugin} onOpenChange={vi.fn()} />
+ </ThemeProvider>,
+ )
+
+ expect(screen.getByTitle('Plugin A · plugin.detailPanel.operation.detail')).toHaveAttribute(
+ 'allow',
+ 'clipboard-write',
+ )
+ })
+
it('installs from the embedded detail frame without opening a confirmation dialog', async () => {
render(
<ThemeProvider forcedTheme="dark">
diff --git a/web/app/components/plugins/marketplace/detail-dialog/frame.tsx b/web/app/components/plugins/marketplace/detail-dialog/frame.tsx
index 27969d2ac78..ab31dcc31af 100644
--- a/web/app/components/plugins/marketplace/detail-dialog/frame.tsx
+++ b/web/app/components/plugins/marketplace/detail-dialog/frame.tsx
@@ -109,6 +109,7 @@ export default function MarketplaceDetailDialogFrame({
// While loading, remove the invisible frame from focus, pointer,
// and accessibility interaction until its content is presentable.
inert={isLoading}
+ allow="clipboard-write"
className={cn(
'size-full border-0 bg-background-default transition-opacity',
isLoading ? 'pointer-events-none opacity-0' : 'opacity-100',
diff --git a/web/app/components/plugins/marketplace/home/__tests__/home-trending.spec.tsx b/web/app/components/plugins/marketplace/home/__tests__/home-trending.spec.tsx
index dd5f2736541..864ca5bddd1 100644
--- a/web/app/components/plugins/marketplace/home/__tests__/home-trending.spec.tsx
+++ b/web/app/components/plugins/marketplace/home/__tests__/home-trending.spec.tsx
@@ -907,7 +907,7 @@ describe('HomeTrending', () => {
expect(screen.getByRole('dialog', { name: 'plugin-detail' })).toHaveTextContent('baserow')
})
- it('shows the served author on recommend template cards the same way as plugins', () => {
+ it('links recommend template cards by ID with the served author or template fallback', () => {
const banner: PluginBanner = {
id: 'recommend-templates',
style_type: 'recommend',
@@ -941,6 +941,8 @@ describe('HomeTrending', () => {
const authored = screen.getByRole('link', { name: 'Go-to-Market' })
const anonymous = screen.getByRole('link', { name: 'Untitled Flow' })
+ expect(authored).toHaveAttribute('href', '/template/aisa-team/tpl-authored')
+ expect(anonymous).toHaveAttribute('href', '/template/template/tpl-anonymous')
expect(
within(authored).getByText('plugin.marketplace.home.trendingByCreator'),
).toBeInTheDocument()
diff --git a/web/app/components/plugins/marketplace/home/__tests__/marketplace-search-autocomplete.spec.tsx b/web/app/components/plugins/marketplace/home/__tests__/marketplace-search-autocomplete.spec.tsx
index b9ea0eb1909..f66370a09c7 100644
--- a/web/app/components/plugins/marketplace/home/__tests__/marketplace-search-autocomplete.spec.tsx
+++ b/web/app/components/plugins/marketplace/home/__tests__/marketplace-search-autocomplete.spec.tsx
@@ -139,9 +139,7 @@ describe('MarketplaceSearchAutocomplete', () => {
expect(screen.getByText('Research legal questions with cited sources.')).toBeInTheDocument()
await user.click(screen.getByText('Legal Research Agent'))
- expect(mockAssign).toHaveBeenCalledWith(
- '/template/dify/Legal%20Research%20Agent?templateId=template-1',
- )
+ expect(mockAssign).toHaveBeenCalledWith('/template/dify/template-1')
expect(container.querySelector('form')).toHaveAttribute('action', '/templates/knowledge')
expect(container.querySelector('input[role="combobox"]')).toHaveAttribute('name', 'q')
diff --git a/web/app/components/plugins/marketplace/home/embedded-marketplace-search.tsx b/web/app/components/plugins/marketplace/home/embedded-marketplace-search.tsx
index 4a91b69912e..a844981da36 100644
--- a/web/app/components/plugins/marketplace/home/embedded-marketplace-search.tsx
+++ b/web/app/components/plugins/marketplace/home/embedded-marketplace-search.tsx
@@ -10,6 +10,7 @@ import { useRouter } from '@/next/navigation'
import { useSearchPluginText } from '../atoms'
import MarketplaceDetailDialog from '../detail-dialog'
import TemplateDetailDialog from '../templates/template-detail-dialog'
+import { useOptionalTemplateDetailRoute } from '../templates/use-optional-template-detail-route'
import { getFormattedPlugin } from '../utils'
import { MarketplaceSearchAutocomplete } from './marketplace-search-autocomplete'
@@ -34,6 +35,7 @@ export default function EmbeddedMarketplaceSearch() {
setValueQuery(query)
setValue(query ?? '')
}
+ const templateDetailRoute = useOptionalTemplateDetailRoute()
const [selectedPlugin, setSelectedPlugin] = useState<Plugin | null>(null)
const [selectedTemplate, setSelectedTemplate] = useState<MarketplaceTemplate | null>(null)
const { installedInfo } = useCheckInstalled({
@@ -41,16 +43,23 @@ export default function EmbeddedMarketplaceSearch() {
enabled: Boolean(selectedPlugin),
})
- const handleSuggestionSelect = useCallback((selection: MarketplaceSearchSelection) => {
- if (selection.kind === 'plugin') {
- setSelectedTemplate(null)
- setSelectedPlugin(normalizePlugin(getFormattedPlugin(selection.plugin)))
- return
- }
+ const handleSuggestionSelect = useCallback(
+ (selection: MarketplaceSearchSelection) => {
+ if (selection.kind === 'plugin') {
+ setSelectedTemplate(null)
+ setSelectedPlugin(normalizePlugin(getFormattedPlugin(selection.plugin)))
+ return
+ }
- setSelectedPlugin(null)
- setSelectedTemplate(selection.template)
- }, [])
+ setSelectedPlugin(null)
+ if (templateDetailRoute) {
+ templateDetailRoute.open(selection.template)
+ return
+ }
+ setSelectedTemplate(selection.template)
+ },
+ [templateDetailRoute],
+ )
return (
<>
diff --git a/web/app/components/plugins/marketplace/home/home-trending-slides.tsx b/web/app/components/plugins/marketplace/home/home-trending-slides.tsx
index 95cdfff3674..032a32b49d2 100644
--- a/web/app/components/plugins/marketplace/home/home-trending-slides.tsx
+++ b/web/app/components/plugins/marketplace/home/home-trending-slides.tsx
@@ -29,7 +29,12 @@ import {
} from '@/utils/marketplace-site-track'
import MarketplaceDetailDialog from '../detail-dialog'
import TemplateDetailDialog from '../templates/template-detail-dialog'
-import { getPluginLinkInMarketplace, getTemplateLinkInMarketplace } from '../utils'
+import { useOptionalTemplateDetailRoute } from '../templates/use-optional-template-detail-route'
+import {
+ getPluginLinkInMarketplace,
+ getTemplateDetailLinkInMarketplace,
+ getTemplateLinkInMarketplace,
+} from '../utils'
import background from './assets/background.webp'
import {
EMBEDDED_MOBILE_BANNER_MEDIA,
@@ -146,7 +151,11 @@ const getLocalCardHref = (card: BannerRecommendCard) => {
return `/plugin/${encodeURIComponent(identity.org)}/${encodeURIComponent(identity.name)}`
}
- if (card.item_type === 'template') return `/templates?tid=${encodeURIComponent(card.item_id)}`
+ if (card.item_type === 'template')
+ return getTemplateDetailLinkInMarketplace({
+ id: card.item_id,
+ publisher_unique_handle: card.creator || 'template',
+ })
return '/'
}
@@ -394,6 +403,7 @@ function EmbeddedRecommendTemplateCard({
}) {
const [open, setOpen] = useState(false)
const router = useRouter()
+ const templateDetailRoute = useOptionalTemplateDetailRoute()
const href = getTemplateLinkInMarketplace(template)
return (
@@ -404,20 +414,23 @@ function EmbeddedRecommendTemplateCard({
className={cn(recommendCardClassName, 'cursor-pointer border-0 text-left')}
onClick={() => {
trackRecommendCardClick(banner, card, page, href)
- setOpen(true)
+ if (templateDetailRoute) templateDetailRoute.open(template)
+ else setOpen(true)
}}
>
<RecommendCardFace card={card} />
</button>
- <TemplateDetailDialog
- open={open}
- template={template}
- onInstall={() => {
- setOpen(false)
- router.push(`/apps?template-id=${encodeURIComponent(template.id)}`)
- }}
- onOpenChange={setOpen}
- />
+ {!templateDetailRoute && (
+ <TemplateDetailDialog
+ open={open}
+ template={template}
+ onInstall={() => {
+ setOpen(false)
+ router.push(`/apps?template-id=${encodeURIComponent(template.id)}`)
+ }}
+ onOpenChange={setOpen}
+ />
+ )}
</>
)
}
diff --git a/web/app/components/plugins/marketplace/templates/__tests__/template-card.spec.tsx b/web/app/components/plugins/marketplace/templates/__tests__/template-card.spec.tsx
index eb63c9d1282..1deaf17f96b 100644
--- a/web/app/components/plugins/marketplace/templates/__tests__/template-card.spec.tsx
+++ b/web/app/components/plugins/marketplace/templates/__tests__/template-card.spec.tsx
@@ -1,9 +1,10 @@
import type { MarketplaceTemplate } from '@dify/contracts/marketplace'
+import type { Window } from 'happy-dom'
import { fireEvent, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import { ThemeProvider } from 'next-themes'
-import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import TemplateCard from '../template-card'
+import { TemplateDetailRouteProvider } from '../template-detail-route'
const { mockPush } = vi.hoisted(() => ({
mockPush: vi.fn(),
@@ -13,12 +14,13 @@ vi.mock('@/next/navigation', () => ({
useRouter: () => ({ push: mockPush }),
}))
-vi.mock('../../utils', () => ({
- getTemplateLinkInMarketplace: (
- currentTemplate: MarketplaceTemplate,
- params: { language: string; source?: string; theme?: string; view: string },
- ) =>
- `about:blank?templateId=${currentTemplate.id}&language=${params.language}&source=${params.source}&theme=${params.theme}&view=${params.view}`,
+vi.mock('next-themes', () => ({
+ useTheme: () => ({ resolvedTheme: 'dark' }),
+}))
+
+vi.mock('@/config', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/config')>()),
+ MARKETPLACE_URL_PREFIX: 'https://marketplace.example.com',
}))
vi.mock('@/app/components/base/app-icon', () => ({
@@ -39,17 +41,24 @@ const template: MarketplaceTemplate = {
}
describe('TemplateCard', () => {
+ const navigationSettings = (window as unknown as Window).happyDOM.settings.navigation
+ const originalDisableChildFrameNavigation = navigationSettings.disableChildFrameNavigation
+
+ beforeAll(() => {
+ navigationSettings.disableChildFrameNavigation = true
+ })
+
beforeEach(() => {
vi.clearAllMocks()
})
+ afterAll(() => {
+ navigationSettings.disableChildFrameNavigation = originalDisableChildFrameNavigation
+ })
+
it('opens template detail before starting the Dify import flow', async () => {
const user = userEvent.setup()
- render(
- <ThemeProvider forcedTheme="dark">
- <TemplateCard partnerText="Verified by a Dify partner" template={template} />
- </ThemeProvider>,
- )
+ render(<TemplateCard partnerText="Verified by a Dify partner" template={template} />)
expect(screen.queryByRole('link', { name: 'Campaign planner' })).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'Campaign planner' }))
@@ -60,7 +69,15 @@ describe('TemplateCard', () => {
const frame = screen.getByTitle(
'Campaign planner · plugin.detailPanel.operation.detail',
) as HTMLIFrameElement
- const marketplaceOrigin = new URL(frame.getAttribute('src')!, window.location.href).origin
+ const frameURL = new URL(frame.getAttribute('src')!, window.location.href)
+ expect(frameURL.pathname).toBe('/template/dify/template%2Fone')
+ expect(Object.fromEntries(frameURL.searchParams)).toEqual({
+ language: 'en-US',
+ source: window.location.origin,
+ theme: 'dark',
+ view: 'modal',
+ })
+ const marketplaceOrigin = frameURL.origin
const installRequest = {
type: 'dify-marketplace:install-template',
templateId: template.id,
@@ -88,4 +105,23 @@ describe('TemplateCard', () => {
expect(screen.getByText('1.2k')).toBeInTheDocument()
expect(screen.getByText('Verified by a Dify partner')).toBeInTheDocument()
})
+
+ it('syncs /templates/{publisher}/{uuid} while the routed detail dialog is open', async () => {
+ window.history.replaceState(window.history.state, '', '/templates')
+ const user = userEvent.setup()
+ const routedTemplate = {
+ ...template,
+ id: 'c558a1fb-bb8c-4a5e-9404-d681c6659cf2',
+ }
+ render(
+ <TemplateDetailRouteProvider>
+ <TemplateCard partnerText="Verified by a Dify partner" template={routedTemplate} />
+ </TemplateDetailRouteProvider>,
+ )
+
+ await user.click(screen.getByRole('button', { name: 'Campaign planner' }))
+
+ expect(window.location.pathname).toBe(`/templates/dify/${routedTemplate.id}`)
+ expect(screen.getByRole('dialog')).toBeInTheDocument()
+ })
})
diff --git a/web/app/components/plugins/marketplace/templates/__tests__/template-detail-route.spec.tsx b/web/app/components/plugins/marketplace/templates/__tests__/template-detail-route.spec.tsx
new file mode 100644
index 00000000000..ee6f43c38ea
--- /dev/null
+++ b/web/app/components/plugins/marketplace/templates/__tests__/template-detail-route.spec.tsx
@@ -0,0 +1,104 @@
+import type { MarketplaceTemplate } from '@dify/contracts/marketplace'
+import { render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import { TemplateDetailRouteProvider } from '../template-detail-route'
+import { useOptionalTemplateDetailRoute } from '../use-optional-template-detail-route'
+
+const id = 'c558a1fb-bb8c-4a5e-9404-d681c6659cf2'
+
+const template: MarketplaceTemplate = {
+ id,
+ template_name: 'Campaign planner',
+ overview: 'Plan a launch campaign.',
+ icon: '📄',
+ icon_background: '#fff',
+ icon_file_key: '',
+ publisher_unique_handle: 'dify',
+ usage_count: 1200,
+ categories: ['marketing'],
+}
+
+vi.mock('@/next/navigation', () => ({
+ useRouter: () => ({ push: vi.fn() }),
+}))
+
+vi.mock('../template-detail-dialog', () => ({
+ default: ({
+ open,
+ template: current,
+ onOpenChange,
+ }: {
+ open: boolean
+ template: MarketplaceTemplate
+ onOpenChange: (open: boolean) => void
+ }) =>
+ open ? (
+ <div role="dialog" aria-label={`${current.template_name} details`}>
+ <button type="button" onClick={() => onOpenChange(false)}>
+ Close
+ </button>
+ </div>
+ ) : null,
+}))
+
+function OpenButton() {
+ const route = useOptionalTemplateDetailRoute()
+ return (
+ <button type="button" onClick={() => route?.open(template)}>
+ Open template
+ </button>
+ )
+}
+
+describe('TemplateDetailRouteProvider', () => {
+ beforeEach(() => {
+ window.history.replaceState(window.history.state, '', '/templates')
+ })
+
+ it('opens the dialog when the templates URL names a template', () => {
+ window.history.replaceState(window.history.state, '', `/templates/dify/${id}`)
+ render(
+ <TemplateDetailRouteProvider initialSelection={{ publisher: 'dify', id }}>
+ <span>catalog</span>
+ </TemplateDetailRouteProvider>,
+ )
+
+ expect(screen.getByRole('dialog')).toBeInTheDocument()
+ })
+
+ it('writes /templates/{publisher}/{uuid} when a template opens and restores /templates on close', async () => {
+ const user = userEvent.setup()
+ render(
+ <TemplateDetailRouteProvider>
+ <OpenButton />
+ </TemplateDetailRouteProvider>,
+ )
+
+ await user.click(screen.getByRole('button', { name: 'Open template' }))
+
+ expect(window.location.pathname).toBe(`/templates/dify/${id}`)
+ expect(screen.getByRole('dialog', { name: 'Campaign planner details' })).toBeInTheDocument()
+
+ await user.click(screen.getByRole('button', { name: 'Close' }))
+
+ expect(window.location.pathname).toBe('/templates')
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
+ })
+
+ it('restores the category catalog URL when the dialog was opened from it', async () => {
+ const user = userEvent.setup()
+ window.history.replaceState(window.history.state, '', '/templates/marketing')
+ render(
+ <TemplateDetailRouteProvider>
+ <OpenButton />
+ </TemplateDetailRouteProvider>,
+ )
+
+ await user.click(screen.getByRole('button', { name: 'Open template' }))
+ expect(window.location.pathname).toBe(`/templates/dify/${id}`)
+
+ await user.click(screen.getByRole('button', { name: 'Close' }))
+ expect(window.location.pathname).toBe('/templates/marketing')
+ })
+})
diff --git a/web/app/components/plugins/marketplace/templates/__tests__/template-links.spec.ts b/web/app/components/plugins/marketplace/templates/__tests__/template-links.spec.ts
index 34993d58447..3faa0feb104 100644
--- a/web/app/components/plugins/marketplace/templates/__tests__/template-links.spec.ts
+++ b/web/app/components/plugins/marketplace/templates/__tests__/template-links.spec.ts
@@ -1,5 +1,12 @@
import { describe, expect, it } from 'vite-plus/test'
-import { buildTemplatesHref } from '../template-links'
+import {
+ buildTemplateDetailHref,
+ buildTemplatesHref,
+ parseTemplateDetailPath,
+ parseTemplatesRoute,
+} from '../template-links'
+
+const id = 'c558a1fb-bb8c-4a5e-9404-d681c6659cf2'
describe('buildTemplatesHref', () => {
it('appends selected languages as a comma-separated query value', () => {
@@ -8,3 +15,33 @@ describe('buildTemplatesHref', () => {
)
})
})
+
+describe('embedded template detail URLs', () => {
+ it('builds /templates/{publisher}/{uuid} independently of the mutable title', () => {
+ expect(
+ buildTemplateDetailHref({
+ id,
+ publisher_unique_handle: 'acme labs',
+ }),
+ ).toBe(`/templates/acme%20labs/${id}`)
+ })
+
+ it('reads a template dialog path and ignores catalog or non-uuid segments', () => {
+ expect(parseTemplateDetailPath(`/templates/acme%20labs/${id}`)).toEqual({
+ publisher: 'acme labs',
+ id,
+ })
+ expect(parseTemplateDetailPath('/templates')).toBeUndefined()
+ expect(parseTemplateDetailPath('/templates/marketing')).toBeUndefined()
+ expect(parseTemplateDetailPath('/templates/acme%20labs/Old%20title')).toBeUndefined()
+ })
+
+ it('keeps /templates/{publisher}/{uuid} on the all catalog with a selected template', () => {
+ expect(parseTemplatesRoute(['acme labs', id])).toEqual({
+ category: 'all',
+ selection: { publisher: 'acme labs', id },
+ })
+ expect(parseTemplatesRoute(['marketing'])).toEqual({ category: 'marketing' })
+ expect(parseTemplatesRoute(undefined)).toEqual({ category: 'all' })
+ })
+})
diff --git a/web/app/components/plugins/marketplace/templates/template-card.tsx b/web/app/components/plugins/marketplace/templates/template-card.tsx
index de0a577e62b..147959922d3 100644
--- a/web/app/components/plugins/marketplace/templates/template-card.tsx
+++ b/web/app/components/plugins/marketplace/templates/template-card.tsx
@@ -11,6 +11,7 @@ import { useRouter } from '@/next/navigation'
import { formatNumberAbbreviated } from '@/utils/format'
import { getIconFromMarketPlace } from '@/utils/get-icon'
import TemplateDetailDialog from './template-detail-dialog'
+import { useOptionalTemplateDetailRoute } from './use-optional-template-detail-route'
type TemplateCardProps = {
template: MarketplaceTemplate
@@ -22,6 +23,7 @@ const MAX_VISIBLE_PLUGIN_DEPENDENCIES = 7
export default function TemplateCard({ template, className, partnerText }: TemplateCardProps) {
const router = useRouter()
+ const templateDetailRoute = useOptionalTemplateDetailRoute()
const [isDetailOpen, { setTrue: showDetail, setFalse: hideDetail }] = useBoolean(false)
const publisher =
template.publisher_handle || template.publisher_unique_handle || template.creator_email || ''
@@ -33,8 +35,13 @@ export default function TemplateCard({ template, className, partnerText }: Templ
const imageUrl = template.icon_file_key
? `${MARKETPLACE_API_PREFIX}/templates/${template.id}/icon`
: undefined
+ const openDetail = () => {
+ if (templateDetailRoute) templateDetailRoute.open(template)
+ else showDetail()
+ }
const handleOpenChange = (open: boolean) => {
- if (open) showDetail()
+ if (open) openDetail()
+ else if (templateDetailRoute) templateDetailRoute.close()
else hideDetail()
}
const handleInstall = useCallback(() => {
@@ -54,7 +61,7 @@ export default function TemplateCard({ template, className, partnerText }: Templ
type="button"
aria-label={template.template_name}
className="absolute inset-0 z-[1] cursor-pointer rounded-xl outline-hidden focus-visible:ring-2 focus-visible:ring-state-accent-solid"
- onClick={showDetail}
+ onClick={openDetail}
/>
<div className="relative z-0 flex shrink-0 items-center gap-3 px-4 pt-4 pb-2">
<AppIcon
@@ -100,12 +107,14 @@ export default function TemplateCard({ template, className, partnerText }: Templ
)}
</div>
</article>
- <TemplateDetailDialog
- open={isDetailOpen}
- template={template}
- onInstall={handleInstall}
- onOpenChange={handleOpenChange}
- />
+ {!templateDetailRoute && (
+ <TemplateDetailDialog
+ open={isDetailOpen}
+ template={template}
+ onInstall={handleInstall}
+ onOpenChange={handleOpenChange}
+ />
+ )}
</>
)
}
diff --git a/web/app/components/plugins/marketplace/templates/template-detail-route.tsx b/web/app/components/plugins/marketplace/templates/template-detail-route.tsx
new file mode 100644
index 00000000000..4c800286a54
--- /dev/null
+++ b/web/app/components/plugins/marketplace/templates/template-detail-route.tsx
@@ -0,0 +1,107 @@
+'use client'
+
+import type { MarketplaceTemplate } from '@dify/contracts/marketplace'
+import type { ReactNode } from 'react'
+import type { TemplateDetailSelection } from './template-links'
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import { useRouter } from '@/next/navigation'
+import TemplateDetailDialog from './template-detail-dialog'
+import { buildTemplateDetailHref, parseTemplateDetailPath } from './template-links'
+import { TemplateDetailRouteContext } from './use-optional-template-detail-route'
+
+const catalogLocation = () => `${window.location.pathname}${window.location.search}`
+
+function templateFromSelection(
+ selection: TemplateDetailSelection,
+ current?: MarketplaceTemplate | null,
+): MarketplaceTemplate {
+ if (current?.id === selection.id) return current
+
+ return {
+ id: selection.id,
+ template_name: current?.template_name || selection.publisher,
+ overview: '',
+ icon: '',
+ icon_background: '',
+ icon_file_key: '',
+ publisher_unique_handle: selection.publisher,
+ usage_count: 0,
+ categories: [],
+ }
+}
+
+export function TemplateDetailRouteProvider({
+ children,
+ initialSelection,
+}: {
+ children: ReactNode
+ initialSelection?: TemplateDetailSelection
+}) {
+ const router = useRouter()
+ const catalogHrefRef = useRef('/templates')
+ const [template, setTemplate] = useState<MarketplaceTemplate | null>(() =>
+ initialSelection ? templateFromSelection(initialSelection) : null,
+ )
+
+ const close = useCallback(() => {
+ setTemplate(null)
+ if (catalogLocation() !== catalogHrefRef.current)
+ window.history.pushState(window.history.state, '', catalogHrefRef.current)
+ }, [])
+
+ const open = useCallback((next: MarketplaceTemplate) => {
+ if (!parseTemplateDetailPath(window.location.pathname))
+ catalogHrefRef.current = catalogLocation() || '/templates'
+
+ setTemplate(next)
+ const href = buildTemplateDetailHref(next)
+ if (catalogLocation() !== href) window.history.pushState(window.history.state, '', href)
+ }, [])
+
+ useEffect(() => {
+ const onPopState = () => {
+ const parsed = parseTemplateDetailPath(window.location.pathname)
+ if (!parsed) {
+ setTemplate(null)
+ return
+ }
+
+ setTemplate((current) => templateFromSelection(parsed, current))
+ }
+
+ window.addEventListener('popstate', onPopState)
+ return () => window.removeEventListener('popstate', onPopState)
+ }, [])
+
+ const handleInstall = useCallback(() => {
+ if (!template) return
+ const templateId = template.id
+ setTemplate(null)
+ router.push(`/apps?template-id=${encodeURIComponent(templateId)}`)
+ }, [router, template])
+
+ const value = useMemo(
+ () => ({
+ close,
+ isOpen: (templateId: string) => template?.id === templateId,
+ open,
+ }),
+ [close, open, template],
+ )
+
+ return (
+ <TemplateDetailRouteContext.Provider value={value}>
+ {children}
+ {template && (
+ <TemplateDetailDialog
+ open
+ template={template}
+ onInstall={handleInstall}
+ onOpenChange={(nextOpen) => {
+ if (!nextOpen) close()
+ }}
+ />
+ )}
+ </TemplateDetailRouteContext.Provider>
+ )
+}
diff --git a/web/app/components/plugins/marketplace/templates/template-links.ts b/web/app/components/plugins/marketplace/templates/template-links.ts
index fc0ae9b9425..39b66eedc1a 100644
--- a/web/app/components/plugins/marketplace/templates/template-links.ts
+++ b/web/app/components/plugins/marketplace/templates/template-links.ts
@@ -1,10 +1,55 @@
+import type { MarketplaceTemplate } from '@dify/contracts/marketplace'
import type { TemplateCategory } from './categories'
+import { validate as isUuid } from 'uuid'
+import { isTemplateCategory } from './categories'
export const PAGE_LINK_CLASS =
'flex h-8 items-center justify-center rounded-lg border-[0.5px] border-divider-regular px-3 system-sm-medium text-text-secondary outline-hidden hover:bg-state-base-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid'
export const PAGE_LINK_DISABLED_CLASS =
'flex h-8 cursor-not-allowed items-center justify-center rounded-lg border-[0.5px] border-divider-subtle px-3 system-sm-medium text-text-quaternary'
+export type TemplateDetailSelection = {
+ id: string
+ publisher: string
+}
+
+export function buildTemplateDetailHref(
+ template: Pick<MarketplaceTemplate, 'id' | 'publisher_handle' | 'publisher_unique_handle'>,
+) {
+ const publisher = template.publisher_unique_handle || template.publisher_handle || 'template'
+ return `/templates/${encodeURIComponent(publisher)}/${encodeURIComponent(template.id)}`
+}
+
+export function parseTemplateDetailPath(pathname: string): TemplateDetailSelection | undefined {
+ const match = pathname.match(/^\/templates\/([^/]+)\/([^/]+)\/?$/)
+ const publisherSegment = match?.[1]
+ const idSegment = match?.[2]
+ if (!publisherSegment || !idSegment) return undefined
+
+ const publisher = decodeURIComponent(publisherSegment)
+ const id = decodeURIComponent(idSegment)
+ return isUuid(id) ? { publisher, id } : undefined
+}
+
+export function parseTemplatesRoute(segments?: string[]): {
+ category: TemplateCategory
+ selection?: TemplateDetailSelection
+} {
+ const publisher = segments?.[0]
+ const id = segments?.[1]
+ if (segments?.length === 2 && publisher && id && isUuid(id)) {
+ return {
+ category: 'all',
+ selection: { publisher, id },
+ }
+ }
+
+ const requested = segments?.[0]
+ return {
+ category: isTemplateCategory(requested) ? requested : 'all',
+ }
+}
+
export type TemplatesHrefOptions = {
category: TemplateCategory
languages?: string[]
diff --git a/web/app/components/plugins/marketplace/templates/use-optional-template-detail-route.ts b/web/app/components/plugins/marketplace/templates/use-optional-template-detail-route.ts
new file mode 100644
index 00000000000..50313d0aab2
--- /dev/null
+++ b/web/app/components/plugins/marketplace/templates/use-optional-template-detail-route.ts
@@ -0,0 +1,16 @@
+'use client'
+
+import type { MarketplaceTemplate } from '@dify/contracts/marketplace'
+import { createContext, useContext } from 'react'
+
+export type TemplateDetailRouteValue = {
+ close: () => void
+ isOpen: (templateId: string) => boolean
+ open: (template: MarketplaceTemplate) => void
+}
+
+export const TemplateDetailRouteContext = createContext<TemplateDetailRouteValue | null>(null)
+
+export function useOptionalTemplateDetailRoute() {
+ return useContext(TemplateDetailRouteContext)
+}
diff --git a/web/app/components/plugins/marketplace/utils.ts b/web/app/components/plugins/marketplace/utils.ts
index 7e00ff3d7ac..6db0268767b 100644
--- a/web/app/components/plugins/marketplace/utils.ts
+++ b/web/app/components/plugins/marketplace/utils.ts
@@ -107,31 +107,25 @@ export const getPluginDetailLinkInMarketplace = (
}
export const getTemplateDetailLinkInMarketplace = (
- template: Pick<
- MarketplaceTemplate,
- 'id' | 'publisher_handle' | 'publisher_unique_handle' | 'template_name'
- >,
+ template: Pick<MarketplaceTemplate, 'id' | 'publisher_handle' | 'publisher_unique_handle'>,
) => {
- const publisher = template.publisher_handle || template.publisher_unique_handle || 'template'
- const search = new URLSearchParams({ templateId: template.id })
+ const publisher = template.publisher_unique_handle || template.publisher_handle || 'template'
- return `/template/${encodeURIComponent(publisher)}/${encodeURIComponent(template.template_name)}?${search.toString()}`
+ return `/template/${encodeURIComponent(publisher)}/${encodeURIComponent(template.id)}`
}
export const getTemplateLinkInMarketplace = (
- template: Pick<
- MarketplaceTemplate,
- 'id' | 'publisher_handle' | 'publisher_unique_handle' | 'template_name'
- >,
+ template: Pick<MarketplaceTemplate, 'id' | 'publisher_handle' | 'publisher_unique_handle'>,
params?: Record<string, string | undefined>,
) => {
- const publisher = template.publisher_handle || template.publisher_unique_handle || 'template'
- const path = `/template/${encodeURIComponent(publisher)}/${encodeURIComponent(template.template_name)}`
+ const {
+ tid: _tid,
+ templateId: _templateId,
+ creationType: _creationType,
+ ...detailParams
+ } = params ?? {}
- return getMarketplaceUrl(path, {
- ...params,
- templateId: template.id,
- })
+ return getMarketplaceUrl(getTemplateDetailLinkInMarketplace(template), detailParams)
}
export const getMarketplaceCategoryUrl = (