Skip to content

Commit f8aa881

Browse files
myk1yttiebreak-probeedelauna
authored
perf(webview): load locales on demand instead of eager-globbing all 18 (#2267)
* perf(webview): load locales on demand instead of eager-globbing all 18 What: `webview-ui/src/i18n/setup.ts` now eager-globs only `./locales/en/*.json` into the entry chunk and keeps a lazy `import.meta.glob` map for the other 17 locales. `loadLanguage(language)` fetches a locale's namespaces on first use, memoizes in-flight requests, and resolves on fetch failure so a broken chunk degrades to the English fallback instead of blocking the view. `TranslationProvider` loads the active language before calling `i18n.changeLanguage`, because that call is what emits `languageChanged`. Why: the eager glob pulled all 162 locale JSON files into the webview entry chunk on every first paint, including the 17 locales a given user cannot read. Impact: webview entry `assets/index.js` 6,187,772 B -> 4,004,079 B raw (-2,183,693 B, -35.29%) and 1,779,406 B -> 1,128,289 B gzip (-658,117 B, -36.99%). The 153 locale chunks (2,165,392 B total) are now fetched only when the user's language needs them. Language switching still works: the 4 new provider tests and 5 new setup tests cover initial non-English render, runtime switch, missing-locale fallback, and concurrent-fetch dedupe. * fix(webview): drop the orphaned loadTranslations export and cover the load failure What: delete `loadTranslations` from `webview-ui/src/i18n/setup.ts` and the `AppProviders` call that was its last consumer. `i18next.init` already receives the eager `en` bundles through `resources:`, so the function only re-registered what init had just registered. Add `setup.rejection.spec.ts`, which stubs one lazy namespace module to throw and asserts `loadLanguage` resolves, warns, leaves the language unregistered, and stays retryable. Tighten the concurrent-fetch test to assert the memoized promise identity and a single registration pass. Why: knip reported "Unused exports (1) loadTranslations" and failed the required code-qa knip leg (CI job 124281842516). The diff removed the export's last src-side consumer and left only `playwright/AppProviders.tsx`, which knip cannot see because `knip.json` disables the playwright plugins. The `.catch` at setup.ts:90 was also the only unexercised branch of the new load path. Impact: `pnpm knip` and `pnpm knip:production` exit 0 (were exit 1), the knip policy guardrail stays 8/8, and the i18n suite covers the rejection path. No production behavior change: the gallery still gets `en` from `init`. * test(webview): cover the cancelled arm of the locale-switch guard What: add one test to `TranslationContext.locale-loading.spec.tsx` that renders the provider with language "vi", unmounts while the locale chunk is still in flight, then awaits the memoized `loadLanguage("vi")` promise. Because the provider attached its `.then` first, its callback has already run when that await returns, so the assertions prove the guard suppressed the switch rather than the promise still being pending. Why: `codecov/patch` failed at 71.42% (target 80%) on the previous head. The two partial branches were both introduced by this PR: the `cancelled` arm at TranslationContext.tsx:33 and the `||` fallback arm at line 21. The unmount path is a real user action (closing the view or switching tasks mid-fetch), so the guard is behavior worth pinning rather than coverage worth suppressing. Impact: branch coverage for `TranslationContext.tsx` 50% -> 75%, and every instrumented added line in the file is now hit (7/7). No production change. * fix(webview): type locale resources and correct the switch comment What: - Replace the `Record<string, any>` locale aliases in i18n/setup.ts with a recursive `string | LocaleResources` map, so a locale JSON leaf that is not a string is a type error instead of silently reaching addResourceBundle. - Correct the TranslationProvider comment: during an uncached fetch the subtree resolves through whichever language is still active, which is `fallbackLng` on a cold start but the previous language on a warm switch between two non-English locales. - Rename the rejection test to what it proves: `loadLanguage` does not memoize a failed load. The comment now records that the engine module map, not this function, decides whether the chunk is re-requested. Why: CodeRabbit raised three threads on PR #2267. The `any` aliases were the only untyped hop on the path from locale JSON to i18next, and the comment described cold-start behavior as if it were the only case. Impact: Type-level only for the aliases; no runtime change. The comment and test name now match observed behavior. `pnpm knip`, `knip:production`, `test:knip-policy`, `tsc --noEmit`, and the four i18n vitest suites stay green. * test(webview): assert the English first paint for a non-English initial locale What: add one synchronous assertion in the non-English initial-language test that the first paint resolves the English fallback string before the loader finishes and the switch lands on Korean. Why: the test jumped straight to a waitFor for the final Korean title, so a provider that gated rendering on the loader, or one that eagerly bundled the requested locale, still passed. A mutation probe that gates non-fallback languages on loadLanguage survives all five existing tests and is caught only by this assertion. Impact: test-only. No production source changes; the suite stays at 5 passing and the i18n folder at 14 passing. * test(webview): pin the warm locale switch to the previous language What: add a de->fr case to TranslationContext.locale-loading.spec.tsx that asserts the rendered error title is still German between the rerender and the French load settling, then asserts the final French state. Why: every warm-path case in the file either starts at English or ends at English, so a fallback-reset flash (changeLanguage(FALLBACK_LANGUAGE) fired mid-switch) passed all five existing tests. French is loaded by no other case, so the intermediate frame is observable and the assertion does not depend on test order. Impact: test-only, 27 added lines, no production change. The new assertion fails 3/3 against the injected fallback-reset mutant while the other five stay green, and passes 5/5 serial runs on the fixed provider. * fix(webview): skip the dead en lazy glob and load ru in the long-locale story * test(webview): prove the locale retry calls the loader again --------- Co-authored-by: myk1yt <[email protected]> Co-authored-by: tiebreak-probe <tiebreak@local> Co-authored-by: Elliott de Launay <[email protected]>
1 parent 12ea0f8 commit f8aa881

10 files changed

Lines changed: 384 additions & 56 deletions

File tree

‎webview-ui/playwright/AppProviders.tsx‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,10 @@ import { providerIdentifiers } from "@roo-code/types"
55

66
import { ExtensionStateContextProvider } from "@/context/ExtensionStateContext"
77
import TranslationProvider from "@/i18n/TranslationContext"
8-
import i18next, { loadTranslations } from "@/i18n/setup"
8+
import i18next from "@/i18n/setup"
99
import { TooltipProvider } from "@/components/ui/tooltip"
1010
import { TranslationContext as PlaywrightTranslationContext } from "@src/i18n/TranslationContext"
1111

12-
loadTranslations()
13-
1412
type InitialState = NonNullable<React.ComponentProps<typeof ExtensionStateContextProvider>["initialState"]>
1513

1614
interface AppProvidersProps {

‎webview-ui/playwright/gallery/stories.tsx‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -420,12 +420,8 @@ export const stories: Record<string, Story> = {
420420
return <UISettingsStory />
421421
},
422422
"ui-settings-long-locale": async () => {
423-
const [{ UISettingsStory }, { default: i18next }] = await Promise.all([
424-
import("@/components/settings/__tests__/UISettings.visual.fixture"),
425-
import("@/i18n/setup"),
426-
])
427-
await i18next.changeLanguage("ru")
428-
return <UISettingsStory />
423+
const { UISettingsStory } = await import("@/components/settings/__tests__/UISettings.visual.fixture")
424+
return <UISettingsStory initialState={{ language: "ru" }} />
429425
},
430426
welcome: async () => {
431427
const [{ AppProviders }, { WelcomeLanding }] = await Promise.all([

‎webview-ui/src/components/chat/__tests__/IndexingStatusBadge.spec.tsx‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@ vi.mock("@/i18n/setup", () => ({
1414
language: "en",
1515
changeLanguage: vi.fn(),
1616
},
17-
loadTranslations: vi.fn(),
1817
}))
1918

2019
vi.mock("react-i18next", () => ({

‎webview-ui/src/components/settings/__tests__/UISettings.visual.fixture.tsx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ interface UIState {
1414
autoCloseZooOpenedNewFiles?: boolean
1515
}
1616

17-
export function UISettingsStory() {
17+
export function UISettingsStory({ initialState }: Pick<React.ComponentProps<typeof AppProviders>, "initialState">) {
1818
const [state, setState] = useState<UIState>({
1919
reasoningBlockCollapsed: true,
2020
enterBehavior: "send",
@@ -42,7 +42,7 @@ export function UISettingsStory() {
4242
}
4343

4444
return (
45-
<AppProviders>
45+
<AppProviders initialState={initialState}>
4646
<div
4747
data-testid="ui-settings-story"
4848
className="w-[488px] max-w-full rounded-lg border border-vscode-panel-border bg-vscode-editor-background p-4 text-vscode-editor-foreground">

‎webview-ui/src/i18n/TranslationContext.tsx‎

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import React, { createContext, useContext, ReactNode, useEffect, useCallback } from "react"
22
import { useTranslation } from "react-i18next"
3-
import i18next, { loadTranslations } from "./setup"
3+
import i18next, { FALLBACK_LANGUAGE, loadLanguage } from "./setup"
44
import { useExtensionState } from "@/context/ExtensionStateContext"
55

66
// Create context for translations
@@ -18,19 +18,29 @@ const TranslationProvider: React.FC<{ children: ReactNode }> = ({ children }) =>
1818
const { i18n } = useTranslation()
1919
// Get the extension state directly - it already contains all state properties
2020
const extensionState = useExtensionState()
21+
const language = extensionState.language || FALLBACK_LANGUAGE
2122

22-
// Load translations once when the component mounts
23+
// Only the fallback locale ships in the entry chunk, so any other language
24+
// has to fetch its bundles before i18next can resolve a key. Switching after
25+
// the fetch is deliberate: `changeLanguage` is what emits `languageChanged`,
26+
// the event `useTranslation` subscribes to for re-renders. Until it fires the
27+
// subtree keeps resolving keys through whichever language is still active:
28+
// `fallbackLng` on a cold start, the previous language on a warm switch
29+
// between two non-English locales. The swap-then-render shape is the same one
30+
// this provider had when every locale was bundled.
2331
useEffect(() => {
24-
try {
25-
loadTranslations()
26-
} catch (error) {
27-
console.error("Failed to load translations:", error)
28-
}
29-
}, [])
32+
let cancelled = false
3033

31-
useEffect(() => {
32-
i18n.changeLanguage(extensionState.language)
33-
}, [i18n, extensionState.language])
34+
void loadLanguage(language).then(() => {
35+
if (!cancelled) {
36+
void i18n.changeLanguage(language)
37+
}
38+
})
39+
40+
return () => {
41+
cancelled = true
42+
}
43+
}, [i18n, language])
3444

3545
// Memoize the translation function to prevent unnecessary re-renders
3646
const translate = useCallback(
Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
import { act, render, screen, waitFor } from "@testing-library/react"
2+
import React from "react"
3+
4+
import i18next, { loadLanguage } from "../setup"
5+
import TranslationProvider, { useAppTranslation } from "../TranslationContext"
6+
7+
// The provider reads the active language from extension state. Tests drive it
8+
// through a mutable holder so a rerender can simulate a settings change.
9+
const extensionState: { language: string } = { language: "en" }
10+
11+
vi.mock("@/context/ExtensionStateContext", () => ({
12+
useExtensionState: () => extensionState,
13+
}))
14+
15+
const Probe = () => {
16+
const { t, i18n } = useAppTranslation()
17+
18+
return (
19+
<div>
20+
<span data-testid="error-title">{t("common:errorBoundary.title")}</span>
21+
<span data-testid="active-language">{i18n.language}</span>
22+
</div>
23+
)
24+
}
25+
26+
const renderProbe = (language: string) => {
27+
extensionState.language = language
28+
29+
return render(
30+
<TranslationProvider>
31+
<Probe />
32+
</TranslationProvider>,
33+
)
34+
}
35+
36+
describe("TranslationProvider locale loading", () => {
37+
beforeEach(async () => {
38+
// i18next is a module-level singleton, so a language left active by an
39+
// earlier test would mask the fallback path this suite is checking.
40+
await i18next.changeLanguage("en")
41+
})
42+
43+
it("renders translated strings for a non-English initial language", async () => {
44+
renderProbe("ko")
45+
46+
// Korean bundles are not in the entry chunk, so the first paint resolves
47+
// through the English fallback and the switch lands after the fetch.
48+
expect(screen.getByTestId("error-title")).toHaveTextContent("Something went wrong")
49+
50+
await waitFor(() => {
51+
expect(screen.getByTestId("error-title")).toHaveTextContent("문제가 발생했습니다")
52+
})
53+
expect(screen.getByTestId("active-language")).toHaveTextContent("ko")
54+
})
55+
56+
it("loads a non-eager locale when the language changes at runtime", async () => {
57+
const { rerender } = renderProbe("en")
58+
59+
expect(screen.getByTestId("error-title")).toHaveTextContent("Something went wrong")
60+
61+
extensionState.language = "ja"
62+
await act(async () => {
63+
rerender(
64+
<TranslationProvider>
65+
<Probe />
66+
</TranslationProvider>,
67+
)
68+
})
69+
70+
await waitFor(() => {
71+
expect(screen.getByTestId("error-title")).toHaveTextContent("問題が発生しました")
72+
})
73+
expect(screen.getByTestId("active-language")).toHaveTextContent("ja")
74+
})
75+
76+
it("falls back to English when the requested locale has no resources", async () => {
77+
renderProbe("xx-unsupported")
78+
79+
await waitFor(() => {
80+
expect(screen.getByTestId("error-title")).toHaveTextContent("Something went wrong")
81+
})
82+
})
83+
84+
it("keeps English available after switching away and back", async () => {
85+
const { rerender } = renderProbe("de")
86+
87+
await waitFor(() => {
88+
expect(screen.getByTestId("error-title")).toHaveTextContent("Etwas ist schiefgelaufen")
89+
})
90+
91+
extensionState.language = "en"
92+
await act(async () => {
93+
rerender(
94+
<TranslationProvider>
95+
<Probe />
96+
</TranslationProvider>,
97+
)
98+
})
99+
100+
await waitFor(() => {
101+
expect(screen.getByTestId("error-title")).toHaveTextContent("Something went wrong")
102+
})
103+
})
104+
105+
it("keeps the previous locale rendered while a warm switch is still loading", async () => {
106+
const { rerender } = renderProbe("de")
107+
108+
await waitFor(() => {
109+
expect(screen.getByTestId("error-title")).toHaveTextContent("Etwas ist schiefgelaufen")
110+
})
111+
112+
extensionState.language = "fr"
113+
await act(async () => {
114+
rerender(
115+
<TranslationProvider>
116+
<Probe />
117+
</TranslationProvider>,
118+
)
119+
})
120+
121+
// French is not in the entry chunk and no other case loads it, so the
122+
// switch cannot have landed yet. A `changeLanguage` fired before the fetch
123+
// resolves would paint the English fallback here instead of German.
124+
expect(screen.getByTestId("error-title")).toHaveTextContent("Etwas ist schiefgelaufen")
125+
126+
await waitFor(() => {
127+
expect(screen.getByTestId("error-title")).toHaveTextContent("Une erreur s'est produite")
128+
})
129+
expect(screen.getByTestId("active-language")).toHaveTextContent("fr")
130+
})
131+
132+
it("skips the language switch when the provider unmounts before the fetch resolves", async () => {
133+
const changeLanguage = vi.spyOn(i18next, "changeLanguage")
134+
135+
const { unmount } = renderProbe("vi")
136+
// The locale chunk is still in flight here, so the effect cleanup runs
137+
// before the fetch settles and `cancelled` decides the outcome.
138+
unmount()
139+
140+
// `loadLanguage` memoizes the in-flight promise, so awaiting the same
141+
// locale here waits for the exact resolution the guard is deciding on.
142+
// The provider attached its `.then` first, so its callback has already run
143+
// by the time this returns: the switch was suppressed, not left pending.
144+
await loadLanguage("vi")
145+
146+
expect(i18next.hasResourceBundle("vi", "common")).toBe(true)
147+
expect(changeLanguage).not.toHaveBeenCalledWith("vi")
148+
expect(i18next.language).not.toBe("vi")
149+
})
150+
})

‎webview-ui/src/i18n/__tests__/TranslationContext.spec.tsx‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,8 @@ vi.mock("../setup", () => ({
3636
},
3737
changeLanguage: vi.fn(),
3838
},
39-
loadTranslations: vi.fn(),
39+
FALLBACK_LANGUAGE: "en",
40+
loadLanguage: vi.fn(() => Promise.resolve()),
4041
}))
4142

4243
const TestComponent = () => {
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
import i18next, { loadLanguage } from "../setup"
2+
3+
// A dynamic import that rejects is what a 404 or a chunk missing from the
4+
// deployed manifest looks like at runtime. One namespace is enough: `loadLanguage`
5+
// registers a language only after every namespace resolves.
6+
const loader = vi.hoisted(() => ({ calls: 0, fail: true }))
7+
8+
vi.mock("../locales/ja/common.json", () => {
9+
loader.calls++
10+
11+
if (loader.fail) {
12+
throw new Error("Failed to fetch dynamically imported module")
13+
}
14+
15+
return { default: { errorBoundary: { title: "問題が発生しました" } } }
16+
})
17+
18+
describe("i18n setup locale load failure", () => {
19+
beforeEach(() => {
20+
loader.calls = 0
21+
loader.fail = true
22+
})
23+
24+
afterEach(() => {
25+
vi.restoreAllMocks()
26+
})
27+
28+
it("resolves without throwing and keeps the English fallback", async () => {
29+
const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined)
30+
31+
await expect(loadLanguage("ja")).resolves.toBeUndefined()
32+
33+
expect(warn).toHaveBeenCalledWith("Could not load ja translations:", expect.any(Error))
34+
// All-or-nothing per language: the namespaces that did resolve are not
35+
// registered either, so no half-translated locale can be activated.
36+
expect(i18next.hasResourceBundle("ja", "common")).toBe(false)
37+
expect(i18next.hasResourceBundle("ja", "settings")).toBe(false)
38+
expect(i18next.t("common:errorBoundary.title", { lng: "ja" })).toBe("Something went wrong")
39+
})
40+
41+
it("does not memoize a failed load, so the next call re-attempts it", async () => {
42+
const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined)
43+
44+
await loadLanguage("ja")
45+
expect(loader.calls).toBe(1)
46+
47+
await loadLanguage("ja")
48+
expect(loader.calls).toBe(2)
49+
50+
// `loadedLanguages` is only updated on success and `pendingLanguages` is
51+
// cleared in `finally`, so a transient failure must not be memoized.
52+
// This covers `loadLanguage`'s own bookkeeping only: engines that cache a
53+
// failed module fetch in the module map (every Chromium below 156, so the
54+
// VS Code webview) can still reject the second import from that cache
55+
// without re-requesting the chunk.
56+
expect(warn).toHaveBeenCalledTimes(2)
57+
})
58+
59+
it("registers the bundles when a later attempt succeeds", async () => {
60+
vi.spyOn(console, "warn").mockImplementation(() => undefined)
61+
62+
await loadLanguage("ja")
63+
expect(i18next.hasResourceBundle("ja", "common")).toBe(false)
64+
65+
loader.fail = false
66+
await loadLanguage("ja")
67+
68+
expect(i18next.t("common:errorBoundary.title", { lng: "ja" })).toBe("問題が発生しました")
69+
})
70+
})
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import i18next, { FALLBACK_LANGUAGE, loadLanguage } from "../setup"
2+
3+
describe("i18n setup locale loading", () => {
4+
it("ships the fallback locale eagerly", () => {
5+
expect(i18next.hasResourceBundle(FALLBACK_LANGUAGE, "common")).toBe(true)
6+
expect(i18next.hasResourceBundle(FALLBACK_LANGUAGE, "settings")).toBe(true)
7+
})
8+
9+
it("does not ship non-fallback locales in the entry graph", () => {
10+
// `hasResourceBundle` is false until `loadLanguage` fetches a chunk, which
11+
// is what keeps the 17 other locales out of the first paint.
12+
for (const language of ["ko", "ja", "de", "zh-CN"]) {
13+
expect(i18next.hasResourceBundle(language, "common")).toBe(false)
14+
}
15+
})
16+
17+
it("registers every namespace of a lazily loaded locale", async () => {
18+
await loadLanguage("ko")
19+
20+
expect(i18next.hasResourceBundle("ko", "common")).toBe(true)
21+
expect(i18next.hasResourceBundle("ko", "settings")).toBe(true)
22+
expect(i18next.t("common:errorBoundary.title", { lng: "ko" })).toBe("문제가 발생했습니다")
23+
})
24+
25+
it("shares one fetch across concurrent requests for the same locale", async () => {
26+
const addResourceBundle = vi.spyOn(i18next, "addResourceBundle")
27+
28+
// `loadLanguage` memoizes the in-flight promise, so concurrent callers get
29+
// the very same promise back: one fetch, one registration pass.
30+
const inFlight = [loadLanguage("ja"), loadLanguage("ja"), loadLanguage("ja")]
31+
expect(inFlight[1]).toBe(inFlight[0])
32+
expect(inFlight[2]).toBe(inFlight[0])
33+
34+
const results = await Promise.all(inFlight)
35+
36+
expect(results).toHaveLength(3)
37+
// 9 namespaces registered once each, not 27.
38+
expect(addResourceBundle).toHaveBeenCalledTimes(9)
39+
expect(i18next.t("common:errorBoundary.title", { lng: "ja" })).toBe("問題が発生しました")
40+
})
41+
42+
it("resolves without throwing for a locale that has no bundles", async () => {
43+
await expect(loadLanguage("xx-unsupported")).resolves.toBeUndefined()
44+
expect(i18next.t("common:errorBoundary.title", { lng: "xx-unsupported" })).toBe("Something went wrong")
45+
})
46+
})

0 commit comments

Comments
 (0)