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.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
refactor(web): load and stream translation namespaces on demand (#42812)
Stephen Zhou7f4a5c241330
diff --git a/web/app/components/provider/__tests__/i18n-hydration.browser.spec.tsx b/web/app/components/provider/__tests__/i18n-hydration.browser.spec.tsxnew file mode 100644index 00000000000..9bf8c9e12b2--- /dev/null+++ b/web/app/components/provider/__tests__/i18n-hydration.browser.spec.tsx@@ -0,0 +1,106 @@+import type { ReactNode } from 'react'+import { Suspense, useState } from 'react'+import { hydrateRoot } from 'react-dom/client'+import { renderToReadableStream } from 'react-dom/server.browser'+import { useTranslation } from 'react-i18next'+import { page } from 'vite-plus/test/browser'+import { CreateAppDropdown } from '@/app/components/app/create-app-dropdown'+import { I18nClientProvider } from '@/app/components/provider/i18n'+import { serializeResourceUpdate } from '@/i18n/streamed-resources'++vi.mock('react-i18next', async (importOriginal) => await importOriginal())+const mocks = vi.hoisted(() => ({+ load: vi.fn(),+ callbacks: [] as (() => ReactNode)[],+ server: true,+}))+vi.mock('next/navigation', () => ({+ useParams: () => ({}),+ useRouter: () => ({}),+ useServerInsertedHTML: (callback: () => ReactNode) => {+ if (mocks.server) mocks.callbacks.push(callback)+ },+}))+vi.mock('@/i18n/load-resource', () => ({ loadI18nResource: mocks.load }))++function DeferredFeature() {+ const { t } = useTranslation(['login'])+ return <p>{t(($) => $.signBtn)}</p>+}++function FeaturePage() {+ const [open, setOpen] = useState(false)+ return (+ <>+ <CreateAppDropdown onCreateBlank={() => {}} />+ <button onClick={() => setOpen(true)}>Show deferred feature</button>+ {open && <DeferredFeature />}+ </>+ )+}++function executeResourceScript(source: string) {+ const script = document.createElement('script')+ script.textContent = source+ document.head.append(script)+ script.remove()+}++// A real mouse click on SSR markup reproduces the interaction lost when+// client translation loading suspends hydration. No disabled trigger or retry.+it('hydrates the menu from automatically collected SSR resources before the first click', async () => {+ mocks.callbacks = []+ delete window.__difyI18nResources+ const app = { 'newApp.startFromBlank': 'Create from Blank' }+ mocks.load.mockImplementation(async (_locale: string, namespace: string) => ({+ default: namespace === 'common' ? { 'operation.create': 'Create' } : app,+ }))+ const view = (+ <I18nClientProvider locale="en-US" resource={{}}>+ <Suspense fallback={<span>Loading</span>}>+ <FeaturePage />+ </Suspense>+ </I18nClientProvider>+ )+ const stream = await renderToReadableStream(view)+ await stream.allReady+ const html = await new Response(stream).text()+ const inserted = await renderToReadableStream(+ <>{mocks.callbacks.map((callback) => callback())}</>,+ )+ const insertedHTML = await new Response(inserted).text()+ expect(insertedHTML).toContain('Create from Blank')+ expect(insertedHTML).toContain('operation.create')+ const container = document.createElement('div')+ container.innerHTML = html+ document.body.append(container)+ const holder = document.createElement('div')+ holder.innerHTML = insertedHTML+ // innerHTML does not execute scripts; inserting fresh script nodes models+ // the HTML parser executing resource updates before the following content.+ for (const source of holder.querySelectorAll('script')) {+ executeResourceScript(source.textContent ?? '')+ }+ mocks.server = false+ mocks.load.mockClear()+ mocks.load.mockImplementation(() => new Promise(() => {}))+ const root = hydrateRoot(container, view)+ try {+ await page.getByRole('button', { name: 'Create', exact: true }).click()+ await expect.element(page.getByRole('menuitem', { name: 'Create from Blank' })).toBeVisible()+ expect(mocks.load).not.toHaveBeenCalled()+ // A later server flush reaches the already-mounted provider. It must be+ // available before its feature renders, without a second backend request.+ const [id] = Object.keys(window.__difyI18nResources ?? {})+ executeResourceScript(+ serializeResourceUpdate(id!, { 'en-US': { login: { signBtn: 'Sign in' } } }),+ )+ await page.getByRole('button', { name: 'Show deferred feature' }).click()+ await expect.element(page.getByText('Sign in', { exact: true })).toBeVisible()+ expect(mocks.load).not.toHaveBeenCalled()+ } finally {+ root.unmount()+ container.remove()+ delete window.__difyI18nResources+ }+})diff --git a/web/app/components/provider/i18n-server.tsx b/web/app/components/provider/i18n-server.tsxindex ad2d2be8f57..698e06bd2c0 100644--- a/web/app/components/provider/i18n-server.tsx+++ b/web/app/components/provider/i18n-server.tsx@@ -1,17 +1,13 @@-import { getRouteNamespaces } from '@/i18n/route-namespaces'-import { getLocaleOnServer, getResources } from '@/i18n/server'+import { getLocaleOnServer } from '@/i18n/server'import { headers } from '@/next/headers'-import { basePath } from '@/utils/var'import { I18nClientProvider } from './i18n'export async function I18nServerProvider({ children }: { children: React.ReactNode }) {+ const nonce = (await headers()).get('x-nonce') ?? undefinedconst locale = await getLocaleOnServer()- const pathname = (await headers()).get('x-dify-pathname')- const requiredNamespaces = getRouteNamespaces(pathname, basePath)- const resource = await getResources(locale, requiredNamespaces, true)return (- <I18nClientProvider locale={locale} resource={resource}>+ <I18nClientProvider locale={locale} resource={{}} nonce={nonce}>{children}</I18nClientProvider>)diff --git a/web/app/components/provider/i18n-stream.tsx b/web/app/components/provider/i18n-stream.tsxnew file mode 100644index 00000000000..d9cde74df7b--- /dev/null+++ b/web/app/components/provider/i18n-stream.tsx@@ -0,0 +1,36 @@+'use client'++import type { Resource } from 'i18next'+import { use, useEffect, useState } from 'react'+import { I18nContext } from 'react-i18next'+import {+ createResourceCollector,+ serializeResourceUpdate,+ subscribeToStreamedResources,+} from '@/i18n/streamed-resources'+import { useServerInsertedHTML } from '@/next/navigation'++export function I18nResourceStream({+ id,+ initial,+ nonce,+}: {+ id: string+ initial: Resource+ nonce?: string+}) {+ const { i18n } = use(I18nContext)+ const [collect] = useState(() => createResourceCollector(i18n, initial))+ useServerInsertedHTML(() => {+ const resources = collect()+ if (Object.keys(resources).length === 0) return null+ return (+ <script+ nonce={nonce}+ dangerouslySetInnerHTML={{ __html: serializeResourceUpdate(id, resources) }}+ />+ )+ })+ useEffect(() => subscribeToStreamedResources(id, i18n), [id, i18n])+ return null+}diff --git a/web/app/components/provider/i18n.tsx b/web/app/components/provider/i18n.tsxindex b938afbd045..9289fc089f8 100644--- a/web/app/components/provider/i18n.tsx+++ b/web/app/components/provider/i18n.tsx@@ -2,52 +2,52 @@import type { Resource } from 'i18next'import type { Locale } from '@/i18n'-import type { Namespace } from '@/i18n/resources'-import { useEffect, useState } from 'react'-import { I18nextProvider, useTranslation } from 'react-i18next'-import { createI18nextInstance } from '@/i18n/client'-import { getRouteNamespaces } from '@/i18n/route-namespaces'-import { usePathname } from '@/next/navigation'-import { basePath } from '@/utils/var'+import { createInstance } from 'i18next'+import resourcesToBackend from 'i18next-resources-to-backend'+import { useId, useState } from 'react'+import { I18nextProvider, initReactI18next } from 'react-i18next'+import { loadI18nResource } from '@/i18n/load-resource'+import { supportedLocales } from '@/i18n/locale'+import { getInitOptions } from '@/i18n/settings'+import { getStreamedResources, mergeResources } from '@/i18n/streamed-resources'+import { I18nResourceStream } from './i18n-stream'export function I18nClientProvider({locale,resource,children,+ nonce,}: {+ nonce?: stringlocale: Localeresource: Resourcechildren: React.ReactNode}) {- const requiredNamespaces = getRouteNamespaces(usePathname(), basePath)- const [i18n] = useState(() => createI18nextInstance(locale, resource))- const defaultNamespace = requiredNamespaces.includes('app') ? 'app' : 'common'+ const streamId = useId()+ // Server resources bootstrap this session. Client preferences and share-app+ // overrides own later language changes, even when the root layout rerenders.+ const [initial] = useState(() => {+ const resources = mergeResources(resource, getStreamedResources(streamId))+ const i18n = createInstance()+ void i18n+ .use(initReactI18next)+ .use(resourcesToBackend(loadI18nResource))+ .init({+ ...getInitOptions([]),+ // Register streamed namespaces so language changes load their translations.+ ns: [...new Set(Object.values(resources).flatMap(Object.keys))],+ lng: locale,+ resources,+ supportedLngs: supportedLocales,+ fallbackNS: false,+ react: { useSuspense: true },+ })+ return { i18n, resources }+ })return (- <I18nextProvider i18n={i18n} defaultNS={defaultNamespace}>- <RouteTranslations- key={requiredNamespaces.join(':')}- i18n={i18n}- requiredNamespaces={requiredNamespaces}- />+ <I18nextProvider i18n={initial.i18n}>+ <I18nResourceStream id={streamId} initial={initial.resources} nonce={nonce} />{children}</I18nextProvider>)}--function RouteTranslations({- i18n,- requiredNamespaces,-}: {- requiredNamespaces: readonly Namespace[]- i18n: ReturnType<typeof createI18nextInstance>-}) {- const defaultNamespace = requiredNamespaces.includes('app') ? 'app' : 'common'- useTranslation([...requiredNamespaces], { i18n })- useEffect(() => {- // i18next remembers every namespace ever requested. Keep language switching- // scoped to the active route while retaining already fetched bundles.- i18n.options.ns = [...requiredNamespaces]- i18n.setDefaultNamespace(defaultNamespace)- }, [i18n, requiredNamespaces, defaultNamespace])- return null-}diff --git a/web/i18n/README.md b/web/i18n/README.mdindex 790db593176..cc5a378e4ef 100644--- a/web/i18n/README.md+++ b/web/i18n/README.md@@ -76,82 +76,84 @@ Changes to `web/i18n/locales/en-US/*.json` on `main` trigger the scoped translatUse the `Translate i18n Files with Claude Code` workflow dispatch for a manual scoped sync. Full mode requires an explicit file list.-## Initial route resources--`route-namespaces.ts` owns the explicit `routeNamespaceDeclarations` opt-in map-shared by server selection, client navigation and production build validation. `/signin` and its child routes use `common` and-`login`. Other routes retain the complete registry until they are migrated.--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.-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.-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-behavior for cross-namespace calls.--### Build validation--Production Vite builds check every opted-in route against its declaration using-the combined client, SSR and RSC module graphs. The check includes page imports,-shared layouts and boundaries, dynamic imports and conservative parallel slots.-An undeclared namespace fails the build and lists the route and source files.-The JSON analysis report is written before validation, so it remains available-when validation fails. Unregistered routes are not checked against a restricted-list and continue to load the full catalog.--Add a subtree to `routeNamespaceDeclarations` after auditing its dependencies;-more specific declarations override ancestor declarations. The check covers-statically recognized translation usage, including namespace constants, imported-arrays and nested static spreads passed to translation hooks or server loaders,-not arbitrary runtime imports or-unknown translation APIs. Consult the analyzer README for its limitations.--### Production validation of the sign-in migration--Measured locally on 2026-09-18 against layer 2 (`b6405a857a`), using production-Vinext standalone builds and fresh Chromium contexts. Both builds used the same-controlled API fixture: `createSystemFeaturesFixture({ is_allow_register: true })`,-completed setup/init, and an unauthenticated account-profile response. These are-frontend transfer diagnostics, not production-backend latency measurements.--| `/signin` metric | Before | After |-| --------------------------------------------- | ------: | ------: |-| English HTML response body, bytes | 438,163 | 95,915 |-| Chinese HTML response body, bytes | 424,123 | 148,172 |-| English RSC response body, bytes | 380,526 | 59,829 |-| Chinese RSC response body, bytes | 366,751 | 108,608 |-| English initial translation-module requests | 0 | 0 |-| Chinese initial translation-module requests | 36 | 0 |-| English → Chinese translation-module requests | 37 | 2 |--HTML includes embedded RSC and other page data; HTML and standalone RSC sizes-must not be added. RSC was requested separately using `RSC: 1` on `/signin?_rsc`-with an explicit locale cookie. Body sizes are decoded bytes, not compressed-wire transfer sizes. Estimated gzip sizes for the HTML bodies were approximately-106 KB → 23 KB (English) and 112 KB → 38 KB (Chinese).--Translation requests were identified using the production client manifest's-`i18n/locales/` entries, rather than chunk-name guesses. The new language-switch-waterfall loads the locale loader module, then the common and login modules in-parallel. No translation modules are requested on initial English or Chinese-sign-in hydration. Rendered page text matched the baseline and no browser runtime-errors were recorded. Client navigation to `/signup` and back rendered correctly;-unmigrated destinations still load their complete namespace set on entry.--Unit coverage uses real i18next/react-i18next to check initial loading, missing-key-fallback, locale persistence, route transitions and active-route language changes.-The route-analysis report is diagnostic guidance, not an automatic resource manifest.-Datasets and authenticated feature-navigation/network validation remain follow-up-work for issue #42442; this migration does not close that issue.+## On-demand resources++The App Router client Provider owns one i18next instance per mounted Provider,+using `react-i18next` with Suspense and the same resource backend during SSR and+browser rendering. The root server Provider starts with an empty resource store+and no initial namespaces, including no `common` preload. Components keep declaring their namespaces+through `react-i18next`; a missing namespace loads through `loadI18nResource` during+both streaming SSR and browser rendering. Optional features load their translations+when rendered, without a separate route namespace map or root readiness gate.++Keep the Provider mounted for the application session. Its initial server locale+and resources bootstrap that session; client language preferences and share-app+overrides own subsequent language changes. Passing the original server props again+must not reset those overrides. The namespace options are created per Provider+because i18next mutates its requested namespace list.++Feature-owned Suspense boundaries can isolate translation loading along with the+feature's other loading work. Shell consumers load `common` on demand during SSR;+the initial shell may wait for that dictionary. During SSR, a Provider-local+collector reads react-i18next's reported namespaces and streams newly loaded+resources through `useServerInsertedHTML`, including the active fallback language.+Inline updates use the request CSP nonce and escape script-sensitive text. Each+Provider has a hydration-stable ID so concurrent requests and separate Providers+do not share a resource collection.++The client merges available streamed resources before creating its i18next instance+and subscribes to later updates. This avoids fetching SSR-used dictionaries again+while hydrating interactive controls. Namespaces for features not rendered during+SSR continue to load on demand. Client navigation has no HTML insertion pass and+continues to use the existing backend. The collector sends complete namespaces,+not individual keys.++Language switching follows i18next's requested namespace list, including features+visited earlier in the session. Previously loaded bundles remain cached. There is+no route policy that resets `i18n.options.ns` on navigation.++Server metadata requests still use the request-scoped server instance and load+exactly their requested namespace. Existing server consumers without a namespace+retain their full-catalog behavior.++The build analyzer continues to report route usage and check unused keys. Its+route report is diagnostic and is not a runtime resource manifest or an allowlist.+The application no longer opts into exhaustive route namespace validation.++Tests cover on-demand feature loading, navigation state, language persistence,+English fallback, and concurrent streaming SSR in different locales. Production+Vinext/browser checks are also needed when changing the Provider or loading strategy.++### Provider trial verification++On 2026-09-23, the production Vinext standalone build was checked in fresh+Chromium contexts using local system-features and unauthenticated API fixtures.+English and Simplified Chinese sign-in rendered correctly after hydration without+runtime or hydration errors. The raw HTML contains the shell and a loading spinner,+not the login form: `NormalForm` waits for the client account-profile probe. This+browser check does not establish that the complete login form is server-rendered.+English hydration requested `en-US/login`; Chinese hydration+requested `zh-Hans/login` and `en-US/login`. Switching English to Chinese requested+only `zh-Hans/common` and `zh-Hans/login`. Navigation to sign-up and back preserved+Chinese and requested no additional translation modules. These counts use the+client build manifest, exclude loader modules, and are not backend latency metrics.+Authenticated feature navigation remains unverified.++### Streaming resource verification++The Chromium hydration regression renders the real creation menu on the server,+collects its dictionaries, and hydrates with client backend requests held pending.+Its first click opens the menu without disabling the trigger or retrying the click.+It also verifies that a later resource update reaches the mounted Provider before+its feature renders. Unit coverage checks incremental collection, fallback+languages, Provider isolation, and inline-script escaping.++A production Next.js sign-in check with controlled unauthenticated API fixtures+confirmed English and Chinese `login` resources in the HTML stream, no repeated+login translation chunk requests, and no browser hydration errors. Production+Vinext validation remains pending; its build was stopped to limit local resource+usage. The complete authenticated Agent creation journey must still pass CI.++Empty-store coverage also verifies shell rendering without an enclosing Suspense+boundary, concurrent locale/fallback rendering, and hydration of both `common`+and feature namespaces without duplicate backend requests.diff --git a/web/i18n/__tests__/route-loading.spec.tsx b/web/i18n/__tests__/route-loading.spec.tsxindex d917a090025..133ceb5be8b 100644--- a/web/i18n/__tests__/route-loading.spec.tsx+++ b/web/i18n/__tests__/route-loading.spec.tsx@@ -2,20 +2,18 @@ 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 { lazy, startTransition, Suspense, useState } 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'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 }),+ headers: async () => new Headers(),cookies: async () => ({ get: () => ({ value: 'zh-Hans' }) }),}))vi.mock('../load-resource', () => ({ loadI18nResource: mocks.loadResource }))@@ -23,9 +21,8 @@ vi.mock('../load-resource', () => ({ loadI18nResource: mocks.loadResource }))const makeResources = () => ({'en-US': {common: { 'operation.save': 'Save', 'operation.cancel': 'Cancel' },- login: { signBtn: 'Sign in' },},- 'zh-Hans': { common: { 'operation.save': '保存' }, login: { signBtn: '登录' } },+ 'zh-Hans': { common: { 'operation.save': '保存' } },})let resources = makeResources()function Label() {@@ -38,14 +35,19 @@ function Label() {)}-describe('route translation loading', () => {+function Destination() {+ const { t } = useTranslation(['workflow'])+ return <span>{t(($) => $['blocks.agent'], { ns: 'workflow' })}</span>+}++describe('on-demand translation loading', () => {beforeEach(() => {resources = makeResources()mocks.pathname = '/signin'mocks.loadResource.mockReset()mocks.loadResource.mockImplementation(async (locale: keyof typeof resources, namespace: string) => ({- default: resources[locale]?.[namespace as 'common' | 'login'] ?? {},+ default: resources[locale]?.[namespace as 'common'] ?? {},}),)})@@ -60,17 +62,24 @@ 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'+ it('starts the root provider without preloading and loads common only when rendered', async () => {const page = await I18nServerProvider({- children: <Label />,+ children: (+ <Suspense fallback={<span>Loading</span>}>+ <Label />+ </Suspense>+ ),})- const html = renderToString(page)- expect(html).toContain('保存')- expect(html).toContain('Cancel')+ expect(mocks.loadResource).not.toHaveBeenCalled()+ render(page)+ expect(await screen.findByText('保存 / Cancel')).toBeVisible()+ expect(mocks.loadResource.mock.calls.map(([lng, ns]) => `${lng}/${ns}`).sort()).toEqual([+ 'en-US/common',+ 'zh-Hans/common',+ ])})- it('loads only active namespaces when switching language and retains that language on rerender', async () => {+ it('switches language for requested namespaces and retains it on rerender', async () => {const view = render(<I18nClientProvider locale="en-US" resource={{ 'en-US': resources['en-US'] }}><Label />@@ -79,7 +88,7 @@ describe('route translation loading', () => {await waitFor(() => expect(screen.getByText('Save / Cancel')).toBeVisible())await act(() => changeLanguage('zh-Hans'))expect(await screen.findByText('保存 / Cancel')).toBeVisible()- expect(mocks.loadResource.mock.calls.map(([, ns]) => ns).sort()).toEqual(['common', 'login'])+ expect(mocks.loadResource.mock.calls.map(([, ns]) => ns).sort()).toEqual(['common'])view.rerender(<I18nClientProvider locale="en-US" resource={{ 'en-US': resources['en-US'] }}><Label />@@ -88,38 +97,71 @@ describe('route translation loading', () => {expect(screen.getByText('保存 / Cancel')).toBeVisible()})- it('loads unmigrated route resources on navigation, then scopes the next language change back to signin', async () => {- const view = render(- <I18nClientProvider locale="en-US" resource={{ 'en-US': resources['en-US'] }}>- <Label />- </I18nClientProvider>,- )- await waitFor(() => expect(screen.getByText('Save / Cancel')).toBeVisible())- mocks.pathname = '/apps'- view.rerender(- <I18nClientProvider locale="en-US" resource={{ 'en-US': resources['en-US'] }}>- <Label />- </I18nClientProvider>,- )- await waitFor(() => expect(screen.getByText('Save / Cancel')).toBeVisible())- expect(mocks.loadResource.mock.calls.map(([, ns]) => ns)).toContain('workflow')- mocks.pathname = '/signin'- view.rerender(+ it('loads destination namespaces on navigation without requesting unrelated features', async () => {+ mocks.loadResource.mockImplementation(async (locale, namespace) => ({+ default:+ namespace === 'workflow'+ ? { 'blocks.agent': locale === 'en-US' ? 'Agent' : '代理' }+ : (resources[locale as keyof typeof resources]?.common ?? {}),+ }))+ const content = (destination = false) => (<I18nClientProvider locale="en-US" resource={{ 'en-US': resources['en-US'] }}>- <Label />- </I18nClientProvider>,+ {destination ? <Destination /> : <Label />}+ </I18nClientProvider>)+ const view = render(content())+ await screen.findByText('Save / Cancel')+ startTransition(() => view.rerender(content(true)))+ expect(await screen.findByText('Agent')).toBeVisible()+ expect(mocks.loadResource.mock.calls.map(([, ns]) => ns)).toEqual(['workflow'])+ startTransition(() => view.rerender(content()))+ await screen.findByText('Save / Cancel')mocks.loadResource.mockClear()await act(() => changeLanguage('zh-Hans'))expect(await screen.findByText('保存 / Cancel')).toBeVisible()- expect(mocks.loadResource.mock.calls.map(([, ns]) => ns).sort()).toEqual(['common', 'login'])+ // i18next retains requested namespaces for subsequent language changes.+ expect(mocks.loadResource.mock.calls.map(([, ns]) => ns).sort()).toEqual(['common', 'workflow'])})- it('retains committed content and shared state until destination translations are ready', async () => {- function Destination() {- const { t } = useTranslation(['workflow'])- return <span>{t(($) => $['blocks.agent'], { ns: 'workflow' })}</span>+ it('loads an optional feature only when opened and keeps the shell visible while loading', async () => {+ let finishLoading!: () => void+ const pending = new Promise<void>((resolve) => {+ finishLoading = resolve+ })+ mocks.loadResource.mockImplementation(async () => {+ await pending+ return { default: { 'blocks.agent': 'Agent' } }+ })+ function Page() {+ const [open, setOpen] = useState(false)+ return (+ <>+ <Label />+ <button onClick={() => setOpen(true)}>Open editor</button>+ <Suspense fallback={<span>Loading editor</span>}>{open && <Destination />}</Suspense>+ </>+ )}+ const user = userEvent.setup()+ render(+ <I18nClientProvider locale="en-US" resource={{ 'en-US': resources['en-US'] }}>+ <Page />+ </I18nClientProvider>,+ )+ expect(mocks.loadResource).not.toHaveBeenCalled()+ await user.click(screen.getByRole('button', { name: 'Open editor' }))+ expect(screen.getByText('Save / Cancel')).toBeVisible()+ expect(screen.getByText('Loading editor')).toBeVisible()+ expect(screen.queryByText('blocks.agent')).not.toBeInTheDocument()+ await act(async () => {+ finishLoading()+ await pending+ })+ expect(await screen.findByText('Agent')).toBeVisible()+ expect(mocks.loadResource).toHaveBeenCalledExactlyOnceWith('en-US', 'workflow')+ })++ it('retains committed content and shared state until destination translations are ready', async () => {const user = userEvent.setup()const manager = createToastManager()const toast = createToast(manager)@@ -165,21 +207,6 @@ describe('route translation loading', () => {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!: () => voidconst pending = new Promise<{ default: () => ReactNode }>((resolve) => {@@ -206,16 +233,4 @@ describe('route translation loading', () => {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',- 'login',- ])- expect(getDeclaredRouteNamespaces('/signin/check-code')).toEqual(['common', 'login'])- expect(getDeclaredRouteNamespaces('/signin-other')).toBeUndefined()- expect(getDeclaredRouteNamespaces('/datasets')).toBeUndefined()- expect(getRouteNamespaces('/signin-other')).toContain('workflow')- expect(getRouteNamespaces(null)).toContain('workflow')- })})diff --git a/web/i18n/__tests__/server.spec.ts b/web/i18n/__tests__/server.spec.tsindex c4b3cf45787..9603377f051 100644--- a/web/i18n/__tests__/server.spec.ts+++ b/web/i18n/__tests__/server.spec.ts@@ -37,20 +37,6 @@ describe('server translations', () => {}))})- it('serializes only requested namespaces, including fallback resources when requested', async () => {- const { getResources } = await import('../server')- const resources = await getResources('zh-Hans', ['common', 'login'], true)- expect(Object.keys(resources)).toEqual(['zh-Hans', 'en-US'])- expect(Object.keys(resources['zh-Hans']!)).toEqual(['common', 'login'])- expect(resources).toMatchObject({ 'en-US': { common: { 'operation.cancel': 'Cancel' } } })- expect(mocks.loadResource.mock.calls.map(([lng, ns]) => `${lng}/${ns}`).sort()).toEqual([- 'en-US/common',- 'en-US/login',- 'zh-Hans/common',- 'zh-Hans/login',- ])- })-it('does not preload the complete catalog for namespaced server metadata', async () => {const { getTranslation } = await import('../server')await getTranslation('en-US', 'login')diff --git a/web/i18n/__tests__/streamed-resources.spec.ts b/web/i18n/__tests__/streamed-resources.spec.tsnew file mode 100644index 00000000000..5bd36d5d176--- /dev/null+++ b/web/i18n/__tests__/streamed-resources.spec.ts@@ -0,0 +1,72 @@+import { createInstance } from 'i18next'+import { initReactI18next } from 'react-i18next'+import {+ createResourceCollector,+ getStreamedResources,+ mergeResources,+ serializeResourceUpdate,+ subscribeToStreamedResources,+} from '../streamed-resources'++it('collects only reported namespaces and active fallback languages, once per stream', async () => {+ const i18n = createInstance().use(initReactI18next)+ await i18n.init({+ lng: 'zh-Hans',+ fallbackLng: 'en-US',+ load: 'currentOnly',+ resources: {+ 'zh-Hans': { common: {}, app: { title: '应用' }, workflow: { title: '流程' } },+ 'en-US': { common: {}, app: { title: 'Apps' } },+ 'de-DE': { app: { title: 'Apps' } },+ },+ })+ Object.assign(i18n, {+ reportNamespaces: {+ getUsedNamespaces: () => ['common', 'app', 'login'],+ addUsedNamespaces: () => {},+ },+ })+ const collect = createResourceCollector(i18n, {+ 'zh-Hans': { common: {} },+ 'en-US': { common: {} },+ })+ expect(collect()).toEqual({+ 'zh-Hans': { app: { title: '应用' } },+ 'en-US': { app: { title: 'Apps' } },+ })+ expect(collect()).toEqual({})+ i18n.addResourceBundle('en-US', 'login', { title: 'Sign in' })+ expect(collect()).toEqual({ 'en-US': { login: { title: 'Sign in' } } })+})++it('receives late resources for the matching provider without switching its language', async () => {+ const i18n = createInstance().use(initReactI18next)+ await i18n.init({ lng: 'zh-Hans', fallbackLng: false, resources: { 'zh-Hans': { common: {} } } })+ const unsubscribe = subscribeToStreamedResources('main', i18n)+ try {+ window.__difyI18nResources = {+ main: { 'en-US': { app: { title: 'Apps' } } },+ other: { 'en-US': { login: { title: 'Sign in' } } },+ }+ window.dispatchEvent(new Event('dify:i18n-resources'))+ expect(i18n.getResourceBundle('en-US', 'app')).toEqual({ title: 'Apps' })+ expect(i18n.hasResourceBundle('en-US', 'login')).toBe(false)+ expect(i18n.language).toBe('zh-Hans')+ expect(mergeResources({ 'en-US': { common: {} } }, getStreamedResources('main'))).toEqual({+ 'en-US': { common: {}, app: { title: 'Apps' } },+ })+ } finally {+ unsubscribe()+ delete window.__difyI18nResources+ }+})++it('escapes translation text and provider identifiers for inline script transport', () => {+ const script = serializeResourceUpdate('</script>', {+ 'en-US': { app: { title: '</script><script>alert(1)</script>&\u2028\u2029' } },+ })+ expect(script).not.toContain('</script>')+ expect(script).not.toContain('<')+ expect(script).toContain('\\u003c/script\\u003e')+ expect(script).toContain('\\u2028\\u2029')+})diff --git a/web/i18n/__tests__/streaming.spec.tsx b/web/i18n/__tests__/streaming.spec.tsxnew file mode 100644index 00000000000..a0107f4144f--- /dev/null+++ b/web/i18n/__tests__/streaming.spec.tsx@@ -0,0 +1,77 @@+// @vitest-environment node++import { Suspense } from 'react'+import { renderToReadableStream } from 'react-dom/server'+import { useTranslation } from 'react-i18next'+import { I18nClientProvider } from '@/app/components/provider/i18n'++vi.unmock('react-i18next')+const mocks = vi.hoisted(() => ({ loadResource: vi.fn() }))+vi.mock('../load-resource', () => ({ loadI18nResource: mocks.loadResource }))++function SignIn() {+ const { t } = useTranslation(['login'])+ return <h1>{t(($) => $.signBtn)}</h1>+}++describe('on-demand translations during SSR', () => {+ it('streams only rendered namespaces with fallback and isolates concurrent locales', async () => {+ mocks.loadResource.mockImplementation(async (locale: string, namespace: string) => ({+ default: namespace === 'login' && locale === 'en-US' ? { signBtn: 'Sign in' } : {},+ }))+ const render = async (locale: 'en-US' | 'zh-Hans') => {+ const errors: unknown[] = []+ const stream = await renderToReadableStream(+ <I18nClientProvider locale={locale} resource={{}}>+ <Suspense fallback={<span>Loading</span>}>+ <SignIn />+ </Suspense>+ </I18nClientProvider>,+ {+ onError: (error) => {+ errors.push(error)+ },+ },+ )+ await stream.allReady+ const html = await new Response(stream).text()+ expect(errors).toEqual([])+ return html+ }++ const [english, chineseFallback] = await Promise.all([render('en-US'), render('zh-Hans')])+ expect(english).toContain('<h1>Sign in</h1>')+ expect(chineseFallback).toContain('<h1>Sign in</h1>')+ expect(mocks.loadResource.mock.calls.map(([lng, ns]) => `${lng}/${ns}`).sort()).toEqual([+ 'en-US/login',+ 'en-US/login',+ 'zh-Hans/login',+ ])++ mocks.loadResource.mockImplementation(async (locale: string) => ({+ default: { signBtn: locale === 'zh-Hans' ? '登录' : 'Sign in' },+ }))+ const [nextEnglish, chinese] = await Promise.all([render('en-US'), render('zh-Hans')])+ expect(nextEnglish).toContain('<h1>Sign in</h1>')+ expect(nextEnglish).not.toContain('登录')+ expect(chinese).toContain('<h1>登录</h1>')+ })+})++function Shell() {+ const { t } = useTranslation(['common'])+ return <header>{t(($) => $['operation.save'])}</header>+}++it('renders the shell from empty resources without a surrounding Suspense boundary', async () => {+ mocks.loadResource.mockReset()+ mocks.loadResource.mockResolvedValue({ default: { 'operation.save': 'Save' } })+ const stream = await renderToReadableStream(+ <I18nClientProvider locale="en-US" resource={{}}>+ <Shell />+ </I18nClientProvider>,+ )+ await stream.allReady+ expect(await new Response(stream).text()).toContain('<header>Save</header>')+ expect(mocks.loadResource.mock.calls).toEqual([['en-US', 'common']])+})diff --git a/web/i18n/client.ts b/web/i18n/client.tsindex 6379fff925d..a1d69f1472c 100644--- a/web/i18n/client.ts+++ b/web/i18n/client.ts@@ -1,35 +1,8 @@'use client'-import type { Resource } from 'i18next'-import type { Locale } from './locale'-import type { Namespace, NamespaceInFileName } from './resources'-import { createInstance } from 'i18next'-import resourcesToBackend from 'i18next-resources-to-backend'import Cookies from 'js-cookie'-import { getI18n, initReactI18next } from 'react-i18next'+import { getI18n } from 'react-i18next'import { LOCALE_COOKIE_NAME } from '@/config'-import { loadI18nResource } from './load-resource'import { normalizeLocale } from './locale'-import { namespaces } from './resources'-import { getInitOptions } from './settings'--export function createI18nextInstance(lng: Locale, resources: Resource) {- const instance = createInstance()- instance- .use(initReactI18next)- .use(- resourcesToBackend((language: Locale, namespace: NamespaceInFileName | Namespace) =>- loadI18nResource(language, namespace),- ),- )- .init({- ...getInitOptions(- namespaces.filter((namespace) => Object.hasOwn(resources[lng] ?? {}, namespace)),- ),- lng,- resources,- })- return instance-}export const changeLanguage = async (lng?: string) => {if (!lng) returndiff --git a/web/i18n/route-namespaces.ts b/web/i18n/route-namespaces.tsdeleted file mode 100644index 971dd493d9f..00000000000--- a/web/i18n/route-namespaces.ts+++ /dev/null@@ -1,26 +0,0 @@-import type { Namespace } from './resources'-import { namespaces } from './resources'--// Opt in route subtrees only after auditing their complete namespace usage.-// More specific declarations override an ancestor declaration.-const routeNamespaceDeclarations: Readonly<Record<string, readonly Namespace[]>> = {- '/signin': ['common', 'login'],-}-const declaredRoutes = Object.keys(routeNamespaceDeclarations).sort((a, b) => b.length - a.length)--export function getDeclaredRouteNamespaces(- pathname: string | null,- basePath = '',-): readonly Namespace[] | undefined {- const route =- basePath && pathname?.startsWith(`${basePath}/`) ? pathname.slice(basePath.length) : pathname- const declaredRoute = declaredRoutes.find(- (path) => route === path || route?.startsWith(`${path}/`),- )- return declaredRoute ? routeNamespaceDeclarations[declaredRoute] : undefined-}--// Unmigrated routes retain their complete namespace set.-export function getRouteNamespaces(pathname: string | null, basePath = ''): readonly Namespace[] {- return getDeclaredRouteNamespaces(pathname, basePath) ?? namespaces-}diff --git a/web/i18n/server.ts b/web/i18n/server.tsindex e10d83aebca..69942db1a2b 100644--- a/web/i18n/server.ts+++ b/web/i18n/server.ts@@ -1,4 +1,3 @@-import type { Resource, ResourceLanguage } from 'i18next'import type { Locale } from '.'import type { Namespace, NamespaceInFileName } from './resources'import { match } from '@formatjs/intl-localematcher'@@ -58,27 +57,3 @@ export const getLocaleOnServer = cache(async (): Promise<Locale> => {return match(languages, supportedLocales, defaultLocale) as Locale})--export const getResources = cache(- async (- lng: Locale,- requiredNamespaces: readonly Namespace[] = namespaces,- includeFallback = false,- ): Promise<Resource> => {- const locales = includeFallback && lng !== defaultLocale ? [lng, defaultLocale] : [lng]- const resources: Resource = {}- await Promise.all(- locales.map(async (locale) => {- const messages: ResourceLanguage = {}- await Promise.all(- requiredNamespaces.map(async (namespace) => {- const mod = await loadI18nResource(locale, namespace)- messages[namespace] = mod.default- }),- )- resources[locale] = messages- }),- )- return resources- },-)diff --git a/web/i18n/streamed-resources.ts b/web/i18n/streamed-resources.tsnew file mode 100644index 00000000000..892dc865634--- /dev/null+++ b/web/i18n/streamed-resources.ts@@ -0,0 +1,64 @@+import type { i18n, Resource } from 'i18next'++const eventName = 'dify:i18n-resources'++declare global {+ // oxlint-disable-next-line typescript/consistent-type-definitions -- Augment the browser Window interface for the SSR resource transport.+ interface Window {+ __difyI18nResources?: Record<string, Resource>+ }+}++export function getStreamedResources(id: string): Resource {+ return typeof window === 'undefined' ? {} : (window.__difyI18nResources?.[id] ?? {})+}++export function mergeResources(initial: Resource, extra: Resource): Resource {+ const result = { ...initial }+ for (const [language, namespaces] of Object.entries(extra))+ result[language] = { ...result[language], ...namespaces }+ return result+}++export function subscribeToStreamedResources(id: string, instance: i18n) {+ const receive = () => {+ for (const [language, namespaces] of Object.entries(getStreamedResources(id))) {+ for (const [namespace, resource] of Object.entries(namespaces)) {+ if (!instance.hasResourceBundle(language, namespace))+ instance.addResourceBundle(language, namespace, resource)+ }+ }+ }+ window.addEventListener(eventName, receive)+ receive()+ return () => window.removeEventListener(eventName, receive)+}++export function createResourceCollector(instance: i18n, initial: Resource) {+ const sent = new Set(+ Object.entries(initial).flatMap(([language, namespaces]) =>+ Object.keys(namespaces).map((namespace) => `${language}/${namespace}`),+ ),+ )+ return () => {+ const resources: Resource = {}+ for (const namespace of instance.reportNamespaces?.getUsedNamespaces() ?? []) {+ for (const language of instance.languages) {+ const key = `${language}/${namespace}`+ if (sent.has(key) || !instance.hasResourceBundle(language, namespace)) continue+ ;(resources[language] ??= {})[namespace] = instance.getResourceBundle(language, namespace)+ sent.add(key)+ }+ }+ return resources+ }+}++export function serializeResourceUpdate(id: string, resources: Resource) {+ // Translation text must never terminate its enclosing script element.+ const payload = JSON.stringify([id, resources]).replace(+ /[<>&\u2028\u2029]/g,+ (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, '0')}`,+ )+ return `(()=>{const [id,resources]=${payload};const stores=window.__difyI18nResources??={};const store=stores[id]??={};for(const [language,namespaces] of Object.entries(resources)){Object.assign(store[language]??={},namespaces)}window.dispatchEvent(new Event('${eventName}'))})()`+}diff --git a/web/next/navigation.ts b/web/next/navigation.tsindex 695194f41b0..5c714699cb8 100644--- a/web/next/navigation.ts+++ b/web/next/navigation.ts@@ -5,6 +5,7 @@ export {usePathname,useRouter,useSearchParams,+ useServerInsertedHTML,useSelectedLayoutSegment,useSelectedLayoutSegments,} from 'next/navigation'diff --git a/web/plugins/vite/i18n-analysis/README.md b/web/plugins/vite/i18n-analysis/README.mdindex ff55863f28a..dec09f371c4 100644--- a/web/plugins/vite/i18n-analysis/README.md+++ b/web/plugins/vite/i18n-analysis/README.md@@ -185,13 +185,10 @@ validation. Undeclared routes remain exempt from strict validation.Explicit, statically resolved `useTranslation` / `getTranslation` namespacearguments are included even when no translation key is consumed.-The application passes `getDeclaredRouteNamespaces` from-`i18n/route-namespaces.ts`, sharing declarations with server resource selection-and client navigation. Currently only `/signin` and its descendants opt in. The-application uses the default non-strict mode: runtime providers emit-unknown warnings, while statically detected undeclared namespaces still fail.-No policy callback substitutes configured values for unknown expressions.-Undeclared routes keep the full catalog and can be migrated independently.+Dify does not currently enable this optional validation. Components load their+namespaces through the next-i18next Provider at render time, so there is no+exhaustive route allowlist. Route reports remain available for diagnostics and+preload investigations.This validates statically detected usage, with the recognition and conservativelimitations described above. It does not prove that arbitrary runtime-generateddiff --git a/web/vite.config.ts b/web/vite.config.tsindex 771a5810fa6..9d44d4cf644 100644--- a/web/vite.config.ts+++ b/web/vite.config.ts@@ -1,7 +1,6 @@import { fileURLToPath } from 'node:url'import { configDefaults, defineConfig, lazyPlugins } from 'vite-plus'import { playwright } from 'vite-plus/test/browser-playwright'-import { getDeclaredRouteNamespaces } from './i18n/route-namespaces.ts'import { customI18nHmrPlugin } from './plugins/vite/custom-i18n-hmr.ts'import { i18nAnalysisPlugin } from './plugins/vite/i18n-analysis.ts'import { getRootClientInjectTarget } from './plugins/vite/inject-target.ts'@@ -58,8 +57,6 @@ export default defineConfig(({ command, mode, isPreview }) => {selectorArgument: 1,},],- getDeclaredNamespaces: getDeclaredRouteNamespaces,- // Runtime namespace providers remain unknown; validate detected usage only.}),Inspect(),inspector,@@ -90,7 +87,6 @@ export default defineConfig(({ command, mode, isPreview }) => {{ find: /^loro-crdt$/, replacement: 'loro-crdt/base64' },],},-// vinext related config...(!isTest && !isStorybook? {