Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion .roo/rules-translate/001-general-rules.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,10 @@
# 4. WEBVIEW UI LOCALIZATION (webview-ui/src/)

- Located in webview-ui/src/i18n/locales/
- Uses standard React i18next patterns with the useTranslation hook
- Use react-i18next's `useTranslation` and `Trans` (`import { Trans, useTranslation } from "react-i18next"`):
- Always pass the component's `t` to `Trans` (`<Trans t={t} i18nKey="..." />`); `Trans` does not follow language changes on its own (ESLint enforces this)
- Never use the global `t` from `i18next` (`i18next.t`); memoized output would keep showing the previous language after a switch (ESLint enforces this). Pass `t` to helpers instead, as `utils/format.ts` and `utils/validate.ts` do
- `useTranslation()` takes fully qualified keys (`t("chat:about")`); `useTranslation("chat")` also takes keys relative to that namespace (`t("about")`); fully qualified keys still work
- All user interface strings should be internationalized
- Always use the Trans component with named components for text with embedded components

Expand All @@ -40,6 +43,7 @@

```
<Trans
t={t}
i18nKey="welcome:telemetry.changeSettings"
components={{
settingsLink: <VSCodeLink href="#" onClick={handleOpenSettings} />
Expand Down
6 changes: 5 additions & 1 deletion .roo/skills/roo-translation/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,10 @@ This guidance file is loaded at runtime and should be consulted for the latest b
## WebView UI Localization (webview-ui/src/)

- Located in `webview-ui/src/i18n/locales/`
- Uses standard React i18next patterns with the `useTranslation` hook
- Use react-i18next's `useTranslation` and `Trans` (`import { Trans, useTranslation } from "react-i18next"`):
- Always pass the component's `t` to `Trans` (`<Trans t={t} i18nKey="..." />`); `Trans` does not follow language changes on its own (ESLint enforces this)
- Never use the global `t` from `i18next` (`i18next.t`); memoized output would keep showing the previous language after a switch (ESLint enforces this). Pass `t` to helpers instead, as `utils/format.ts` and `utils/validate.ts` do
- `useTranslation()` takes fully qualified keys (`t("chat:about")`); `useTranslation("chat")` also takes keys relative to that namespace (`t("about")`); fully qualified keys still work
- All user interface strings should be internationalized
- Always use the `Trans` component with named components for text with embedded components

Expand All @@ -86,6 +89,7 @@ React component usage:

```tsx
<Trans
t={t}
i18nKey="welcome:telemetry.changeSettings"
components={{
settingsLink: <VSCodeLink href="#" onClick={handleOpenSettings} />,
Expand Down
73 changes: 73 additions & 0 deletions packages/config-eslint/i18n-language-switch.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
// Guards that keep translated output in step with a language switch. Built-in no-restricted-syntax only.
// Translations must come from the component's `t` (react-i18next's `useTranslation`), which changes identity
// on a language switch; the global instance's `t` gives React (and React Compiler caches) nothing to
// invalidate on, so memoized output would keep the previous language.

// Selectors cannot follow bindings, so the instance is recognised by name: a default import or
// `useTranslation().i18n` held as `i18n`/`i18next`. The aliasing selectors below keep it under those names.
// Passing the instance as an argument and reading `.t` from the parameter is not caught.
const i18nInstanceName = "/^(i18n|i18next)$/"
const i18nInstance = `:matches([name=${i18nInstanceName}], MemberExpression[property.name=${i18nInstanceName}])`

// i18next itself and modules that re-export its instance as their default (webview-ui's i18n/setup).
const i18nInstanceSource = "/^(i18next|(.*\\/)?i18n\\/setup|\\.\\.?\\/setup)$/"

const globalTMessage = "Use t from react-i18next's useTranslation so memoized output follows language changes."
const aliasMessage =
"Keep the i18next instance named i18n or i18next: the global-t check recognises it by name, so an alias hides i18n.t."

export const i18nLanguageSwitchSelectors = [
{
// Global t read off the instance: i18next.t(...), i18n?.t(...), i18next["t"], useTranslation().i18n.t.
selector: `MemberExpression:matches([property.name='t'][computed=false], [property.value='t']):has(> ${i18nInstance}.object)`,
message: globalTMessage,
},
{
// Global t destructured from the instance: const { t } = i18next, const { t: translate } = i18n.
// Other properties stay allowed: const { language } = i18next.
selector: `VariableDeclarator:has(> ${i18nInstance}.init) > ObjectPattern > Property[key.name='t']`,
message: globalTMessage,
},
{
// Default import under another name: import lang from "i18next", import { default as lang } from "@/i18n/setup".
// Named imports such as initReactI18next or `type TFunction` are other specifiers and are not matched.
selector: `ImportDeclaration[source.value=${i18nInstanceSource}] > :matches(ImportDefaultSpecifier, ImportSpecifier[imported.name='default']):not([local.name=${i18nInstanceName}])`,
message: aliasMessage,
},
{
// Namespace import: import * as lang from "i18next" exposes the instance's t as lang.t whatever lang is called.
selector: `ImportDeclaration[source.value=${i18nInstanceSource}] > ImportNamespaceSpecifier`,
message: aliasMessage,
},
{
// Re-export under another name: export { default as lang } from "i18next" lets importers alias it unseen.
selector: `ExportNamedDeclaration[source.value=${i18nInstanceSource}] > ExportSpecifier[local.name='default']:not([exported.name=${i18nInstanceName}])`,
message: aliasMessage,
},
{
// Variable alias: const lang = i18next, const lang = useTranslation().i18n.
// Keeping the name is fine (const i18n = useTranslation().i18n); calls such as i18next.createInstance() are not
// the instance itself and are not matched.
selector: `VariableDeclarator[id.type='Identifier']:not([id.name=${i18nInstanceName}]):has(> ${i18nInstance}.init)`,
message: aliasMessage,
},
{
// Assignment alias to an existing variable: lang = i18n.
selector: `AssignmentExpression:not([left.name=${i18nInstanceName}]):has(> ${i18nInstance}.right)`,
message: aliasMessage,
},
{
// Destructuring rename, in declarations and parameters: const { i18n: lang } = useTranslation(),
// ({ i18n: lang }) => ..., and a nested pattern such as const { i18n: { t } } = useTranslation().
// The shorthand const { i18n } = useTranslation() keeps the name and is allowed.
selector: `ObjectPattern > Property[key.name=${i18nInstanceName}]:not([value.name=${i18nInstanceName}])`,
message: aliasMessage,
},
{
// <Trans> without its own t={t}: it reads the global instance, so a memoized element keeps the old language.
// Direct child only: <Trans components={{ b: <Foo t={1} /> }} /> is allowed.
selector: "JSXOpeningElement[name.name='Trans']:not(:has(> JSXAttribute[name.name='t']))",
message:
"Pass t={t} from useTranslation: Trans does not subscribe to language changes, so a cached <Trans> keeps the previous language.",
},
]
111 changes: 111 additions & 0 deletions packages/config-eslint/i18n-language-switch.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import assert from "node:assert/strict"
import { describe, it } from "node:test"

import { Linter } from "eslint"
import typescriptEslint from "typescript-eslint"

import { i18nLanguageSwitchSelectors } from "./i18n-language-switch.js"

const linter = new Linter({ configType: "flat" })
const config = [
{
files: ["**/*.tsx"],
languageOptions: { parser: typescriptEslint.parser, parserOptions: { ecmaFeatures: { jsx: true } } },
rules: { "no-restricted-syntax": ["error", ...i18nLanguageSwitchSelectors] },
},
]

const lint = (code) => linter.verify(code, config, { filename: "example.tsx" }).map((message) => message.message)

describe("i18n language switch: global t", () => {
for (const code of [
'i18next.t("chat:about")',
'import i18n from "i18next"\ni18n.t("chat:about")',
'i18n?.t("chat:about")',
'i18next["t"]("chat:about")',
'useTranslation().i18n.t("chat:about")',
"const { t } = i18next",
"const { t: translate } = i18n",
"const { t } = useTranslation().i18n",
]) {
it(`flags: ${code}`, () => {
assert.equal(lint(code).length, 1)
})
}

for (const code of [
'const { t } = useTranslation()\nt("chat:about")',
'i18next.changeLanguage("es")',
"i18n.language",
"i18next[t]",
"const { language } = i18n",
'other.t("chat:about")',
]) {
it(`allows: ${code}`, () => {
assert.deepEqual(lint(code), [])
})
}
})

describe("i18n language switch: aliasing the instance", () => {
for (const code of [
'import lang from "i18next"',
'import { default as lang } from "i18next"',
'import * as lang from "i18next"',
'import lang from "@src/i18n/setup"',
'import lang from "@/i18n/setup"',
'import lang from "../setup"',
'export { default as lang } from "i18next"',
"const lang = i18next",
"const lang = useTranslation().i18n",
"lang = i18n",
"const { i18n: lang } = useTranslation()",
"const { i18n: { t } } = useTranslation()",
"function Foo({ i18n: lang }) {}",
]) {
it(`flags: ${code}`, () => {
assert.equal(lint(code).length, 1)
})
}

for (const code of [
'import i18next from "i18next"',
'import i18n from "i18next"',
'import i18next, { type TFunction } from "i18next"',
'import { initReactI18next } from "react-i18next"',
'import i18next from "@src/i18n/setup"',
'import { default as i18next } from "i18next"',
'import config from "./config"',
"const i18n = useTranslation().i18n",
"const { i18n } = useTranslation()",
"const { language } = i18next",
"const instance = i18next.createInstance()",
"changeLanguage(i18next)",
]) {
it(`allows: ${code}`, () => {
assert.deepEqual(lint(code), [])
})
}
})

describe("i18n language switch: Trans", () => {
for (const code of [
'<Trans i18nKey="chat:about" />',
"<Trans components={{ b: <Foo t={1} /> }} />",
"<Trans {...props} />",
]) {
it(`flags a Trans without its own t: ${code}`, () => {
assert.equal(lint(code).length, 1)
})
}

for (const code of [
'<Trans t={t} i18nKey="chat:about" />',
"<Trans t={t} components={{ b: <Foo t={1} /> }} />",
'<Other i18nKey="chat:about" />',
]) {
it(`allows: ${code}`, () => {
assert.deepEqual(lint(code), [])
})
}
})
5 changes: 3 additions & 2 deletions packages/config-eslint/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@
"./next-js": "./next.js",
"./provider-identifiers": "./provider-identifiers.js",
"./api-provider-hygiene": "./api-provider-hygiene.js",
"./i18n-keys": "./i18n-keys.js"
"./i18n-keys": "./i18n-keys.js",
"./i18n-language-switch": "./i18n-language-switch.js"
},
"scripts": {
"lint": "eslint . --max-warnings=0",
"test": "node --test provider-identifiers.test.js api-provider-hygiene.test.js i18n-keys.test.js"
"test": "node --test *.test.js"
},
"devDependencies": {
"@eslint/js": "9.39.5",
Expand Down
7 changes: 7 additions & 0 deletions packages/types/src/vscode-extension-host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -450,6 +450,13 @@ export type ExtensionState = Pick<
* (captured during async getStateToPostToWebview) from overwriting newer messages.
*/
clineMessagesSeq?: number

/**
* Monotonically increasing sequence number for every state snapshot, assigned before the
* snapshot is read. Snapshots are built asynchronously and can be posted out of order, so the
* frontend applies `language` only from a snapshot newer than the last one it applied.
*/
stateSeq?: number
}

export interface Command {
Expand Down
9 changes: 9 additions & 0 deletions src/core/webview/ClineProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -406,6 +406,12 @@ export class ClineProvider
*/
private clineMessagesSeq = 0

/**
* Monotonically increasing sequence number for every state snapshot.
* Used by the frontend to ignore the language from snapshots that arrive out-of-order.
*/
private stateSeq = 0

public isViewLaunched = false
public settingsImportedAt?: number
public readonly latestAnnouncementId = "oct-2026-v3.94.0-models-oauth-chat" // v3.94.0 model support, MCP OAuth, and chat reliability
Expand Down Expand Up @@ -3051,6 +3057,8 @@ export class ClineProvider
}

async getStateToPostToWebview({ includeTaskHistory = true }: GetStateOptions = {}): Promise<ExtensionState> {
// Assign the sequence before the first await so it orders snapshots by when they were read.
const stateSeq = ++this.stateSeq
// Ensure the store is initialized before reading task history
await this.taskHistoryStore.initialized

Expand Down Expand Up @@ -3292,6 +3300,7 @@ export class ClineProvider
showRooIgnoredFiles: showRooIgnoredFiles ?? false,
enableSubfolderRules: enableSubfolderRules ?? false,
language: language ?? formatLanguage(vscode.env.language),
stateSeq,
renderContext: this.renderContext,
maxImageFileSize: maxImageFileSize ?? 5,
maxTotalImageSize: maxTotalImageSize ?? 20,
Expand Down
36 changes: 36 additions & 0 deletions src/core/webview/__tests__/ClineProvider.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3438,6 +3438,42 @@ describe("ClineProvider", () => {
expect(postMessageSpy.mock.calls.map(([message]) => message.state?.clineMessagesSeq)).toEqual([2, 1])
})

test.each([
["postStateToWebview", (currentProvider: ClineProvider) => currentProvider.postStateToWebview()],
[
"postStateToWebviewWithoutTaskHistory",
(currentProvider: ClineProvider) => currentProvider.postStateToWebviewWithoutTaskHistory(),
],
[
"postStateToWebviewWithoutClineMessages",
(currentProvider: ClineProvider) => currentProvider.postStateToWebviewWithoutClineMessages(),
],
])("%s orders snapshots by when they were read, not when they were posted", async (_methodName, postState) => {
const baseState = await provider.getState({ includeTaskHistory: false })
let releaseOlderRead!: () => void
const olderRead = new Promise<void>((resolve) => {
releaseOlderRead = resolve
})
vi.spyOn(provider, "getState")
.mockImplementationOnce(async () => {
await olderRead
return { ...baseState, language: "en" }
})
.mockResolvedValueOnce({ ...baseState, language: "es" })
const postMessageSpy = vi.spyOn(provider, "postMessageToWebview").mockResolvedValue(undefined)

const olderPost = postState(provider)
await Promise.resolve()
await postState(provider)
releaseOlderRead()
await olderPost

const posted = postMessageSpy.mock.calls.map(([message]) => message.state)
expect(posted.map((state) => state?.language)).toEqual(["es", "en"])
const [newer, older] = posted.map((state) => state?.stateSeq ?? 0)
expect(older).toBeLessThan(newer)
})

test.each([
[
"postStateToWebviewWithoutTaskHistory",
Expand Down
14 changes: 14 additions & 0 deletions webview-ui/eslint.config.mjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { reactConfig } from "@roo-code/config-eslint/react"
import { i18nLanguageSwitchSelectors } from "@roo-code/config-eslint/i18n-language-switch"
import { createProviderIdentifierConfig } from "@roo-code/config-eslint/provider-identifiers"
import { createI18nDotKeyConfig } from "@roo-code/config-eslint/i18n-keys"
import { providerIdentifiers, retiredProviderIdentifiers } from "@roo-code/types/provider-identifiers"
Expand Down Expand Up @@ -75,9 +76,16 @@ export default [
message:
"axios was removed from the webview bundle in favour of global fetch. Use fetch() for network calls. The dependency is no longer declared in webview-ui/package.json, so an import here only resolves through the hoisted store and would fail at build time.",
},
{
name: "i18next",
importNames: ["t"],
message:
"Use t from react-i18next's useTranslation so memoized output follows language changes.",
},
],
},
],
"no-restricted-syntax": ["error", ...i18nLanguageSwitchSelectors],
},
},
{
Expand Down Expand Up @@ -108,6 +116,12 @@ export default [
message:
"axios was removed from the webview bundle in favour of global fetch. Use fetch() for network calls. The dependency is no longer declared in webview-ui/package.json, so an import here only resolves through the hoisted store and would fail at build time.",
},
{
name: "i18next",
importNames: ["t"],
message:
"Use t from react-i18next's useTranslation so memoized output follows language changes.",
},
{
name: "@tanstack/react-query",
importNames: ["QueryClientProvider"],
Expand Down
17 changes: 5 additions & 12 deletions webview-ui/playwright/AppProviders.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,8 @@ import { I18nextProvider } from "react-i18next"
import { providerIdentifiers } from "@roo-code/types"

import { ExtensionStateContextProvider } from "@/context/ExtensionStateContext"
import TranslationProvider from "@/i18n/TranslationContext"
import i18next from "@/i18n/setup"
import { TooltipProvider } from "@/components/ui/tooltip"
import { TranslationContext as PlaywrightTranslationContext } from "@src/i18n/TranslationContext"

type InitialState = NonNullable<React.ComponentProps<typeof ExtensionStateContextProvider>["initialState"]>

Expand Down Expand Up @@ -40,16 +38,11 @@ export function AppProviders({ children, initialState }: AppProvidersProps) {
return (
<I18nextProvider i18n={i18next}>
<ExtensionStateContextProvider initialState={{ ...defaultInitialState, ...initialState }}>
<TranslationProvider>
<PlaywrightTranslationContext.Provider
value={{ t: (key, options) => i18next.t(key, options), i18n: i18next }}>
<QueryClientProvider client={queryClient}>
<TooltipProvider>
<div data-testid="ct-app-shell">{children}</div>
</TooltipProvider>
</QueryClientProvider>
</PlaywrightTranslationContext.Provider>
</TranslationProvider>
<QueryClientProvider client={queryClient}>
<TooltipProvider>
<div data-testid="ct-app-shell">{children}</div>
</TooltipProvider>
</QueryClientProvider>
</ExtensionStateContextProvider>
</I18nextProvider>
)
Expand Down
Loading
Loading