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.

fix(i18n): avoid hiding the app during hydration (#42647)

yyh1dfa8733a51c
diff --git a/web/app/components/provider/i18n-server.tsx b/web/app/components/provider/i18n-server.tsx
index 3ea4cd77341..ad2d2be8f57 100644
--- a/web/app/components/provider/i18n-server.tsx
+++ b/web/app/components/provider/i18n-server.tsx
@@ -1,4 +1,4 @@
-import { getDeclaredRouteNamespaces, getRouteNamespaces } from '@/i18n/route-namespaces'
+import { getRouteNamespaces } from '@/i18n/route-namespaces'
import { getLocaleOnServer, getResources } from '@/i18n/server'
import { headers } from '@/next/headers'
import { basePath } from '@/utils/var'
@@ -8,11 +8,7 @@ export async function I18nServerProvider({ children }: { children: React.ReactNo
const locale = await getLocaleOnServer()
const pathname = (await headers()).get('x-dify-pathname')
const requiredNamespaces = getRouteNamespaces(pathname, basePath)
- const resource = await getResources(
- locale,
- requiredNamespaces,
- getDeclaredRouteNamespaces(pathname, basePath) !== undefined,
- )
+ const resource = await getResources(locale, requiredNamespaces, true)
return (
<I18nClientProvider locale={locale} resource={resource}>
diff --git a/web/app/components/provider/i18n.tsx b/web/app/components/provider/i18n.tsx
index 5d91b09f3e1..b938afbd045 100644
--- a/web/app/components/provider/i18n.tsx
+++ b/web/app/components/provider/i18n.tsx
@@ -3,7 +3,7 @@
import type { Resource } from 'i18next'
import type { Locale } from '@/i18n'
import type { Namespace } from '@/i18n/resources'
-import { Suspense, useEffect, useState } from 'react'
+import { useEffect, useState } from 'react'
import { I18nextProvider, useTranslation } from 'react-i18next'
import { createI18nextInstance } from '@/i18n/client'
import { getRouteNamespaces } from '@/i18n/route-namespaces'
@@ -24,14 +24,12 @@ export function I18nClientProvider({
const defaultNamespace = requiredNamespaces.includes('app') ? 'app' : 'common'
return (
<I18nextProvider i18n={i18n} defaultNS={defaultNamespace}>
- <Suspense fallback={null}>
- <RouteTranslations
- key={requiredNamespaces.join(':')}
- i18n={i18n}
- requiredNamespaces={requiredNamespaces}
- />
- {children}
- </Suspense>
+ <RouteTranslations
+ key={requiredNamespaces.join(':')}
+ i18n={i18n}
+ requiredNamespaces={requiredNamespaces}
+ />
+ {children}
</I18nextProvider>
)
}
diff --git a/web/i18n/README.md b/web/i18n/README.md
index 826985292b3..790db593176 100644
--- a/web/i18n/README.md
+++ b/web/i18n/README.md
@@ -84,17 +84,18 @@ shared by server selection, client navigation and production build validation. `
The server reads the pathname that `proxy.ts` overwrites on every request. Missing
or unknown paths conservatively use the full registry. Base paths are supported.
-For sign-in, the serialized resources include the requested locale and, when it
-differs, English fallback resources for those same two namespaces. Unmigrated
-routes retain their existing fallback loading behavior.
+Serialized resources include the requested locale and English fallback for the
+selected namespaces, keeping translation initialization ready for SSR and hydration.
+Sign-in still includes only `common` and `login`.
Client initialization uses only the provided namespaces. The default namespace is
`common` for sign-in, so a bare `useTranslation()` does not request `app`. The
provider keeps the same i18next instance across rerenders and locale changes.
A namespace-set change resets only the translation readiness component; the
provider and business subtree retain their state, including active notifications.
-Suspense reveals children after the destination's namespaces are loaded. The current route's namespace list also
-controls language switching, without discarding previously loaded bundles.
+The loader suspends missing translations into the existing router/root boundaries;
+the provider adds no application-wide Suspense fallback. The current route's
+namespace list also controls language switching without discarding loaded bundles.
Server metadata requests initialize an empty instance and load their requested
namespace. Existing server consumers without a namespace keep the full-catalog
diff --git a/web/i18n/__tests__/route-loading.spec.tsx b/web/i18n/__tests__/route-loading.spec.tsx
index 4f42d09fa31..348b62045b7 100644
--- a/web/i18n/__tests__/route-loading.spec.tsx
+++ b/web/i18n/__tests__/route-loading.spec.tsx
@@ -1,7 +1,12 @@
+import type { ReactNode } from 'react'
import { createToast, createToastManager } from '@langgenius/dify-ui/toast'
import { act, render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { lazy, startTransition } from 'react'
+import { renderToString } from 'react-dom/server'
import { useTranslation } from 'react-i18next'
import { I18nClientProvider } from '@/app/components/provider/i18n'
+import { I18nServerProvider } from '@/app/components/provider/i18n-server'
import { AppToastHost } from '@/app/notifications/host'
import { changeLanguage } from '../client'
import { getDeclaredRouteNamespaces, getRouteNamespaces } from '../route-namespaces'
@@ -9,6 +14,10 @@ import { getDeclaredRouteNamespaces, getRouteNamespaces } from '../route-namespa
vi.unmock('react-i18next')
const mocks = vi.hoisted(() => ({ pathname: '/signin', loadResource: vi.fn() }))
vi.mock('@/next/navigation', () => ({ usePathname: () => mocks.pathname }))
+vi.mock('@/next/headers', () => ({
+ headers: async () => new Headers({ 'x-dify-pathname': mocks.pathname }),
+ cookies: async () => ({ get: () => ({ value: 'zh-Hans' }) }),
+}))
vi.mock('../load-resource', () => ({ loadI18nResource: mocks.loadResource }))
const makeResources = () => ({
@@ -51,6 +60,16 @@ describe('route translation loading', () => {
expect(mocks.loadResource).not.toHaveBeenCalled()
})
+ it('includes localized content and English fallback in an unmigrated route server response', async () => {
+ mocks.pathname = '/agents/example/configure'
+ const page = await I18nServerProvider({
+ children: <Label />,
+ })
+ const html = renderToString(page)
+ expect(html).toContain('保存')
+ expect(html).toContain('Cancel')
+ })
+
it('loads only active namespaces when switching language and retains that language on rerender', async () => {
const view = render(
<I18nClientProvider locale="en-US" resource={{ 'en-US': resources['en-US'] }}>
@@ -96,17 +115,24 @@ describe('route translation loading', () => {
expect(mocks.loadResource.mock.calls.map(([, ns]) => ns).sort()).toEqual(['common', 'login'])
})
- it('preserves global notifications across namespace changes, including suspended navigation', async () => {
+ it('retains committed content and shared state until destination translations are ready', async () => {
+ function Destination() {
+ const { t } = useTranslation('common')
+ return <span>{t(($) => $['blocks.agent'], { ns: 'workflow' })}</span>
+ }
+ const user = userEvent.setup()
const manager = createToastManager()
const toast = createToast(manager)
const content = () => (
<I18nClientProvider locale="en-US" resource={{ 'en-US': resources['en-US'] }}>
<AppToastHost manager={manager} timeout={0} />
- <Label />
+ <input aria-label="Shared draft" />
+ {mocks.pathname === '/signin' ? <Label /> : <Destination />}
</I18nClientProvider>
)
const view = render(content())
await screen.findByText('Save / Cancel')
+ await user.type(screen.getByRole('textbox', { name: 'Shared draft' }), 'Keep me')
act(() => {
toast.success('Still relevant after navigation')
})
@@ -116,24 +142,71 @@ describe('route translation loading', () => {
const pending = new Promise<void>((resolve) => {
finishLoading = resolve
})
- mocks.loadResource.mockImplementation(async () => {
+ mocks.loadResource.mockImplementation(async (_locale, namespace) => {
await pending
- return { default: {} }
+ return { default: namespace === 'workflow' ? { 'blocks.agent': 'Agent' } : {} }
})
mocks.pathname = '/apps'
- view.rerender(content())
+ startTransition(() => view.rerender(content()))
await waitFor(() => expect(mocks.loadResource).toHaveBeenCalled())
+ expect(screen.getByText('Save / Cancel')).toBeVisible()
+ expect(screen.queryByText('blocks.agent')).not.toBeInTheDocument()
+ expect(screen.getByText('Still relevant after navigation')).toBeVisible()
await act(async () => {
finishLoading()
await pending
})
expect(await screen.findByText('Still relevant after navigation')).toBeVisible()
+ expect(await screen.findByText('Agent')).toBeVisible()
+ expect(screen.getByRole('textbox', { name: 'Shared draft' })).toHaveValue('Keep me')
mocks.pathname = '/signin'
- view.rerender(content())
+ startTransition(() => view.rerender(content()))
expect(await screen.findByText('Still relevant after navigation')).toBeVisible()
})
+ it('preserves route state when navigating within the same namespace scope', async () => {
+ mocks.pathname = '/apps'
+ const user = userEvent.setup()
+ const content = () => (
+ <I18nClientProvider locale="en-US" resource={{ 'en-US': resources['en-US'] }}>
+ <input aria-label="Draft" />
+ </I18nClientProvider>
+ )
+ const view = render(content())
+ await user.type(await screen.findByRole('textbox', { name: 'Draft' }), 'Keep this draft')
+ mocks.pathname = '/agents'
+ startTransition(() => view.rerender(content()))
+ expect(screen.getByRole('textbox', { name: 'Draft' })).toHaveValue('Keep this draft')
+ })
+
+ it('keeps server-rendered navigation visible while a client module hydrates', async () => {
+ let finishLoading!: () => void
+ const pending = new Promise<{ default: () => ReactNode }>((resolve) => {
+ finishLoading = () => resolve({ default: () => <main>Page content</main> })
+ })
+ const ClientPage = lazy(() => pending)
+ const content = (page: ReactNode) => (
+ <I18nClientProvider locale="en-US" resource={{ 'en-US': resources['en-US'] }}>
+ <nav aria-label="App navigation">Navigation</nav>
+ {page}
+ </I18nClientProvider>
+ )
+ const container = document.createElement('div')
+ container.innerHTML = renderToString(content(<main>Page content</main>))
+ document.body.appendChild(container)
+ const view = render(content(<ClientPage />), { container, hydrate: true })
+ view.rerender(content(<ClientPage />))
+
+ expect(screen.getByRole('navigation', { name: 'App navigation' })).toBeVisible()
+ await act(async () => {
+ finishLoading()
+ await pending
+ })
+ expect(screen.getByRole('navigation', { name: 'App navigation' })).toBeVisible()
+ expect(screen.getByRole('main')).toHaveTextContent('Page content')
+ })
+
it('matches signin segments with a base path and keeps unknown routes complete', () => {
expect(getRouteNamespaces('/console/signin/check-code', '/console')).toEqual([
'common',