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.

perf(web): load Zendesk on support intent (#41653)

yyhbc716020c716
diff --git a/web/app/(commonLayout)/external-service-sync.tsx b/web/app/(commonLayout)/external-service-sync.tsx
index 08bb786d379..4e27aba7551 100644
--- a/web/app/(commonLayout)/external-service-sync.tsx
+++ b/web/app/(commonLayout)/external-service-sync.tsx
@@ -14,7 +14,7 @@ import {
} from '@/app/components/base/amplitude/registration-tracking'
import { useAmplitudeInitialized } from '@/app/components/base/amplitude/use-amplitude-initialized'
import { useAnalyticsConsent } from '@/app/components/base/analytics-consent/consent-store'
-import { setZendeskConversationFields } from '@/app/components/base/zendesk/utils'
+import { zendeskRuntime } from '@/app/components/base/zendesk/runtime'
import { ZENDESK_FIELD_IDS } from '@/config'
import { getLangGeniusVersionInfo } from '@/context/app-context-normalizers'
import { currentWorkspaceAtom } from '@/context/workspace-state'
@@ -106,7 +106,7 @@ function syncZendeskField({
}) {
if (deploymentEdition !== 'CLOUD' || !fieldId || !value || value === previousValue) return
- setZendeskConversationFields(
+ zendeskRuntime.setConversationFields(
[
{
id: fieldId,
diff --git a/web/app/components/base/zendesk/__tests__/index.spec.tsx b/web/app/components/base/zendesk/__tests__/index.spec.tsx
index 51709643cee..a4e6c58643c 100644
--- a/web/app/components/base/zendesk/__tests__/index.spec.tsx
+++ b/web/app/components/base/zendesk/__tests__/index.spec.tsx
@@ -15,6 +15,7 @@ const systemFeaturesQueryKey = ['console', 'system-features']
const getSystemFeatures = vi.fn()
const mocks = vi.hoisted(() => ({
headers: vi.fn(),
+ scriptProps: vi.fn(),
}))
// Mock react's memo to just return the function
@@ -52,21 +53,15 @@ vi.mock('@/next/headers', () => ({
headers: mocks.headers,
}))
-// Mock next/script
-type ScriptProps = {
- children?: ReactNode
- id?: string
- src?: string
+type ZendeskScriptProps = {
nonce?: string
- 'data-testid'?: string
+ widgetKey: string
}
-vi.mock('@/next/script', () => ({
- __esModule: true,
- default: vi.fn(({ children, id, src, nonce, 'data-testid': testId }: ScriptProps) => (
- <div data-testid={testId} id={id} data-src={src} data-nonce={nonce}>
- {children}
- </div>
- )),
+vi.mock('../script', () => ({
+ ZendeskScript: (props: ZendeskScriptProps) => {
+ mocks.scriptProps(props)
+ return <div data-testid="zendesk-runtime" data-nonce={props.nonce} />
+ },
}))
describe('Zendesk', () => {
@@ -118,25 +113,13 @@ describe('Zendesk', () => {
expect(result).toBeNull()
})
- it('should render scripts correctly in non-production environment', async () => {
+ it('should mount the runtime without a nonce in non-production', async () => {
mockIsProd = false
const result = await renderZendesk()
render(result as React.ReactElement) // result is ReactNode, which render accepts but types might be picky
- const snippet = screen.getByTestId('ze-snippet')
- expect(snippet).toBeInTheDocument()
- expect(snippet).toHaveAttribute('id', 'ze-snippet')
- expect(snippet).toHaveAttribute(
- 'data-src',
- 'https://static.zdassets.com/ekr/snippet.js?key=test-key',
- )
- expect(snippet).toHaveAttribute('data-nonce', '')
-
- const init = screen.getByTestId('ze-init')
- expect(init).toBeInTheDocument()
- expect(init).toHaveAttribute('id', 'ze-init')
- expect(init).toHaveTextContent("window.zE('messenger', 'hide')")
- expect(init).toHaveAttribute('data-nonce', '')
+ expect(screen.getByTestId('zendesk-runtime')).toHaveAttribute('data-nonce', '')
+ expect(mocks.scriptProps).toHaveBeenCalledWith({ nonce: '', widgetKey: 'test-key' })
})
it('should render scripts with nonce in production environment', async () => {
@@ -145,11 +128,8 @@ describe('Zendesk', () => {
const result = await renderZendesk()
render(result as React.ReactElement)
- const snippet = screen.getByTestId('ze-snippet')
- expect(snippet).toHaveAttribute('data-nonce', 'prod-nonce')
-
- const init = screen.getByTestId('ze-init')
- expect(init).toHaveAttribute('data-nonce', 'prod-nonce')
+ expect(screen.getByTestId('zendesk-runtime')).toHaveAttribute('data-nonce', 'prod-nonce')
+ expect(mocks.scriptProps).toHaveBeenCalledWith({ nonce: 'prod-nonce', widgetKey: 'test-key' })
})
it('should render scripts with empty nonce in production when header is missing', async () => {
@@ -158,10 +138,6 @@ describe('Zendesk', () => {
const result = await renderZendesk()
render(result as React.ReactElement)
- const snippet = screen.getByTestId('ze-snippet')
- expect(snippet).toHaveAttribute('data-nonce', '')
-
- const init = screen.getByTestId('ze-init')
- expect(init).toHaveAttribute('data-nonce', '')
+ expect(screen.getByTestId('zendesk-runtime')).toHaveAttribute('data-nonce', '')
})
})
diff --git a/web/app/components/base/zendesk/__tests__/runtime.spec.ts b/web/app/components/base/zendesk/__tests__/runtime.spec.ts
new file mode 100644
index 00000000000..04e2f7e0164
--- /dev/null
+++ b/web/app/components/base/zendesk/__tests__/runtime.spec.ts
@@ -0,0 +1,104 @@
+import type { Mock } from 'vite-plus/test'
+import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
+import { createZendeskRuntime } from '../runtime'
+
+describe('Zendesk runtime', () => {
+ let api: Mock
+ let runtime: ReturnType<typeof createZendeskRuntime>
+
+ beforeEach(() => {
+ api = vi.fn()
+ runtime = createZendeskRuntime(() => api)
+ })
+
+ it('queues fields and opens only after the single requested load is ready', async () => {
+ const fieldsCallback = vi.fn()
+ runtime.setConversationFields(
+ [{ id: 'email', value: '[email protected]' }],
+ 'CLOUD',
+ fieldsCallback,
+ )
+
+ const firstOpen = runtime.open('CLOUD')
+ const secondOpen = runtime.open('CLOUD')
+
+ expect(firstOpen).toBe(secondOpen)
+ expect(runtime.getSnapshot()).toEqual({ attempt: 1, status: 'loading' })
+ expect(api).not.toHaveBeenCalled()
+
+ runtime.markReady()
+ await firstOpen
+
+ expect(api).toHaveBeenCalledWith(
+ 'messenger:set',
+ 'conversationFields',
+ [{ id: 'email', value: '[email protected]' }],
+ expect.any(Function),
+ )
+ const flushedFieldsCallback = api.mock.calls[0]![3] as () => void
+ flushedFieldsCallback()
+ expect(fieldsCallback).toHaveBeenCalledOnce()
+ expect(api).toHaveBeenNthCalledWith(2, 'messenger', 'show')
+ expect(api).toHaveBeenNthCalledWith(3, 'messenger', 'open')
+ expect(runtime.getSnapshot()).toEqual({ attempt: 1, status: 'ready' })
+ })
+
+ it('flushes only the latest pending value for each field', async () => {
+ runtime.setConversationFields(
+ [
+ { id: 'email', value: '[email protected]' },
+ { id: 'workspace', value: 'workspace-1' },
+ ],
+ 'CLOUD',
+ )
+ runtime.setConversationFields(
+ [
+ { id: 'email', value: '[email protected]' },
+ { id: 'plan', value: 'professional-plan' },
+ ],
+ 'CLOUD',
+ )
+
+ const openPromise = runtime.open('CLOUD')
+ runtime.markReady()
+ await openPromise
+
+ expect(api).toHaveBeenNthCalledWith(
+ 1,
+ 'messenger:set',
+ 'conversationFields',
+ [
+ { id: 'email', value: '[email protected]' },
+ { id: 'workspace', value: 'workspace-1' },
+ { id: 'plan', value: 'professional-plan' },
+ ],
+ undefined,
+ )
+ expect(api).toHaveBeenCalledTimes(3)
+ })
+
+ it('can retry a failed load and report the original failure', async () => {
+ const failedOpen = runtime.open('CLOUD')
+ runtime.markFailed()
+
+ await expect(failedOpen).rejects.toThrow('Failed to load Zendesk')
+ expect(runtime.getSnapshot()).toEqual({ attempt: 1, status: 'error' })
+
+ const retriedOpen = runtime.open('CLOUD')
+ expect(runtime.getSnapshot()).toEqual({ attempt: 2, status: 'loading' })
+
+ runtime.markReady()
+ await retriedOpen
+
+ expect(api).toHaveBeenCalledWith('messenger', 'show')
+ expect(api).toHaveBeenCalledWith('messenger', 'open')
+ })
+
+ it('does not load or queue fields outside Cloud deployments', async () => {
+ runtime.setConversationFields([{ id: 'plan', value: 'sandbox-plan' }], 'COMMUNITY')
+ await runtime.open('COMMUNITY')
+
+ expect(runtime.getSnapshot()).toEqual({ attempt: 0, status: 'idle' })
+ expect(api).not.toHaveBeenCalled()
+ })
+})
diff --git a/web/app/components/base/zendesk/__tests__/script.spec.tsx b/web/app/components/base/zendesk/__tests__/script.spec.tsx
new file mode 100644
index 00000000000..372a94d1319
--- /dev/null
+++ b/web/app/components/base/zendesk/__tests__/script.spec.tsx
@@ -0,0 +1,138 @@
+import { act, render, waitFor } from '@testing-library/react'
+import { StrictMode } from 'react'
+import { afterEach, describe, expect, it, vi } from 'vite-plus/test'
+import { createZendeskRuntime } from '../runtime'
+import { ZendeskScript } from '../script'
+
+describe('ZendeskScript', () => {
+ afterEach(() => {
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+ window.zE = undefined
+ })
+
+ it('does not insert the SDK script until loading is requested', async () => {
+ const runtime = createZendeskRuntime(() => window.zE)
+ const appendChild = vi.spyOn(document.body, 'appendChild').mockImplementation((node) => node)
+ const getScripts = () =>
+ appendChild.mock.calls
+ .map(([node]) => node)
+ .filter((node): node is HTMLScriptElement => node instanceof HTMLScriptElement)
+ render(<ZendeskScript nonce="test-nonce" runtime={runtime} widgetKey="test-key" />)
+
+ expect(getScripts()).toHaveLength(0)
+
+ let loadPromise!: Promise<void>
+ act(() => {
+ loadPromise = runtime.requestLoad()
+ void runtime.requestLoad()
+ })
+
+ await waitFor(() => expect(getScripts()).toHaveLength(1))
+ const script = getScripts()[0]!
+ expect(script.src).toBe('https://static.zdassets.com/ekr/snippet.js?key=test-key')
+ expect(script.nonce).toBe('test-nonce')
+
+ window.zE = vi.fn()
+ act(() => script.dispatchEvent(new Event('load')))
+ await loadPromise
+ })
+
+ it('removes a failed script and inserts a fresh one when retried', async () => {
+ const runtime = createZendeskRuntime(() => window.zE)
+ const appendChild = vi.spyOn(document.body, 'appendChild').mockImplementation((node) => node)
+ const getScripts = () =>
+ appendChild.mock.calls
+ .map(([node]) => node)
+ .filter((node): node is HTMLScriptElement => node instanceof HTMLScriptElement)
+ render(<ZendeskScript runtime={runtime} widgetKey="test-key" />)
+
+ let failedLoad!: Promise<void>
+ act(() => {
+ failedLoad = runtime.requestLoad()
+ })
+ await waitFor(() => expect(getScripts()).toHaveLength(1))
+ const failedScript = getScripts()[0]!
+ const failedExpectation = expect(failedLoad).rejects.toThrow('Failed to load Zendesk')
+ act(() => failedScript.dispatchEvent(new Event('error')))
+ await failedExpectation
+
+ let retryLoad!: Promise<void>
+ act(() => {
+ retryLoad = runtime.requestLoad()
+ })
+ await waitFor(() => expect(getScripts()).toHaveLength(2))
+ const retryScript = getScripts()[1]!
+ expect(retryScript).not.toBe(failedScript)
+
+ window.zE = vi.fn()
+ act(() => retryScript.dispatchEvent(new Event('load')))
+ await retryLoad
+ })
+
+ it('fails a stalled load so the user can retry', async () => {
+ vi.useFakeTimers()
+ const runtime = createZendeskRuntime(() => window.zE)
+ const appendChild = vi.spyOn(document.body, 'appendChild').mockImplementation((node) => node)
+ const getScripts = () =>
+ appendChild.mock.calls
+ .map(([node]) => node)
+ .filter((node): node is HTMLScriptElement => node instanceof HTMLScriptElement)
+ render(<ZendeskScript runtime={runtime} widgetKey="test-key" />)
+
+ let stalledLoad!: Promise<void>
+ act(() => {
+ stalledLoad = runtime.requestLoad()
+ })
+ expect(getScripts()).toHaveLength(1)
+ const stalledScript = getScripts()[0]!
+ const remove = vi.spyOn(stalledScript, 'remove')
+ const stalledExpectation = expect(stalledLoad).rejects.toThrow('Failed to load Zendesk')
+
+ await act(() => vi.advanceTimersByTimeAsync(15_000))
+
+ await stalledExpectation
+ expect(runtime.getSnapshot()).toEqual({ attempt: 1, status: 'error' })
+ expect(remove).toHaveBeenCalledOnce()
+ })
+
+ it('fails the pending load when its loader unmounts', async () => {
+ const runtime = createZendeskRuntime(() => window.zE)
+ const appendChild = vi.spyOn(document.body, 'appendChild').mockImplementation((node) => node)
+ const loadPromise = runtime.requestLoad()
+ const loadExpectation = expect(loadPromise).rejects.toThrow('Failed to load Zendesk')
+ const { unmount } = render(<ZendeskScript runtime={runtime} widgetKey="test-key" />)
+ const script = appendChild.mock.calls.at(-1)![0] as HTMLScriptElement
+ const remove = vi.spyOn(script, 'remove')
+
+ await act(async () => {
+ unmount()
+ await Promise.resolve()
+ })
+
+ await loadExpectation
+ expect(runtime.getSnapshot()).toEqual({ attempt: 1, status: 'error' })
+ expect(remove).toHaveBeenCalledOnce()
+ })
+
+ it('keeps the first load active through Strict Mode effect replay', async () => {
+ const runtime = createZendeskRuntime(() => window.zE)
+ const appendChild = vi.spyOn(document.body, 'appendChild').mockImplementation((node) => node)
+ const loadPromise = runtime.requestLoad()
+
+ render(
+ <StrictMode>
+ <ZendeskScript runtime={runtime} widgetKey="test-key" />
+ </StrictMode>,
+ )
+ await act(() => Promise.resolve())
+
+ expect(runtime.getSnapshot()).toEqual({ attempt: 1, status: 'loading' })
+ const activeScript = appendChild.mock.calls.at(-1)![0] as HTMLScriptElement
+ window.zE = vi.fn()
+ act(() => activeScript.dispatchEvent(new Event('load')))
+
+ await loadPromise
+ expect(runtime.getSnapshot()).toEqual({ attempt: 1, status: 'ready' })
+ })
+})
diff --git a/web/app/components/base/zendesk/__tests__/utils.spec.ts b/web/app/components/base/zendesk/__tests__/utils.spec.ts
deleted file mode 100644
index ffac513a5de..00000000000
--- a/web/app/components/base/zendesk/__tests__/utils.spec.ts
+++ /dev/null
@@ -1,86 +0,0 @@
-import { openZendeskWindow, setZendeskConversationFields } from '../utils'
-
-describe('zendesk/utils', () => {
- const mockZE = vi.fn()
-
- beforeEach(() => {
- vi.clearAllMocks()
- window.zE = mockZE
- })
-
- afterEach(() => {
- vi.useRealTimers()
- window.zE = mockZE
- })
-
- describe('setZendeskConversationFields', () => {
- it('sets conversation fields in Cloud when zE exists', () => {
- const fields = [
- { id: 'field1', value: 'value1' },
- { id: 'field2', value: 'value2' },
- ]
- const callback = vi.fn()
-
- setZendeskConversationFields(fields, 'CLOUD', callback)
-
- expect(window.zE).toHaveBeenCalledWith(
- 'messenger:set',
- 'conversationFields',
- fields,
- callback,
- )
- })
-
- it.each(['COMMUNITY', 'ENTERPRISE'] as const)(
- 'does not set fields when deployment edition is %s',
- (deploymentEdition) => {
- setZendeskConversationFields([{ id: 'field1', value: 'value1' }], deploymentEdition)
-
- expect(window.zE).not.toHaveBeenCalled()
- },
- )
-
- it('works without a callback', () => {
- const fields = [{ id: 'field1', value: 'value1' }]
-
- setZendeskConversationFields(fields, 'CLOUD')
-
- expect(window.zE).toHaveBeenCalledWith(
- 'messenger:set',
- 'conversationFields',
- fields,
- undefined,
- )
- })
- })
-
- describe('openZendeskWindow', () => {
- it('shows and opens the messenger in Cloud when zE exists', () => {
- openZendeskWindow('CLOUD')
-
- expect(window.zE).toHaveBeenCalledWith('messenger', 'show')
- expect(window.zE).toHaveBeenCalledWith('messenger', 'open')
- })
-
- it('retries opening until zE is ready', () => {
- vi.useFakeTimers()
- window.zE = undefined
-
- openZendeskWindow('CLOUD', { interval: 10, retries: 2 })
- window.zE = mockZE
- vi.advanceTimersByTime(10)
-
- expect(window.zE).toHaveBeenCalledWith('messenger', 'show')
- expect(window.zE).toHaveBeenCalledWith('messenger', 'open')
- })
-
- it.each(['COMMUNITY', 'ENTERPRISE'] as const)(
- 'does not open when deployment edition is %s',
- (deploymentEdition) => {
- openZendeskWindow(deploymentEdition)
-
- expect(window.zE).not.toHaveBeenCalled()
- },
- )
- })
-})
diff --git a/web/app/components/base/zendesk/index.tsx b/web/app/components/base/zendesk/index.tsx
index 6b0add6abef..e3763dad878 100644
--- a/web/app/components/base/zendesk/index.tsx
+++ b/web/app/components/base/zendesk/index.tsx
@@ -2,7 +2,7 @@ import { memo } from 'react'
import { IS_PROD, ZENDESK_WIDGET_KEY } from '@/config'
import { prefetchSystemFeatures } from '@/features/system-features/server'
import { headers } from '@/next/headers'
-import Script from '@/next/script'
+import { ZendeskScript } from './script'
const Zendesk = async () => {
if (!ZENDESK_WIDGET_KEY) return null
@@ -14,26 +14,7 @@ const Zendesk = async () => {
/* v8 ignore next -- `nonce` is always a string (`''` or header value), so nullish fallback is unreachable in runtime. @preserve */
const scriptNonce = nonce ?? undefined
- return (
- <>
- <Script
- nonce={scriptNonce}
- id="ze-snippet"
- src={`https://static.zdassets.com/ekr/snippet.js?key=${ZENDESK_WIDGET_KEY}`}
- data-testid="ze-snippet"
- />
- <Script nonce={scriptNonce} id="ze-init" data-testid="ze-init">
- {`
- (function () {
- window.addEventListener('load', function () {
- if (window.zE)
- window.zE('messenger', 'hide')
- })
- })()
- `}
- </Script>
- </>
- )
+ return <ZendeskScript nonce={scriptNonce} widgetKey={ZENDESK_WIDGET_KEY} />
}
export default memo(Zendesk)
diff --git a/web/app/components/base/zendesk/runtime.ts b/web/app/components/base/zendesk/runtime.ts
new file mode 100644
index 00000000000..299e520c1f9
--- /dev/null
+++ b/web/app/components/base/zendesk/runtime.ts
@@ -0,0 +1,152 @@
+import type { DeploymentEdition } from '@dify/contracts/api/console/system-features/types.gen'
+
+export type ZendeskConversationField = {
+ id: string
+ value: unknown
+}
+
+type ZendeskApi = (
+ command: string,
+ value: string,
+ payload?: ZendeskConversationField[] | string | string[] | (() => unknown),
+ callback?: () => unknown,
+) => void
+
+declare global {
+ // oxlint-disable-next-line typescript/consistent-type-definitions
+ interface Window {
+ zE?: ZendeskApi
+ }
+}
+
+type ZendeskRuntimeStatus = 'idle' | 'loading' | 'ready' | 'error'
+
+export type ZendeskRuntimeSnapshot = {
+ attempt: number
+ status: ZendeskRuntimeStatus
+}
+
+type LoadDeferred = {
+ promise: Promise<void>
+ reject: (error: Error) => void
+ resolve: () => void
+}
+
+const idleSnapshot: ZendeskRuntimeSnapshot = { attempt: 0, status: 'idle' }
+
+export function createZendeskRuntime(getApi: () => ZendeskApi | undefined) {
+ let snapshot = idleSnapshot
+ let loadDeferred: LoadDeferred | undefined
+ let openPromise: Promise<void> | undefined
+ const listeners = new Set<() => void>()
+ const pendingFields = new Map<string, ZendeskConversationField>()
+ const pendingFieldsCallbacks: Array<() => unknown> = []
+
+ const publish = (nextSnapshot: ZendeskRuntimeSnapshot) => {
+ snapshot = nextSnapshot
+ listeners.forEach((listener) => listener())
+ }
+
+ const requestLoad = () => {
+ if (snapshot.status === 'ready') return Promise.resolve()
+ if (snapshot.status === 'loading' && loadDeferred) return loadDeferred.promise
+
+ let resolve!: () => void
+ let reject!: (error: Error) => void
+ const promise = new Promise<void>((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise
+ reject = rejectPromise
+ })
+ loadDeferred = { promise, reject, resolve }
+ publish({ attempt: snapshot.attempt + 1, status: 'loading' })
+ return promise
+ }
+
+ const rejectLoad = (error: Error) => {
+ if (snapshot.status !== 'loading') return
+
+ const deferred = loadDeferred
+ loadDeferred = undefined
+ publish({ ...snapshot, status: 'error' })
+ deferred?.reject(error)
+ }
+
+ const markReady = () => {
+ if (snapshot.status !== 'loading') return
+
+ const api = getApi()
+ if (!api) {
+ rejectLoad(new Error('Zendesk loaded without exposing its client API'))
+ return
+ }
+
+ const deferred = loadDeferred
+ loadDeferred = undefined
+ publish({ ...snapshot, status: 'ready' })
+
+ const fields = Array.from(pendingFields.values())
+ const callbacks = pendingFieldsCallbacks.splice(0)
+ pendingFields.clear()
+ if (fields.length > 0) {
+ api(
+ 'messenger:set',
+ 'conversationFields',
+ fields,
+ callbacks.length > 0 ? () => callbacks.forEach((callback) => callback()) : undefined,
+ )
+ }
+ deferred?.resolve()
+ }
+
+ const setConversationFields = (
+ fields: ZendeskConversationField[],
+ deploymentEdition: DeploymentEdition,
+ callback?: () => unknown,
+ ) => {
+ if (deploymentEdition !== 'CLOUD') return
+
+ if (snapshot.status === 'ready') {
+ getApi()?.('messenger:set', 'conversationFields', fields, callback)
+ return
+ }
+
+ fields.forEach((field) => pendingFields.set(field.id, field))
+ if (callback) pendingFieldsCallbacks.push(callback)
+ }
+
+ const open = (deploymentEdition: DeploymentEdition) => {
+ if (deploymentEdition !== 'CLOUD') return Promise.resolve()
+ if (openPromise) return openPromise
+
+ openPromise = requestLoad()
+ .then(() => {
+ const api = getApi()
+ if (!api) throw new Error('Zendesk client API is unavailable')
+
+ api('messenger', 'show')
+ api('messenger', 'open')
+ })
+ .finally(() => {
+ openPromise = undefined
+ })
+ return openPromise
+ }
+
+ return {
+ getServerSnapshot: () => idleSnapshot,
+ getSnapshot: () => snapshot,
+ markFailed: () => rejectLoad(new Error('Failed to load Zendesk')),
+ markReady,
+ open,
+ requestLoad,
+ setConversationFields,
+ subscribe: (listener: () => void) => {
+ listeners.add(listener)
+ return () => listeners.delete(listener)
+ },
+ }
+}
+
+export type ZendeskRuntime = ReturnType<typeof createZendeskRuntime>
+
+export const zendeskRuntime = createZendeskRuntime(() => window.zE)
diff --git a/web/app/components/base/zendesk/script.tsx b/web/app/components/base/zendesk/script.tsx
new file mode 100644
index 00000000000..633c7f4218d
--- /dev/null
+++ b/web/app/components/base/zendesk/script.tsx
@@ -0,0 +1,82 @@
+'use client'
+
+import type { ZendeskRuntime } from './runtime'
+import { useEffect, useSyncExternalStore } from 'react'
+import { zendeskRuntime } from './runtime'
+
+const ZENDESK_SCRIPT_LOAD_TIMEOUT = 15_000
+const activeLoaders = new WeakMap<ZendeskRuntime, number>()
+
+function retainLoader(runtime: ZendeskRuntime) {
+ activeLoaders.set(runtime, (activeLoaders.get(runtime) ?? 0) + 1)
+}
+
+function releaseLoader(runtime: ZendeskRuntime) {
+ const nextCount = (activeLoaders.get(runtime) ?? 1) - 1
+ if (nextCount > 0) activeLoaders.set(runtime, nextCount)
+ else activeLoaders.delete(runtime)
+}
+
+type ZendeskScriptProps = {
+ nonce?: string
+ runtime?: ZendeskRuntime
+ widgetKey: string
+}
+
+export function ZendeskScript({ nonce, runtime = zendeskRuntime, widgetKey }: ZendeskScriptProps) {
+ const { attempt, status } = useSyncExternalStore(
+ runtime.subscribe,
+ runtime.getSnapshot,
+ runtime.getServerSnapshot,
+ )
+
+ useEffect(() => {
+ if (status !== 'loading') return
+
+ retainLoader(runtime)
+ const existingScript = document.getElementById('ze-snippet')
+ if (existingScript) existingScript.remove()
+
+ const script = document.createElement('script')
+ script.id = 'ze-snippet'
+ script.src = `https://static.zdassets.com/ekr/snippet.js?key=${widgetKey}`
+ script.async = true
+ if (nonce) script.nonce = nonce
+
+ let timeoutId: number
+ const handleLoad = () => {
+ window.clearTimeout(timeoutId)
+ runtime.markReady()
+ }
+ const handleError = () => {
+ window.clearTimeout(timeoutId)
+ script.remove()
+ runtime.markFailed()
+ }
+ script.addEventListener('load', handleLoad)
+ script.addEventListener('error', handleError)
+ document.body.appendChild(script)
+ timeoutId = window.setTimeout(handleError, ZENDESK_SCRIPT_LOAD_TIMEOUT)
+
+ return () => {
+ window.clearTimeout(timeoutId)
+ script.removeEventListener('load', handleLoad)
+ script.removeEventListener('error', handleError)
+ releaseLoader(runtime)
+ queueMicrotask(() => {
+ const currentSnapshot = runtime.getSnapshot()
+ if (
+ activeLoaders.has(runtime) ||
+ currentSnapshot.status !== 'loading' ||
+ currentSnapshot.attempt !== attempt
+ )
+ return
+
+ script.remove()
+ runtime.markFailed()
+ })
+ }
+ }, [attempt, nonce, runtime, status, widgetKey])
+
+ return null
+}
diff --git a/web/app/components/base/zendesk/utils.ts b/web/app/components/base/zendesk/utils.ts
deleted file mode 100644
index d3a6ed74f41..00000000000
--- a/web/app/components/base/zendesk/utils.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-import type { DeploymentEdition } from '@dify/contracts/api/console/system-features/types.gen'
-
-type ConversationField = {
- id: string
- value: unknown
-}
-
-declare global {
- // oxlint-disable-next-line typescript/consistent-type-definitions
- interface Window {
- zE?: (
- command: string,
- value: string,
- payload?: ConversationField[] | string | string[] | (() => unknown),
- callback?: () => unknown,
- ) => void
- }
-}
-
-export const setZendeskConversationFields = (
- fields: ConversationField[],
- deploymentEdition: DeploymentEdition,
- callback?: () => unknown,
-) => {
- if (deploymentEdition === 'CLOUD' && window.zE)
- window.zE('messenger:set', 'conversationFields', fields, callback)
-}
-
-type OpenZendeskWindowOptions = {
- interval?: number
- retries?: number
-}
-
-const openZendeskWindowOnce = (deploymentEdition: DeploymentEdition) => {
- if (deploymentEdition !== 'CLOUD' || !window.zE) return false
-
- window.zE('messenger', 'show')
- window.zE('messenger', 'open')
- return true
-}
-
-export const openZendeskWindow = (
- deploymentEdition: DeploymentEdition,
- { interval = 100, retries = 20 }: OpenZendeskWindowOptions = {},
-) => {
- if (deploymentEdition !== 'CLOUD') return
-
- if (openZendeskWindowOnce(deploymentEdition)) return
-
- let attempts = 0
- const timer = window.setInterval(() => {
- attempts += 1
- if (openZendeskWindowOnce(deploymentEdition) || attempts >= retries) window.clearInterval(timer)
- }, interval)
-}
diff --git a/web/app/components/main-nav/components/__tests__/support-menu.spec.tsx b/web/app/components/main-nav/components/__tests__/support-menu.spec.tsx
index 17f01fe1c3e..dc6ba29391a 100644
--- a/web/app/components/main-nav/components/__tests__/support-menu.spec.tsx
+++ b/web/app/components/main-nav/components/__tests__/support-menu.spec.tsx
@@ -4,8 +4,8 @@ import {
DropdownMenuContent,
DropdownMenuTrigger,
} from '@langgenius/dify-ui/dropdown-menu'
-import { fireEvent, screen } from '@testing-library/react'
-import { openZendeskWindow } from '@/app/components/base/zendesk/utils'
+import { fireEvent, screen, waitFor } from '@testing-library/react'
+import { zendeskRuntime } from '@/app/components/base/zendesk/runtime'
import { mailToSupport } from '@/app/components/header/utils/util'
import { useModalContext } from '@/context/modal-context'
import { useProviderContext } from '@/context/provider-context'
@@ -13,16 +13,22 @@ import { createConsoleQueryWrapper } from '@/test/console/query-data'
import { render } from '@/test/console/render'
import SupportMenu from '../support-menu'
-const { mockConfig, mockOpenZendeskWindow, mockMailToSupport, mockSetShowPricingModal } =
- vi.hoisted(() => ({
- mockConfig: {
- supportEmailAddress: '',
- zendeskWidgetKey: 'zendesk-key',
- },
- mockOpenZendeskWindow: vi.fn(),
- mockMailToSupport: vi.fn(),
- mockSetShowPricingModal: vi.fn(),
- }))
+const {
+ mockConfig,
+ mockOpenZendeskWindow,
+ mockMailToSupport,
+ mockSetShowPricingModal,
+ mockToastError,
+} = vi.hoisted(() => ({
+ mockConfig: {
+ supportEmailAddress: '',
+ zendeskWidgetKey: 'zendesk-key',
+ },
+ mockOpenZendeskWindow: vi.fn(),
+ mockMailToSupport: vi.fn(),
+ mockSetShowPricingModal: vi.fn(),
+ mockToastError: vi.fn(),
+}))
const mockConsoleState = vi.hoisted(() => ({
current: {
langGeniusVersionInfo: { current_version: '1.0.0' },
@@ -30,8 +36,14 @@ const mockConsoleState = vi.hoisted(() => ({
},
}))
-vi.mock('@/app/components/base/zendesk/utils', () => ({
- openZendeskWindow: mockOpenZendeskWindow,
+vi.mock('@/app/components/base/zendesk/runtime', () => ({
+ zendeskRuntime: {
+ open: mockOpenZendeskWindow,
+ },
+}))
+
+vi.mock('@langgenius/dify-ui/toast', () => ({
+ toast: { error: mockToastError },
}))
vi.mock('@/app/components/header/utils/util', () => ({
@@ -67,6 +79,7 @@ describe('SupportMenu', () => {
deploymentEdition = 'CLOUD'
mockConfig.supportEmailAddress = ''
mockConfig.zendeskWidgetKey = 'zendesk-key'
+ mockOpenZendeskWindow.mockResolvedValue(undefined)
mockConsoleState.current = {
langGeniusVersionInfo: { current_version: '1.0.0' },
userProfile: { email: '[email protected]' },
@@ -113,7 +126,16 @@ describe('SupportMenu', () => {
fireEvent.click(screen.getByRole('menuitem', { name: 'common.userProfile.contactUs' }))
- expect(openZendeskWindow).toHaveBeenCalledWith('CLOUD')
+ expect(zendeskRuntime.open).toHaveBeenCalledWith('CLOUD')
+ })
+
+ it('reports a Zendesk load failure so the user can retry', async () => {
+ mockOpenZendeskWindow.mockRejectedValueOnce(new Error('load failed'))
+ renderSupportMenu()
+
+ fireEvent.click(screen.getByRole('menuitem', { name: 'common.userProfile.contactUs' }))
+
+ await waitFor(() => expect(mockToastError).toHaveBeenCalledWith('common.api.actionFailed'))
})
it('renders contact us with upgrade badge for Cloud sandbox plan without dedicated support', () => {
@@ -141,7 +163,7 @@ describe('SupportMenu', () => {
)
expect(mockSetShowPricingModal).toHaveBeenCalled()
- expect(openZendeskWindow).not.toHaveBeenCalled()
+ expect(zendeskRuntime.open).not.toHaveBeenCalled()
})
it('hides upgrade contact for Cloud sandbox plan when billing is disabled', () => {
@@ -171,7 +193,7 @@ describe('SupportMenu', () => {
expect(screen.queryByText('billing.upgradeBtn.encourageShort')).not.toBeInTheDocument()
fireEvent.click(screen.getByRole('menuitem', { name: 'common.userProfile.contactUs' }))
- expect(openZendeskWindow).toHaveBeenCalledWith('CLOUD')
+ expect(zendeskRuntime.open).toHaveBeenCalledWith('CLOUD')
expect(mockSetShowPricingModal).not.toHaveBeenCalled()
})
diff --git a/web/app/components/main-nav/components/support-menu.tsx b/web/app/components/main-nav/components/support-menu.tsx
index 4bb93f0999c..cca0b866863 100644
--- a/web/app/components/main-nav/components/support-menu.tsx
+++ b/web/app/components/main-nav/components/support-menu.tsx
@@ -1,7 +1,8 @@
import { DropdownMenuItem, DropdownMenuLinkItem } from '@langgenius/dify-ui/dropdown-menu'
+import { toast } from '@langgenius/dify-ui/toast'
import { useSuspenseQuery } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
-import { openZendeskWindow } from '@/app/components/base/zendesk/utils'
+import { zendeskRuntime } from '@/app/components/base/zendesk/runtime'
import {
ExternalLinkIndicator,
MenuItemContent,
@@ -68,7 +69,9 @@ export default function SupportMenu() {
<DropdownMenuItem
className="mx-0 h-8 gap-1 px-3 py-1"
onClick={() => {
- openZendeskWindow(deploymentEdition)
+ void zendeskRuntime.open(deploymentEdition).catch(() => {
+ toast.error(t(($) => $['api.actionFailed'], { ns: 'common' }))
+ })
}}
>
<MenuItemContent
diff --git a/web/context/__tests__/console-bootstrap.spec.tsx b/web/context/__tests__/console-bootstrap.spec.tsx
index 3287a77cd5a..c23e52866ea 100644
--- a/web/context/__tests__/console-bootstrap.spec.tsx
+++ b/web/context/__tests__/console-bootstrap.spec.tsx
@@ -10,7 +10,7 @@ import { ExternalServiceSync } from '@/app/(commonLayout)/external-service-sync'
import { setUserId, setUserProperties } from '@/app/components/base/amplitude'
import { flushRegistrationSuccess } from '@/app/components/base/amplitude/registration-tracking'
import { setAnalyticsConsent } from '@/app/components/base/analytics-consent/consent-store'
-import { setZendeskConversationFields } from '@/app/components/base/zendesk/utils'
+import { zendeskRuntime } from '@/app/components/base/zendesk/runtime'
import { ZENDESK_FIELD_IDS } from '@/config'
import { createSystemFeaturesFixture } from '@/test/console/system-features'
import { initialWorkspaceSummary } from '../app-context-defaults'
@@ -190,8 +190,10 @@ vi.mock('@/app/components/base/amplitude/registration-tracking', () => ({
getRegistrationSuccessSnapshot: () => 0,
}))
-vi.mock('@/app/components/base/zendesk/utils', () => ({
- setZendeskConversationFields: vi.fn(),
+vi.mock('@/app/components/base/zendesk/runtime', () => ({
+ zendeskRuntime: {
+ setConversationFields: vi.fn(),
+ },
}))
vi.mock('@/app/components/header/maintenance-notice', () => ({
@@ -457,7 +459,7 @@ describe('Console bootstrap', () => {
renderConsoleBootstrap()
await waitFor(() => {
- expect(setZendeskConversationFields).toHaveBeenCalledWith(
+ expect(zendeskRuntime.setConversationFields).toHaveBeenCalledWith(
[
{
id: ZENDESK_FIELD_IDS.ENVIRONMENT,
@@ -467,7 +469,7 @@ describe('Console bootstrap', () => {
'CLOUD',
)
})
- expect(setZendeskConversationFields).toHaveBeenCalledWith(
+ expect(zendeskRuntime.setConversationFields).toHaveBeenCalledWith(
[
{
id: ZENDESK_FIELD_IDS.VERSION,
@@ -476,7 +478,7 @@ describe('Console bootstrap', () => {
],
'CLOUD',
)
- expect(setZendeskConversationFields).toHaveBeenCalledWith(
+ expect(zendeskRuntime.setConversationFields).toHaveBeenCalledWith(
[
{
id: ZENDESK_FIELD_IDS.EMAIL,
@@ -486,7 +488,7 @@ describe('Console bootstrap', () => {
'CLOUD',
)
await waitFor(() => {
- expect(setZendeskConversationFields).toHaveBeenCalledWith(
+ expect(zendeskRuntime.setConversationFields).toHaveBeenCalledWith(
[
{
id: ZENDESK_FIELD_IDS.WORKSPACE_ID,
@@ -520,13 +522,13 @@ describe('Console bootstrap', () => {
renderConsoleBootstrap()
await screen.findByText('workspace:Workspace')
- expect(setZendeskConversationFields).not.toHaveBeenCalled()
+ expect(zendeskRuntime.setConversationFields).not.toHaveBeenCalled()
})
it('should resync only changed Zendesk fields', async () => {
const { queryClient, rerender } = renderConsoleBootstrap()
- await waitFor(() => expect(setZendeskConversationFields).toHaveBeenCalledTimes(4))
+ await waitFor(() => expect(zendeskRuntime.setConversationFields).toHaveBeenCalledTimes(4))
rerender(
<JotaiProvider>
@@ -540,7 +542,7 @@ describe('Console bootstrap', () => {
</QueryClientProvider>
</JotaiProvider>,
)
- expect(setZendeskConversationFields).toHaveBeenCalledTimes(4)
+ expect(zendeskRuntime.setConversationFields).toHaveBeenCalledTimes(4)
act(() => {
queryClient.setQueryData(['user-profile'], {
@@ -553,8 +555,8 @@ describe('Console bootstrap', () => {
})
await waitFor(() => {
- expect(setZendeskConversationFields).toHaveBeenCalledTimes(5)
- expect(setZendeskConversationFields).toHaveBeenLastCalledWith(
+ expect(zendeskRuntime.setConversationFields).toHaveBeenCalledTimes(5)
+ expect(zendeskRuntime.setConversationFields).toHaveBeenLastCalledWith(
[
{
id: ZENDESK_FIELD_IDS.EMAIL,
diff --git a/web/context/provider-context-provider.tsx b/web/context/provider-context-provider.tsx
index 3320c10d935..6d7c8850dbd 100644
--- a/web/context/provider-context-provider.tsx
+++ b/web/context/provider-context-provider.tsx
@@ -4,7 +4,7 @@ import type { ReactNode } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { useAtomValue } from 'jotai'
import { useEffect } from 'react'
-import { setZendeskConversationFields } from '@/app/components/base/zendesk/utils'
+import { zendeskRuntime } from '@/app/components/base/zendesk/runtime'
import { defaultPlan } from '@/app/components/billing/config'
import { parseCurrentPlan } from '@/app/components/billing/utils'
import {
@@ -68,7 +68,7 @@ export const ProviderContextProvider = ({ children }: ProviderContextProviderPro
// #region Zendesk conversation fields
useEffect(() => {
if (ZENDESK_FIELD_IDS.PLAN && plan.type) {
- setZendeskConversationFields(
+ zendeskRuntime.setConversationFields(
[
{
id: ZENDESK_FIELD_IDS.PLAN,